index.js 16 KB

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