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.

202 lines
5.2 KiB

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