index.js 12 KB

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