recover_zip_from_backup.mjs 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  1. // @ts-check
  2. import { loadGlobalBlobs } from '../lib/blob_store/index.js'
  3. import commandLineArgs from 'command-line-args'
  4. import assert from '../lib/assert.js'
  5. import fs from 'node:fs'
  6. import { setTimeout } from 'node:timers/promises'
  7. import {
  8. archiveLatestChunk,
  9. archiveRawProject,
  10. BackupPersistorError,
  11. } from '../lib/backupArchiver.mjs'
  12. import knex from '../lib/knex.js'
  13. import { client } from '../lib/mongodb.js'
  14. import archiver from 'archiver'
  15. import Events from 'node:events'
  16. import { Chunk } from 'overleaf-editor-core'
  17. import _ from 'lodash'
  18. // Silence warning.
  19. Events.setMaxListeners(20)
  20. const SUPPORTED_MODES = ['raw', 'latest']
  21. // Pads the mode name to a fixed length for better alignment in output.
  22. const padModeName = _.partialRight(
  23. _.padEnd,
  24. Math.max(...SUPPORTED_MODES.map(mode => mode.length))
  25. )
  26. const SUPPORTED_MODES_HELP = {
  27. raw: 'Retrieve all chunk and blob files from the project backup.',
  28. latest: 'Retrieves the last backed up state of the project.',
  29. }
  30. // outputFile needs to be available in the shutdown function (which may be called before it's declared)
  31. // eslint-disable-next-line prefer-const
  32. let outputFile
  33. /**
  34. * Gracefully shutdown the process
  35. * @param {number} code
  36. */
  37. async function shutdown(code = 0) {
  38. if (outputFile) {
  39. outputFile.close()
  40. }
  41. await knex.destroy()
  42. await client.close()
  43. await setTimeout(1000)
  44. process.exit(code)
  45. }
  46. function usage() {
  47. console.log(
  48. 'Usage: node recover_zip_from_backup.mjs --historyId=<historyId> --output=<output> [--mode=<mode>] [--verbose] [--useBackupGlobalBlobs]'
  49. )
  50. console.log(
  51. '--useBackupGlobalBlobs can be used if the global blobs have not been restored from the backup yet.'
  52. )
  53. console.log('Supported modes: ' + SUPPORTED_MODES.join(', '))
  54. SUPPORTED_MODES.forEach(mode => {
  55. console.log(
  56. ` --mode=${padModeName(mode)} - ${SUPPORTED_MODES_HELP[mode] || ''}`
  57. )
  58. })
  59. }
  60. /**
  61. * @typedef {import('archiver').ZipArchive} ZipArchive
  62. */
  63. /**
  64. * @typedef {import('archiver').ProgressData} ProgressData
  65. */
  66. /**
  67. * @typedef {import('archiver').EntryData} EntryData
  68. */
  69. /**
  70. * @typedef {Object} ArchiverError
  71. * @property {string} message
  72. * @property {string} code
  73. * @property {Object} data
  74. */
  75. let historyId, help, mode, output, useBackupGlobalBlobs, verbose
  76. try {
  77. ;({ historyId, help, mode, output, useBackupGlobalBlobs, verbose } =
  78. commandLineArgs([
  79. { name: 'historyId', type: String },
  80. { name: 'output', type: String },
  81. { name: 'mode', type: String, defaultValue: 'raw' },
  82. { name: 'verbose', type: Boolean, defaultValue: false },
  83. { name: 'useBackupGlobalBlobs', type: Boolean, defaultValue: false },
  84. { name: 'help', type: Boolean },
  85. ]))
  86. } catch (err) {
  87. console.error(err instanceof Error ? err.message : err)
  88. help = true
  89. }
  90. if (help) {
  91. usage()
  92. await shutdown(0)
  93. }
  94. if (!historyId) {
  95. console.error('missing --historyId')
  96. usage()
  97. await shutdown(1)
  98. }
  99. if (!output) {
  100. console.error('missing --output')
  101. usage()
  102. await shutdown(1)
  103. }
  104. try {
  105. assert.projectId(historyId)
  106. } catch (error) {
  107. console.error('Invalid history ID')
  108. await shutdown(1)
  109. }
  110. if (!SUPPORTED_MODES.includes(mode)) {
  111. console.error(
  112. 'Invalid mode; supported modes are: ' + SUPPORTED_MODES.join(', ')
  113. )
  114. await shutdown(1)
  115. }
  116. await loadGlobalBlobs()
  117. outputFile = fs.createWriteStream(output)
  118. const archive = archiver.create('zip', {})
  119. archive.on('close', function () {
  120. console.log(archive.pointer() + ' total bytes')
  121. console.log(`Wrote ${output}`)
  122. shutdown().catch(e => console.error('Error shutting down', e))
  123. })
  124. archive.on(
  125. 'error',
  126. /**
  127. *
  128. * @param {ArchiverError} e
  129. */
  130. function (e) {
  131. console.error(`Error writing archive: ${e.message}`)
  132. }
  133. )
  134. archive.on('end', function () {
  135. console.log(`Wrote ${archive.pointer()} total bytes to ${output}`)
  136. shutdown().catch(e => console.error('Error shutting down', e))
  137. })
  138. archive.on(
  139. 'progress',
  140. /**
  141. *
  142. * @param {ProgressData} progress
  143. */
  144. function (progress) {
  145. if (verbose) {
  146. console.log(
  147. `${progress.entries.processed} processed out of ${progress.entries.total}`
  148. )
  149. }
  150. }
  151. )
  152. archive.on(
  153. 'entry',
  154. /**
  155. *
  156. * @param {EntryData} entry
  157. */
  158. function (entry) {
  159. if (verbose) {
  160. console.log(`${entry.name} added`)
  161. }
  162. }
  163. )
  164. archive.on(
  165. 'warning',
  166. /**
  167. *
  168. * @param {ArchiverError} warning
  169. */
  170. function (warning) {
  171. console.warn(`Warning encountered when writing archive: ${warning.message}`)
  172. }
  173. )
  174. try {
  175. switch (mode) {
  176. case 'latest':
  177. await archiveLatestChunk(archive, historyId, useBackupGlobalBlobs)
  178. break
  179. case 'raw':
  180. default:
  181. await archiveRawProject(archive, historyId, useBackupGlobalBlobs)
  182. break
  183. }
  184. archive.pipe(outputFile)
  185. } catch (error) {
  186. if (error instanceof BackupPersistorError) {
  187. console.error(error.message)
  188. }
  189. if (error instanceof Chunk.NotPersistedError) {
  190. console.error('Chunk not found. Project may not have been fully backed up.')
  191. }
  192. if (verbose) {
  193. console.error(error)
  194. } else {
  195. console.error('Error encountered when writing archive')
  196. }
  197. } finally {
  198. await Promise.race([
  199. await archive.finalize(),
  200. setTimeout(10000).then(() => {
  201. console.error('Archive did not finalize in time')
  202. return shutdown(1)
  203. }),
  204. ])
  205. }