2021-08-19 14:19:14 +00:00
|
|
|
import { BaseServiceWorker } from "eris-fleet";
|
|
|
|
import * as logger from "../logger.js";
|
|
|
|
import fs from "fs";
|
|
|
|
import path from "path";
|
|
|
|
import { fileURLToPath } from "url";
|
|
|
|
import { Worker } from "worker_threads";
|
2022-01-29 22:14:27 +00:00
|
|
|
import { createRequire } from "module";
|
2022-04-17 15:40:56 +00:00
|
|
|
import { createServer } from "http";
|
2022-08-11 16:46:56 +00:00
|
|
|
import { request } from "undici";
|
2022-04-17 15:40:56 +00:00
|
|
|
import EventEmitter from "events";
|
2021-11-27 05:05:09 +00:00
|
|
|
|
2022-01-29 21:08:27 +00:00
|
|
|
// only requiring this to work around an issue regarding worker threads
|
|
|
|
const nodeRequire = createRequire(import.meta.url);
|
2022-01-29 22:14:27 +00:00
|
|
|
nodeRequire(`../../build/${process.env.DEBUG && process.env.DEBUG === "true" ? "Debug" : "Release"}/image.node`);
|
2022-01-29 21:08:27 +00:00
|
|
|
|
2021-11-27 05:05:09 +00:00
|
|
|
import ImageConnection from "../imageConnection.js";
|
2021-07-06 00:20:21 +00:00
|
|
|
|
|
|
|
class ImageWorker extends BaseServiceWorker {
|
|
|
|
constructor(setup) {
|
|
|
|
super(setup);
|
|
|
|
|
2022-01-23 05:16:55 +00:00
|
|
|
console.info = (str) => this.ipc.sendToAdmiral("info", str);
|
|
|
|
|
2022-04-17 15:40:56 +00:00
|
|
|
if (process.env.API_TYPE === "ws") {
|
2021-07-06 00:20:21 +00:00
|
|
|
this.connections = new Map();
|
2022-07-26 15:38:42 +00:00
|
|
|
this.servers = JSON.parse(fs.readFileSync(new URL("../../config/servers.json", import.meta.url), { encoding: "utf8" })).image;
|
2021-11-27 05:05:09 +00:00
|
|
|
this.nextID = 0;
|
2022-04-17 15:40:56 +00:00
|
|
|
} else if (process.env.API_TYPE === "azure") {
|
|
|
|
this.jobs = new Map();
|
|
|
|
this.webhook = createServer();
|
|
|
|
this.port = parseInt(process.env.WEBHOOK_PORT) || 3763;
|
2021-07-06 00:20:21 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
this.begin().then(() => this.serviceReady());
|
|
|
|
}
|
|
|
|
|
|
|
|
async begin() {
|
|
|
|
// connect to image api if enabled
|
2022-04-17 15:40:56 +00:00
|
|
|
if (process.env.API_TYPE === "ws") {
|
2021-07-06 00:20:21 +00:00
|
|
|
for (const server of this.servers) {
|
|
|
|
try {
|
2021-08-06 22:13:29 +00:00
|
|
|
await this.connect(server.server, server.auth);
|
2021-07-06 00:20:21 +00:00
|
|
|
} catch (e) {
|
|
|
|
logger.error(e);
|
|
|
|
}
|
|
|
|
}
|
2022-04-17 15:40:56 +00:00
|
|
|
} else if (process.env.API_TYPE === "azure") {
|
|
|
|
this.webhook.on("request", async (req, res) => {
|
|
|
|
if (req.method !== "POST") {
|
|
|
|
res.statusCode = 405;
|
|
|
|
return res.end("405 Method Not Allowed");
|
|
|
|
}
|
|
|
|
if (process.env.AZURE_PASS && req.headers.authorization !== process.env.AZURE_PASS) {
|
|
|
|
res.statusCode = 401;
|
|
|
|
return res.end("401 Unauthorized");
|
|
|
|
}
|
|
|
|
const reqUrl = new URL(req.url, `http://${req.headers.host}`);
|
|
|
|
if (reqUrl.pathname === "/callback") {
|
|
|
|
try {
|
|
|
|
const chunks = [];
|
|
|
|
req.on("data", (data) => {
|
|
|
|
chunks.push(data);
|
|
|
|
});
|
|
|
|
req.once("end", () => {
|
|
|
|
if (this.jobs.has(req.headers["x-azure-id"])) {
|
|
|
|
try {
|
|
|
|
const error = JSON.parse(Buffer.concat(chunks).toString());
|
|
|
|
if (error.error) this.jobs.get(req.headers["x-azure-id"]).emit("error", new Error(error.message));
|
|
|
|
} catch {
|
|
|
|
// no-op
|
|
|
|
}
|
|
|
|
const contentType = req.headers["content-type"];
|
|
|
|
let type;
|
|
|
|
switch (contentType) {
|
|
|
|
case "image/gif":
|
|
|
|
type = "gif";
|
|
|
|
break;
|
|
|
|
case "image/png":
|
|
|
|
type = "png";
|
|
|
|
break;
|
|
|
|
case "image/jpeg":
|
|
|
|
type = "jpg";
|
|
|
|
break;
|
|
|
|
case "image/webp":
|
|
|
|
type = "webp";
|
|
|
|
break;
|
|
|
|
default:
|
|
|
|
type = contentType;
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
this.jobs.get(req.headers["x-azure-id"]).emit("image", { buffer: Buffer.concat(chunks), type });
|
|
|
|
return res.end("OK");
|
|
|
|
} else {
|
|
|
|
res.statusCode = 409;
|
|
|
|
return res.end("409 Conflict");
|
|
|
|
}
|
|
|
|
});
|
|
|
|
} catch (e) {
|
|
|
|
logger.error("An error occurred while processing a webhook request: ", e);
|
|
|
|
res.statusCode = 500;
|
|
|
|
return res.end("500 Internal Server Error");
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
res.statusCode = 404;
|
|
|
|
return res.end("404 Not Found");
|
|
|
|
}
|
|
|
|
});
|
|
|
|
this.webhook.on("error", (e) => {
|
|
|
|
logger.error("An error occurred on the Azure webhook: ", e);
|
|
|
|
});
|
|
|
|
this.webhook.listen(this.port, () => {
|
|
|
|
logger.log(`Azure HTTP webhook listening on port ${this.port}`);
|
|
|
|
});
|
2021-07-06 00:20:21 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
async repopulate() {
|
2022-07-26 15:38:42 +00:00
|
|
|
const data = await fs.promises.readFile(new URL("../../config/servers.json", import.meta.url), { encoding: "utf8" });
|
2021-07-06 00:20:21 +00:00
|
|
|
this.servers = JSON.parse(data).image;
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
async getRunning() {
|
|
|
|
const statuses = [];
|
2022-04-17 15:40:56 +00:00
|
|
|
if (process.env.API_TYPE === "ws") {
|
2022-01-17 02:12:54 +00:00
|
|
|
for (const [address, connection] of this.connections) {
|
|
|
|
if (connection.conn.readyState !== 0 && connection.conn.readyState !== 1) {
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
statuses.push({
|
|
|
|
address,
|
|
|
|
runningJobs: connection.njobs,
|
|
|
|
max: connection.max
|
|
|
|
});
|
2021-07-06 00:20:21 +00:00
|
|
|
}
|
|
|
|
}
|
2021-11-27 05:05:09 +00:00
|
|
|
return statuses;
|
2021-07-06 00:20:21 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
async chooseServer(ideal) {
|
|
|
|
if (ideal.length === 0) throw "No available servers";
|
|
|
|
const sorted = ideal.sort((a, b) => {
|
2022-01-05 16:17:59 +00:00
|
|
|
return a.load - b.load;
|
2021-09-01 05:21:13 +00:00
|
|
|
}).filter((e, i, array) => {
|
|
|
|
return !(e.load < array[0].load);
|
2021-07-06 00:20:21 +00:00
|
|
|
});
|
|
|
|
return sorted[0];
|
|
|
|
}
|
|
|
|
|
2021-11-29 21:27:13 +00:00
|
|
|
async getIdeal(object) {
|
2021-07-06 00:20:21 +00:00
|
|
|
const idealServers = [];
|
2021-11-27 05:05:09 +00:00
|
|
|
for (const [address, connection] of this.connections) {
|
|
|
|
if (connection.conn.readyState !== 0 && connection.conn.readyState !== 1) {
|
2021-07-06 00:20:21 +00:00
|
|
|
continue;
|
|
|
|
}
|
2022-07-23 21:02:04 +00:00
|
|
|
if (object.params.type && !connection.formats[object.cmd]?.includes(object.params.type)) continue;
|
2021-11-27 05:05:09 +00:00
|
|
|
idealServers.push({
|
|
|
|
addr: address,
|
|
|
|
load: connection.njobs / connection.max
|
|
|
|
});
|
2021-07-06 00:20:21 +00:00
|
|
|
}
|
2021-11-27 05:05:09 +00:00
|
|
|
const server = await this.chooseServer(idealServers);
|
|
|
|
return this.connections.get(server.addr);
|
2021-07-06 00:20:21 +00:00
|
|
|
}
|
|
|
|
|
2021-08-06 22:13:29 +00:00
|
|
|
async connect(server, auth) {
|
2021-12-03 00:01:33 +00:00
|
|
|
const connection = new ImageConnection(server, auth);
|
2021-07-06 00:20:21 +00:00
|
|
|
this.connections.set(server, connection);
|
|
|
|
}
|
|
|
|
|
|
|
|
async disconnect() {
|
|
|
|
for (const connection of this.connections.values()) {
|
|
|
|
connection.close();
|
|
|
|
}
|
|
|
|
this.connections.clear();
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2021-11-27 05:05:09 +00:00
|
|
|
waitForWorker(worker) {
|
2021-07-06 00:20:21 +00:00
|
|
|
return new Promise((resolve, reject) => {
|
2021-11-27 05:05:09 +00:00
|
|
|
worker.once("message", (data) => {
|
|
|
|
resolve({
|
|
|
|
buffer: Buffer.from([...data.buffer]),
|
|
|
|
type: data.fileExtension
|
2021-07-06 00:20:21 +00:00
|
|
|
});
|
2021-11-27 05:05:09 +00:00
|
|
|
});
|
|
|
|
worker.once("error", reject);
|
2021-07-06 00:20:21 +00:00
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2022-04-17 15:40:56 +00:00
|
|
|
waitForAzure(event) {
|
|
|
|
return new Promise((resolve, reject) => {
|
|
|
|
event.once("image", (data) => {
|
|
|
|
resolve(data);
|
|
|
|
});
|
|
|
|
event.once("error", reject);
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2021-11-27 05:05:09 +00:00
|
|
|
async run(object) {
|
2022-04-17 15:40:56 +00:00
|
|
|
if (process.env.API_TYPE === "ws") {
|
2021-12-06 07:25:38 +00:00
|
|
|
let num = this.nextID++;
|
|
|
|
if (num > 4294967295) num = this.nextID = 0;
|
2022-01-26 21:24:10 +00:00
|
|
|
for (let i = 0; i < 3; i++) {
|
|
|
|
const currentServer = await this.getIdeal(object);
|
|
|
|
try {
|
|
|
|
await currentServer.queue(num, object);
|
|
|
|
await currentServer.wait(num);
|
|
|
|
const output = await currentServer.getOutput(num);
|
|
|
|
return output;
|
|
|
|
} catch (e) {
|
|
|
|
if (i < 2 && e === "Request ended prematurely due to a closed connection") {
|
|
|
|
continue;
|
|
|
|
} else {
|
2022-03-10 20:24:03 +00:00
|
|
|
if (e === "No available servers" && i >= 2) throw "Request ended prematurely due to a closed connection";
|
2022-03-13 19:42:27 +00:00
|
|
|
throw e;
|
2022-01-26 21:24:10 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2022-04-17 15:40:56 +00:00
|
|
|
} else if (process.env.API_TYPE === "azure") {
|
|
|
|
object.callback = `${process.env.AZURE_CALLBACK_URL}:${this.port}/callback`;
|
2022-08-11 16:46:56 +00:00
|
|
|
const response = await request(`${process.env.AZURE_URL}/api/orchestrators/ImageOrchestrator`, { method: "POST", body: JSON.stringify(object) }).then(r => r.body.json());
|
2022-04-17 15:40:56 +00:00
|
|
|
const event = new EventEmitter();
|
|
|
|
this.jobs.set(response.id, event);
|
|
|
|
return await this.waitForAzure(event);
|
2021-11-27 05:05:09 +00:00
|
|
|
} else {
|
|
|
|
// Called from command (not using image API)
|
|
|
|
const worker = new Worker(path.join(path.dirname(fileURLToPath(import.meta.url)), "../image-runner.js"), {
|
|
|
|
workerData: object
|
|
|
|
});
|
|
|
|
return await this.waitForWorker(worker);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-07-06 00:20:21 +00:00
|
|
|
async handleCommand(data) {
|
|
|
|
try {
|
|
|
|
if (data.type === "run") {
|
2021-07-31 18:36:00 +00:00
|
|
|
const result = await this.run(data.obj);
|
|
|
|
return result;
|
2021-07-06 00:20:21 +00:00
|
|
|
} else if (data.type === "reload") {
|
|
|
|
await this.disconnect();
|
|
|
|
await this.repopulate();
|
|
|
|
let amount = 0;
|
|
|
|
for (const server of this.servers) {
|
|
|
|
try {
|
2021-08-06 22:13:29 +00:00
|
|
|
await this.connect(server.server, server.auth);
|
2021-07-06 00:20:21 +00:00
|
|
|
amount += 1;
|
|
|
|
} catch (e) {
|
|
|
|
logger.error(e);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return amount;
|
|
|
|
} else if (data.type === "stats") {
|
|
|
|
return await this.getRunning();
|
|
|
|
}
|
|
|
|
} catch (err) {
|
2021-07-31 18:36:00 +00:00
|
|
|
return { err: typeof err === "string" ? err : err.message };
|
2021-07-06 00:20:21 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
shutdown(done) {
|
|
|
|
done();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-08-19 14:19:14 +00:00
|
|
|
export default ImageWorker;
|