index.js 17 KB

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