fffleet-orchestrator 2.6.0 → 2.8.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 +6 -0
- package/bin/fffleet-orchestrator.js +6 -1
- package/package.json +2 -2
- package/src/config.js +9 -5
- package/src/orchestrator.js +20 -6
- package/src/placement.js +52 -0
package/README.md
CHANGED
|
@@ -43,3 +43,9 @@ License: EUPL-1.2
|
|
|
43
43
|
## Dashboard
|
|
44
44
|
|
|
45
45
|
The orchestrator serves a small dashboard at `/ui/` (set `ui: false` in the library options to turn it off). It has no build step and no data of its own: the page asks you to log in with a client that has the `admin` scope, gets a token from `POST /v1/auth/token`, and then polls `GET /v1/workers` and `GET /v1/jobs` once a second. It shows the number of nodes (distinct worker hosts), workers, slots in use, running and queued jobs, the worker kinds (batch, stream) and pools, and the running jobs. The token is kept in `sessionStorage` only, so it ends with the tab.
|
|
46
|
+
|
|
47
|
+
## Placement rules
|
|
48
|
+
|
|
49
|
+
Callers need not set `workerPreference` on every job: the config file's `placement` list orders workers by job `type`,
|
|
50
|
+
`kind`, `class` or required capability (first matching rule wins; `others: true` lets unlisted workers serve after the
|
|
51
|
+
listed ones; a job's own `workerPreference` overrides). Deployment configs live in the piecosystem repository (`deploy/fleet-pi/`).
|
|
@@ -13,10 +13,14 @@ if (process.argv[2] === 'add-client') {
|
|
|
13
13
|
}
|
|
14
14
|
|
|
15
15
|
let scaling = null;
|
|
16
|
+
let placement = [];
|
|
16
17
|
const configPath = env.FFFLEET_CONFIG || (process.argv[2] === '--config' ? process.argv[3] : null);
|
|
17
18
|
if (configPath) {
|
|
18
19
|
try {
|
|
19
|
-
|
|
20
|
+
const config = loadConfig(configPath);
|
|
21
|
+
placement = config.placement;
|
|
22
|
+
// Without pools there is nothing to scale: workers just register (a Pi with static workers, for example).
|
|
23
|
+
scaling = config.pools.length ? config : null;
|
|
20
24
|
} catch (err) {
|
|
21
25
|
console.error(`[fffleet-orchestrator] ${err.message}`);
|
|
22
26
|
process.exit(1);
|
|
@@ -25,6 +29,7 @@ if (configPath) {
|
|
|
25
29
|
|
|
26
30
|
const orchestrator = createOrchestrator({
|
|
27
31
|
scaling,
|
|
32
|
+
placement,
|
|
28
33
|
port: Number(env.PORT ?? 5000),
|
|
29
34
|
host: env.HOST ?? '0.0.0.0',
|
|
30
35
|
token: env.FFFLEET_TOKEN || null,
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "fffleet-orchestrator",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.8.0",
|
|
4
4
|
"description": "fffleet orchestrator: schedules ffmpeg jobs across a pool of fffleet workers",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./src/orchestrator.js",
|
|
@@ -21,7 +21,7 @@
|
|
|
21
21
|
"test": "node --test test/*.test.js"
|
|
22
22
|
},
|
|
23
23
|
"dependencies": {
|
|
24
|
-
"fffleet": "^2.
|
|
24
|
+
"fffleet": "^2.8.0"
|
|
25
25
|
},
|
|
26
26
|
"keywords": [
|
|
27
27
|
"ffmpeg",
|
package/src/config.js
CHANGED
|
@@ -3,11 +3,12 @@
|
|
|
3
3
|
import { readFileSync } from 'node:fs';
|
|
4
4
|
import { KINDS, normalizeKinds, normalizeSlots } from 'fffleet';
|
|
5
5
|
import { parseYaml } from './yaml.js';
|
|
6
|
+
import { normalizePlacement } from './placement.js';
|
|
6
7
|
|
|
7
8
|
export const PROVIDERS = ['process', 'docker', 'hetzner'];
|
|
8
9
|
const DEFAULT_WORKER_IMAGE = 'ghcr.io/jsilvanus/fffleet-worker:latest';
|
|
9
10
|
|
|
10
|
-
const TOP_KEYS = ['publicUrl', 'autoscale', 'pools'];
|
|
11
|
+
const TOP_KEYS = ['publicUrl', 'autoscale', 'pools', 'placement'];
|
|
11
12
|
const AUTOSCALE_KEYS = ['id', 'interval', 'scaleUpAfter', 'idleAfter', 'bootTimeout', 'maxWorkers', 'joinSecret'];
|
|
12
13
|
const POOL_KEYS = ['name', 'provider', 'min', 'max', 'kinds', 'slots', 'slotsHint', 'capabilities', 'env', 'maxConcurrentCreates', 'idleAfter', 'process', 'docker', 'hetzner'];
|
|
13
14
|
const PROVIDER_KEYS = {
|
|
@@ -48,7 +49,7 @@ function onlyKeys(obj, allowed, where) {
|
|
|
48
49
|
|
|
49
50
|
/**
|
|
50
51
|
* Checks a parsed config and fills in defaults. Throws an Error that names the offending setting.
|
|
51
|
-
* @returns {{ publicUrl: string | null, autoscale: object, pools: object[] }}
|
|
52
|
+
* @returns {{ publicUrl: string | null, autoscale: object, pools: object[], placement: object[] }}
|
|
52
53
|
*/
|
|
53
54
|
export function normalizeConfig(raw, env = process.env) {
|
|
54
55
|
const doc = interpolateEnv(raw ?? {}, env);
|
|
@@ -69,9 +70,12 @@ export function normalizeConfig(raw, env = process.env) {
|
|
|
69
70
|
if (autoscale.interval < 100) throw new Error('autoscale.interval must be at least 100ms');
|
|
70
71
|
if (!(autoscale.maxWorkers >= 1)) throw new Error('autoscale.maxWorkers must be at least 1');
|
|
71
72
|
|
|
72
|
-
|
|
73
|
+
const placement = normalizePlacement(doc.placement);
|
|
74
|
+
const poolList = doc.pools ?? [];
|
|
75
|
+
if (!Array.isArray(poolList)) throw new Error('pools must be a list');
|
|
76
|
+
if (!poolList.length && !placement.length) throw new Error('config must list at least one pool or one placement rule');
|
|
73
77
|
const names = new Set();
|
|
74
|
-
const pools =
|
|
78
|
+
const pools = poolList.map((p, i) => {
|
|
75
79
|
const where = `pools[${i}]`;
|
|
76
80
|
onlyKeys(p, POOL_KEYS, where);
|
|
77
81
|
if (typeof p.name !== 'string' || !/^[a-z0-9][a-z0-9-]{0,30}$/.test(p.name)) throw new Error(`${where}.name must be lowercase letters, digits and "-" (for example "batch-cloud")`);
|
|
@@ -133,7 +137,7 @@ export function normalizeConfig(raw, env = process.env) {
|
|
|
133
137
|
|
|
134
138
|
const publicUrl = doc.publicUrl ? String(doc.publicUrl).replace(/\/+$/, '') : null;
|
|
135
139
|
if (!publicUrl && pools.some(p => p.provider !== 'process')) throw new Error('publicUrl is required when a pool uses the docker or hetzner provider (the address new workers use to reach this orchestrator)');
|
|
136
|
-
return { publicUrl, autoscale, pools };
|
|
140
|
+
return { publicUrl, autoscale, pools, placement };
|
|
137
141
|
}
|
|
138
142
|
|
|
139
143
|
/** Reads and checks a config file; `.json` is parsed as JSON, anything else as YAML. */
|
package/src/orchestrator.js
CHANGED
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
import { readFileSync } from 'node:fs';
|
|
2
2
|
import { createAutoscaler } from './autoscaler.js';
|
|
3
|
+
import { normalizePlacement, preferenceFor } from './placement.js';
|
|
3
4
|
import { createProviders } from './providers/index.js';
|
|
4
5
|
import { openSqliteJobStore } from './job-store.js';
|
|
5
6
|
import { serveUi } from './ui.js';
|
|
6
7
|
import { randomUUID } from 'node:crypto';
|
|
7
|
-
import { FleetError, JobRecord, byPriority, canonicalJson, followJobEvents, implicitRequirements, normalizeKinds, normalizeSlots, parseSpec, pruneFinished, satisfies } from 'fffleet';
|
|
8
|
+
import { FleetError, JobRecord, byPriority, canonicalJson, followJobEvents, implicitRequirements, normalizeKinds, normalizeSlots, parseSpec, pruneFinished, resolveVariant, satisfies } from 'fffleet';
|
|
8
9
|
import {
|
|
9
10
|
Registry, allowed, checkBearer, close, createApiHandler, createAuthenticator, createClientStore, createTokenSigner, createTokenVerifier,
|
|
10
11
|
bearerOf, getStream, issueToken, jobMetrics, listen, loadSigningKey, processMetrics, readBody, readJson, send, sendError,
|
|
@@ -31,6 +32,7 @@ const REDISPATCH_DELAY_MS = 500;
|
|
|
31
32
|
* @param {import('node:crypto').KeyObject | string | null} [opts.signingKey] Ed25519 key for tokens (KeyObject or PEM).
|
|
32
33
|
* @param {string | null} [opts.signingKeyFile] Where the signing key is kept; created when missing. Without it tokens die with the process.
|
|
33
34
|
* @param {number} [opts.tokenTtlSeconds]
|
|
35
|
+
* @param {object[]} [opts.placement] Worker preference rules by job type, kind or class (see placement.js and the README).
|
|
34
36
|
* @param {{ publicUrl: string | null, autoscale: object, pools: object[] } | null} [opts.scaling] Where to start more workers (see loadConfig). Without it the pool is whatever registers.
|
|
35
37
|
* @param {Record<string, object>} [opts.providers] Provider instances by pool name, replacing the built-in ones (tests).
|
|
36
38
|
* @param {Buffer | string | null} [opts.joinKey] Key the workers' join secrets derive from. Default: the signing key's file contents, else random.
|
|
@@ -56,6 +58,7 @@ export function createOrchestrator({
|
|
|
56
58
|
signingKeyFile = null,
|
|
57
59
|
tokenTtlSeconds = 3600,
|
|
58
60
|
scaling = null,
|
|
61
|
+
placement: placementRules = [],
|
|
59
62
|
providers: providerOverrides = {},
|
|
60
63
|
joinKey = null,
|
|
61
64
|
workerToken = null,
|
|
@@ -71,6 +74,7 @@ export function createOrchestrator({
|
|
|
71
74
|
ui = true,
|
|
72
75
|
log = () => {},
|
|
73
76
|
} = {}) {
|
|
77
|
+
const placement = normalizePlacement(placementRules);
|
|
74
78
|
/** @type {Map<string, Worker>} */
|
|
75
79
|
const workers = new Map();
|
|
76
80
|
/** @type {Map<string, Job>} */
|
|
@@ -164,7 +168,12 @@ export function createOrchestrator({
|
|
|
164
168
|
const pool = poolFor(worker, job.spec.class);
|
|
165
169
|
const total = worker.slots[pool] ?? 0;
|
|
166
170
|
return total > 0 && (worker.used[pool] ?? 0) < total
|
|
167
|
-
&& satisfies(worker.capabilities, implicitRequirements(job.spec)) && satisfies(worker.capabilities, job.spec.requires);
|
|
171
|
+
&& satisfies(worker.capabilities, implicitRequirements(specFor(job, worker).spec)) && satisfies(worker.capabilities, job.spec.requires);
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/** The spec a worker gets: the job's variant for that worker, or the base spec. */
|
|
175
|
+
function specFor(job, worker) {
|
|
176
|
+
return resolveVariant(job.spec, { workerId: worker.id, capabilities: worker.capabilities });
|
|
168
177
|
}
|
|
169
178
|
|
|
170
179
|
function load(worker) {
|
|
@@ -174,7 +183,11 @@ export function createOrchestrator({
|
|
|
174
183
|
|
|
175
184
|
function pump() {
|
|
176
185
|
for (const job of [...queue]) {
|
|
177
|
-
const
|
|
186
|
+
const preference = preferenceFor(placement, job.spec);
|
|
187
|
+
const rank = w => { const i = preference.workers.indexOf(w.id); return i < 0 ? Infinity : i; };
|
|
188
|
+
const candidates = [...workers.values()]
|
|
189
|
+
.filter(w => fits(w, job) && (!preference || preference.others || preference.workers.includes(w.id)))
|
|
190
|
+
.sort((a, b) => (preference ? (rank(a) === rank(b) ? 0 : rank(a) < rank(b) ? -1 : 1) : 0) || load(a) - load(b));
|
|
178
191
|
if (!candidates.length) continue;
|
|
179
192
|
queue.splice(queue.indexOf(job), 1);
|
|
180
193
|
dispatch(job, candidates[0]);
|
|
@@ -264,14 +277,15 @@ export function createOrchestrator({
|
|
|
264
277
|
job.pool = pool;
|
|
265
278
|
job.released = false;
|
|
266
279
|
job.assignedAt = Date.now();
|
|
267
|
-
|
|
280
|
+
const { spec, variant } = specFor(job, worker);
|
|
281
|
+
job.push({ state: 'assigned', workerId: worker.id, variant });
|
|
268
282
|
|
|
269
283
|
let res;
|
|
270
284
|
try {
|
|
271
285
|
res = await fetch(`${worker.url}/v1/jobs`, {
|
|
272
286
|
method: 'POST',
|
|
273
287
|
headers: workerHeaders(worker, { 'content-type': 'application/json' }),
|
|
274
|
-
body: JSON.stringify(
|
|
288
|
+
body: JSON.stringify(spec),
|
|
275
289
|
signal: AbortSignal.timeout(10000),
|
|
276
290
|
});
|
|
277
291
|
} catch (err) {
|
|
@@ -302,7 +316,7 @@ export function createOrchestrator({
|
|
|
302
316
|
release(job, false);
|
|
303
317
|
if (dropWorker) removeWorker(worker, null);
|
|
304
318
|
if (job.final) return;
|
|
305
|
-
job.push({ state: 'queued', workerId: null });
|
|
319
|
+
job.push({ state: 'queued', workerId: null, variant: null });
|
|
306
320
|
enqueue(job);
|
|
307
321
|
schedulePump(REDISPATCH_DELAY_MS);
|
|
308
322
|
}
|
package/src/placement.js
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
// Placement rules: which workers a kind of job prefers, in order, so callers need not know worker IDs.
|
|
2
|
+
|
|
3
|
+
const MATCH_KEYS = ['type', 'kind', 'class', 'requires'];
|
|
4
|
+
const RULE_KEYS = ['match', 'workers', 'others'];
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Checks the `placement` list of the config. Rules are tried in order and the first whose `match` fits wins.
|
|
8
|
+
* A rule: `{ match: { type?, kind?, class?, requires? }, workers: [ids], others?: boolean }`.
|
|
9
|
+
* @returns {{ match: object, workers: string[], others: boolean }[]}
|
|
10
|
+
*/
|
|
11
|
+
export function normalizePlacement(raw) {
|
|
12
|
+
if (raw === undefined || raw === null) return [];
|
|
13
|
+
if (!Array.isArray(raw)) throw new Error('placement must be a list of rules');
|
|
14
|
+
return raw.map((rule, i) => {
|
|
15
|
+
const where = `placement[${i}]`;
|
|
16
|
+
if (!rule || typeof rule !== 'object' || Array.isArray(rule)) throw new Error(`${where} must be a mapping`);
|
|
17
|
+
for (const k of Object.keys(rule)) if (!RULE_KEYS.includes(k)) throw new Error(`${where}: unknown setting "${k}" (known: ${RULE_KEYS.join(', ')})`);
|
|
18
|
+
const match = rule.match ?? {};
|
|
19
|
+
if (typeof match !== 'object' || Array.isArray(match)) throw new Error(`${where}.match must be a mapping`);
|
|
20
|
+
for (const k of Object.keys(match)) if (!MATCH_KEYS.includes(k)) throw new Error(`${where}.match: unknown setting "${k}" (known: ${MATCH_KEYS.join(', ')})`);
|
|
21
|
+
const requires = match.requires === undefined ? undefined : [].concat(match.requires).map(String);
|
|
22
|
+
for (const k of ['type', 'kind', 'class']) {
|
|
23
|
+
if (match[k] !== undefined && typeof match[k] !== 'string') throw new Error(`${where}.match.${k} must be a string`);
|
|
24
|
+
}
|
|
25
|
+
const workers = rule.workers;
|
|
26
|
+
if (!Array.isArray(workers) || !workers.length || workers.some(w => typeof w !== 'string' || !w.trim()) || new Set(workers).size !== workers.length) {
|
|
27
|
+
throw new Error(`${where}.workers must be a non-empty list of unique worker IDs, most preferred first`);
|
|
28
|
+
}
|
|
29
|
+
if (rule.others !== undefined && typeof rule.others !== 'boolean') throw new Error(`${where}.others must be true or false`);
|
|
30
|
+
return { match: { ...match, ...(requires ? { requires } : {}) }, workers: [...workers], others: rule.others ?? false };
|
|
31
|
+
});
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** True if a job spec fits a rule's `match` (an empty match fits every job). */
|
|
35
|
+
export function ruleMatches(rule, spec) {
|
|
36
|
+
const m = rule.match;
|
|
37
|
+
if (m.type !== undefined && m.type !== spec.type) return false;
|
|
38
|
+
if (m.kind !== undefined && m.kind !== spec.kind) return false;
|
|
39
|
+
if (m.class !== undefined && m.class !== spec.class) return false;
|
|
40
|
+
if (m.requires && !m.requires.every(r => (spec.requires ?? []).includes(r))) return false;
|
|
41
|
+
return true;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* The worker order for a job: its own `workerPreference` (a strict allowlist) wins over the config rules.
|
|
46
|
+
* @returns {{ workers: string[], others: boolean } | null} null = no preference, least-loaded placement.
|
|
47
|
+
*/
|
|
48
|
+
export function preferenceFor(rules, spec) {
|
|
49
|
+
if (spec.workerPreference) return { workers: spec.workerPreference, others: false };
|
|
50
|
+
const rule = rules.find(r => ruleMatches(r, spec));
|
|
51
|
+
return rule ? { workers: rule.workers, others: rule.others } : null;
|
|
52
|
+
}
|