index.js 9.9 KB

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