index.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524
  1. import "./loadEnvVariables.js";
  2. import util from "util";
  3. import config from "config";
  4. const REQUIRED_CONFIG_VERSION = 1;
  5. // eslint-disable-next-line
  6. Array.prototype.remove = function (item) {
  7. this.splice(this.indexOf(item), 1);
  8. };
  9. process.on("uncaughtException", err => {
  10. if (err.code === "ECONNREFUSED" || err.code === "UNCERTAIN_STATE") return;
  11. console.log(`UNCAUGHT EXCEPTION: ${err.stack}`);
  12. });
  13. const blacklistedConsoleLogs = [];
  14. const oldConsole = {};
  15. oldConsole.log = console.log;
  16. console.log = (...args) => {
  17. const string = util.format.apply(null, args);
  18. let blacklisted = false;
  19. blacklistedConsoleLogs.forEach(blacklistedConsoleLog => {
  20. if (string.indexOf(blacklistedConsoleLog) !== -1) blacklisted = true;
  21. });
  22. if (!blacklisted) oldConsole.log.apply(null, args);
  23. };
  24. if (!config.has("configVersion") || config.get("configVersion") !== REQUIRED_CONFIG_VERSION) {
  25. console.log("CONFIG VERSION IS WRONG. PLEASE UPDATE YOUR CONFIG WITH THE HELP OF THE TEMPLATE FILE AND THE README FILE.");
  26. process.exit();
  27. }
  28. const fancyConsole = config.get("fancyConsole");
  29. if (config.debug && config.debug.traceUnhandledPromises === true) {
  30. console.log("Enabled trace-unhandled/register");
  31. import("trace-unhandled/register");
  32. }
  33. // class ModuleManager {
  34. // constructor() {
  35. // this.modules = {};
  36. // this.modulesInitialized = 0;
  37. // this.totalModules = 0;
  38. // this.modulesLeft = [];
  39. // this.i = 0;
  40. // this.lockdown = false;
  41. // this.fancyConsole = fancyConsole;
  42. // }
  43. // addModule(moduleName) {
  44. // console.log("add module", moduleName);
  45. // const moduleClass = new require(`./logic/${moduleName}`);
  46. // this.modules[moduleName] = new moduleClass(moduleName, this);
  47. // this.totalModules++;
  48. // this.modulesLeft.push(moduleName);
  49. // }
  50. // initialize() {
  51. // if (!this.modules["logger"]) return console.error("There is no logger module");
  52. // this.logger = this.modules["logger"];
  53. // if (this.fancyConsole) {
  54. // this.replaceConsoleWithLogger();
  55. // this.logger.reservedLines = Object.keys(this.modules).length + 5;
  56. // }
  57. // for (let moduleName in this.modules) {
  58. // let module = this.modules[moduleName];
  59. // if (this.lockdown) break;
  60. // module._onInitialize().then(() => {
  61. // this.moduleInitialized(moduleName);
  62. // });
  63. // let dependenciesInitializedPromises = [];
  64. // module.dependsOn.forEach(dependencyName => {
  65. // let dependency = this.modules[dependencyName];
  66. // dependenciesInitializedPromises.push(dependency._onInitialize());
  67. // });
  68. // module.lastTime = Date.now();
  69. // Promise.all(dependenciesInitializedPromises).then((res, res2) => {
  70. // if (this.lockdown) return;
  71. // this.logger.info("MODULE_MANAGER", `${moduleName} dependencies have been completed`);
  72. // module._initialize();
  73. // });
  74. // }
  75. // }
  76. // async printStatus() {
  77. // try { await Promise.race([this.logger._onInitialize(), this.logger._isInitialized()]); } catch { return; }
  78. // if (!this.fancyConsole) return;
  79. // let colors = this.logger.colors;
  80. // const rows = process.stdout.rows;
  81. // process.stdout.cursorTo(0, rows - this.logger.reservedLines);
  82. // process.stdout.clearScreenDown();
  83. // process.stdout.cursorTo(0, (rows - this.logger.reservedLines) + 2);
  84. // process.stdout.write(`${colors.FgYellow}Modules${colors.FgWhite}:\n`);
  85. // for (let moduleName in this.modules) {
  86. // let module = this.modules[moduleName];
  87. // let tabsAmount = Math.max(0, Math.ceil(2 - (moduleName.length / 8)));
  88. // let tabs = Array(tabsAmount).fill(`\t`).join("");
  89. // let timing = module.timeDifferences.map((timeDifference) => {
  90. // return `${colors.FgMagenta}${timeDifference}${colors.FgCyan}ms${colors.FgWhite}`;
  91. // }).join(", ");
  92. // let stateColor;
  93. // if (module.state === "NOT_INITIALIZED") stateColor = colors.FgWhite;
  94. // else if (module.state === "INITIALIZED") stateColor = colors.FgGreen;
  95. // else if (module.state === "LOCKDOWN" && !module.failed) stateColor = colors.FgRed;
  96. // else if (module.state === "LOCKDOWN" && module.failed) stateColor = colors.FgMagenta;
  97. // else stateColor = colors.FgYellow;
  98. // 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`);
  99. // }
  100. // }
  101. // moduleInitialized(moduleName) {
  102. // this.modulesInitialized++;
  103. // this.modulesLeft.splice(this.modulesLeft.indexOf(moduleName), 1);
  104. // this.logger.info("MODULE_MANAGER", `Initialized: ${this.modulesInitialized}/${this.totalModules}.`);
  105. // if (this.modulesLeft.length === 0) this.allModulesInitialized();
  106. // }
  107. // allModulesInitialized() {
  108. // this.logger.success("MODULE_MANAGER", "All modules have started!");
  109. // }
  110. // aModuleFailed(failedModule) {
  111. // this.logger.error("MODULE_MANAGER", `A module has failed, locking down. Module: ${failedModule.name}`);
  112. // this._lockdown();
  113. // }
  114. // replaceConsoleWithLogger() {
  115. // this.oldConsole = {
  116. // log: console.log,
  117. // debug: console.debug,
  118. // info: console.info,
  119. // warn: console.warn,
  120. // error: console.error
  121. // };
  122. // console.log = (...args) => this.logger.debug(args.map(arg => util.format(arg)));
  123. // console.debug = (...args) => this.logger.debug(args.map(arg => util.format(arg)));
  124. // console.info = (...args) => this.logger.debug(args.map(arg => util.format(arg)));
  125. // console.warn = (...args) => this.logger.debug(args.map(arg => util.format(arg)));
  126. // console.error = (...args) => this.logger.error("CONSOLE", args.map(arg => util.format(arg)));
  127. // }
  128. // replaceLoggerWithConsole() {
  129. // console.log = this.oldConsole.log;
  130. // console.debug = this.oldConsole.debug;
  131. // console.info = this.oldConsole.info;
  132. // console.warn = this.oldConsole.warn;
  133. // console.error = this.oldConsole.error;
  134. // }
  135. // _lockdown() {
  136. // this.lockdown = true;
  137. // for (let moduleName in this.modules) {
  138. // let module = this.modules[moduleName];
  139. // if (module.lockdownImmune) continue;
  140. // module._lockdown();
  141. // }
  142. // }
  143. // }
  144. // const moduleManager = new ModuleManager();
  145. // module.exports = moduleManager;
  146. // moduleManager.addModule("cache");
  147. // moduleManager.addModule("db");
  148. // moduleManager.addModule("mail");
  149. // moduleManager.addModule("api");
  150. // moduleManager.addModule("app");
  151. // moduleManager.addModule("io");
  152. // moduleManager.addModule("logger");
  153. // moduleManager.addModule("notifications");
  154. // moduleManager.addModule("activities");
  155. // moduleManager.addModule("playlists");
  156. // moduleManager.addModule("punishments");
  157. // moduleManager.addModule("songs");
  158. // moduleManager.addModule("stations");
  159. // moduleManager.addModule("tasks");
  160. // moduleManager.addModule("utils");
  161. // moduleManager.initialize();
  162. // process.stdin.on("data", function (data) {
  163. // if(data.toString() === "lockdown\r\n"){
  164. // console.log("Locking down.");
  165. // moduleManager._lockdown();
  166. // }
  167. // });
  168. // if (fancyConsole) {
  169. // const rows = process.stdout.rows;
  170. // for(let i = 0; i < rows; i++) {
  171. // process.stdout.write("\n");
  172. // }
  173. // }
  174. class ModuleManager {
  175. // eslint-disable-next-line require-jsdoc
  176. constructor() {
  177. this.modules = {};
  178. this.modulesNotInitialized = [];
  179. this.i = 0;
  180. this.lockdown = false;
  181. this.fancyConsole = fancyConsole;
  182. this.debugLogs = {
  183. stationIssue: []
  184. };
  185. this.debugJobs = {
  186. all: [],
  187. completed: []
  188. };
  189. this.name = "MODULE_MANAGER";
  190. }
  191. /**
  192. * Adds a new module to the backend server/module manager
  193. *
  194. * @param {string} moduleName - the name of the module (also needs to be the same as the filename of a module located in the logic folder or "logic/moduleName/index.js")
  195. */
  196. async addModule(moduleName) {
  197. this.log("INFO", "Adding module", moduleName);
  198. // import(`./logic/${moduleName}`).then(Module => {
  199. // // eslint-disable-next-line new-cap
  200. // const instantiatedModule = new Module.default();
  201. // this.modules[moduleName] = instantiatedModule;
  202. // this.modulesNotInitialized.push(instantiatedModule);
  203. // if (moduleName === "cache") console.log(56, this.modules);
  204. // });
  205. this.modules[moduleName] = import(`./logic/${moduleName}`);
  206. }
  207. /**
  208. * Initialises a new module to the backend server/module manager
  209. *
  210. */
  211. async initialize() {
  212. // if (!this.modules["logger"]) return console.error("There is no logger module");
  213. // this.logger = this.modules["logger"];
  214. // if (this.fancyConsole) {
  215. // this.replaceConsoleWithLogger();
  216. this.reservedLines = Object.keys(this.modules).length + 5;
  217. // }
  218. await Promise.all(Object.values(this.modules)).then(modules => {
  219. for (let module = 0; module < modules.length; module += 1) {
  220. this.modules[modules[module].default.name] = modules[module].default;
  221. this.modulesNotInitialized.push(modules[module].default);
  222. }
  223. }); // ensures all modules are imported, then converts promise to the default export of the import
  224. Object.keys(this.modules).every(moduleKey => {
  225. const module = this.modules[moduleKey];
  226. module.setModuleManager(this);
  227. if (this.lockdown) return false;
  228. module._initialize();
  229. // let dependenciesInitializedPromises = [];
  230. // module.dependsOn.forEach(dependencyName => {
  231. // let dependency = this.modules[dependencyName];
  232. // dependenciesInitializedPromises.push(dependency._onInitialize());
  233. // });
  234. // module.lastTime = Date.now();
  235. // Promise.all(dependenciesInitializedPromises).then((res, res2) => {
  236. // if (this.lockdown) return;
  237. // this.logger.info("MODULE_MANAGER", `${moduleName} dependencies have been completed`);
  238. // module._initialize();
  239. // });
  240. return true;
  241. });
  242. }
  243. /**
  244. * Called when a module is initialised
  245. *
  246. * @param {object} module - the module object/class
  247. */
  248. onInitialize(module) {
  249. if (this.modulesNotInitialized.indexOf(module) !== -1) {
  250. this.modulesNotInitialized.splice(this.modulesNotInitialized.indexOf(module), 1);
  251. this.log(
  252. "INFO",
  253. `Initialized: ${Object.keys(this.modules).length - this.modulesNotInitialized.length}/${
  254. Object.keys(this.modules).length
  255. }.`
  256. );
  257. if (this.modulesNotInitialized.length === 0) this.onAllModulesInitialized();
  258. }
  259. }
  260. /**
  261. * Called when a module fails to initialise
  262. *
  263. * @param {object} module - the module object/class
  264. */
  265. onFail(module) {
  266. if (this.modulesNotInitialized.indexOf(module) !== -1) {
  267. this.log("ERROR", "A module failed to initialize!");
  268. }
  269. }
  270. /**
  271. * Called when every module has initialised
  272. *
  273. */
  274. onAllModulesInitialized() {
  275. this.log("INFO", "All modules initialized!");
  276. }
  277. /**
  278. * Creates a new log message
  279. *
  280. * @param {...any} args - anything to be included in the log message, the first argument is the type of log
  281. */
  282. log(...args) {
  283. const _arguments = Array.from(args);
  284. const type = _arguments[0];
  285. _arguments.splice(0, 1);
  286. const start = `|${this.name.toUpperCase()}|`;
  287. const numberOfSpacesNeeded = 20 - start.length;
  288. _arguments.unshift(`${start}${Array(numberOfSpacesNeeded).join(" ")}`);
  289. if (type === "INFO") {
  290. _arguments[0] += "\x1b[36m";
  291. _arguments.push("\x1b[0m");
  292. console.log.apply(null, _arguments);
  293. } else if (type === "ERROR") {
  294. _arguments[0] += "\x1b[31m";
  295. _arguments.push("\x1b[0m");
  296. console.error.apply(null, _arguments);
  297. }
  298. }
  299. }
  300. const moduleManager = new ModuleManager();
  301. if (!config.get("migration")) {
  302. moduleManager.addModule("cache");
  303. moduleManager.addModule("db");
  304. moduleManager.addModule("mail");
  305. moduleManager.addModule("activities");
  306. moduleManager.addModule("api");
  307. moduleManager.addModule("app");
  308. moduleManager.addModule("io");
  309. moduleManager.addModule("notifications");
  310. moduleManager.addModule("playlists");
  311. moduleManager.addModule("punishments");
  312. moduleManager.addModule("songs");
  313. moduleManager.addModule("stations");
  314. moduleManager.addModule("tasks");
  315. moduleManager.addModule("utils");
  316. moduleManager.addModule("youtube");
  317. } else {
  318. moduleManager.addModule("migration");
  319. }
  320. moduleManager.initialize();
  321. /**
  322. * Prints a job
  323. *
  324. * @param {object} job - the job
  325. * @param {number} layer - the layer
  326. */
  327. function printJob(job, layer) {
  328. const tabs = Array(layer).join("\t");
  329. console.log(`${tabs}${job.name} (${job.toString()}) ${job.status}`);
  330. job.childJobs.forEach(childJob => {
  331. printJob(childJob, layer + 1);
  332. });
  333. }
  334. /**
  335. * Prints a task
  336. *
  337. * @param {object} task - the task
  338. * @param {number} layer - the layer
  339. */
  340. function printTask(task, layer) {
  341. const tabs = Array(layer).join("\t");
  342. console.log(`${tabs}${task.job.name} (${task.job.toString()}) ${task.job.status} (priority: ${task.priority})`);
  343. task.job.childJobs.forEach(childJob => {
  344. printJob(childJob, layer + 1);
  345. });
  346. }
  347. process.stdin.on("data", data => {
  348. const command = data.toString().replace(/\r?\n|\r/g, "");
  349. if (command === "lockdown") {
  350. console.log("Locking down.");
  351. moduleManager._lockdown();
  352. }
  353. if (command === "status") {
  354. console.log("Status:");
  355. Object.keys(moduleManager.modules).forEach(moduleName => {
  356. const module = moduleManager.modules[moduleName];
  357. const tabsNeeded = 4 - Math.ceil((moduleName.length + 1) / 8);
  358. console.log(
  359. `${moduleName.toUpperCase()}${Array(tabsNeeded).join(
  360. "\t"
  361. )}${module.getStatus()}. Jobs in queue: ${module.jobQueue.lengthQueue()}. Jobs in progress: ${module.jobQueue.lengthRunning()}. Jobs paused: ${module.jobQueue.lengthPaused()} Concurrency: ${
  362. module.jobQueue.concurrency
  363. }. Stage: ${module.getStage()}`
  364. );
  365. });
  366. // moduleManager._lockdown();
  367. }
  368. if (command.startsWith("running")) {
  369. const parts = command.split(" ");
  370. moduleManager.modules[parts[1]].jobQueue.runningTasks.forEach(task => {
  371. printTask(task, 1);
  372. });
  373. }
  374. if (command.startsWith("queued")) {
  375. const parts = command.split(" ");
  376. moduleManager.modules[parts[1]].jobQueue.queue.forEach(task => {
  377. printTask(task, 1);
  378. });
  379. }
  380. if (command.startsWith("paused")) {
  381. const parts = command.split(" ");
  382. moduleManager.modules[parts[1]].jobQueue.pausedTasks.forEach(task => {
  383. printTask(task, 1);
  384. });
  385. }
  386. if (command.startsWith("stats")) {
  387. const parts = command.split(" ");
  388. console.log(moduleManager.modules[parts[1]].jobStatistics);
  389. }
  390. if (command.startsWith("jobinfo")) {
  391. const parts = command.split(" ");
  392. const uuid = parts[1];
  393. let jobFound = null;
  394. Object.keys(moduleManager.modules).forEach(moduleName => {
  395. const module = moduleManager.modules[moduleName];
  396. const task1 = module.jobQueue.runningTasks.find(task => task.job.uniqueId === uuid);
  397. const task2 = module.jobQueue.queue.find(task => task.job.uniqueId === uuid);
  398. const task3 = module.jobQueue.pausedTasks.find(task => task.job.uniqueId === uuid);
  399. if (task1) jobFound = task1.job;
  400. if (task2) jobFound = task2.job;
  401. if (task3) jobFound = task3.job;
  402. });
  403. if (jobFound) {
  404. let topParent = jobFound;
  405. let levelsDeep = 0;
  406. while (topParent.parentJob && topParent !== topParent.parentJob) {
  407. topParent = jobFound.parentJob;
  408. levelsDeep += 1;
  409. }
  410. console.log(
  411. `Found job, displaying that job and the full tree from the top parent job. The job is ${levelsDeep} levels deep from the top parent.`
  412. );
  413. console.log(jobFound);
  414. printJob(topParent, 1);
  415. } else console.log("Could not find job in any running, queued or paused lists in any module.");
  416. }
  417. if (command.startsWith("runjob")) {
  418. const parts = command.split(" ");
  419. const module = parts[1];
  420. const jobName = parts[2];
  421. const payload = JSON.parse(parts[3]);
  422. moduleManager.modules[module]
  423. .runJob(jobName, payload)
  424. .then(response => {
  425. console.log("runjob success", response);
  426. })
  427. .catch(err => {
  428. console.log("runjob error", err);
  429. });
  430. }
  431. if (command.startsWith("eval")) {
  432. const evalCommand = command.replace("eval ", "");
  433. console.log(`Running eval command: ${evalCommand}`);
  434. // eslint-disable-next-line no-eval
  435. const response = eval(evalCommand);
  436. console.log(`Eval response: `, response);
  437. }
  438. });
  439. export default moduleManager;