62 lines
1.5 KiB
JavaScript
62 lines
1.5 KiB
JavaScript
|
import { v4 } from "uuid";
|
||
|
import applyJob from "./k8s/kubernetes.js";
|
||
|
import buildJob from "./job-builder.js";
|
||
|
|
||
|
const maxJobs = process.env.MAX_JOBS ? parseInt(process.env.MAX_JOBS) : 3;
|
||
|
|
||
|
class JobManager {
|
||
|
constructor() {
|
||
|
this.clientMaxJobs = maxJobs;
|
||
|
this.clients = {};
|
||
|
}
|
||
|
|
||
|
getJob(clientId, jobId) {
|
||
|
return this.clients[clientId].jobs.find((j) => j.id === jobId);
|
||
|
}
|
||
|
|
||
|
getJobById(jobId) {
|
||
|
for (var client of Object.values(this.clients)) {
|
||
|
const job = client.jobs.find((j) => j.id === jobId);
|
||
|
if (!job) continue;
|
||
|
return job;
|
||
|
}
|
||
|
}
|
||
|
|
||
|
pushLog(jobId, log) {
|
||
|
const job = this.getJobById(jobId);
|
||
|
if (log instanceof Array) job.log.push(...log);
|
||
|
else job.log.push(log);
|
||
|
}
|
||
|
|
||
|
closeJob(jobId, exitcode) {
|
||
|
const job = this.getJobById(jobId);
|
||
|
job.exitcode = exitcode;
|
||
|
}
|
||
|
|
||
|
newJob(jobRequest, id) {
|
||
|
if (!jobRequest) throw Error("Request Must Be Object!");
|
||
|
if (!this.clients[id]) this.clients[id] = { jobs: [] };
|
||
|
const client = this.clients[id];
|
||
|
if (
|
||
|
client.jobs.filter((j) => j.exitcode === undefined).length >=
|
||
|
this.clientMaxJobs
|
||
|
)
|
||
|
throw Error("Client's Active Jobs Exceeded!");
|
||
|
|
||
|
const job = buildJob(jobRequest, id);
|
||
|
job.id = v4();
|
||
|
job.log = [];
|
||
|
this.clients[id].jobs.push(job);
|
||
|
applyJob(job);
|
||
|
return { ...job };
|
||
|
}
|
||
|
|
||
|
removeJob(clientId, id) {
|
||
|
this.clients[clientId].jobs = this.clients[clientId].jobs.filter(
|
||
|
(j) => j.id !== id
|
||
|
);
|
||
|
}
|
||
|
}
|
||
|
|
||
|
export default new JobManager();
|