index.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529
  1. import "./loadEnvVariables.js";
  2. import util from "util";
  3. import config from "config";
  4. const REQUIRED_CONFIG_VERSION = 4;
  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 ModuleManager {
  180. // eslint-disable-next-line require-jsdoc
  181. constructor() {
  182. this.modules = {};
  183. this.modulesNotInitialized = [];
  184. this.i = 0;
  185. this.lockdown = false;
  186. this.fancyConsole = fancyConsole;
  187. this.debugLogs = {
  188. stationIssue: []
  189. };
  190. this.debugJobs = {
  191. all: [],
  192. completed: []
  193. };
  194. this.name = "MODULE_MANAGER";
  195. }
  196. /**
  197. * Adds a new module to the backend server/module manager
  198. *
  199. * @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")
  200. */
  201. async addModule(moduleName) {
  202. this.log("INFO", "Adding module", moduleName);
  203. // import(`./logic/${moduleName}`).then(Module => {
  204. // // eslint-disable-next-line new-cap
  205. // const instantiatedModule = new Module.default();
  206. // this.modules[moduleName] = instantiatedModule;
  207. // this.modulesNotInitialized.push(instantiatedModule);
  208. // if (moduleName === "cache") console.log(56, this.modules);
  209. // });
  210. this.modules[moduleName] = import(`./logic/${moduleName}`);
  211. }
  212. /**
  213. * Initialises a new module to the backend server/module manager
  214. *
  215. */
  216. async initialize() {
  217. // if (!this.modules["logger"]) return console.error("There is no logger module");
  218. // this.logger = this.modules["logger"];
  219. // if (this.fancyConsole) {
  220. // this.replaceConsoleWithLogger();
  221. this.reservedLines = Object.keys(this.modules).length + 5;
  222. // }
  223. await Promise.all(Object.values(this.modules)).then(modules => {
  224. for (let module = 0; module < modules.length; module += 1) {
  225. this.modules[modules[module].default.name] = modules[module].default;
  226. this.modulesNotInitialized.push(modules[module].default);
  227. }
  228. }); // ensures all modules are imported, then converts promise to the default export of the import
  229. Object.keys(this.modules).every(moduleKey => {
  230. const module = this.modules[moduleKey];
  231. module.setModuleManager(this);
  232. if (this.lockdown) return false;
  233. module._initialize();
  234. // let dependenciesInitializedPromises = [];
  235. // module.dependsOn.forEach(dependencyName => {
  236. // let dependency = this.modules[dependencyName];
  237. // dependenciesInitializedPromises.push(dependency._onInitialize());
  238. // });
  239. // module.lastTime = Date.now();
  240. // Promise.all(dependenciesInitializedPromises).then((res, res2) => {
  241. // if (this.lockdown) return;
  242. // this.logger.info("MODULE_MANAGER", `${moduleName} dependencies have been completed`);
  243. // module._initialize();
  244. // });
  245. return true;
  246. });
  247. }
  248. /**
  249. * Called when a module is initialised
  250. *
  251. * @param {object} module - the module object/class
  252. */
  253. onInitialize(module) {
  254. if (this.modulesNotInitialized.indexOf(module) !== -1) {
  255. this.modulesNotInitialized.splice(this.modulesNotInitialized.indexOf(module), 1);
  256. this.log(
  257. "INFO",
  258. `Initialized: ${Object.keys(this.modules).length - this.modulesNotInitialized.length}/${
  259. Object.keys(this.modules).length
  260. }.`
  261. );
  262. if (this.modulesNotInitialized.length === 0) this.onAllModulesInitialized();
  263. }
  264. }
  265. /**
  266. * Called when a module fails to initialise
  267. *
  268. * @param {object} module - the module object/class
  269. */
  270. onFail(module) {
  271. if (this.modulesNotInitialized.indexOf(module) !== -1) {
  272. this.log("ERROR", "A module failed to initialize!");
  273. }
  274. }
  275. /**
  276. * Called when every module has initialised
  277. *
  278. */
  279. onAllModulesInitialized() {
  280. this.log("INFO", "All modules initialized!");
  281. }
  282. /**
  283. * Creates a new log message
  284. *
  285. * @param {...any} args - anything to be included in the log message, the first argument is the type of log
  286. */
  287. log(...args) {
  288. const _arguments = Array.from(args);
  289. const type = _arguments[0];
  290. _arguments.splice(0, 1);
  291. const start = `|${this.name.toUpperCase()}|`;
  292. const numberOfSpacesNeeded = 20 - start.length;
  293. _arguments.unshift(`${start}${Array(numberOfSpacesNeeded).join(" ")}`);
  294. if (type === "INFO") {
  295. _arguments[0] += "\x1b[36m";
  296. _arguments.push("\x1b[0m");
  297. console.log.apply(null, _arguments);
  298. } else if (type === "ERROR") {
  299. _arguments[0] += "\x1b[31m";
  300. _arguments.push("\x1b[0m");
  301. console.error.apply(null, _arguments);
  302. }
  303. }
  304. }
  305. const moduleManager = new ModuleManager();
  306. if (!config.get("migration")) {
  307. moduleManager.addModule("cache");
  308. moduleManager.addModule("db");
  309. moduleManager.addModule("mail");
  310. moduleManager.addModule("activities");
  311. moduleManager.addModule("api");
  312. moduleManager.addModule("app");
  313. moduleManager.addModule("ws");
  314. moduleManager.addModule("notifications");
  315. moduleManager.addModule("playlists");
  316. moduleManager.addModule("punishments");
  317. moduleManager.addModule("songs");
  318. moduleManager.addModule("stations");
  319. moduleManager.addModule("tasks");
  320. moduleManager.addModule("utils");
  321. moduleManager.addModule("youtube");
  322. } else {
  323. moduleManager.addModule("migration");
  324. }
  325. moduleManager.initialize();
  326. /**
  327. * Prints a job
  328. *
  329. * @param {object} job - the job
  330. * @param {number} layer - the layer
  331. */
  332. function printJob(job, layer) {
  333. const tabs = Array(layer).join("\t");
  334. console.log(`${tabs}${job.name} (${job.toString()}) ${job.status}`);
  335. job.childJobs.forEach(childJob => {
  336. printJob(childJob, layer + 1);
  337. });
  338. }
  339. /**
  340. * Prints a task
  341. *
  342. * @param {object} task - the task
  343. * @param {number} layer - the layer
  344. */
  345. function printTask(task, layer) {
  346. const tabs = Array(layer).join("\t");
  347. console.log(`${tabs}${task.job.name} (${task.job.toString()}) ${task.job.status} (priority: ${task.priority})`);
  348. task.job.childJobs.forEach(childJob => {
  349. printJob(childJob, layer + 1);
  350. });
  351. }
  352. process.stdin.on("data", data => {
  353. const command = data.toString().replace(/\r?\n|\r/g, "");
  354. if (command === "lockdown") {
  355. console.log("Locking down.");
  356. moduleManager._lockdown();
  357. }
  358. if (command === "status") {
  359. console.log("Status:");
  360. Object.keys(moduleManager.modules).forEach(moduleName => {
  361. const module = moduleManager.modules[moduleName];
  362. const tabsNeeded = 4 - Math.ceil((moduleName.length + 1) / 8);
  363. console.log(
  364. `${moduleName.toUpperCase()}${Array(tabsNeeded).join(
  365. "\t"
  366. )}${module.getStatus()}. Jobs in queue: ${module.jobQueue.lengthQueue()}. Jobs in progress: ${module.jobQueue.lengthRunning()}. Jobs paused: ${module.jobQueue.lengthPaused()} Concurrency: ${
  367. module.jobQueue.concurrency
  368. }. Stage: ${module.getStage()}`
  369. );
  370. });
  371. // moduleManager._lockdown();
  372. }
  373. if (command.startsWith("running")) {
  374. const parts = command.split(" ");
  375. moduleManager.modules[parts[1]].jobQueue.runningTasks.forEach(task => {
  376. printTask(task, 1);
  377. });
  378. }
  379. if (command.startsWith("queued")) {
  380. const parts = command.split(" ");
  381. moduleManager.modules[parts[1]].jobQueue.queue.forEach(task => {
  382. printTask(task, 1);
  383. });
  384. }
  385. if (command.startsWith("paused")) {
  386. const parts = command.split(" ");
  387. moduleManager.modules[parts[1]].jobQueue.pausedTasks.forEach(task => {
  388. printTask(task, 1);
  389. });
  390. }
  391. if (command.startsWith("stats")) {
  392. const parts = command.split(" ");
  393. console.log(moduleManager.modules[parts[1]].jobStatistics);
  394. }
  395. if (command.startsWith("jobinfo")) {
  396. const parts = command.split(" ");
  397. const uuid = parts[1];
  398. let jobFound = null;
  399. Object.keys(moduleManager.modules).forEach(moduleName => {
  400. const module = moduleManager.modules[moduleName];
  401. const task1 = module.jobQueue.runningTasks.find(task => task.job.uniqueId === uuid);
  402. const task2 = module.jobQueue.queue.find(task => task.job.uniqueId === uuid);
  403. const task3 = module.jobQueue.pausedTasks.find(task => task.job.uniqueId === uuid);
  404. if (task1) jobFound = task1.job;
  405. if (task2) jobFound = task2.job;
  406. if (task3) jobFound = task3.job;
  407. });
  408. if (jobFound) {
  409. let topParent = jobFound;
  410. let levelsDeep = 0;
  411. while (topParent.parentJob && topParent !== topParent.parentJob) {
  412. topParent = jobFound.parentJob;
  413. levelsDeep += 1;
  414. }
  415. console.log(
  416. `Found job, displaying that job and the full tree from the top parent job. The job is ${levelsDeep} levels deep from the top parent.`
  417. );
  418. console.log(jobFound);
  419. printJob(topParent, 1);
  420. } else console.log("Could not find job in any running, queued or paused lists in any module.");
  421. }
  422. if (command.startsWith("runjob")) {
  423. const parts = command.split(" ");
  424. const module = parts[1];
  425. const jobName = parts[2];
  426. const payload = JSON.parse(parts[3]);
  427. moduleManager.modules[module]
  428. .runJob(jobName, payload)
  429. .then(response => {
  430. console.log("runjob success", response);
  431. })
  432. .catch(err => {
  433. console.log("runjob error", err);
  434. });
  435. }
  436. if (command.startsWith("eval")) {
  437. const evalCommand = command.replace("eval ", "");
  438. console.log(`Running eval command: ${evalCommand}`);
  439. // eslint-disable-next-line no-eval
  440. const response = eval(evalCommand);
  441. console.log(`Eval response: `, response);
  442. }
  443. });
  444. export default moduleManager;