index.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563
  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. const moduleManager = new ModuleManager();
  344. if (!config.get("migration")) {
  345. moduleManager.addModule("cache");
  346. moduleManager.addModule("db");
  347. moduleManager.addModule("mail");
  348. moduleManager.addModule("activities");
  349. moduleManager.addModule("api");
  350. moduleManager.addModule("app");
  351. moduleManager.addModule("ws");
  352. moduleManager.addModule("notifications");
  353. moduleManager.addModule("playlists");
  354. moduleManager.addModule("punishments");
  355. moduleManager.addModule("songs");
  356. moduleManager.addModule("stations");
  357. moduleManager.addModule("tasks");
  358. moduleManager.addModule("utils");
  359. moduleManager.addModule("youtube");
  360. } else {
  361. moduleManager.addModule("migration");
  362. }
  363. moduleManager.initialize();
  364. /**
  365. * Prints a job
  366. *
  367. * @param {object} job - the job
  368. * @param {number} layer - the layer
  369. */
  370. function printJob(job, layer) {
  371. const tabs = Array(layer).join("\t");
  372. if (job) {
  373. console.log(`${tabs}${job.name} (${job.toString()}) ${job.status}`);
  374. job.childJobs.forEach(childJob => {
  375. printJob(childJob, layer + 1);
  376. });
  377. } else console.log(`${tabs}JOB WAS REMOVED`);
  378. }
  379. /**
  380. * Prints a task
  381. *
  382. * @param {object} task - the task
  383. * @param {number} layer - the layer
  384. */
  385. function printTask(task, layer) {
  386. const tabs = Array(layer).join("\t");
  387. console.log(`${tabs}${task.job.name} (${task.job.toString()}) ${task.job.status} (priority: ${task.priority})`);
  388. task.job.childJobs.forEach(childJob => {
  389. printJob(childJob, layer + 1);
  390. });
  391. }
  392. process.stdin.on("data", data => {
  393. const command = data.toString().replace(/\r?\n|\r/g, "");
  394. if (command === "lockdown") {
  395. console.log("Locking down.");
  396. moduleManager._lockdown();
  397. }
  398. if (command === "status") {
  399. console.log("Status:");
  400. Object.keys(moduleManager.modules).forEach(moduleName => {
  401. const module = moduleManager.modules[moduleName];
  402. const tabsNeeded = 4 - Math.ceil((moduleName.length + 1) / 8);
  403. console.log(
  404. `${moduleName.toUpperCase()}${Array(tabsNeeded).join(
  405. "\t"
  406. )}${module.getStatus()}. Jobs in queue: ${module.jobQueue.lengthQueue()}. Jobs in progress: ${module.jobQueue.lengthRunning()}. Jobs paused: ${module.jobQueue.lengthPaused()} Concurrency: ${
  407. module.jobQueue.concurrency
  408. }. Stage: ${module.getStage()}`
  409. );
  410. });
  411. // moduleManager._lockdown();
  412. }
  413. if (command.startsWith("running")) {
  414. const parts = command.split(" ");
  415. moduleManager.modules[parts[1]].jobQueue.runningTasks.forEach(task => {
  416. printTask(task, 1);
  417. });
  418. }
  419. if (command.startsWith("queued")) {
  420. const parts = command.split(" ");
  421. moduleManager.modules[parts[1]].jobQueue.queue.forEach(task => {
  422. printTask(task, 1);
  423. });
  424. }
  425. if (command.startsWith("paused")) {
  426. const parts = command.split(" ");
  427. moduleManager.modules[parts[1]].jobQueue.pausedTasks.forEach(task => {
  428. printTask(task, 1);
  429. });
  430. }
  431. if (command.startsWith("stats")) {
  432. const parts = command.split(" ");
  433. console.log(moduleManager.modules[parts[1]].jobStatistics);
  434. }
  435. if (command.startsWith("jobinfo")) {
  436. const parts = command.split(" ");
  437. const uuid = parts[1];
  438. const jobFound = moduleManager.jobManager.getJob(uuid);
  439. if (jobFound) {
  440. let topParent = jobFound;
  441. let levelsDeep = 0;
  442. while (topParent.parentJob && topParent !== topParent.parentJob) {
  443. topParent = jobFound.parentJob;
  444. levelsDeep += 1;
  445. }
  446. console.log(
  447. `Found job, displaying that job and the full tree from the top parent job. The job is ${levelsDeep} levels deep from the top parent.`
  448. );
  449. console.log(jobFound);
  450. printJob(topParent, 1);
  451. } else console.log("Could not find job in job manager.");
  452. }
  453. if (command.startsWith("runjob")) {
  454. const parts = command.split(" ");
  455. const module = parts[1];
  456. const jobName = parts[2];
  457. const payload = JSON.parse(parts[3]);
  458. moduleManager.modules[module]
  459. .runJob(jobName, payload)
  460. .then(response => {
  461. console.log("runjob success", response);
  462. })
  463. .catch(err => {
  464. console.log("runjob error", err);
  465. });
  466. }
  467. if (command.startsWith("eval")) {
  468. const evalCommand = command.replace("eval ", "");
  469. console.log(`Running eval command: ${evalCommand}`);
  470. // eslint-disable-next-line no-eval
  471. const response = eval(evalCommand);
  472. console.log(`Eval response: `, response);
  473. }
  474. });
  475. export default moduleManager;