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.

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