index.js 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197
  1. 'use strict';
  2. const util = require("util");
  3. process.env.NODE_CONFIG_DIR = `${__dirname}/config`;
  4. const config = require("config");
  5. process.on('uncaughtException', err => {
  6. if (err.code === 'ECONNREFUSED' || err.code === 'UNCERTAIN_STATE') return;
  7. console.log(`UNCAUGHT EXCEPTION: ${err.stack}`);
  8. });
  9. const fancyConsole = config.get("fancyConsole");
  10. class ModuleManager {
  11. constructor() {
  12. this.modules = {};
  13. this.modulesInitialized = 0;
  14. this.totalModules = 0;
  15. this.modulesLeft = [];
  16. this.i = 0;
  17. this.lockdown = false;
  18. this.fancyConsole = fancyConsole;
  19. }
  20. addModule(moduleName) {
  21. console.log("add module", moduleName);
  22. const moduleClass = new require(`./logic/${moduleName}`);
  23. this.modules[moduleName] = new moduleClass(moduleName, this);
  24. this.totalModules++;
  25. this.modulesLeft.push(moduleName);
  26. }
  27. initialize() {
  28. if (!this.modules["logger"]) return console.error("There is no logger module");
  29. this.logger = this.modules["logger"];
  30. if (this.fancyConsole) {
  31. this.replaceConsoleWithLogger();
  32. this.logger.reservedLines = Object.keys(this.modules).length + 5;
  33. }
  34. for (let moduleName in this.modules) {
  35. let module = this.modules[moduleName];
  36. if (this.lockdown) break;
  37. module._onInitialize().then(() => {
  38. this.moduleInitialized(moduleName);
  39. });
  40. let dependenciesInitializedPromises = [];
  41. module.dependsOn.forEach(dependencyName => {
  42. let dependency = this.modules[dependencyName];
  43. dependenciesInitializedPromises.push(dependency._onInitialize());
  44. });
  45. module.lastTime = Date.now();
  46. Promise.all(dependenciesInitializedPromises).then((res, res2) => {
  47. if (this.lockdown) return;
  48. this.logger.info("MODULE_MANAGER", `${moduleName} dependencies have been completed`);
  49. module._initialize();
  50. });
  51. }
  52. }
  53. async printStatus() {
  54. try { await Promise.race([this.logger._onInitialize, this.logger._isInitialized]); } catch { return; }
  55. if (!this.fancyConsole) return;
  56. let colors = this.logger.colors;
  57. const rows = process.stdout.rows;
  58. process.stdout.cursorTo(0, rows - this.logger.reservedLines);
  59. process.stdout.clearScreenDown();
  60. process.stdout.cursorTo(0, (rows - this.logger.reservedLines) + 2);
  61. process.stdout.write(`${colors.FgYellow}Modules${colors.FgWhite}:\n`);
  62. for (let moduleName in this.modules) {
  63. let module = this.modules[moduleName];
  64. let tabsAmount = 2 - (moduleName.length / 8);
  65. let tabs = "";
  66. for(let i = 0; i < tabsAmount; i++)
  67. tabs += "\t";
  68. let timing = module.timeDifferences.map((timeDifference) => {
  69. return `${colors.FgMagenta}${timeDifference}${colors.FgCyan}ms${colors.FgWhite}`;
  70. }).join(", ");
  71. let stateColor;
  72. if (module.state === "NOT_INITIALIZED") stateColor = colors.FgWhite;
  73. if (module.state === "INITIALIZING") stateColor = colors.FgYellow;
  74. if (module.state === "INITIALIZED") stateColor = colors.FgGreen;
  75. if (module.state === "LOCKDOWN" && !module.failed) stateColor = colors.FgRed;
  76. if (module.state === "LOCKDOWN" && module.failed) stateColor = colors.FgMagenta;
  77. process.stdout.write(`${moduleName}${tabs}${stateColor}${module.state}\t${colors.FgYellow}Stage: ${colors.FgRed}${module.stage}${colors.FgWhite}. ${colors.FgYellow}Timing${colors.FgWhite}: [${timing}]${colors.FgWhite}${colors.FgWhite}. ${colors.FgYellow}Total time${colors.FgWhite}: ${colors.FgRed}${module.totalTimeInitialize}${colors.FgCyan}ms${colors.Reset}\n`);
  78. }
  79. }
  80. moduleInitialized(moduleName) {
  81. this.modulesInitialized++;
  82. this.modulesLeft.splice(this.modulesLeft.indexOf(moduleName), 1);
  83. this.logger.info("MODULE_MANAGER", `Initialized: ${this.modulesInitialized}/${this.totalModules}.`);
  84. if (this.modulesLeft.length === 0) this.allModulesInitialized();
  85. }
  86. allModulesInitialized() {
  87. this.logger.success("MODULE_MANAGER", "All modules have started!");
  88. this.modules["discord"].sendAdminAlertMessage("The backend server started successfully.", "#00AA00", "Startup", false, []);
  89. }
  90. aModuleFailed(failedModule) {
  91. this.logger.error("MODULE_MANAGER", `A module has failed, locking down. Module: ${failedModule.name}`);
  92. this.modules["discord"].sendAdminAlertMessage(`The backend server failed to start due to a failing module: ${failedModule.name}.`, "#AA0000", "Startup", false, []);
  93. this._lockdown();
  94. }
  95. replaceConsoleWithLogger() {
  96. this.oldConsole = {
  97. log: console.log,
  98. debug: console.debug,
  99. info: console.info,
  100. warn: console.warn,
  101. error: console.error
  102. };
  103. console.log = (...args) => this.logger.debug(args.map(arg => util.format(arg)));
  104. console.debug = (...args) => this.logger.debug(args.map(arg => util.format(arg)));
  105. console.info = (...args) => this.logger.debug(args.map(arg => util.format(arg)));
  106. console.warn = (...args) => this.logger.debug(args.map(arg => util.format(arg)));
  107. console.error = (...args) => this.logger.error("CONSOLE", args.map(arg => util.format(arg)));
  108. }
  109. replaceLoggerWithConsole() {
  110. console.log = this.oldConsole.log;
  111. console.debug = this.oldConsole.debug;
  112. console.info = this.oldConsole.info;
  113. console.warn = this.oldConsole.warn;
  114. console.error = this.oldConsole.error;
  115. }
  116. _lockdown() {
  117. this.lockdown = true;
  118. for (let moduleName in this.modules) {
  119. let module = this.modules[moduleName];
  120. module._lockdown();
  121. }
  122. }
  123. }
  124. const moduleManager = new ModuleManager();
  125. module.exports = moduleManager;
  126. moduleManager.addModule("cache");
  127. moduleManager.addModule("db");
  128. moduleManager.addModule("mail");
  129. moduleManager.addModule("api");
  130. moduleManager.addModule("app");
  131. moduleManager.addModule("discord");
  132. moduleManager.addModule("io");
  133. moduleManager.addModule("logger");
  134. moduleManager.addModule("notifications");
  135. moduleManager.addModule("playlists");
  136. moduleManager.addModule("punishments");
  137. moduleManager.addModule("songs");
  138. moduleManager.addModule("spotify");
  139. moduleManager.addModule("stations");
  140. moduleManager.addModule("tasks");
  141. moduleManager.addModule("utils");
  142. moduleManager.initialize();
  143. process.stdin.on("data", function (data) {
  144. if(data.toString() === "lockdown\r\n"){
  145. console.log("Locking down.");
  146. moduleManager._lockdown();
  147. }
  148. });
  149. if (fancyConsole) {
  150. const rows = process.stdout.rows;
  151. for(let i = 0; i < rows; i++) {
  152. process.stdout.write("\n");
  153. }
  154. }