fffleet-worker 2.2.0 → 2.4.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 CHANGED
@@ -15,6 +15,8 @@ docker run -p 5100:5100 -e FFFLEET_TOKEN=secret ghcr.io/jsilvanus/fffleet-worker
15
15
  | `FFFLEET_SLOTS` | `default=2` | Slot pools, e.g. `default=2,stream=1`, or `auto` (from the CPU count) / `auto:4` (4 cores per slot). |
16
16
  | `FFFLEET_KINDS` | `batch,stream` | Job kinds this worker takes. Others get 422 `UNSUPPORTED_KIND`, and the orchestrator does not send them. |
17
17
  | `FFFLEET_CAPABILITIES` | | Extra capabilities, comma separated, e.g. `mount:/media,site:hel1`. |
18
+ | `FFFLEET_PROBE` | | Hosts to test with a TCP connect, comma separated `[alias=]host:port`, e.g. `mediamtx=10.1.2.3:8554,db.internal:5432`. While one connects the worker advertises `net:<host>:<port>`, plus `net:<alias>` (or `net:<host>` for a host name without alias). A job with `requires: ['net:mediamtx']` then only runs where that host is reachable, and a worker that loses it drops out of scheduling by itself. |
19
+ | `FFFLEET_PROBE_INTERVAL_MS` | `30000` | How often the probes run. |
18
20
  | `FFFLEET_ORCHESTRATOR_URL` | | Register and heartbeat here. |
19
21
  | `FFFLEET_WORKER_TOKEN` | | Token for the orchestrator. |
20
22
  | `FFFLEET_ADVERTISE_URL` | listen URL | URL the orchestrator should call this worker on. |
@@ -32,8 +34,24 @@ The worker detects `type:ffmpeg`, `ffmpeg:<version>`, `filter:*`, `encoder:*` an
32
34
 
33
35
  The Docker image is Debian's ffmpeg build, with x264, x265, vpx, aom, lame, opus, libass and freetype, plus DejaVu fonts.
34
36
 
37
+ ## Download jobs (yt-dlp)
38
+
39
+ `FFFLEET_EXECUTORS=fffleet-worker/executors/download` (or the `fffleet-worker-ytdlp` image, which has it and yt-dlp) adds job type `download`; the worker then claims `type:download`. `YTDLP_PATH` overrides the yt-dlp binary.
40
+
41
+ ```js
42
+ { type: 'download',
43
+ download: { url: 'https://…', format: 'bv*+ba/b', extraArgs: ['--limit-rate', '5M'] }, // url must be http(s)
44
+ inputs: [{ name: 'cookies', uri: 's3://bucket/tmp/cookies.txt' }], // optional Netscape cookies.txt
45
+ outputs: [{ name: 'video', uri: 's3://bucket/out/video.mp4' },
46
+ { name: 'cookies-out', uri: 's3://bucket/tmp/cookies-out.txt' }] } // optional
47
+ ```
48
+
49
+ **Credentials are a cookies.txt passed as an input**, so they travel like any other file (`s3:`, `http(s):` or `file:`) and never appear in the job spec, logs or errors. Stage the cookie file in a private object, and delete it when the job ends. yt-dlp rewrites its cookie file, so the executor works on a copy in the job's work directory; `cookies-out` is uploaded only when yt-dlp changed it, so you can store the refreshed cookies. `extraArgs` refuses options that run commands or touch other files (`--exec`, `--output`, `--cookies`, config and plugin options). Progress comes from yt-dlp's percentages and cancelling the job stops yt-dlp.
50
+
35
51
  Programmatic use: `import { createWorker } from 'fffleet-worker'`. Pass `executors` to add job types other than ffmpeg.
36
52
 
37
53
  `GET /metrics` (Prometheus text format, `metrics` scope or the static token) reports slots, running jobs with their encoding speed and fps, ffmpeg CPU and memory, bytes staged and uploaded, and host load and memory.
38
54
 
