HealthCheckManager.coffee 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. metrics = require "metrics-sharelatex"
  2. logger = require("logger-sharelatex")
  3. os = require "os"
  4. HOST = os.hostname()
  5. PID = process.pid
  6. COUNT = 0
  7. CHANNEL_MANAGER = {} # hash of event checkers by channel name
  8. CHANNEL_ERROR = {} # error status by channel name
  9. module.exports = class HealthCheckManager
  10. # create an instance of this class which checks that an event with a unique
  11. # id is received only once within a timeout
  12. constructor: (@channel, timeout = 1000) ->
  13. # unique event string
  14. @id = "host=#{HOST}:pid=#{PID}:count=#{COUNT++}"
  15. # count of number of times the event is received
  16. @count = 0
  17. # after a timeout check the status of the count
  18. @handler = setTimeout () =>
  19. @setStatus()
  20. , timeout
  21. # use a timer to record the latency of the channel
  22. @timer = new metrics.Timer("event.#{@channel}.latency")
  23. # keep a record of these objects to dispatch on
  24. CHANNEL_MANAGER[@channel] = @
  25. processEvent: (id) ->
  26. # if this is our event record it
  27. if id == @id
  28. @count++
  29. @timer?.done()
  30. @timer = null # only time the latency of the first event
  31. setStatus: () ->
  32. # if we saw the event anything other than a single time that is an error
  33. if @count != 1
  34. logger.err channel:@channel, count:@count, id:@id, "redis channel health check error"
  35. error = (@count != 1)
  36. CHANNEL_ERROR[@channel] = error
  37. # class methods
  38. @check: (channel, id) ->
  39. # dispatch event to manager for channel
  40. CHANNEL_MANAGER[channel]?.processEvent id
  41. @status: () ->
  42. # return status of all channels for logging
  43. return CHANNEL_ERROR
  44. @isFailing: () ->
  45. # check if any channel status is bad
  46. for channel, error of CHANNEL_ERROR
  47. return true if error is true
  48. return false