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.

210 lines
5.5 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. let uploadsPath = path.join(repoPath, 'uploads');
  62. // ----------------------------------------
  63. // Compile Jobs
  64. // ----------------------------------------
  65. //*****************************************
  66. //-> Resync with Git remote
  67. //*****************************************
  68. jobs.push(git.onReady.then(() => {
  69. return git.resync().then(() => {
  70. //-> Stream all documents
  71. let cacheJobs = [];
  72. let jobCbStreamDocs_resolve = null,
  73. jobCbStreamDocs = new Promise((resolve, reject) => {
  74. jobCbStreamDocs_resolve = resolve;
  75. });
  76. fs.walk(repoPath).on('data', function (item) {
  77. if(path.extname(item.path) === '.md') {
  78. let entryPath = entries.parsePath(entries.getEntryPathFromFullPath(item.path));
  79. let cachePath = entries.getCachePath(entryPath);
  80. //-> Purge outdated cache
  81. cacheJobs.push(
  82. fs.statAsync(cachePath).then((st) => {
  83. return moment(st.mtime).isBefore(item.stats.mtime) ? 'expired' : 'active';
  84. }).catch((err) => {
  85. return (err.code !== 'EEXIST') ? err : 'new';
  86. }).then((fileStatus) => {
  87. //-> Delete expired cache file
  88. if(fileStatus === 'expired') {
  89. return fs.unlinkAsync(cachePath).return(fileStatus);
  90. }
  91. return fileStatus;
  92. }).then((fileStatus) => {
  93. //-> Update cache and search index
  94. if(fileStatus !== 'active') {
  95. return entries.updateCache(entryPath);
  96. }
  97. return true;
  98. })
  99. );
  100. }
  101. }).on('end', () => {
  102. jobCbStreamDocs_resolve(Promise.all(cacheJobs));
  103. });
  104. return jobCbStreamDocs;
  105. });
  106. }));
  107. //*****************************************
  108. //-> Refresh uploads data
  109. //*****************************************
  110. jobs.push(fs.readdirAsync(uploadsPath).then((ls) => {
  111. return Promise.map(ls, (f) => {
  112. return fs.statAsync(path.join(uploadsPath, f)).then((s) => { return { filename: f, stat: s }; });
  113. }).filter((s) => { return s.stat.isDirectory(); }).then((arrStats) => {
  114. ws.emit('uploadsSetFolders', {
  115. auth: WSInternalKey,
  116. content: _.map(arrStats, 'filename')
  117. });
  118. return true;
  119. });
  120. }));
  121. // ----------------------------------------
  122. // Run
  123. // ----------------------------------------
  124. Promise.all(jobs).then(() => {
  125. winston.info('[AGENT] All jobs completed successfully! Going to sleep for now.');
  126. }).catch((err) => {
  127. winston.error('[AGENT] One or more jobs have failed: ', err);
  128. }).finally(() => {
  129. jobIsBusy = false;
  130. });
  131. },
  132. start: false,
  133. timeZone: 'UTC',
  134. runOnInit: true
  135. });
  136. // ----------------------------------------
  137. // Connect to local WebSocket server
  138. // ----------------------------------------
  139. ws.on('connect', function () {
  140. winston.info('[AGENT] Background Agent started successfully! [RUNNING]');
  141. job.start();
  142. });
  143. ws.on('connect_error', function () {
  144. winston.warn('[AGENT] Unable to connect to WebSocket server! Retrying...');
  145. });
  146. ws.on('reconnect_failed', function () {
  147. winston.error('[AGENT] Failed to reconnect to WebSocket server too many times! Stopping agent...');
  148. process.exit(1);
  149. });
  150. // ----------------------------------------
  151. // Shutdown gracefully
  152. // ----------------------------------------
  153. process.on('disconnect', () => {
  154. winston.warn('[AGENT] Lost connection to main server. Exiting...');
  155. job.stop();
  156. process.exit();
  157. });
  158. process.on('exit', () => {
  159. job.stop();
  160. });