55
+ See also the [install and use guide](https://github.com/jsilvanus/fffleet/blob/main/docs/getting-started.md) and [security notes](https://github.com/jsilvanus/fffleet/blob/main/docs/security.md).
56
+
39
57
  License: EUPL-1.2
@@ -34,6 +34,8 @@ const worker = createWorker({
34
34
  keysUrl: env.FFFLEET_KEYS_URL || ((env.FFFLEET_TOKEN || env.FFFLEET_WORKER_TOKEN) && env.FFFLEET_ORCHESTRATOR_URL ? `${env.FFFLEET_ORCHESTRATOR_URL.replace(/\/+$/, '')}/v1/auth/keys` : null),
35
35
  workRoot: env.FFFLEET_WORK_DIR || undefined,
36
36
  extraCapabilities: list(env.FFFLEET_CAPABILITIES),
37
+ probe: list(env.FFFLEET_PROBE),
38
+ probeIntervalMs: Number(env.FFFLEET_PROBE_INTERVAL_MS ?? 30000),
37
39
  orchestratorUrl: env.FFFLEET_ORCHESTRATOR_URL || null,
38
40
  orchestratorToken: env.FFFLEET_WORKER_TOKEN || null,
39
41
  advertiseUrl: env.FFFLEET_ADVERTISE_URL || null,
package/package.json CHANGED
@@ -1,12 +1,13 @@
1
1
  {
2
2
  "name": "fffleet-worker",
3
- "version": "2.2.0",
3
+ "version": "2.4.0",
4
4
  "description": "fffleet worker daemon: runs ffmpeg jobs and serves the fffleet job API",
5
5
  "type": "module",
6
6
  "main": "./src/worker.js",
7
7
  "exports": {
8
8
  ".": "./src/worker.js",
9
- "./package.json": "./package.json"
9
+ "./package.json": "./package.json",
10
+ "./executors/download": "./src/executors/download.js"
10
11
  },
11
12
  "bin": {
12
13
  "fffleet-worker": "bin/fffleet-worker.js"
@@ -21,7 +22,7 @@
21
22
  "test": "node --test test/*.test.js"
22
23
  },
23
24
  "dependencies": {
24
- "fffleet": "^2.2.0"
25
+ "fffleet": "^2.4.0"
25
26
  },
26
27
  "keywords": [
27
28
  "ffmpeg",
@@ -0,0 +1,230 @@
1
+ // Built-in executor for yt-dlp downloads (job type "download").
2
+ //
3
+ // Enable it on a worker with FFFLEET_EXECUTORS=fffleet-worker/executors/download (yt-dlp must be on the PATH, or set
4
+ // YTDLP_PATH). The worker image `fffleet-worker-ytdlp` has both.
5
+ //
6
+ // Spec: spec.download = { url, format?, extraArgs? } (url is http(s); format is a yt-dlp format selector)
7
+ // Inputs: "cookies" (optional) Netscape cookies.txt; s3:, http(s): or file:. Copied into the work directory, because
8
+ // yt-dlp rewrites the cookie file it is given.
9
+ // Outputs: "video" the downloaded mp4 (s3:, file: or http(s) PUT)
10
+ // "cookies-out" (opt.) the cookie file after the run, uploaded only when yt-dlp changed it
11
+ //
12
+ // Cookie contents are never logged and never put into errors: error text is built from yt-dlp's stderr after cookie
13
+ // values, the cookie file path and cookie-shaped lines are removed.
14
+ import { spawn } from "node:child_process";
15
+ import { createHash } from "node:crypto";
16
+ import { copyFile, mkdir, readFile, stat, writeFile } from "node:fs/promises";
17
+ import { dirname, join } from "node:path";
18
+ import { fileURLToPath } from "node:url";
19
+
20
+ const DEFAULT_FORMAT = "bv*+ba/b";
21
+ const KILL_GRACE_MS = 5000;
22
+ const TAIL_CHARS = 2000;
23
+ // Options that would let a job spec run commands, read other files or move the output elsewhere.
24
+ const FORBIDDEN_ARGS = /^(?:-o|-a|-P|--output|--paths|--exec(?:-before-download)?|--config(?:-location|-locations)?|--plugin-dirs|--batch-file|--cookies|--cookies-from-browser|--load-info-json|--netrc-cmd|--ffmpeg-location|--no-config|--write-.*|--print-to-file)(?:=|$)/;
25
+
26
+ function fail(code, message, details) {
27
+ const err = new Error(message);
28
+ err.code = code;
29
+ if (details !== undefined) err.details = details;
30
+ return err;
31
+ }
32
+
33
+ function parseS3(uri) {
34
+ const m = /^s3:\/\/([^/]+)\/(.+)$/.exec(uri);
35
+ if (!m) throw fail("BAD_SPEC", `not an s3://bucket/key URI: ${uri}`);
36
+ return { bucket: m[1], key: m[2] };
37
+ }
38
+
39
+ function endpoint(list, name) {
40
+ return Array.isArray(list) ? list.find(e => e.name === name) : undefined;
41
+ }
42
+
43
+ export function readPayload(spec) {
44
+ const d = spec.download;
45
+ if (!d || typeof d !== "object" || typeof d.url !== "string") throw fail("BAD_SPEC", "spec.download.url is required");
46
+ let url;
47
+ try { url = new URL(d.url); } catch { throw fail("BAD_SPEC", "spec.download.url is not a URL"); }
48
+ if (url.protocol !== "http:" && url.protocol !== "https:") throw fail("BAD_SPEC", "spec.download.url must be http(s)");
49
+ const extraArgs = d.extraArgs ?? [];
50
+ if (!Array.isArray(extraArgs) || extraArgs.some(a => typeof a !== "string")) throw fail("BAD_SPEC", "spec.download.extraArgs must be an array of strings");
51
+ const bad = extraArgs.find(a => FORBIDDEN_ARGS.test(a));
52
+ if (bad) throw fail("BAD_SPEC", `yt-dlp option not allowed in extraArgs: ${bad.split("=")[0]}`);
53
+ const format = typeof d.format === "string" && d.format ? d.format : DEFAULT_FORMAT;
54
+ return { url: url.href, format, extraArgs };
55
+ }
56
+
57
+ async function stageCookies(input, dest, rt) {
58
+ await mkdir(dirname(dest), { recursive: true });
59
+ const url = new URL(input.uri);
60
+ try {
61
+ if (url.protocol === "s3:") {
62
+ if (!rt.s3) throw fail("UNSUPPORTED_SCHEME", "this runner has no S3 credentials for s3: URIs");
63
+ const { bucket, key } = parseS3(input.uri);
64
+ await rt.s3.getFile(bucket, key, dest, { signal: rt.signal });
65
+ } else if (url.protocol === "file:") {
66
+ await copyFile(fileURLToPath(url), dest);
67
+ } else if (url.protocol === "http:" || url.protocol === "https:") {
68
+ const res = await (rt.fetch ?? globalThis.fetch)(input.uri, { signal: rt.signal });
69
+ if (!res.ok) throw fail("INPUT_FAILED", `HTTP ${res.status}`);
70
+ await writeFile(dest, Buffer.from(await res.arrayBuffer()));
71
+ } else {
72
+ throw fail("UNSUPPORTED_SCHEME", `unsupported scheme ${url.protocol}`);
73
+ }
74
+ } catch (err) {
75
+ if (rt.signal.aborted) throw rt.signal.reason;
76
+ // Only the endpoint name, never the URI (it may carry a signature) or file contents.
77
+ throw fail(err.code ?? "INPUT_FAILED", `could not fetch input "${input.name}": ${err.message}`);
78
+ }
79
+ }
80
+
81
+ async function deliver(output, file, rt, contentType) {
82
+ const url = new URL(output.uri);
83
+ if (url.protocol === "s3:") {
84
+ if (!rt.s3) throw fail("UNSUPPORTED_SCHEME", "this runner has no S3 credentials for s3: URIs");
85
+ const { bucket, key } = parseS3(output.uri);
86
+ await rt.s3.putFile(bucket, key, file, { contentType, signal: rt.signal });
87
+ } else if (url.protocol === "file:") {
88
+ const target = fileURLToPath(url);
89
+ await mkdir(dirname(target), { recursive: true });
90
+ await copyFile(file, target);
91
+ } else if (url.protocol === "http:" || url.protocol === "https:") {
92
+ const body = await readFile(file);
93
+ const res = await (rt.fetch ?? globalThis.fetch)(output.uri, { method: "PUT", headers: { "content-type": contentType ?? "application/octet-stream" }, body, signal: rt.signal });
94
+ if (!res.ok) throw fail("UPLOAD_FAILED", `upload of output "${output.name}" failed: HTTP ${res.status}`);
95
+ } else {
96
+ throw fail("UNSUPPORTED_SCHEME", `unsupported scheme ${url.protocol}`);
97
+ }
98
+ }
99
+
100
+ const sha = buf => createHash("sha256").update(buf).digest("hex");
101
+
102
+ /** Removes everything that could reveal cookies from yt-dlp's output before it goes into an error. */
103
+ export function scrub(text, { cookiePath, secrets = [] }) {
104
+ let out = text;
105
+ if (cookiePath) out = out.split(cookiePath).join("<cookies>");
106
+ for (const s of secrets) out = out.split(s).join("[redacted]");
107
+ return out
108
+ .split("\n")
109
+ .filter(line => (line.match(/\t/g) ?? []).length < 5) // Netscape cookie lines have 6 or 7 tab-separated fields.
110
+ .join("\n");
111
+ }
112
+
113
+ /** Cookie values and names long enough to be worth masking. */
114
+ function cookieSecrets(text) {
115
+ const secrets = new Set();
116
+ for (const line of text.split(/\r?\n/)) {
117
+ const f = line.replace(/^#HttpOnly_/, "").split("\t");
118
+ if (f.length >= 7) for (const v of [f[5], f[6]]) if (v && v.length >= 6) secrets.add(v.trim());
119
+ }
120
+ return [...secrets].sort((a, b) => b.length - a.length);
121
+ }
122
+
123
+ const PROGRESS_RE = /\[download\]\s+(\d+(?:\.\d+)?)%/;
124
+
125
+ function runYtDlp(command, args, rt, onLine) {
126
+ return new Promise((resolve, reject) => {
127
+ let child;
128
+ try {
129
+ child = spawn(command, args, { stdio: ["ignore", "pipe", "pipe"], env: process.env });
130
+ } catch (err) {
131
+ reject(fail("YTDLP_SPAWN", `could not start yt-dlp: ${err.message}`));
132
+ return;
133
+ }
134
+ let stderr = "";
135
+ let buffered = "";
136
+ let killTimer;
137
+ const kill = () => {
138
+ child.kill("SIGTERM");
139
+ killTimer = setTimeout(() => child.kill("SIGKILL"), KILL_GRACE_MS);
140
+ killTimer.unref?.();
141
+ };
142
+ const onAbort = () => kill();
143
+ if (rt.signal.aborted) kill();
144
+ else rt.signal.addEventListener("abort", onAbort, { once: true });
145
+ child.stdout.on("data", chunk => {
146
+ buffered += chunk.toString();
147
+ const lines = buffered.split(/\r?\n|\r/);
148
+ buffered = lines.pop() ?? "";
149
+ for (const line of lines) onLine(line);
150
+ });
151
+ child.stderr.on("data", chunk => { stderr = (stderr + chunk.toString()).slice(-16 * 1024); });
152
+ child.on("error", err => {
153
+ clearTimeout(killTimer);
154
+ rt.signal.removeEventListener("abort", onAbort);
155
+ reject(fail("YTDLP_SPAWN", `could not start yt-dlp: ${err.code === "ENOENT" ? "yt-dlp is not installed on this worker" : err.message}`));
156
+ });
157
+ child.on("close", (code, signal) => {
158
+ clearTimeout(killTimer);
159
+ rt.signal.removeEventListener("abort", onAbort);
160
+ if (buffered) onLine(buffered);
161
+ resolve({ code, signal, stderr });
162
+ });
163
+ });
164
+ }
165
+
166
+ export async function runDownload(spec, rt) {
167
+ const { url, format, extraArgs } = readPayload(spec);
168
+ const videoOut = endpoint(spec.outputs, "video");
169
+ if (!videoOut) throw fail("BAD_SPEC", 'output "video" is required');
170
+ const cookiesIn = endpoint(spec.inputs, "cookies");
171
+ const cookiesOut = endpoint(spec.outputs, "cookies-out");
172
+
173
+ const videoPath = join(rt.workDir, "out", "video.mp4");
174
+ await mkdir(dirname(videoPath), { recursive: true });
175
+
176
+ let cookiePath;
177
+ let cookieHash;
178
+ let secrets = [];
179
+ if (cookiesIn) {
180
+ rt.setState("staging");
181
+ cookiePath = join(rt.workDir, "cookies", "cookies.txt");
182
+ await stageCookies(cookiesIn, cookiePath, rt);
183
+ const bytes = await readFile(cookiePath);
184
+ cookieHash = sha(bytes);
185
+ secrets = cookieSecrets(bytes.toString("utf8"));
186
+ }
187
+ rt.signal.throwIfAborted();
188
+
189
+ const args = [
190
+ "--no-playlist", "--format", format, "--merge-output-format", "mp4", "--newline", "--progress", "--no-colors",
191
+ ...(cookiePath ? ["--cookies", cookiePath] : []),
192
+ ...extraArgs,
193
+ "--output", videoPath,
194
+ "--", url,
195
+ ];
196
+ rt.setState("running");
197
+ const { code, signal, stderr } = await runYtDlp(process.env.YTDLP_PATH || "yt-dlp", args, rt, line => {
198
+ const m = PROGRESS_RE.exec(line);
199
+ if (m) rt.progress({ pct: Math.max(0, Math.min(100, Number(m[1]))), outTimeMs: null, speed: null, fps: null, frame: null });
200
+ });
201
+
202
+ if (rt.signal.aborted) throw rt.signal.reason ?? fail("CANCELLED", "cancelled");
203
+ if (code !== 0) {
204
+ const tail = scrub(stderr, { cookiePath, secrets }).trim().slice(-TAIL_CHARS);
205
+ const how = code === null ? `was killed by ${signal}` : `exited with code ${code}`;
206
+ throw fail("YTDLP_EXIT", `yt-dlp ${how}${tail ? `: ${tail}` : ""}`, { exitCode: code });
207
+ }
208
+
209
+ let size;
210
+ try { size = (await stat(videoPath)).size; } catch { size = 0; }
211
+ if (!size) throw fail("OUTPUT_MISSING", "yt-dlp finished but wrote no video file");
212
+
213
+ rt.setState("uploading");
214
+ const results = [];
215
+ await deliver(videoOut, videoPath, rt, "video/mp4");
216
+ results.push({ name: "video", uri: videoOut.uri, bytes: size });
217
+
218
+ if (cookiesOut && cookiePath) {
219
+ let after;
220
+ try { after = await readFile(cookiePath); } catch { after = null; }
221
+ // Upload only a changed file: an unchanged one means nothing to write back.
222
+ if (after && sha(after) !== cookieHash) {
223
+ await deliver(cookiesOut, cookiePath, rt, "text/plain");
224
+ results.push({ name: "cookies-out", uri: cookiesOut.uri, bytes: after.length });
225
+ }
226
+ }
227
+ return { exitCode: 0, outputs: results, stderrTail: null };
228
+ }
229
+
230
+ export default { type: "download", run: runDownload };
package/src/worker.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { hostname } from 'node:os';
2
2
  import { readFileSync } from 'node:fs';
3
- import { JobManager, detectCapabilities } from 'fffleet';
3
+ import { JobManager, detectCapabilities, parseProbes, probeCapabilities } from 'fffleet';
4
4
  import {
5
5
  Registry, close, createApiHandler, createAuthenticator, createRemoteKeySet, createTokenVerifier,
6
6
  hostMetrics, jobMetrics, listen, procStats, processMetrics,
@@ -24,6 +24,8 @@ const VERSION = JSON.parse(readFileSync(new URL('../package.json', import.meta.u
24
24
  * @param {string} [opts.ffmpegPath]
25
25
  * @param {string} [opts.workRoot]
26
26
  * @param {string[]} [opts.extraCapabilities] Added to the detected ones, e.g. 'mount:/data/media'.
27
+ * @param {string | string[]} [opts.probe] Hosts to test with a TCP connect, `[alias=]host:port`. While one connects the worker advertises net:<host>:<port> (and net:<alias>).
28
+ * @param {number} [opts.probeIntervalMs]
27
29
  * @param {string | null} [opts.orchestratorUrl]
28
30
  * @param {string | null} [opts.orchestratorToken] Worker token the orchestrator expects.
29
31
  * @param {string | null} [opts.advertiseUrl] URL the orchestrator should call; defaults to the listen URL.
@@ -44,6 +46,8 @@ export function createWorker({
44
46
  ffmpegPath = 'ffmpeg',
45
47
  workRoot,
46
48
  extraCapabilities = [],
49
+ probe = [],
50
+ probeIntervalMs = 30000,
47
51
  orchestratorUrl = null,
48
52
  orchestratorToken = null,
49
53
  advertiseUrl = null,
@@ -55,7 +59,19 @@ export function createWorker({
55
59
  log = () => {},
56
60
  } = {}) {
57
61
  const manager = new JobManager({ slots, kinds, ffmpegPath, workRoot, workerId: id, progressIntervalMs, executors, s3, cache });
62
+ const probes = parseProbes(probe);
63
+ let baseCapabilities = [];
64
+ let probed = [];
58
65
  let capabilities = [];
66
+ let probeTimer = null;
67
+ const rebuild = () => { capabilities = [...new Set([...baseCapabilities, ...probed])].sort(); };
68
+ async function refreshProbes() {
69
+ const next = await probeCapabilities(probes);
70
+ const changed = next.join() !== probed.join();
71
+ probed = next;
72
+ rebuild();
73
+ if (changed) log(`reachable: ${next.join(', ') || 'none of the probed hosts'}`);
74
+ }
59
75
  let server = null;
60
76
  let url = null;
61
77
  let heartbeat = null;
@@ -150,8 +166,17 @@ export function createWorker({
150
166
  // type:ffmpeg and type:ffprobe come from detection, so a machine without ffmpeg does not claim it.
151
167
  const types = Object.keys(manager.executors).filter(t => t !== 'ffmpeg' && t !== 'ffprobe').map(t => `type:${t}`);
152
168
  const schemes = manager.s3 ? ['scheme:s3'] : [];
153
- capabilities = [...new Set([...(await detectCapabilities(ffmpegPath)), ...types, ...schemes, ...extraCapabilities])].sort();
169
+ baseCapabilities = [...new Set([...(await detectCapabilities(ffmpegPath)), ...types, ...schemes, ...extraCapabilities])];
170
+ await refreshProbes();
171
+ if (probes.length) {
172
+ // The heartbeat carries the capabilities, so a host that becomes (un)reachable is picked up by the orchestrator within a beat.
173
+ probeTimer = setInterval(() => void refreshProbes().catch(() => {}), probeIntervalMs);
174
+ probeTimer.unref?.();
175
+ }
154
176
  ({ server, url } = await listen(createApiHandler({ backend, authenticate, metrics: () => registry.render() }), { port, host }));
177
+ if (!token && !keysUrl && !['127.0.0.1', '::1', 'localhost'].includes(host)) {
178
+ log('no FFFLEET_TOKEN or FFFLEET_WORKER_TOKEN: anyone who can reach this port can run ffmpeg as this user (docs/security.md)');
179
+ }
155
180
  log(`fffleet-worker ${id} listening on ${url} with slots ${JSON.stringify(manager.slots)} for ${manager.kinds.join(' and ')} jobs`);
156
181
  if (orchestratorUrl) {
157
182
  await register().catch(err => log(`first registration failed, retrying: ${err.message}`));
@@ -164,6 +189,7 @@ export function createWorker({
164
189
  /** Stops taking jobs, cancels running ones and closes the server. */
165
190
  async stop() {
166
191
  clearInterval(heartbeat);
192
+ clearInterval(probeTimer);
167
193
  await manager.close();
168
194
  if (server) await close(server);
169
195
  },