LockManager.js 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  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(OError.tag(err))
  61. }
  62. if (gotLock === 'OK') {
  63. metrics.inc('lock.project.try.success')
  64. return callback(err, true, lockValue)
  65. } else {
  66. metrics.inc('lock.project.try.failed')
  67. return callback(err, false)
  68. }
  69. }
  70. )
  71. }
  72. export function tryLock(...args) {
  73. _mocks.tryLock(...args)
  74. }
  75. _mocks.extendLock = (key, lockValue, callback) => {
  76. if (callback == null) {
  77. callback = function () {}
  78. }
  79. return rclient.eval(
  80. EXTEND_SCRIPT,
  81. 1,
  82. key,
  83. lockValue,
  84. LOCK_TTL,
  85. function (err, result) {
  86. if (err != null) {
  87. return callback(OError.tag(err))
  88. }
  89. if (result != null && result !== 1) {
  90. // successful extension should release exactly one key
  91. metrics.inc('lock.project.extend.failed')
  92. const error = new OError('failed to extend lock', {
  93. key,
  94. lockValue,
  95. result,
  96. })
  97. return callback(error)
  98. }
  99. metrics.inc('lock.project.extend.success')
  100. return callback()
  101. }
  102. )
  103. }
  104. export function extendLock(...args) {
  105. _mocks.extendLock(...args)
  106. }
  107. _mocks.getLock = (key, callback) => {
  108. let attempt
  109. if (callback == null) {
  110. callback = function () {}
  111. }
  112. const startTime = Date.now()
  113. let attempts = 0
  114. return (attempt = function () {
  115. if (Date.now() - startTime > MAX_LOCK_WAIT_TIME) {
  116. metrics.inc('lock.project.get.failed')
  117. const e = new OError('Timeout')
  118. e.key = key
  119. return callback(e)
  120. }
  121. attempts += 1
  122. return tryLock(key, function (error, gotLock, lockValue) {
  123. if (error != null) {
  124. return callback(OError.tag(error))
  125. }
  126. if (gotLock) {
  127. metrics.gauge('lock.project.get.success.tries', attempts)
  128. return callback(null, lockValue)
  129. } else {
  130. return setTimeout(attempt, LOCK_TEST_INTERVAL)
  131. }
  132. })
  133. })()
  134. }
  135. export function getLock(...args) {
  136. _mocks.getLock(...args)
  137. }
  138. export function checkLock(key, callback) {
  139. if (callback == null) {
  140. callback = function () {}
  141. }
  142. return rclient.exists(key, function (err, exists) {
  143. if (err != null) {
  144. return callback(OError.tag(err))
  145. }
  146. exists = parseInt(exists)
  147. if (exists === 1) {
  148. return callback(err, false)
  149. } else {
  150. return callback(err, true)
  151. }
  152. })
  153. }
  154. _mocks.releaseLock = (key, lockValue, callback) => {
  155. return rclient.eval(UNLOCK_SCRIPT, 1, key, lockValue, function (err, result) {
  156. if (err != null) {
  157. return callback(OError.tag(err))
  158. }
  159. if (result != null && result !== 1) {
  160. // successful unlock should release exactly one key
  161. const error = new OError('tried to release timed out lock', {
  162. key,
  163. lockValue,
  164. redis_result: result,
  165. })
  166. return callback(error)
  167. }
  168. return callback(err, result)
  169. })
  170. }
  171. export function releaseLock(...args) {
  172. _mocks.releaseLock(...args)
  173. }
  174. export function runWithLock(key, runner, callback) {
  175. if (callback == null) {
  176. callback = function () {}
  177. }
  178. return getLock(key, function (error, lockValue) {
  179. if (error != null) {
  180. return callback(OError.tag(error))
  181. }
  182. const lock = new Lock(key, lockValue)
  183. return runner(lock.extend.bind(lock), (error1, ...args) =>
  184. lock.release(function (error2) {
  185. error = error1 || error2
  186. if (error != null) {
  187. return callback(OError.tag(error), ...Array.from(args))
  188. }
  189. return callback(null, ...Array.from(args))
  190. })
  191. )
  192. })
  193. }
  194. export function healthCheck(callback) {
  195. const action = (extendLock, releaseLock) => releaseLock()
  196. return runWithLock(
  197. `HistoryLock:HealthCheck:host=${HOST}:pid=${PID}:random=${RND}`,
  198. action,
  199. callback
  200. )
  201. }
  202. export function close(callback) {
  203. rclient.quit()
  204. return rclient.once('end', callback)
  205. }
  206. class Lock {
  207. constructor(key, value) {
  208. this.key = key
  209. this.value = value
  210. this.slowExecutionError = new OError('slow execution during lock')
  211. this.lockTakenAt = Date.now()
  212. this.timer = new metrics.Timer('lock.project')
  213. }
  214. extend(callback) {
  215. const lockLength = Date.now() - this.lockTakenAt
  216. if (lockLength < MIN_LOCK_EXTENSION_INTERVAL) {
  217. return async.setImmediate(callback)
  218. }
  219. return extendLock(this.key, this.value, error => {
  220. if (error != null) {
  221. return callback(OError.tag(error))
  222. }
  223. this.lockTakenAt = Date.now()
  224. return callback()
  225. })
  226. }
  227. release(callback) {
  228. // The lock can expire in redis but the process carry on. This setTimout call
  229. // is designed to log if this happens.
  230. const lockLength = Date.now() - this.lockTakenAt
  231. if (lockLength > LOCK_TTL * 1000) {
  232. metrics.inc('lock.project.exceeded_lock_timeout')
  233. logger.debug('exceeded lock timeout', {
  234. key: this.key,
  235. slowExecutionError: this.slowExecutionError,
  236. })
  237. }
  238. return releaseLock(this.key, this.value, error => {
  239. this.timer.done()
  240. if (error != null) {
  241. return callback(OError.tag(error))
  242. }
  243. return callback()
  244. })
  245. }
  246. }