agent.js 6.0 KB

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