index.js 17 KB

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