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.

191 lines
5.6 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)
  93. }
  94. return true
  95. })
  96. )
  97. }
  98. }).on('end', () => {
  99. jobCbStreamDocsResolve(Promise.all(cacheJobs))
  100. })
  101. return jobCbStreamDocs
  102. })
  103. }))
  104. //* ****************************************
  105. // -> Clear failed temporary upload files
  106. //* ****************************************
  107. jobs.push(
  108. fs.readdirAsync(uploadsTempPath).then((ls) => {
  109. let fifteenAgo = moment().subtract(15, 'minutes')
  110. return Promise.map(ls, (f) => {
  111. return fs.statAsync(path.join(uploadsTempPath, f)).then((s) => { return { filename: f, stat: s } })
  112. }).filter((s) => { return s.stat.isFile() }).then((arrFiles) => {
  113. return Promise.map(arrFiles, (f) => {
  114. if (moment(f.stat.ctime).isBefore(fifteenAgo, 'minute')) {
  115. return fs.unlinkAsync(path.join(uploadsTempPath, f.filename))
  116. } else {
  117. return true
  118. }
  119. })
  120. })
  121. })
  122. )
  123. // ----------------------------------------
  124. // Run
  125. // ----------------------------------------
  126. Promise.all(jobs).then(() => {
  127. winston.info('[AGENT] All jobs completed successfully! Going to sleep for now.')
  128. if (!jobUplWatchStarted) {
  129. jobUplWatchStarted = true
  130. upl.initialScan().then(() => {
  131. job.start()
  132. })
  133. }
  134. return true
  135. }).catch((err) => {
  136. winston.error('[AGENT] One or more jobs have failed: ', err)
  137. }).finally(() => {
  138. jobIsBusy = false
  139. })
  140. },
  141. start: false,
  142. timeZone: 'UTC',
  143. runOnInit: true
  144. })
  145. // ----------------------------------------
  146. // Shutdown gracefully
  147. // ----------------------------------------
  148. process.on('disconnect', () => {
  149. winston.warn('[AGENT] Lost connection to main server. Exiting...')
  150. job.stop()
  151. process.exit()
  152. })
  153. process.on('exit', () => {
  154. job.stop()
  155. })