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.

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