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.

201 lines
5.1 KiB

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