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.

90 lines
2.3 KiB

  1. // ===========================================
  2. // REQUARKS WIKI - Background Agent
  3. // 1.0.0
  4. // Licensed under AGPLv3
  5. // ===========================================
  6. global.ROOTPATH = __dirname;
  7. // ----------------------------------------
  8. // Load modules
  9. // ----------------------------------------
  10. global.winston = require('winston');
  11. winston.info('[AGENT] Requarks Wiki BgAgent is initializing...');
  12. var appconfig = require('./models/config')('./config.yml');
  13. global.git = require('./models/git').init(appconfig, true);
  14. global.entries = require('./models/entries').init(appconfig);
  15. global.mark = require('./models/markdown');
  16. var _ = require('lodash');
  17. var moment = require('moment');
  18. var Promise = require('bluebird');
  19. var cron = require('cron').CronJob;
  20. // ----------------------------------------
  21. // Start Cron
  22. // ----------------------------------------
  23. var jobIsBusy = false;
  24. var job = new cron({
  25. cronTime: '0 */5 * * * *',
  26. onTick: () => {
  27. // Make sure we don't start two concurrent jobs
  28. if(jobIsBusy) {
  29. winston.warn('[AGENT] Previous job has not completed gracefully or is still running! Skipping for now. (This is not normal, you should investigate)');
  30. return;
  31. }
  32. jobIsBusy = true;
  33. // Prepare async job collector
  34. let jobs = [];
  35. // ----------------------------------------
  36. // Compile Jobs
  37. // ----------------------------------------
  38. //-> Resync with Git remote
  39. jobs.push(git.resync().then(() => {
  40. //-> Purge outdated cache
  41. return entries.purgeStaleCache();
  42. }));
  43. // ----------------------------------------
  44. // Run
  45. // ----------------------------------------
  46. Promise.all(jobs).then(() => {
  47. winston.info('[AGENT] All jobs completed successfully! Going to sleep for now... [' + moment().toISOString() + ']');
  48. }).catch((err) => {
  49. winston.error('[AGENT] One or more jobs have failed [' + moment().toISOString() + ']: ', err);
  50. }).finally(() => {
  51. jobIsBusy = false;
  52. });
  53. },
  54. start: true,
  55. timeZone: 'UTC'
  56. });
  57. // ----------------------------------------
  58. // Shutdown gracefully
  59. // ----------------------------------------
  60. process.on('disconnect', () => {
  61. winston.warn('[AGENT] Lost connection to main server. Exiting... [' + moment().toISOString() + ']');
  62. job.stop();
  63. process.exit();
  64. });
  65. process.on('exit', () => {
  66. job.stop();
  67. });