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.

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