index.js 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369
  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 JobManager {
  39. // eslint-disable-next-line require-jsdoc
  40. constructor() {
  41. this.runningJobs = {};
  42. }
  43. /**
  44. * Adds a job to the list of running jobs
  45. *
  46. * @param {object} job - the job object
  47. */
  48. addJob(job) {
  49. if (!this.runningJobs[job.module.name]) this.runningJobs[job.module.name] = {};
  50. this.runningJobs[job.module.name][job.toString()] = job;
  51. }
  52. /**
  53. * Removes a job from the list of running jobs (after it's completed)
  54. *
  55. * @param {object} job - the job object
  56. */
  57. removeJob(job) {
  58. if (!this.runningJobs[job.module.name]) this.runningJobs[job.module.name] = {};
  59. delete this.runningJobs[job.module.name][job.toString()];
  60. }
  61. /**
  62. * Returns detail about a job via a identifier
  63. *
  64. * @param {string} uuid - the job identifier
  65. * @returns {object} - the job object
  66. */
  67. getJob(uuid) {
  68. let job = null;
  69. Object.keys(this.runningJobs).forEach(moduleName => {
  70. if (this.runningJobs[moduleName][uuid]) job = this.runningJobs[moduleName][uuid];
  71. });
  72. return job;
  73. }
  74. }
  75. class ModuleManager {
  76. // eslint-disable-next-line require-jsdoc
  77. constructor() {
  78. this.modules = {};
  79. this.modulesNotInitialized = [];
  80. this.jobManager = new JobManager();
  81. this.i = 0;
  82. this.lockdown = false;
  83. this.fancyConsole = fancyConsole;
  84. this.debugLogs = {
  85. stationIssue: []
  86. };
  87. this.debugJobs = {
  88. all: [],
  89. completed: []
  90. };
  91. this.name = "MODULE_MANAGER";
  92. }
  93. /**
  94. * Adds a new module to the backend server/module manager
  95. *
  96. * @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")
  97. */
  98. async addModule(moduleName) {
  99. this.log("INFO", "Adding module", moduleName);
  100. this.modules[moduleName] = import(`./logic/${moduleName}`);
  101. }
  102. /**
  103. * Initialises a new module to the backend server/module manager
  104. *
  105. */
  106. async initialize() {
  107. this.reservedLines = Object.keys(this.modules).length + 5;
  108. await Promise.all(Object.values(this.modules)).then(modules => {
  109. for (let module = 0; module < modules.length; module += 1) {
  110. this.modules[modules[module].default.name] = modules[module].default;
  111. this.modulesNotInitialized.push(modules[module].default);
  112. }
  113. }); // ensures all modules are imported, then converts promise to the default export of the import
  114. Object.keys(this.modules).every(moduleKey => {
  115. const module = this.modules[moduleKey];
  116. module.setModuleManager(this);
  117. if (this.lockdown) return false;
  118. module._initialize();
  119. return true;
  120. });
  121. }
  122. /**
  123. * Called when a module is initialised
  124. *
  125. * @param {object} module - the module object/class
  126. */
  127. onInitialize(module) {
  128. if (this.modulesNotInitialized.indexOf(module) !== -1) {
  129. this.modulesNotInitialized.splice(this.modulesNotInitialized.indexOf(module), 1);
  130. this.log(
  131. "INFO",
  132. `Initialized: ${Object.keys(this.modules).length - this.modulesNotInitialized.length}/${
  133. Object.keys(this.modules).length
  134. }.`
  135. );
  136. if (this.modulesNotInitialized.length === 0) this.onAllModulesInitialized();
  137. }
  138. }
  139. /**
  140. * Called when a module fails to initialise
  141. *
  142. * @param {object} module - the module object/class
  143. */
  144. onFail(module) {
  145. if (this.modulesNotInitialized.indexOf(module) !== -1) {
  146. this.log("ERROR", "A module failed to initialize!");
  147. }
  148. }
  149. /**
  150. * Called when every module has initialised
  151. *
  152. */
  153. onAllModulesInitialized() {
  154. this.log("INFO", "All modules initialized!");
  155. }
  156. /**
  157. * Creates a new log message
  158. *
  159. * @param {...any} args - anything to be included in the log message, the first argument is the type of log
  160. */
  161. log(...args) {
  162. const _arguments = Array.from(args);
  163. const type = _arguments[0];
  164. _arguments.splice(0, 1);
  165. const start = `|${this.name.toUpperCase()}|`;
  166. const numberOfSpacesNeeded = 20 - start.length;
  167. _arguments.unshift(`${start}${Array(numberOfSpacesNeeded).join(" ")}`);
  168. if (type === "INFO") {
  169. _arguments[0] += "\x1b[36m";
  170. _arguments.push("\x1b[0m");
  171. console.log.apply(null, _arguments);
  172. } else if (type === "ERROR") {
  173. _arguments[0] += "\x1b[31m";
  174. _arguments.push("\x1b[0m");
  175. console.error.apply(null, _arguments);
  176. }
  177. }
  178. /**
  179. * Locks down all modules
  180. */
  181. _lockdown() {
  182. this.lockdown = true;
  183. Object.keys(this.modules).every(moduleKey => {
  184. const module = this.modules[moduleKey];
  185. module.setStatus("LOCKDOWN");
  186. return true;
  187. });
  188. }
  189. }
  190. const moduleManager = new ModuleManager();
  191. if (!config.get("migration")) {
  192. moduleManager.addModule("cache");
  193. moduleManager.addModule("db");
  194. moduleManager.addModule("mail");
  195. moduleManager.addModule("activities");
  196. moduleManager.addModule("api");
  197. moduleManager.addModule("app");
  198. moduleManager.addModule("ws");
  199. moduleManager.addModule("notifications");
  200. moduleManager.addModule("playlists");
  201. moduleManager.addModule("punishments");
  202. moduleManager.addModule("songs");
  203. moduleManager.addModule("stations");
  204. moduleManager.addModule("tasks");
  205. moduleManager.addModule("utils");
  206. moduleManager.addModule("youtube");
  207. } else {
  208. moduleManager.addModule("migration");
  209. }
  210. moduleManager.initialize();
  211. /**
  212. * Prints a job
  213. *
  214. * @param {object} job - the job
  215. * @param {number} layer - the layer
  216. */
  217. function printJob(job, layer) {
  218. const tabs = Array(layer).join("\t");
  219. if (job) {
  220. console.log(`${tabs}${job.name} (${job.toString()}) ${job.status}`);
  221. job.childJobs.forEach(childJob => {
  222. printJob(childJob, layer + 1);
  223. });
  224. } else console.log(`${tabs}JOB WAS REMOVED`);
  225. }
  226. /**
  227. * Prints a task
  228. *
  229. * @param {object} task - the task
  230. * @param {number} layer - the layer
  231. */
  232. function printTask(task, layer) {
  233. const tabs = Array(layer).join("\t");
  234. console.log(`${tabs}${task.job.name} (${task.job.toString()}) ${task.job.status} (priority: ${task.priority})`);
  235. task.job.childJobs.forEach(childJob => {
  236. printJob(childJob, layer + 1);
  237. });
  238. }
  239. process.stdin.on("data", data => {
  240. const command = data.toString().replace(/\r?\n|\r/g, "");
  241. if (command === "lockdown") {
  242. console.log("Locking down.");
  243. moduleManager._lockdown();
  244. }
  245. if (command === "status") {
  246. console.log("Status:");
  247. Object.keys(moduleManager.modules).forEach(moduleName => {
  248. const module = moduleManager.modules[moduleName];
  249. const tabsNeeded = 4 - Math.ceil((moduleName.length + 1) / 8);
  250. console.log(
  251. `${moduleName.toUpperCase()}${Array(tabsNeeded).join(
  252. "\t"
  253. )}${module.getStatus()}. Jobs in queue: ${module.jobQueue.lengthQueue()}. Jobs in progress: ${module.jobQueue.lengthRunning()}. Jobs paused: ${module.jobQueue.lengthPaused()} Concurrency: ${
  254. module.jobQueue.concurrency
  255. }. Stage: ${module.getStage()}`
  256. );
  257. });
  258. }
  259. if (command.startsWith("running")) {
  260. const parts = command.split(" ");
  261. moduleManager.modules[parts[1]].jobQueue.runningTasks.forEach(task => {
  262. printTask(task, 1);
  263. });
  264. }
  265. if (command.startsWith("queued")) {
  266. const parts = command.split(" ");
  267. moduleManager.modules[parts[1]].jobQueue.queue.forEach(task => {
  268. printTask(task, 1);
  269. });
  270. }
  271. if (command.startsWith("paused")) {
  272. const parts = command.split(" ");
  273. moduleManager.modules[parts[1]].jobQueue.pausedTasks.forEach(task => {
  274. printTask(task, 1);
  275. });
  276. }
  277. if (command.startsWith("stats")) {
  278. const parts = command.split(" ");
  279. console.log(moduleManager.modules[parts[1]].jobStatistics);
  280. }
  281. if (command.startsWith("jobinfo")) {
  282. const parts = command.split(" ");
  283. const uuid = parts[1];
  284. const jobFound = moduleManager.jobManager.getJob(uuid);
  285. if (jobFound) {
  286. let topParent = jobFound;
  287. let levelsDeep = 0;
  288. while (topParent.parentJob && topParent !== topParent.parentJob) {
  289. topParent = jobFound.parentJob;
  290. levelsDeep += 1;
  291. }
  292. console.log(
  293. `Found job, displaying that job and the full tree from the top parent job. The job is ${levelsDeep} levels deep from the top parent.`
  294. );
  295. console.log(jobFound);
  296. printJob(topParent, 1);
  297. } else console.log("Could not find job in job manager.");
  298. }
  299. if (command.startsWith("runjob")) {
  300. const parts = command.split(" ");
  301. const module = parts[1];
  302. const jobName = parts[2];
  303. const payload = JSON.parse(parts[3]);
  304. moduleManager.modules[module]
  305. .runJob(jobName, payload)
  306. .then(response => {
  307. console.log("runjob success", response);
  308. })
  309. .catch(err => {
  310. console.log("runjob error", err);
  311. });
  312. }
  313. if (command.startsWith("eval")) {
  314. const evalCommand = command.replace("eval ", "");
  315. console.log(`Running eval command: ${evalCommand}`);
  316. // eslint-disable-next-line no-eval
  317. const response = eval(evalCommand);
  318. console.log(`Eval response: `, response);
  319. }
  320. });
  321. export default moduleManager;