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.

187 lines
4.7 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. jobIsBusy = true;
  57. // Prepare async job collector
  58. let jobs = [];
  59. let repoPath = path.resolve(ROOTPATH, appconfig.datadir.repo);
  60. // ----------------------------------------
  61. // Compile Jobs
  62. // ----------------------------------------
  63. //-> Resync with Git remote
  64. jobs.push(git.onReady.then(() => {
  65. return git.resync().then(() => {
  66. //-> Stream all documents
  67. let cacheJobs = [];
  68. fs.walk(repoPath).on('data', function (item) {
  69. if(path.extname(item.path) === '.md') {
  70. let entryPath = entries.parsePath(entries.getEntryPathFromFullPath(item.path));
  71. let cachePath = entries.getCachePath(entryPath);
  72. //-> Purge outdated cache
  73. cacheJobs.push(
  74. fs.statAsync(cachePath).then((st) => {
  75. return moment(st.mtime).isBefore(item.stats.mtime) ? 'expired' : 'active';
  76. }).catch((err) => {
  77. return (err.code !== 'EEXIST') ? err : 'new';
  78. }).then((fileStatus) => {
  79. //-> Delete expired cache file
  80. if(fileStatus === 'expired') {
  81. return fs.unlinkAsync(cachePath).return(fileStatus);
  82. }
  83. return fileStatus;
  84. }).then((fileStatus) => {
  85. //-> Update search index
  86. if(fileStatus !== 'active') {
  87. return entries.fetchIndexableVersion(entryPath).then((content) => {
  88. ws.emit('searchAdd', {
  89. auth: WSInternalKey,
  90. content
  91. });
  92. });
  93. }
  94. return true;
  95. })
  96. );
  97. }
  98. });
  99. return Promise.all(cacheJobs);
  100. });
  101. }));
  102. // ----------------------------------------
  103. // Run
  104. // ----------------------------------------
  105. Promise.all(jobs).then(() => {
  106. winston.info('[AGENT] All jobs completed successfully! Going to sleep for now...');
  107. }).catch((err) => {
  108. winston.error('[AGENT] One or more jobs have failed: ', err);
  109. }).finally(() => {
  110. jobIsBusy = false;
  111. });
  112. },
  113. start: false,
  114. timeZone: 'UTC',
  115. runOnInit: true
  116. });
  117. // ----------------------------------------
  118. // Connect to local WebSocket server
  119. // ----------------------------------------
  120. ws.on('connect', function () {
  121. job.start();
  122. winston.info('[AGENT] Background Agent started successfully! [RUNNING]');
  123. });
  124. ws.on('connect_error', function () {
  125. winston.warn('[AGENT] Unable to connect to WebSocket server! Retrying...');
  126. });
  127. ws.on('reconnect_failed', function () {
  128. winston.error('[AGENT] Failed to reconnect to WebSocket server too many times! Stopping agent...');
  129. process.exit(1);
  130. });
  131. // ----------------------------------------
  132. // Shutdown gracefully
  133. // ----------------------------------------
  134. process.on('disconnect', () => {
  135. winston.warn('[AGENT] Lost connection to main server. Exiting...');
  136. job.stop();
  137. process.exit();
  138. });
  139. process.on('exit', () => {
  140. job.stop();
  141. });