LockManager.js 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  1. // TODO: This file was created by bulk-decaffeinate.
  2. // Fix any style issues and re-enable lint.
  3. /*
  4. * decaffeinate suggestions:
  5. * DS101: Remove unnecessary use of Array.from
  6. * DS102: Remove unnecessary code created because of implicit returns
  7. * DS207: Consider shorter variations of null checks
  8. * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
  9. */
  10. import async from 'async'
  11. import metrics from '@overleaf/metrics'
  12. import Settings from '@overleaf/settings'
  13. import redis from '@overleaf/redis-wrapper'
  14. import os from 'os'
  15. import crypto from 'crypto'
  16. import logger from '@overleaf/logger'
  17. import OError from '@overleaf/o-error'
  18. const LOCK_TEST_INTERVAL = 50 // 50ms between each test of the lock
  19. const MAX_LOCK_WAIT_TIME = 10000 // 10s maximum time to spend trying to get the lock
  20. export const LOCK_TTL = 360 // seconds
  21. export const MIN_LOCK_EXTENSION_INTERVAL = 1000 // 1s minimum interval when extending a lock
  22. export const UNLOCK_SCRIPT =
  23. 'if redis.call("get", KEYS[1]) == ARGV[1] then return redis.call("del", KEYS[1]) else return 0 end'
  24. const EXTEND_SCRIPT =
  25. 'if redis.call("get", KEYS[1]) == ARGV[1] then return redis.call("expire", KEYS[1], ARGV[2]) else return 0 end'
  26. const HOST = os.hostname()
  27. const PID = process.pid
  28. const RND = crypto.randomBytes(4).toString('hex')
  29. let COUNT = 0
  30. const rclient = redis.createClient(Settings.redis.lock)
  31. /**
  32. * Container for functions that need to be mocked in tests
  33. *
  34. * TODO: Rewrite tests in terms of exported functions only
  35. */
  36. export const _mocks = {}
  37. // Use a signed lock value as described in
  38. // http://redis.io/topics/distlock#correct-implementation-with-a-single-instance
  39. // to prevent accidental unlocking by multiple processes
  40. _mocks.randomLock = () => {
  41. const time = Date.now()
  42. return `locked:host=${HOST}:pid=${PID}:random=${RND}:time=${time}:count=${COUNT++}`
  43. }
  44. export function randomLock(...args) {
  45. return _mocks.randomLock(...args)
  46. }
  47. _mocks.tryLock = (key, callback) => {
  48. if (callback == null) {
  49. callback = function () {}
  50. }
  51. const lockValue = randomLock()
  52. return rclient.set(
  53. key,
  54. lockValue,
  55. 'EX',
  56. LOCK_TTL,
  57. 'NX',
  58. function (err, gotLock) {
  59. if (err != null) {
  60. return callback(
  61. OError.tag(err, 'redis error trying to get lock', { key })
  62. )
  63. }
  64. if (gotLock === 'OK') {
  65. metrics.inc('lock.project.try.success')
  66. return callback(err, true, lockValue)
  67. } else {
  68. metrics.inc('lock.project.try.failed')
  69. return callback(err, false)
  70. }
  71. }
  72. )
  73. }
  74. export function tryLock(...args) {
  75. _mocks.tryLock(...args)
  76. }
  77. _mocks.extendLock = (key, lockValue, callback) => {
  78. if (callback == null) {
  79. callback = function () {}
  80. }
  81. return rclient.eval(
  82. EXTEND_SCRIPT,
  83. 1,
  84. key,
  85. lockValue,
  86. LOCK_TTL,
  87. function (err, result) {
  88. if (err != null) {
  89. return callback(
  90. OError.tag(err, 'redis error trying to extend lock', { key })
  91. )
  92. }
  93. if (result != null && result !== 1) {
  94. // successful extension should release exactly one key
  95. metrics.inc('lock.project.extend.failed')
  96. const error = new OError('failed to extend lock', {
  97. key,
  98. lockValue,
  99. result,
  100. })
  101. return callback(error)
  102. }
  103. metrics.inc('lock.project.extend.success')
  104. return callback()
  105. }
  106. )
  107. }
  108. export function extendLock(...args) {
  109. _mocks.extendLock(...args)
  110. }
  111. _mocks.getLock = (key, callback) => {
  112. let attempt
  113. if (callback == null) {
  114. callback = function () {}
  115. }
  116. const startTime = Date.now()
  117. let attempts = 0
  118. return (attempt = function () {
  119. if (Date.now() - startTime > MAX_LOCK_WAIT_TIME) {
  120. metrics.inc('lock.project.get.failed')
  121. return callback(new OError('Timeout', { key }))
  122. }
  123. attempts += 1
  124. return tryLock(key, function (error, gotLock, lockValue) {
  125. if (error != null) {
  126. return callback(OError.tag(error))
  127. }
  128. if (gotLock) {
  129. metrics.gauge('lock.project.get.success.tries', attempts)
  130. return callback(null, lockValue)
  131. } else {
  132. return setTimeout(attempt, LOCK_TEST_INTERVAL)
  133. }
  134. })
  135. })()
  136. }
  137. export function getLock(...args) {
  138. _mocks.getLock(...args)
  139. }
  140. export function checkLock(key, callback) {
  141. if (callback == null) {
  142. callback = function () {}
  143. }
  144. return rclient.exists(key, function (err, exists) {
  145. if (err != null) {
  146. return callback(OError.tag(err))
  147. }
  148. exists = parseInt(exists)
  149. if (exists === 1) {
  150. return callback(err, false)
  151. } else {
  152. return callback(err, true)
  153. }
  154. })
  155. }
  156. _mocks.releaseLock = (key, lockValue, callback) => {
  157. return rclient.eval(UNLOCK_SCRIPT, 1, key, lockValue, function (err, result) {
  158. if (err != null) {
  159. return callback(OError.tag(err))
  160. }
  161. if (result != null && result !== 1) {
  162. // successful unlock should release exactly one key
  163. const error = new OError('tried to release timed out lock', {
  164. key,
  165. lockValue,
  166. redis_result: result,
  167. })
  168. return callback(error)
  169. }
  170. return callback(err, result)
  171. })
  172. }
  173. export function releaseLock(...args) {
  174. _mocks.releaseLock(...args)
  175. }
  176. export function runWithLock(key, runner, callback) {
  177. if (callback == null) {
  178. callback = function () {}
  179. }
  180. return getLock(key, function (error, lockValue) {
  181. if (error != null) {
  182. return callback(OError.tag(error))
  183. }
  184. const lock = new Lock(key, lockValue)
  185. return runner(lock.extend.bind(lock), (error1, ...args) =>
  186. lock.release(function (error2) {
  187. error = error1 || error2
  188. if (error != null) {
  189. return callback(OError.tag(error), ...Array.from(args))
  190. }
  191. return callback(null, ...Array.from(args))
  192. })
  193. )
  194. })
  195. }
  196. export function healthCheck(callback) {
  197. const action = (extendLock, releaseLock) => releaseLock()
  198. return runWithLock(
  199. `HistoryLock:HealthCheck:host=${HOST}:pid=${PID}:random=${RND}`,
  200. action,
  201. callback
  202. )
  203. }
  204. export function close(callback) {
  205. rclient.quit()
  206. return rclient.once('end', callback)
  207. }
  208. class Lock {
  209. constructor(key, value) {
  210. this.key = key
  211. this.value = value
  212. this.slowExecutionError = new OError('slow execution during lock')
  213. this.lockTakenAt = Date.now()
  214. this.timer = new metrics.Timer('lock.project')
  215. }
  216. extend(callback) {
  217. const lockLength = Date.now() - this.lockTakenAt
  218. if (lockLength < MIN_LOCK_EXTENSION_INTERVAL) {
  219. return async.setImmediate(callback)
  220. }
  221. return extendLock(this.key, this.value, error => {
  222. if (error != null) {
  223. return callback(OError.tag(error))
  224. }
  225. this.lockTakenAt = Date.now()
  226. return callback()
  227. })
  228. }
  229. release(callback) {
  230. // The lock can expire in redis but the process carry on. This setTimout call
  231. // is designed to log if this happens.
  232. const lockLength = Date.now() - this.lockTakenAt
  233. if (lockLength > LOCK_TTL * 1000) {
  234. metrics.inc('lock.project.exceeded_lock_timeout')
  235. logger.debug('exceeded lock timeout', {
  236. key: this.key,
  237. slowExecutionError: this.slowExecutionError,
  238. })
  239. }
  240. return releaseLock(this.key, this.value, error => {
  241. this.timer.done()
  242. if (error != null) {
  243. return callback(OError.tag(error))
  244. }
  245. return callback()
  246. })
  247. }
  248. }