You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

196 lines
5.8 KiB

  1. // ===========================================
  2. // Wiki.js - Background Agent
  3. // 1.0.0
  4. // Licensed under AGPLv3
  5. // ===========================================
  6. global.PROCNAME = 'AGENT'
  7. global.ROOTPATH = __dirname
  8. global.IS_DEBUG = process.env.NODE_ENV === 'development'
  9. let appconf = require('./libs/config')()
  10. global.appconfig = appconf.config
  11. global.appdata = appconf.data
  12. // ----------------------------------------
  13. // Load Winston
  14. // ----------------------------------------
  15. global.winston = require('./libs/logger')(IS_DEBUG)
  16. // ----------------------------------------
  17. // Load global modules
  18. // ----------------------------------------
  19. winston.info('[AGENT] Background Agent is initializing...')
  20. global.db = require('./libs/db').init()
  21. global.upl = require('./libs/uploads-agent').init()
  22. global.git = require('./libs/git').init()
  23. global.entries = require('./libs/entries').init()
  24. global.mark = require('./libs/markdown')
  25. // ----------------------------------------
  26. // Load modules
  27. // ----------------------------------------
  28. var moment = require('moment')
  29. var Promise = require('bluebird')
  30. var fs = Promise.promisifyAll(require('fs-extra'))
  31. var klaw = require('klaw')
  32. var path = require('path')
  33. var Cron = require('cron').CronJob
  34. // ----------------------------------------
  35. // Start Cron
  36. // ----------------------------------------
  37. var job
  38. var jobIsBusy = false
  39. var jobUplWatchStarted = false
  40. db.onReady.then(() => {
  41. return db.Entry.remove({})
  42. }).then(() => {
  43. job = new Cron({
  44. cronTime: '0 */5 * * * *',
  45. onTick: () => {
  46. // Make sure we don't start two concurrent jobs
  47. if (jobIsBusy) {
  48. winston.warn('[AGENT] Previous job has not completed gracefully or is still running! Skipping for now. (This is not normal, you should investigate)')
  49. return
  50. }
  51. winston.info('[AGENT] Running all jobs...')
  52. jobIsBusy = true
  53. // Prepare async job collector
  54. let jobs = []
  55. let repoPath = path.resolve(ROOTPATH, appconfig.paths.repo)
  56. let dataPath = path.resolve(ROOTPATH, appconfig.paths.data)
  57. let uploadsTempPath = path.join(dataPath, 'temp-upload')
  58. // ----------------------------------------
  59. // REGULAR JOBS
  60. // ----------------------------------------
  61. //* ****************************************
  62. // -> Sync with Git remote
  63. //* ****************************************
  64. jobs.push(git.resync().then(() => {
  65. // -> Stream all documents
  66. let cacheJobs = []
  67. let jobCbStreamDocsResolve = null
  68. let jobCbStreamDocs = new Promise((resolve, reject) => {
  69. jobCbStreamDocsResolve = resolve
  70. })
  71. klaw(repoPath).on('data', function (item) {
  72. if (path.extname(item.path) === '.md' && path.basename(item.path) !== 'README.md') {
  73. let entryPath = entries.parsePath(entries.getEntryPathFromFullPath(item.path))
  74. let cachePath = entries.getCachePath(entryPath)
  75. // -> Purge outdated cache
  76. cacheJobs.push(
  77. fs.statAsync(cachePath).then((st) => {
  78. return moment(st.mtime).isBefore(item.stats.mtime) ? 'expired' : 'active'
  79. }).catch((err) => {
  80. return (err.code !== 'EEXIST') ? err : 'new'
  81. }).then((fileStatus) => {
  82. // -> Delete expired cache file
  83. if (fileStatus === 'expired') {
  84. return fs.unlinkAsync(cachePath).return(fileStatus)
  85. }
  86. return fileStatus
  87. }).then((fileStatus) => {
  88. // -> Update cache and search index
  89. if (fileStatus !== 'active') {
  90. return entries.updateCache(entryPath).then(entry => {
  91. process.send({
  92. action: 'searchAdd',
  93. content: entry
  94. })
  95. return true
  96. })
  97. }
  98. return true
  99. })
  100. )
  101. }
  102. }).on('end', () => {
  103. jobCbStreamDocsResolve(Promise.all(cacheJobs))
  104. })
  105. return jobCbStreamDocs
  106. }))
  107. //* ****************************************
  108. // -> Clear failed temporary upload files
  109. //* ****************************************
  110. jobs.push(
  111. fs.readdirAsync(uploadsTempPath).then((ls) => {
  112. let fifteenAgo = moment().subtract(15, 'minutes')
  113. return Promise.map(ls, (f) => {
  114. return fs.statAsync(path.join(uploadsTempPath, f)).then((s) => { return { filename: f, stat: s } })
  115. }).filter((s) => { return s.stat.isFile() }).then((arrFiles) => {
  116. return Promise.map(arrFiles, (f) => {
  117. if (moment(f.stat.ctime).isBefore(fifteenAgo, 'minute')) {
  118. return fs.unlinkAsync(path.join(uploadsTempPath, f.filename))
  119. } else {
  120. return true
  121. }
  122. })
  123. })
  124. })
  125. )
  126. // ----------------------------------------
  127. // Run
  128. // ----------------------------------------
  129. Promise.all(jobs).then(() => {
  130. winston.info('[AGENT] All jobs completed successfully! Going to sleep for now.')
  131. if (!jobUplWatchStarted) {
  132. jobUplWatchStarted = true
  133. upl.initialScan().then(() => {
  134. job.start()
  135. })
  136. }
  137. return true
  138. }).catch((err) => {
  139. winston.error('[AGENT] One or more jobs have failed: ', err)
  140. }).finally(() => {
  141. jobIsBusy = false
  142. })
  143. },
  144. start: false,
  145. timeZone: 'UTC',
  146. runOnInit: true
  147. })
  148. })
  149. // ----------------------------------------
  150. // Shutdown gracefully
  151. // ----------------------------------------
  152. process.on('disconnect', () => {
  153. winston.warn('[AGENT] Lost connection to main server. Exiting...')
  154. job.stop()
  155. process.exit()
  156. })
  157. process.on('exit', () => {
  158. job.stop()
  159. })