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.

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