2014-09-26 09:46:23 -04:00
|
|
|
_ = require("underscore")
|
|
|
|
|
2014-11-19 06:01:02 -05:00
|
|
|
module.exports = RedisSharelatex =
|
|
|
|
createClient: (opts = {port: 6379, host: "localhost"})->
|
2014-11-19 06:02:27 -05:00
|
|
|
if !opts.retry_max_delay?
|
|
|
|
opts.retry_max_delay = 5000 # ms
|
|
|
|
|
2014-09-29 06:40:40 -04:00
|
|
|
if opts.password?
|
|
|
|
opts.auth_pass = opts.password
|
|
|
|
delete opts.password
|
2014-09-26 09:46:23 -04:00
|
|
|
if opts.endpoints?
|
|
|
|
standardOpts = _.clone(opts)
|
|
|
|
delete standardOpts.endpoints
|
|
|
|
delete standardOpts.masterName
|
|
|
|
client = require("redis-sentinel").createClient opts.endpoints, opts.masterName, standardOpts
|
2014-09-25 12:33:27 -04:00
|
|
|
else
|
2014-09-26 09:46:23 -04:00
|
|
|
standardOpts = _.clone(opts)
|
|
|
|
delete standardOpts.port
|
|
|
|
delete standardOpts.host
|
|
|
|
client = require("redis").createClient opts.port, opts.host, standardOpts
|
2014-11-19 18:18:56 -05:00
|
|
|
return client
|
|
|
|
|
|
|
|
|
|
|
|
activeHealthCheckRedis: (connectionInfo)->
|
|
|
|
sub = RedisSharelatex.createClient(connectionInfo)
|
|
|
|
pub = RedisSharelatex.createClient(connectionInfo)
|
|
|
|
|
2014-11-20 06:09:44 -05:00
|
|
|
redisIsOk = true
|
2014-11-20 07:50:19 -05:00
|
|
|
lastPingMessage = ""
|
2014-11-19 18:18:56 -05:00
|
|
|
heartbeatInterval = 2000 #ms
|
|
|
|
isAliveTimeout = 10000 #ms
|
|
|
|
|
|
|
|
id = require("crypto").pseudoRandomBytes(16).toString("hex")
|
|
|
|
heartbeatChannel = "heartbeat-#{id}"
|
|
|
|
lastHeartbeat = Date.now()
|
|
|
|
|
|
|
|
sub.subscribe heartbeatChannel, (error) ->
|
|
|
|
if error?
|
|
|
|
console.error "ERROR: failed to subscribe to #{heartbeatChannel} channel", error
|
|
|
|
sub.on "message", (channel, message) ->
|
2014-11-20 07:50:19 -05:00
|
|
|
if lastPingMessage == message #we got the same message twice
|
|
|
|
redisIsOk = false
|
|
|
|
lastPingMessage = message
|
2014-11-19 18:18:56 -05:00
|
|
|
if channel == heartbeatChannel
|
|
|
|
lastHeartbeat = Date.now()
|
|
|
|
|
|
|
|
setInterval ->
|
2014-11-20 07:50:19 -05:00
|
|
|
message = "ping:#{Date.now()}"
|
|
|
|
pub.publish heartbeatChannel, message
|
2014-11-19 18:18:56 -05:00
|
|
|
, heartbeatInterval
|
|
|
|
|
|
|
|
isAlive = ->
|
|
|
|
timeSinceLastHeartbeat = Date.now() - lastHeartbeat
|
2014-11-20 06:09:44 -05:00
|
|
|
if !redisIsOk
|
|
|
|
return false
|
|
|
|
else if timeSinceLastHeartbeat > isAliveTimeout
|
2014-11-19 18:18:56 -05:00
|
|
|
console.error "heartbeat from redis timed out"
|
2014-11-20 06:09:44 -05:00
|
|
|
redisIsOk = false
|
2014-11-19 18:18:56 -05:00
|
|
|
return false
|
|
|
|
else
|
|
|
|
return true
|
|
|
|
|
|
|
|
return {
|
|
|
|
isAlive:isAlive
|
|
|
|
}
|