backup_worker.mjs 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150
  1. import Queue from 'bull'
  2. import logger from '@overleaf/logger'
  3. import config from 'config'
  4. import metrics from '@overleaf/metrics'
  5. import {
  6. backupProject,
  7. initializeProjects,
  8. configureBackup,
  9. } from './backup.mjs'
  10. const JOB_CONCURRENCY = parseInt(process.env.JOB_CONCURRENCY, 10) || 15
  11. const UPLOAD_CONCURRENCY = parseInt(process.env.UPLOAD_CONCURRENCY, 10) || 50
  12. const WARN_THRESHOLD = 2 * 60 * 60 * 1000 // warn if projects are older than this
  13. const redisOptions = config.get('redis.queue')
  14. const JOB_TIME_BUCKETS = [10, 100, 500, 1000, 5000, 10000, 30000, 60000] // milliseconds
  15. const LAG_TIME_BUCKETS_HRS = [
  16. 0.5, 0.6, 0.7, 0.8, 0.9, 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.75, 2, 3, 4, 5, 6,
  17. ] // hours
  18. // Configure backup settings to match worker concurrency
  19. configureBackup({ concurrency: UPLOAD_CONCURRENCY, useSecondary: true })
  20. // Create a Bull queue named 'backup'
  21. const backupQueue = new Queue('backup', {
  22. redis: redisOptions,
  23. settings: {
  24. lockDuration: 15 * 60 * 1000, // 15 minutes
  25. lockRenewTime: 60 * 1000, // 1 minute
  26. maxStalledCount: 0, // mark stalled jobs as failed
  27. },
  28. })
  29. // Log queue events
  30. backupQueue.on('active', job => {
  31. logger.debug({ job }, 'job is now active')
  32. })
  33. backupQueue.on('completed', (job, result) => {
  34. metrics.inc('backup_worker_job', 1, { status: 'completed' })
  35. logger.debug({ job, result }, 'job completed')
  36. })
  37. backupQueue.on('failed', (job, err) => {
  38. metrics.inc('backup_worker_job', 1, { status: 'failed' })
  39. logger.error({ job, err }, 'job failed')
  40. })
  41. backupQueue.on('waiting', jobId => {
  42. logger.debug({ jobId }, 'job is waiting')
  43. })
  44. backupQueue.on('error', error => {
  45. logger.error({ error }, 'queue error')
  46. })
  47. backupQueue.on('stalled', job => {
  48. logger.error({ job }, 'job has stalled')
  49. })
  50. backupQueue.on('lock-extension-failed', (job, err) => {
  51. logger.error({ job, err }, 'lock extension failed')
  52. })
  53. backupQueue.on('paused', () => {
  54. logger.info('queue paused')
  55. })
  56. backupQueue.on('resumed', () => {
  57. logger.info('queue resumed')
  58. })
  59. // Process jobs
  60. backupQueue.process(JOB_CONCURRENCY, async job => {
  61. const { projectId, startDate, endDate } = job.data
  62. if (projectId) {
  63. return await runBackup(projectId, job.data, job)
  64. } else if (startDate && endDate) {
  65. return await runInit(startDate, endDate)
  66. } else {
  67. throw new Error('invalid job data')
  68. }
  69. })
  70. async function runBackup(projectId, data, job) {
  71. const { pendingChangeAt } = data
  72. // record the time it takes to run the backup job
  73. const timer = new metrics.Timer(
  74. 'backup_worker_job_duration',
  75. 1,
  76. {},
  77. JOB_TIME_BUCKETS
  78. )
  79. const pendingAge = Date.now() - pendingChangeAt
  80. if (pendingAge > WARN_THRESHOLD) {
  81. logger.warn(
  82. { projectId, pendingAge, job },
  83. 'project has been pending for a long time'
  84. )
  85. }
  86. try {
  87. logger.debug({ projectId }, 'processing backup for project')
  88. await backupProject(projectId, {})
  89. metrics.inc('backup_worker_project', 1, {
  90. status: 'success',
  91. })
  92. timer.done()
  93. // record the replication lag (time from change to backup)
  94. if (pendingChangeAt) {
  95. metrics.histogram(
  96. 'backup_worker_replication_lag_in_hours',
  97. (Date.now() - pendingChangeAt) / (3600 * 1000),
  98. LAG_TIME_BUCKETS_HRS
  99. )
  100. }
  101. return `backup completed ${projectId}`
  102. } catch (err) {
  103. if (err.message === 'Project deleted') {
  104. metrics.inc('backup_worker_project', 1, { status: 'deleted' })
  105. logger.warn({ projectId, err }, 'skipping backup of deleted project')
  106. } else {
  107. metrics.inc('backup_worker_project', 1, { status: 'failed' })
  108. logger.error({ projectId, err }, 'backup failed')
  109. throw err // Re-throw to mark job as failed
  110. }
  111. }
  112. }
  113. async function runInit(startDate, endDate) {
  114. try {
  115. logger.info({ startDate, endDate }, 'initializing projects')
  116. await initializeProjects({ 'start-date': startDate, 'end-date': endDate })
  117. return `initialization completed ${startDate} - ${endDate}`
  118. } catch (err) {
  119. logger.error({ startDate, endDate, err }, 'initialization failed')
  120. throw err
  121. }
  122. }
  123. export async function drainQueue() {
  124. logger.info({ queue: backupQueue.name }, 'pausing queue')
  125. await backupQueue.pause(true) // pause this worker and wait for jobs to finish
  126. logger.info({ queue: backupQueue.name }, 'closing queue')
  127. await backupQueue.close()
  128. }
  129. export async function healthCheck() {
  130. const count = await backupQueue.count()
  131. metrics.gauge('backup_worker_queue_length', count)
  132. }