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.

189 lines
4.9 KiB

  1. // ===========================================
  2. // REQUARKS WIKI - Background Agent
  3. // 1.0.0
  4. // Licensed under AGPLv3
  5. // ===========================================
  6. global.ROOTPATH = __dirname;
  7. // ----------------------------------------
  8. // Load Winston
  9. // ----------------------------------------
  10. var _isDebug = process.env.NODE_ENV === 'development';
  11. global.winston = require('winston');
  12. winston.remove(winston.transports.Console)
  13. winston.add(winston.transports.Console, {
  14. level: (_isDebug) ? 'info' : 'warn',
  15. prettyPrint: true,
  16. colorize: true,
  17. silent: false,
  18. timestamp: true
  19. });
  20. // ----------------------------------------
  21. // Fetch internal handshake key
  22. // ----------------------------------------
  23. if(!process.argv[2] || process.argv[2].length !== 40) {
  24. winston.error('[WS] Illegal process start. Missing handshake key.');
  25. process.exit(1);
  26. }
  27. global.WSInternalKey = process.argv[2];
  28. // ----------------------------------------
  29. // Load modules
  30. // ----------------------------------------
  31. winston.info('[AGENT] Background Agent is initializing...');
  32. var appconfig = require('./models/config')('./config.yml');
  33. global.git = require('./models/git').init(appconfig);
  34. global.entries = require('./models/entries').init(appconfig);
  35. global.mark = require('./models/markdown');
  36. var _ = require('lodash');
  37. var moment = require('moment');
  38. var Promise = require('bluebird');
  39. var fs = Promise.promisifyAll(require("fs-extra"));
  40. var path = require('path');
  41. var cron = require('cron').CronJob;
  42. var wsClient = require('socket.io-client');
  43. global.ws = wsClient('http://localhost:' + appconfig.wsPort, { reconnectionAttempts: 10 });
  44. // ----------------------------------------
  45. // Start Cron
  46. // ----------------------------------------
  47. var jobIsBusy = false;
  48. var job = new cron({
  49. cronTime: '0 */5 * * * *',
  50. onTick: () => {
  51. // Make sure we don't start two concurrent jobs
  52. if(jobIsBusy) {
  53. winston.warn('[AGENT] Previous job has not completed gracefully or is still running! Skipping for now. (This is not normal, you should investigate)');
  54. return;
  55. }
  56. winston.info('[AGENT] Running all jobs...');
  57. jobIsBusy = true;
  58. // Prepare async job collector
  59. let jobs = [];
  60. let repoPath = path.resolve(ROOTPATH, appconfig.datadir.repo);
  61. // ----------------------------------------
  62. // Compile Jobs
  63. // ----------------------------------------
  64. //-> Resync with Git remote
  65. jobs.push(git.onReady.then(() => {
  66. return git.resync().then(() => {
  67. //-> Stream all documents
  68. let cacheJobs = [];
  69. let jobCbStreamDocs_resolve = null,
  70. jobCbStreamDocs = new Promise((resolve, reject) => {
  71. jobCbStreamDocs_resolve = resolve;
  72. });
  73. fs.walk(repoPath).on('data', function (item) {
  74. if(path.extname(item.path) === '.md') {
  75. let entryPath = entries.parsePath(entries.getEntryPathFromFullPath(item.path));
  76. let cachePath = entries.getCachePath(entryPath);
  77. //-> Purge outdated cache
  78. cacheJobs.push(
  79. fs.statAsync(cachePath).then((st) => {
  80. return moment(st.mtime).isBefore(item.stats.mtime) ? 'expired' : 'active';
  81. }).catch((err) => {
  82. return (err.code !== 'EEXIST') ? err : 'new';
  83. }).then((fileStatus) => {
  84. //-> Delete expired cache file
  85. if(fileStatus === 'expired') {
  86. return fs.unlinkAsync(cachePath).return(fileStatus);
  87. }
  88. return fileStatus;
  89. }).then((fileStatus) => {
  90. //-> Update cache and search index
  91. if(fileStatus !== 'active') {
  92. return entries.updateCache(entryPath);
  93. }
  94. return true;
  95. })
  96. );
  97. }
  98. }).on('end', () => {
  99. jobCbStreamDocs_resolve(Promise.all(cacheJobs));
  100. });
  101. return jobCbStreamDocs;
  102. });
  103. }));
  104. // ----------------------------------------
  105. // Run
  106. // ----------------------------------------
  107. Promise.all(jobs).then(() => {
  108. winston.info('[AGENT] All jobs completed successfully! Going to sleep for now.');
  109. }).catch((err) => {
  110. winston.error('[AGENT] One or more jobs have failed: ', err);
  111. }).finally(() => {
  112. jobIsBusy = false;
  113. });
  114. },
  115. start: false,
  116. timeZone: 'UTC',
  117. runOnInit: true
  118. });
  119. // ----------------------------------------
  120. // Connect to local WebSocket server
  121. // ----------------------------------------
  122. ws.on('connect', function () {
  123. winston.info('[AGENT] Background Agent started successfully! [RUNNING]');
  124. job.start();
  125. });
  126. ws.on('connect_error', function () {
  127. winston.warn('[AGENT] Unable to connect to WebSocket server! Retrying...');
  128. });
  129. ws.on('reconnect_failed', function () {
  130. winston.error('[AGENT] Failed to reconnect to WebSocket server too many times! Stopping agent...');
  131. process.exit(1);
  132. });
  133. // ----------------------------------------
  134. // Shutdown gracefully
  135. // ----------------------------------------
  136. process.on('disconnect', () => {
  137. winston.warn('[AGENT] Lost connection to main server. Exiting...');
  138. job.stop();
  139. process.exit();
  140. });
  141. process.on('exit', () => {
  142. job.stop();
  143. });