fffleet 0.1.0 → 2.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/index.d.ts +95 -4
- package/package.json +1 -1
- package/server.d.ts +66 -2
- package/src/auth.js +304 -0
- package/src/client.js +45 -15
- package/src/contract.js +55 -6
- package/src/executor.js +89 -14
- package/src/http-api.js +53 -16
- package/src/http-stream.js +29 -0
- package/src/index.js +5 -2
- package/src/input-cache.js +104 -0
- package/src/job-manager.js +106 -9
- package/src/metrics.js +227 -0
- package/src/s3.js +290 -0
- package/src/server.js +7 -1
- package/src/sse.js +3 -2
- package/src/types.js +1 -0
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
// A worker-side cache of staged inputs, so a large source is downloaded once and not for every job.
|
|
2
|
+
|
|
3
|
+
import { createHash, randomBytes } from 'node:crypto';
|
|
4
|
+
import { copyFile, link, mkdir, readFile, readdir, rename, rm, stat, utimes, writeFile } from 'node:fs/promises';
|
|
5
|
+
import { dirname, join } from 'node:path';
|
|
6
|
+
|
|
7
|
+
/** "500", "20MB", "50GB" (decimal units) as a number of bytes. */
|
|
8
|
+
export function parseSize(value) {
|
|
9
|
+
if (typeof value === 'number') return value;
|
|
10
|
+
const m = String(value).trim().match(/^(\d+(?:\.\d+)?)\s*(b|kb|mb|gb|tb)?$/i);
|
|
11
|
+
if (!m) throw new Error(`invalid size "${value}" (use for example 500MB or 50GB)`);
|
|
12
|
+
const unit = { b: 1, kb: 1e3, mb: 1e6, gb: 1e9, tb: 1e12 }[(m[2] ?? 'b').toLowerCase()];
|
|
13
|
+
return Math.round(Number(m[1]) * unit);
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* @param {object} opts
|
|
18
|
+
* @param {string} opts.dir Where cached files live.
|
|
19
|
+
* @param {number} [opts.maxBytes] Least recently used files are removed above this. Default 20 GB.
|
|
20
|
+
*/
|
|
21
|
+
export function createInputCache({ dir, maxBytes = 20e9 }) {
|
|
22
|
+
const hashOf = key => createHash('sha256').update(key).digest('hex').slice(0, 40);
|
|
23
|
+
const stats = { hits: 0, misses: 0 };
|
|
24
|
+
|
|
25
|
+
async function place(entry, target) {
|
|
26
|
+
await mkdir(dirname(target), { recursive: true });
|
|
27
|
+
await rm(target, { force: true });
|
|
28
|
+
try {
|
|
29
|
+
await link(entry, target);
|
|
30
|
+
} catch {
|
|
31
|
+
await copyFile(entry, target); // another file system, or no hard links
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
async function evict(keep) {
|
|
36
|
+
let names;
|
|
37
|
+
try {
|
|
38
|
+
names = (await readdir(dir)).filter(n => n.endsWith('.json'));
|
|
39
|
+
} catch {
|
|
40
|
+
return;
|
|
41
|
+
}
|
|
42
|
+
const entries = [];
|
|
43
|
+
let total = 0;
|
|
44
|
+
for (const n of names) {
|
|
45
|
+
const base = n.slice(0, -5);
|
|
46
|
+
try {
|
|
47
|
+
const [m, f] = await Promise.all([stat(join(dir, n)), stat(join(dir, `${base}.bin`))]);
|
|
48
|
+
entries.push({ base, used: m.mtimeMs, size: f.size });
|
|
49
|
+
total += f.size;
|
|
50
|
+
} catch {
|
|
51
|
+
// half-written or already removed
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
entries.sort((a, b) => a.used - b.used);
|
|
55
|
+
for (const e of entries) {
|
|
56
|
+
if (total <= maxBytes) break;
|
|
57
|
+
if (e.base === keep) continue;
|
|
58
|
+
await rm(join(dir, `${e.base}.bin`), { force: true });
|
|
59
|
+
await rm(join(dir, `${e.base}.json`), { force: true });
|
|
60
|
+
total -= e.size;
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
return {
|
|
65
|
+
stats,
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Puts the file for `key` at `target`: from the cache when its `validator` (an ETag or similar) still
|
|
69
|
+
* matches, else by calling `download(path)` and keeping the result. Hard-links, so no copy is made.
|
|
70
|
+
* @returns {Promise<'hit' | 'miss'>}
|
|
71
|
+
*/
|
|
72
|
+
async stage({ key, validator, target, download }) {
|
|
73
|
+
const base = hashOf(key);
|
|
74
|
+
const entry = join(dir, `${base}.bin`);
|
|
75
|
+
const metaPath = join(dir, `${base}.json`);
|
|
76
|
+
await mkdir(dir, { recursive: true });
|
|
77
|
+
try {
|
|
78
|
+
const meta = JSON.parse(await readFile(metaPath, 'utf8'));
|
|
79
|
+
if (meta.validator === validator && (await stat(entry)).size === meta.size) {
|
|
80
|
+
const now = new Date();
|
|
81
|
+
await utimes(metaPath, now, now).catch(() => {});
|
|
82
|
+
await place(entry, target);
|
|
83
|
+
stats.hits++;
|
|
84
|
+
return 'hit';
|
|
85
|
+
}
|
|
86
|
+
} catch {
|
|
87
|
+
// not cached yet
|
|
88
|
+
}
|
|
89
|
+
const part = join(dir, `${base}.${randomBytes(4).toString('hex')}.part`);
|
|
90
|
+
try {
|
|
91
|
+
await download(part);
|
|
92
|
+
const { size } = await stat(part);
|
|
93
|
+
await rename(part, entry);
|
|
94
|
+
await writeFile(metaPath, JSON.stringify({ key, validator, size }));
|
|
95
|
+
} finally {
|
|
96
|
+
await rm(part, { force: true });
|
|
97
|
+
}
|
|
98
|
+
await place(entry, target);
|
|
99
|
+
stats.misses++;
|
|
100
|
+
await evict(base);
|
|
101
|
+
return 'miss';
|
|
102
|
+
},
|
|
103
|
+
};
|
|
104
|
+
}
|
package/src/job-manager.js
CHANGED
|
@@ -1,8 +1,12 @@
|
|
|
1
1
|
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import { PassThrough } from 'node:stream';
|
|
3
|
+
import { EventEmitter } from 'node:events';
|
|
2
4
|
import { mkdir, rm } from 'node:fs/promises';
|
|
3
|
-
import { tmpdir } from 'node:os';
|
|
5
|
+
import { availableParallelism, tmpdir } from 'node:os';
|
|
4
6
|
import { join } from 'node:path';
|
|
5
|
-
import { canonicalJson, parseSpec } from './contract.js';
|
|
7
|
+
import { KINDS, canonicalJson, implicitRequirements, parseSpec } from './contract.js';
|
|
8
|
+
import { createInputCache, parseSize } from './input-cache.js';
|
|
9
|
+
import { createS3Client } from './s3.js';
|
|
6
10
|
import { runFfmpegJob } from './executor.js';
|
|
7
11
|
import { FleetError, JobRecord, byPriority, pruneFinished } from './job-record.js';
|
|
8
12
|
|
|
@@ -13,11 +17,15 @@ import { FleetError, JobRecord, byPriority, pruneFinished } from './job-record.j
|
|
|
13
17
|
*
|
|
14
18
|
* Slots: `{ default: 2, stream: 1 }` means two jobs of any class plus one extra slot
|
|
15
19
|
* reserved for class "stream". A class without its own pool uses "default".
|
|
20
|
+
*
|
|
21
|
+
* Events: 'job' (record) for every new job, 'transfer' ({ direction: 'in' | 'out', scheme, bytes })
|
|
22
|
+
* after an input is staged or an output uploaded.
|
|
16
23
|
*/
|
|
17
|
-
export class JobManager {
|
|
24
|
+
export class JobManager extends EventEmitter {
|
|
18
25
|
/**
|
|
19
26
|
* @param {object} [opts]
|
|
20
|
-
* @param {Record<string, number>} [opts.slots]
|
|
27
|
+
* @param {Record<string, number> | string} [opts.slots] Pools, or 'auto' / 'auto:<cores per job>' to size them from this machine's CPUs.
|
|
28
|
+
* @param {('batch' | 'stream')[]} [opts.kinds] Job kinds this runner accepts (both by default).
|
|
21
29
|
* @param {string} [opts.workRoot]
|
|
22
30
|
* @param {string} [opts.ffmpegPath]
|
|
23
31
|
* @param {number} [opts.maxQueued]
|
|
@@ -26,9 +34,12 @@ export class JobManager {
|
|
|
26
34
|
* @param {Record<string, Function>} [opts.executors] type -> (spec, runtime) => Promise<result>
|
|
27
35
|
* @param {string} [opts.workerId]
|
|
28
36
|
* @param {typeof fetch} [opts.fetch]
|
|
37
|
+
* @param {object | null} [opts.s3] S3 settings (see s3ConfigFromEnv) or a client; enables s3: URIs.
|
|
38
|
+
* @param {{ dir: string, maxBytes?: number | string } | null} [opts.cache] Keeps staged s3: and http(s): inputs between jobs (least recently used removed above maxBytes, default 20 GB).
|
|
29
39
|
*/
|
|
30
40
|
constructor({
|
|
31
41
|
slots = { default: 2 },
|
|
42
|
+
kinds = KINDS,
|
|
32
43
|
workRoot = join(tmpdir(), 'fffleet'),
|
|
33
44
|
ffmpegPath = 'ffmpeg',
|
|
34
45
|
maxQueued = 1000,
|
|
@@ -37,8 +48,12 @@ export class JobManager {
|
|
|
37
48
|
executors = {},
|
|
38
49
|
workerId = null,
|
|
39
50
|
fetch: fetchImpl,
|
|
51
|
+
s3 = null,
|
|
52
|
+
cache = null,
|
|
40
53
|
} = {}) {
|
|
41
|
-
|
|
54
|
+
super();
|
|
55
|
+
this.kinds = normalizeKinds(kinds);
|
|
56
|
+
this.slots = normalizeSlots(slots, { kinds: this.kinds });
|
|
42
57
|
this.used = Object.fromEntries(Object.keys(this.slots).map(k => [k, 0]));
|
|
43
58
|
this.workRoot = workRoot;
|
|
44
59
|
this.ffmpegPath = ffmpegPath;
|
|
@@ -48,6 +63,8 @@ export class JobManager {
|
|
|
48
63
|
this.executors = { ffmpeg: runFfmpegJob, ...executors };
|
|
49
64
|
this.workerId = workerId;
|
|
50
65
|
this.fetch = fetchImpl;
|
|
66
|
+
this.cache = cache ? createInputCache({ dir: cache.dir, maxBytes: cache.maxBytes === undefined ? undefined : parseSize(cache.maxBytes) }) : null;
|
|
67
|
+
this.s3 = !s3 ? null : typeof s3.getFile === 'function' ? s3 : createS3Client({ fetch: fetchImpl, ...s3 });
|
|
51
68
|
/** @type {Map<string, JobRecord & { run?: any }>} */
|
|
52
69
|
this.jobs = new Map();
|
|
53
70
|
/** @type {JobRecord[]} */
|
|
@@ -76,9 +93,15 @@ export class JobManager {
|
|
|
76
93
|
}
|
|
77
94
|
return { created: false, job: existing.snapshot() };
|
|
78
95
|
}
|
|
96
|
+
if (!this.kinds.includes(spec.kind)) {
|
|
97
|
+
throw new FleetError('UNSUPPORTED_KIND', `this runner only takes ${this.kinds.join(' and ')} jobs`, { status: 422 });
|
|
98
|
+
}
|
|
79
99
|
if (!this.executors[spec.type]) {
|
|
80
100
|
throw new FleetError('UNSUPPORTED_TYPE', `no executor for job type "${spec.type}"`, { status: 422 });
|
|
81
101
|
}
|
|
102
|
+
if (!this.s3 && implicitRequirements(spec).includes('scheme:s3')) {
|
|
103
|
+
throw new FleetError('UNSUPPORTED_SCHEME', 's3: URIs need S3 credentials on this runner', { status: 422 });
|
|
104
|
+
}
|
|
82
105
|
const pool = this.poolFor(spec.class);
|
|
83
106
|
if (this.slots[pool] === undefined || this.slots[pool] === 0) {
|
|
84
107
|
throw new FleetError('NO_SLOTS', `no slot pool for class "${spec.class}"`, { status: 422 });
|
|
@@ -89,9 +112,11 @@ export class JobManager {
|
|
|
89
112
|
|
|
90
113
|
pruneFinished(this.jobs, this.keepFinished);
|
|
91
114
|
const record = new JobRecord(spec);
|
|
115
|
+
if (spec.stdout) record.stdoutPipe = new PassThrough();
|
|
92
116
|
this.jobs.set(spec.id, record);
|
|
93
117
|
this.queue.push(record);
|
|
94
118
|
this.queue.sort(byPriority);
|
|
119
|
+
this.emit('job', record);
|
|
95
120
|
this.pump();
|
|
96
121
|
return { created: true, queued: this.queue.includes(record), job: record.snapshot() };
|
|
97
122
|
}
|
|
@@ -124,6 +149,7 @@ export class JobManager {
|
|
|
124
149
|
if (idx >= 0) {
|
|
125
150
|
this.queue.splice(idx, 1);
|
|
126
151
|
record.push({ state: 'cancelled', error: { code: 'CANCELLED', message: 'cancelled before it started' } });
|
|
152
|
+
record.stdoutPipe?.end();
|
|
127
153
|
return record.snapshot();
|
|
128
154
|
}
|
|
129
155
|
record.run?.abort.abort(new FleetError('CANCELLED', 'cancelled'));
|
|
@@ -141,6 +167,30 @@ export class JobManager {
|
|
|
141
167
|
return { bytes: Buffer.byteLength(data) };
|
|
142
168
|
}
|
|
143
169
|
|
|
170
|
+
/** Closes a running job's stdin (EOF to ffmpeg), e.g. after sending a whole input. */
|
|
171
|
+
async closeStdin(id) {
|
|
172
|
+
const record = this.jobs.get(id);
|
|
173
|
+
if (!record) throw new FleetError('NOT_FOUND', `job ${id} not found`, { status: 404 });
|
|
174
|
+
if (!record.spec.stdin) throw new FleetError('NO_STDIN', 'job was not started with stdin: true', { status: 409 });
|
|
175
|
+
const stdin = record.run?.stdin;
|
|
176
|
+
if (!stdin || record.final) throw new FleetError('NOT_RUNNING', 'job is not running', { status: 409 });
|
|
177
|
+
await new Promise(resolve => stdin.end(resolve));
|
|
178
|
+
return { closed: true };
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/**
|
|
182
|
+
* Opens a stdout job's output as a Readable (one reader per job; it ends when the job does).
|
|
183
|
+
* Until a reader is attached ffmpeg stalls once the pipe's buffer is full.
|
|
184
|
+
*/
|
|
185
|
+
openStdout(id) {
|
|
186
|
+
const record = this.jobs.get(id);
|
|
187
|
+
if (!record) throw new FleetError('NOT_FOUND', `job ${id} not found`, { status: 404 });
|
|
188
|
+
if (!record.stdoutPipe) throw new FleetError('NO_STDOUT', 'job was not started with stdout: true', { status: 409 });
|
|
189
|
+
if (record.stdoutOpened) throw new FleetError('STDOUT_TAKEN', 'stdout already has a reader', { status: 409 });
|
|
190
|
+
record.stdoutOpened = true;
|
|
191
|
+
return record.stdoutPipe;
|
|
192
|
+
}
|
|
193
|
+
|
|
144
194
|
stats() {
|
|
145
195
|
const pools = Object.fromEntries(Object.keys(this.slots).map(k => [k, { total: this.slots[k], used: this.used[k] }]));
|
|
146
196
|
return { pools, queued: this.queue.length, running: Object.values(this.used).reduce((a, b) => a + b, 0) };
|
|
@@ -166,7 +216,7 @@ export class JobManager {
|
|
|
166
216
|
|
|
167
217
|
start(record, pool) {
|
|
168
218
|
const abort = new AbortController();
|
|
169
|
-
const run = { abort, stdin: null, done: null };
|
|
219
|
+
const run = { abort, stdin: null, done: null, pid: null };
|
|
170
220
|
record.run = run;
|
|
171
221
|
let timer = null;
|
|
172
222
|
if (record.spec.timeoutMs) {
|
|
@@ -180,7 +230,10 @@ export class JobManager {
|
|
|
180
230
|
signal: abort.signal,
|
|
181
231
|
ffmpegPath: this.ffmpegPath,
|
|
182
232
|
fetch: this.fetch,
|
|
183
|
-
|
|
233
|
+
s3: this.s3,
|
|
234
|
+
cache: this.cache,
|
|
235
|
+
setState: (state, extra) => {
|
|
236
|
+
if (extra?.pid) run.pid = extra.pid;
|
|
184
237
|
if (!abort.signal.aborted) record.push({ state, ...(this.workerId ? { workerId: this.workerId } : {}) });
|
|
185
238
|
},
|
|
186
239
|
progress: p => {
|
|
@@ -195,6 +248,12 @@ export class JobManager {
|
|
|
195
248
|
attachStdin: s => {
|
|
196
249
|
run.stdin = s;
|
|
197
250
|
},
|
|
251
|
+
attachStdout: s => {
|
|
252
|
+
if (record.stdoutPipe) s.pipe(record.stdoutPipe, { end: false });
|
|
253
|
+
},
|
|
254
|
+
transfer: (direction, scheme, bytes) => {
|
|
255
|
+
if (bytes > 0) this.emit('transfer', { direction, scheme, bytes });
|
|
256
|
+
},
|
|
198
257
|
};
|
|
199
258
|
|
|
200
259
|
run.done = (async () => {
|
|
@@ -215,7 +274,9 @@ export class JobManager {
|
|
|
215
274
|
});
|
|
216
275
|
} finally {
|
|
217
276
|
clearTimeout(timer);
|
|
277
|
+
record.stdoutPipe?.end();
|
|
218
278
|
run.stdin = null;
|
|
279
|
+
run.pid = null;
|
|
219
280
|
this.used[pool]--;
|
|
220
281
|
await rm(workDir, { recursive: true, force: true }).catch(() => {});
|
|
221
282
|
if (!this.closed) this.pump();
|
|
@@ -224,8 +285,44 @@ export class JobManager {
|
|
|
224
285
|
}
|
|
225
286
|
}
|
|
226
287
|
|
|
227
|
-
/** Parses "
|
|
228
|
-
export function
|
|
288
|
+
/** Parses "batch", "stream", "batch,stream" or an array into a list of job kinds. */
|
|
289
|
+
export function normalizeKinds(kinds) {
|
|
290
|
+
const list = (typeof kinds === 'string' ? kinds.split(',') : kinds ?? []).map(k => String(k).trim()).filter(Boolean);
|
|
291
|
+
if (!list.length) return [...KINDS];
|
|
292
|
+
for (const k of list) if (!KINDS.includes(k)) throw new Error(`invalid job kind "${k}"; kinds are ${KINDS.join(' and ')}`);
|
|
293
|
+
return [...new Set(list)];
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
/**
|
|
297
|
+
* Slot pools sized from the CPU count. A batch job (an encode) is assumed to use about two cores,
|
|
298
|
+
* a stream job (a relay or a light live encode) about one; `auto:N` sets the cores per slot.
|
|
299
|
+
*
|
|
300
|
+
* - batch and stream: `default` for batch work plus a separate `stream` pool of a quarter of the cores.
|
|
301
|
+
* - batch only: `default` = cores / 2.
|
|
302
|
+
* - stream only: `default` = cores.
|
|
303
|
+
*
|
|
304
|
+
* @param {{ cpus?: number, kinds?: string[], coresPerSlot?: number }} [opts]
|
|
305
|
+
*/
|
|
306
|
+
export function autoSlots({ cpus = availableParallelism(), kinds = KINDS, coresPerSlot } = {}) {
|
|
307
|
+
const streamOnly = kinds.length === 1 && kinds[0] === 'stream';
|
|
308
|
+
const per = coresPerSlot ?? (streamOnly ? 1 : 2);
|
|
309
|
+
const slots = { default: Math.max(1, Math.floor(cpus / per)) };
|
|
310
|
+
if (kinds.includes('batch') && kinds.includes('stream') && coresPerSlot === undefined) slots.stream = Math.max(1, Math.floor(cpus / 4));
|
|
311
|
+
return slots;
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
/**
|
|
315
|
+
* Parses "default=2,stream=1", "auto", "auto:1" or an object into { pool: count }.
|
|
316
|
+
* @param {string | Record<string, number | string>} slots
|
|
317
|
+
* @param {{ kinds?: string[], cpus?: number }} [opts] used by "auto"
|
|
318
|
+
*/
|
|
319
|
+
export function normalizeSlots(slots, { kinds = KINDS, cpus } = {}) {
|
|
320
|
+
const auto = typeof slots === 'string' ? slots.trim().match(/^auto(?::(\d+(?:\.\d+)?))?$/) : null;
|
|
321
|
+
if (auto) {
|
|
322
|
+
const coresPerSlot = auto[1] === undefined ? undefined : Number(auto[1]);
|
|
323
|
+
if (coresPerSlot !== undefined && !(coresPerSlot > 0)) throw new Error(`invalid slots "${slots}": cores per slot must be above 0`);
|
|
324
|
+
return autoSlots({ kinds, cpus, coresPerSlot });
|
|
325
|
+
}
|
|
229
326
|
const obj = typeof slots === 'string'
|
|
230
327
|
? Object.fromEntries(slots.split(',').map(s => s.trim()).filter(Boolean).map(s => s.split('=').map(x => x.trim())))
|
|
231
328
|
: slots;
|
package/src/metrics.js
ADDED
|
@@ -0,0 +1,227 @@
|
|
|
1
|
+
// Prometheus metrics in the text exposition format (0.0.4). No dependencies.
|
|
2
|
+
|
|
3
|
+
import { readFile, statfs } from 'node:fs/promises';
|
|
4
|
+
import { cpus, freemem, loadavg, totalmem } from 'node:os';
|
|
5
|
+
|
|
6
|
+
export const METRICS_CONTENT_TYPE = 'text/plain; version=0.0.4; charset=utf-8';
|
|
7
|
+
const DURATION_BUCKETS = [0.1, 0.5, 1, 5, 15, 60, 300, 900, 3600, 14400];
|
|
8
|
+
|
|
9
|
+
const escapeLabel = v => String(v).replace(/\\/g, '\\\\').replace(/\n/g, '\\n').replace(/"/g, '\\"');
|
|
10
|
+
const formatValue = v => (Number.isNaN(v) ? 'NaN' : v === Infinity ? '+Inf' : v === -Infinity ? '-Inf' : String(v));
|
|
11
|
+
|
|
12
|
+
function labelString(names, values, extra = '') {
|
|
13
|
+
const parts = names.map((n, i) => `${n}="${escapeLabel(values[i] ?? '')}"`);
|
|
14
|
+
if (extra) parts.push(extra);
|
|
15
|
+
return parts.length ? `{${parts.join(',')}}` : '';
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
class Metric {
|
|
19
|
+
constructor(type, name, help, labelNames = []) {
|
|
20
|
+
this.type = type;
|
|
21
|
+
this.name = name;
|
|
22
|
+
this.help = help;
|
|
23
|
+
this.labelNames = labelNames;
|
|
24
|
+
/** @type {Map<string, { values: string[], value: any }>} */
|
|
25
|
+
this.series = new Map();
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
slot(labels = {}) {
|
|
29
|
+
const values = this.labelNames.map(n => String(labels[n] ?? ''));
|
|
30
|
+
const key = values.join('\u0000');
|
|
31
|
+
let s = this.series.get(key);
|
|
32
|
+
if (!s) {
|
|
33
|
+
s = { values, value: this.initial() };
|
|
34
|
+
this.series.set(key, s);
|
|
35
|
+
}
|
|
36
|
+
return s;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
initial() {
|
|
40
|
+
return 0;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** Drops every series (gauges that are rebuilt on each scrape). */
|
|
44
|
+
reset() {
|
|
45
|
+
this.series.clear();
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
render() {
|
|
49
|
+
const lines = [`# HELP ${this.name} ${this.help}`, `# TYPE ${this.name} ${this.type}`];
|
|
50
|
+
for (const s of this.series.values()) lines.push(...this.renderSeries(s));
|
|
51
|
+
return lines.join('\n');
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
renderSeries(s) {
|
|
55
|
+
return [`${this.name}${labelString(this.labelNames, s.values)} ${formatValue(s.value)}`];
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
class Counter extends Metric {
|
|
60
|
+
inc(labels, n = 1) {
|
|
61
|
+
this.slot(labels).value += n;
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
class Gauge extends Metric {
|
|
66
|
+
set(labels, v) {
|
|
67
|
+
this.slot(labels).value = v;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
inc(labels, n = 1) {
|
|
71
|
+
this.slot(labels).value += n;
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
class Histogram extends Metric {
|
|
76
|
+
constructor(name, help, labelNames, buckets = DURATION_BUCKETS) {
|
|
77
|
+
super('histogram', name, help, labelNames);
|
|
78
|
+
this.buckets = [...buckets].sort((a, b) => a - b);
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
initial() {
|
|
82
|
+
return { counts: new Array(this.buckets.length).fill(0), sum: 0, count: 0 };
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
observe(labels, v) {
|
|
86
|
+
const h = this.slot(labels).value;
|
|
87
|
+
for (let i = 0; i < this.buckets.length; i++) if (v <= this.buckets[i]) h.counts[i]++;
|
|
88
|
+
h.sum += v;
|
|
89
|
+
h.count++;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
renderSeries(s) {
|
|
93
|
+
const h = s.value;
|
|
94
|
+
const lines = this.buckets.map((b, i) => `${this.name}_bucket${labelString(this.labelNames, s.values, `le="${b}"`)} ${h.counts[i]}`);
|
|
95
|
+
lines.push(`${this.name}_bucket${labelString(this.labelNames, s.values, 'le="+Inf"')} ${h.count}`);
|
|
96
|
+
lines.push(`${this.name}_sum${labelString(this.labelNames, s.values)} ${h.sum}`);
|
|
97
|
+
lines.push(`${this.name}_count${labelString(this.labelNames, s.values)} ${h.count}`);
|
|
98
|
+
return lines;
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** A set of metrics plus collectors that refresh gauges right before each scrape. */
|
|
103
|
+
export class Registry {
|
|
104
|
+
constructor() {
|
|
105
|
+
/** @type {Metric[]} */
|
|
106
|
+
this.metrics = [];
|
|
107
|
+
/** @type {(() => void | Promise<void>)[]} */
|
|
108
|
+
this.collectors = [];
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
counter(name, help, labelNames) {
|
|
112
|
+
return this.add(new Counter('counter', name, help, labelNames));
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
gauge(name, help, labelNames) {
|
|
116
|
+
return this.add(new Gauge('gauge', name, help, labelNames));
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
histogram(name, help, labelNames, buckets) {
|
|
120
|
+
return this.add(new Histogram(name, help, labelNames, buckets));
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
add(metric) {
|
|
124
|
+
this.metrics.push(metric);
|
|
125
|
+
return metric;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
collect(fn) {
|
|
129
|
+
this.collectors.push(fn);
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
async render() {
|
|
133
|
+
for (const fn of this.collectors) await fn();
|
|
134
|
+
return `${this.metrics.map(m => m.render()).join('\n')}\n`;
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
const seconds = (from, to) => (Date.parse(to) - Date.parse(from)) / 1000;
|
|
139
|
+
|
|
140
|
+
/**
|
|
141
|
+
* Job metrics shared by the orchestrator and the worker. Call `track(record)` once per new job.
|
|
142
|
+
* @param {Registry} registry
|
|
143
|
+
* @param {() => Iterable<import('./job-record.js').JobRecord>} records The jobs currently known.
|
|
144
|
+
*/
|
|
145
|
+
export function jobMetrics(registry, records) {
|
|
146
|
+
const submitted = registry.counter('fffleet_jobs_submitted_total', 'Jobs accepted.', ['owner', 'class', 'kind']);
|
|
147
|
+
const finished = registry.counter('fffleet_jobs_finished_total', 'Jobs that ended, by final state and error code.', ['owner', 'class', 'kind', 'state', 'code']);
|
|
148
|
+
const wait = registry.histogram('fffleet_job_wait_seconds', 'Time from submit until ffmpeg started.', ['class']);
|
|
149
|
+
const duration = registry.histogram('fffleet_job_run_seconds', 'Time from start until the job ended.', ['class', 'kind', 'state']);
|
|
150
|
+
const current = registry.gauge('fffleet_jobs', 'Unfinished jobs by state.', ['owner', 'class', 'state']);
|
|
151
|
+
registry.collect(() => {
|
|
152
|
+
current.reset();
|
|
153
|
+
for (const r of records()) if (!r.final) current.inc({ owner: r.spec.owner, class: r.spec.class, state: r.state });
|
|
154
|
+
});
|
|
155
|
+
return {
|
|
156
|
+
track(record) {
|
|
157
|
+
const { owner, kind } = record.spec;
|
|
158
|
+
const cls = record.spec.class;
|
|
159
|
+
submitted.inc({ owner, class: cls, kind });
|
|
160
|
+
let started = false;
|
|
161
|
+
record.subscribe(record.seq, e => {
|
|
162
|
+
if (e.state === 'running' && !started && record.startedAt) {
|
|
163
|
+
started = true;
|
|
164
|
+
wait.observe({ class: cls }, seconds(record.createdAt, record.startedAt));
|
|
165
|
+
}
|
|
166
|
+
if (['succeeded', 'failed', 'cancelled'].includes(e.state)) {
|
|
167
|
+
finished.inc({ owner, class: cls, kind, state: e.state, code: e.error?.code ?? '' });
|
|
168
|
+
if (record.startedAt) duration.observe({ class: cls, kind, state: e.state }, seconds(record.startedAt, record.finishedAt));
|
|
169
|
+
}
|
|
170
|
+
});
|
|
171
|
+
},
|
|
172
|
+
};
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/** process_* metrics of this Node process. */
|
|
176
|
+
export function processMetrics(registry) {
|
|
177
|
+
const cpu = registry.gauge('process_cpu_seconds_total', 'User and system CPU time of this process.');
|
|
178
|
+
const rss = registry.gauge('process_resident_memory_bytes', 'Resident memory of this process.');
|
|
179
|
+
const start = registry.gauge('process_start_time_seconds', 'Start time of this process since the Unix epoch.');
|
|
180
|
+
const startedAt = Date.now() / 1000 - process.uptime();
|
|
181
|
+
cpu.type = 'counter';
|
|
182
|
+
registry.collect(() => {
|
|
183
|
+
const u = process.cpuUsage();
|
|
184
|
+
cpu.set({}, (u.user + u.system) / 1e6);
|
|
185
|
+
rss.set({}, process.memoryUsage.rss());
|
|
186
|
+
start.set({}, Math.round(startedAt));
|
|
187
|
+
});
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
/** Host metrics a worker reports: CPUs, load, memory and free space under `dir`. */
|
|
191
|
+
export function hostMetrics(registry, dir) {
|
|
192
|
+
const ncpu = registry.gauge('fffleet_host_cpus', 'CPUs on this host.');
|
|
193
|
+
const load = registry.gauge('fffleet_host_load1', 'One-minute load average.');
|
|
194
|
+
const memTotal = registry.gauge('fffleet_host_memory_total_bytes', 'Memory on this host.');
|
|
195
|
+
const memFree = registry.gauge('fffleet_host_memory_available_bytes', 'Memory available on this host.');
|
|
196
|
+
const disk = registry.gauge('fffleet_workdir_free_bytes', 'Free space in the work directory.');
|
|
197
|
+
registry.collect(async () => {
|
|
198
|
+
ncpu.set({}, cpus().length);
|
|
199
|
+
load.set({}, loadavg()[0]);
|
|
200
|
+
memTotal.set({}, totalmem());
|
|
201
|
+
memFree.set({}, freemem());
|
|
202
|
+
disk.reset();
|
|
203
|
+
if (dir) {
|
|
204
|
+
try {
|
|
205
|
+
const s = await statfs(dir);
|
|
206
|
+
disk.set({}, s.bavail * s.bsize);
|
|
207
|
+
} catch {
|
|
208
|
+
// The work directory may not exist until the first job.
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
});
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
const CLK_TCK = 100;
|
|
215
|
+
const PAGE_SIZE = 4096;
|
|
216
|
+
|
|
217
|
+
/** CPU seconds and resident bytes of a process, from /proc (Linux only; null elsewhere). */
|
|
218
|
+
export async function procStats(pid) {
|
|
219
|
+
try {
|
|
220
|
+
const stat = await readFile(`/proc/${pid}/stat`, 'utf8');
|
|
221
|
+
// Fields after the parenthesised command name; utime and stime are fields 14 and 15, rss is 24.
|
|
222
|
+
const f = stat.slice(stat.lastIndexOf(')') + 2).split(' ');
|
|
223
|
+
return { cpuSeconds: (Number(f[11]) + Number(f[12])) / CLK_TCK, rssBytes: Number(f[21]) * PAGE_SIZE };
|
|
224
|
+
} catch {
|
|
225
|
+
return null;
|
|
226
|
+
}
|
|
227
|
+
}
|