From 53383435e71e49e2512a8703e8c34baab210319d Mon Sep 17 00:00:00 2001 From: David White Date: Thu, 22 Oct 2026 08:52:30 +0100 Subject: [PATCH 1/7] fix(cloudui): the update gets ten minutes, a stopped update leaves nothing behind, and a missing version file is updated The CloudUI release tarball is about 55 MB, so the update now has ten minutes instead of two. It runs in its own process group, and a timeout kills the whole group, download included. The update's temporary files go in /tmp/fluxwatchdog-cloudui (its TMPDIR), which is emptied before and after every run. On ArcaneOS /tmp is memory. A CloudUI directory without its version file has no installed hash, so it is updated like an out-of-date one, which writes the file. Co-Authored-By: Claude Opus 5.5 --- cloudui_update.js | 104 ++++++++++++++++++++++++++++++++ package.json | 2 +- test/cloudui_update.test.js | 116 ++++++++++++++++++++++++++++++++++++ watchdog.js | 39 ++++++++---- 4 files changed, 247 insertions(+), 14 deletions(-) create mode 100644 cloudui_update.js create mode 100644 test/cloudui_update.test.js diff --git a/cloudui_update.js b/cloudui_update.js new file mode 100644 index 0000000..dcd0a9d --- /dev/null +++ b/cloudui_update.js @@ -0,0 +1,104 @@ +/** + * Runs FluxOS's CloudUI update (`npm run update:cloudui -- `). + * + * The update downloads a release tarball of about 55 MB, so the timeout is sized for a + * slow link. The update runs in its own process group and a timeout kills the whole + * group: killing only the first process leaves the download running on its own. + * + * The update's temporary files go in one scratch directory the watchdog owns + * (`TMPDIR`), emptied before and after every run. A run cut short by the watchdog + * itself stopping is cleared by the next run. On ArcaneOS /tmp is memory, so a + * leftover download costs RAM until it is removed. + */ + +const { spawn } = require('child_process'); +const fs = require('fs'); +const os = require('os'); +const path = require('node:path'); + +const CLOUDUI_UPDATE_TIMEOUT_MS = 10 * 60 * 1000; +const CLOUDUI_SCRATCH_DIR = path.join(os.tmpdir(), 'fluxwatchdog-cloudui'); +const MAX_OUTPUT_CHARS = 4000; + +function clearScratch(scratchDir) { + fs.rmSync(scratchDir, { recursive: true, force: true }); +} + +function killGroup(pid) { + try { + process.kill(-pid, 'SIGKILL'); + } catch { + // ESRCH: every process in the group has already exited. + } +} + +/** + * @param {object} options + * @param {string} options.fluxOsRootDir - FluxOS checkout the update runs in. + * @param {string} options.apiBaseUrl - GitHub API host the update reads the release from. + * @param {number} [options.timeoutMs] + * @param {string} [options.scratchDir] - Directory given to the update as TMPDIR. + * @param {string[]} [options.command] - Command and arguments; defaults to the npm script. + * @returns {Promise<{ok: boolean, timedOut: boolean, code: number|null, + * signal: string|null, error: Error|null, output: string}>} + */ +function runCloudUiUpdate({ + fluxOsRootDir, + apiBaseUrl, + timeoutMs = CLOUDUI_UPDATE_TIMEOUT_MS, + scratchDir = CLOUDUI_SCRATCH_DIR, + command = ['npm', 'run', 'update:cloudui', '--', apiBaseUrl], +}) { + clearScratch(scratchDir); + fs.mkdirSync(scratchDir, { recursive: true, mode: 0o700 }); + + return new Promise((resolve) => { + let output = ''; + let timedOut = false; + let spawnError = null; + let settled = false; + + const finish = (code, signal) => { + if (settled) return; + settled = true; + clearTimeout(timer); + clearScratch(scratchDir); + resolve({ + ok: !timedOut && !spawnError && code === 0, + timedOut, + code, + signal, + error: spawnError, + output: output.slice(-MAX_OUTPUT_CHARS), + }); + }; + + const child = spawn(command[0], command.slice(1), { + cwd: fluxOsRootDir, + env: { ...process.env, TMPDIR: scratchDir }, + detached: true, + stdio: ['ignore', 'pipe', 'pipe'], + }); + + const collect = (chunk) => { + output = (output + chunk).slice(-MAX_OUTPUT_CHARS * 2); + }; + child.stdout.on('data', collect); + child.stderr.on('data', collect); + + const timer = setTimeout(() => { + timedOut = true; + killGroup(child.pid); + }, timeoutMs); + + child.on('error', (error) => { + spawnError = error; + finish(null, null); + }); + // Anything the update left running in its group is stopped once the update exits. + child.on('exit', () => killGroup(child.pid)); + child.on('close', finish); + }); +} + +module.exports = { runCloudUiUpdate, CLOUDUI_UPDATE_TIMEOUT_MS, CLOUDUI_SCRATCH_DIR }; diff --git a/package.json b/package.json index ecf8ddf..eb25f44 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "watchdog", - "version": "6.8.0", + "version": "6.8.3", "description": "Watchdog for fluxnode", "main": "watchdog.js", "dependencies": { diff --git a/test/cloudui_update.test.js b/test/cloudui_update.test.js new file mode 100644 index 0000000..8c07a8f --- /dev/null +++ b/test/cloudui_update.test.js @@ -0,0 +1,116 @@ +const test = require('node:test'); +const assert = require('node:assert'); +const fs = require('fs'); +const os = require('os'); +const path = require('node:path'); + +const { runCloudUiUpdate } = require('../cloudui_update'); + +function tempDirs() { + const base = fs.mkdtempSync(path.join(os.tmpdir(), 'cloudui-update-test-')); + return { base, scratchDir: path.join(base, 'scratch') }; +} + +function alive(pid) { + try { + process.kill(pid, 0); + return true; + } catch { + return false; + } +} + +test('runs the update with TMPDIR set to the scratch directory', async () => { + const { base, scratchDir } = tempDirs(); + const result = await runCloudUiUpdate({ + fluxOsRootDir: base, + apiBaseUrl: 'https://api.github.com', + scratchDir, + command: ['sh', '-c', 'd=$(mktemp -d) && echo "made $d" && touch "$d/dist.tar.gz"'], + }); + assert.strictEqual(result.ok, true); + assert.strictEqual(result.timedOut, false); + assert.match(result.output, new RegExp(`made ${scratchDir}/`)); + assert.strictEqual(fs.existsSync(scratchDir), false); +}); + +test('removes what a previous run left before starting', async () => { + const { base, scratchDir } = tempDirs(); + fs.mkdirSync(path.join(scratchDir, 'tmp.left'), { recursive: true }); + fs.writeFileSync(path.join(scratchDir, 'tmp.left', 'dist.tar.gz'), 'x'); + const result = await runCloudUiUpdate({ + fluxOsRootDir: base, + apiBaseUrl: 'https://api.github.com', + scratchDir, + command: ['sh', '-c', 'echo "dir:$TMPDIR"; ls -A "$TMPDIR"; echo end'], + }); + assert.strictEqual(result.ok, true); + assert.match(result.output, new RegExp(`dir:${scratchDir}\\s+end`)); +}); + +test('a timeout kills every process the update started and removes its files', async () => { + const { base, scratchDir } = tempDirs(); + const pidFile = path.join(base, 'download.pid'); + const result = await runCloudUiUpdate({ + fluxOsRootDir: base, + apiBaseUrl: 'https://api.github.com', + scratchDir, + timeoutMs: 500, + command: [ + 'sh', + '-c', + `d=$(mktemp -d); (while :; do date >> "$d/dist.tar.gz"; sleep 0.05; done) & echo $! > ${pidFile}; wait`, + ], + }); + assert.strictEqual(result.ok, false); + assert.strictEqual(result.timedOut, true); + const downloadPid = Number(fs.readFileSync(pidFile, 'utf8')); + assert.ok(downloadPid > 0); + await new Promise((r) => setTimeout(r, 200)); + assert.strictEqual(alive(downloadPid), false); + assert.strictEqual(fs.existsSync(scratchDir), false); +}); + +test('stops a process the update left running after it exited', async () => { + const { base, scratchDir } = tempDirs(); + const pidFile = path.join(base, 'straggler.pid'); + const result = await runCloudUiUpdate({ + fluxOsRootDir: base, + apiBaseUrl: 'https://api.github.com', + scratchDir, + command: ['sh', '-c', `sleep 30 >/dev/null 2>&1 & echo $! > ${pidFile}`], + }); + assert.strictEqual(result.ok, true); + const stragglerPid = Number(fs.readFileSync(pidFile, 'utf8')); + assert.ok(stragglerPid > 0); + await new Promise((r) => setTimeout(r, 200)); + assert.strictEqual(alive(stragglerPid), false); +}); + +test('reports a failed update and still removes its files', async () => { + const { base, scratchDir } = tempDirs(); + const result = await runCloudUiUpdate({ + fluxOsRootDir: base, + apiBaseUrl: 'https://api.github.com', + scratchDir, + command: ['sh', '-c', 'touch "$(mktemp -d)/release.json"; echo "Error: no release"; exit 1'], + }); + assert.strictEqual(result.ok, false); + assert.strictEqual(result.timedOut, false); + assert.strictEqual(result.code, 1); + assert.match(result.output, /Error: no release/); + assert.strictEqual(fs.existsSync(scratchDir), false); +}); + +test('reports a command that cannot start', async () => { + const { base, scratchDir } = tempDirs(); + const result = await runCloudUiUpdate({ + fluxOsRootDir: base, + apiBaseUrl: 'https://api.github.com', + scratchDir, + command: [path.join(base, 'no-such-command')], + }); + assert.strictEqual(result.ok, false); + assert.ok(result.error); + assert.strictEqual(fs.existsSync(scratchDir), false); +}); diff --git a/watchdog.js b/watchdog.js index a6c73d1..eb725f8 100644 --- a/watchdog.js +++ b/watchdog.js @@ -17,6 +17,7 @@ const { compareVersions } = require('./versions'); const { discordPayload, sendDiscord, sendTelegram } = require('./alerts'); const { simulateInstallCommand, aptInstallPlan, updateServices } = require('./apt_plan'); const { runSyncCheck } = require('./fluxd_chain'); +const { runCloudUiUpdate, CLOUDUI_UPDATE_TIMEOUT_MS } = require('./cloudui_update'); const execFilePromise = promisify(execFile); @@ -221,6 +222,21 @@ function cloudUiApiBaseUrl() { } } +// Runs FluxOS's CloudUI update, and logs why when it fails. +async function updateCloudUI(apiBaseUrl) { + const result = await runCloudUiUpdate({ fluxOsRootDir, apiBaseUrl }); + if (!result.ok) { + let reason = `exited with code ${result.code}`; + if (result.timedOut) reason = `timed out after ${CLOUDUI_UPDATE_TIMEOUT_MS / 60_000} minutes`; + else if (result.error) reason = result.error.message; + console.log(`CloudUI update failed: ${reason}`); + const lastLines = result.output.trim().split('\n').slice(-5).join('\n'); + if (lastLines) console.log(lastLines); + } + + return result.ok; +} + async function checkCloudUI() { const cloudUIDir = path.join(fluxOsRootDir, 'CloudUI'); if (fs.existsSync(cloudUIDir)) { @@ -241,10 +257,9 @@ async function checkCloudUI() { return; } console.log(`checkCloudUI: FluxOS version ${version} >= 8.0.0. Downloading CloudUI...`); - await runShellCommand(`cd ${fluxOsRootDir} && npm run update:cloudui -- ${apiBaseUrl}`, { - timeout: 120000, - }); - console.log('checkCloudUI: CloudUI download completed.'); + if (await updateCloudUI(apiBaseUrl)) { + console.log('checkCloudUI: CloudUI download completed.'); + } } else { console.log('checkCloudUI: FluxOS version < 8.0.0 or not detected. Skipping CloudUI download.'); } @@ -1034,10 +1049,11 @@ async function auto_update() { } } await checkCloudUI(); - // FluxCloud UI version check (only if CloudUI is installed) + // FluxCloud UI version check (only if CloudUI is installed). A CloudUI without its + // version file has no installed hash, so it never matches the release and is updated. const cloudui_dir = path.join(fluxOsRootDir, 'CloudUI'); const cloudui_local_version_file = path.join(cloudui_dir, 'version'); - if (fs.existsSync(cloudui_dir) && fs.existsSync(cloudui_local_version_file)) { + if (fs.existsSync(cloudui_dir)) { const cloudui_release_info = ( await runShellCommand( 'curl -sS -m 10 https://api.github.com/repos/RunOnFlux/fluxos-frontend/releases/latest', @@ -1061,7 +1077,9 @@ async function auto_update() { console.log('FluxCloud UI: Failed to parse release info'); } - const cloudui_local_hash = fs.readFileSync(cloudui_local_version_file, 'utf8').trim(); + const cloudui_local_hash = fs.existsSync(cloudui_local_version_file) + ? fs.readFileSync(cloudui_local_version_file, 'utf8').trim() + : ''; console.log( `FluxCloud UI current: ${cloudui_remote_tag} (${cloudui_remote_hash.substring(0, 8) || 'N/A'}) installed: ${cloudui_local_hash.substring(0, 8) || 'N/A'}`, @@ -1082,12 +1100,7 @@ async function auto_update() { if (!cloudui_api_base_url) { console.log('No API host available, skipping the FluxCloud UI update.'); } else { - ( - await runShellCommand( - `cd ${fluxOsRootDir} && npm run update:cloudui -- ${cloudui_api_base_url}`, - { timeout: 120000 }, - ) - ).stdout; + await updateCloudUI(cloudui_api_base_url); } await sleep(5 * 1_000); let cloudui_lv = ''; From e0bd8d24058fa88576a130efe39e9d5f6f645f28 Mon Sep 17 00:00:00 2001 From: David White Date: Thu, 22 Oct 2026 09:01:29 +0100 Subject: [PATCH 2/7] chore: the version is set at release, not in this change Co-Authored-By: Claude Opus 5.5 --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index eb25f44..ecf8ddf 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "watchdog", - "version": "6.8.3", + "version": "6.8.0", "description": "Watchdog for fluxnode", "main": "watchdog.js", "dependencies": { From 32497ab5c4adfa738f9c9cf2dc7f1ae10d8c657a Mon Sep 17 00:00:00 2001 From: David White Date: Thu, 22 Oct 2026 20:22:11 +0100 Subject: [PATCH 3/7] fix(cloudui): an update ended by a signal logs the signal Co-Authored-By: Claude Opus 5.5 --- cloudui_update.js | 20 +++++++++++++++++++- test/cloudui_update.test.js | 20 +++++++++++++++++++- watchdog.js | 7 ++----- 3 files changed, 40 insertions(+), 7 deletions(-) diff --git a/cloudui_update.js b/cloudui_update.js index dcd0a9d..3cba24c 100644 --- a/cloudui_update.js +++ b/cloudui_update.js @@ -101,4 +101,22 @@ function runCloudUiUpdate({ }); } -module.exports = { runCloudUiUpdate, CLOUDUI_UPDATE_TIMEOUT_MS, CLOUDUI_SCRATCH_DIR }; +/** + * Why an update that did not succeed failed, for the log. + * @param {{timedOut: boolean, error: Error|null, signal: string|null, code: number|null}} result + * @returns {string} + */ +function failureReason(result) { + if (result.timedOut) return `timed out after ${CLOUDUI_UPDATE_TIMEOUT_MS / 60_000} minutes`; + if (result.error) return result.error.message; + if (result.signal) return `killed by ${result.signal}`; + + return `exited with code ${result.code}`; +} + +module.exports = { + runCloudUiUpdate, + failureReason, + CLOUDUI_UPDATE_TIMEOUT_MS, + CLOUDUI_SCRATCH_DIR, +}; diff --git a/test/cloudui_update.test.js b/test/cloudui_update.test.js index 8c07a8f..65b94c3 100644 --- a/test/cloudui_update.test.js +++ b/test/cloudui_update.test.js @@ -4,7 +4,7 @@ const fs = require('fs'); const os = require('os'); const path = require('node:path'); -const { runCloudUiUpdate } = require('../cloudui_update'); +const { runCloudUiUpdate, failureReason } = require('../cloudui_update'); function tempDirs() { const base = fs.mkdtempSync(path.join(os.tmpdir(), 'cloudui-update-test-')); @@ -64,6 +64,7 @@ test('a timeout kills every process the update started and removes its files', a }); assert.strictEqual(result.ok, false); assert.strictEqual(result.timedOut, true); + assert.strictEqual(failureReason(result), 'timed out after 10 minutes'); const downloadPid = Number(fs.readFileSync(pidFile, 'utf8')); assert.ok(downloadPid > 0); await new Promise((r) => setTimeout(r, 200)); @@ -99,9 +100,25 @@ test('reports a failed update and still removes its files', async () => { assert.strictEqual(result.timedOut, false); assert.strictEqual(result.code, 1); assert.match(result.output, /Error: no release/); + assert.strictEqual(failureReason(result), 'exited with code 1'); assert.strictEqual(fs.existsSync(scratchDir), false); }); +test('reports an update ended by a signal from outside the watchdog', async () => { + const { base, scratchDir } = tempDirs(); + const result = await runCloudUiUpdate({ + fluxOsRootDir: base, + apiBaseUrl: 'https://api.github.com', + scratchDir, + command: ['sh', '-c', 'kill -TERM $$'], + }); + assert.strictEqual(result.ok, false); + assert.strictEqual(result.timedOut, false); + assert.strictEqual(result.code, null); + assert.strictEqual(result.signal, 'SIGTERM'); + assert.strictEqual(failureReason(result), 'killed by SIGTERM'); +}); + test('reports a command that cannot start', async () => { const { base, scratchDir } = tempDirs(); const result = await runCloudUiUpdate({ @@ -112,5 +129,6 @@ test('reports a command that cannot start', async () => { }); assert.strictEqual(result.ok, false); assert.ok(result.error); + assert.strictEqual(failureReason(result), result.error.message); assert.strictEqual(fs.existsSync(scratchDir), false); }); diff --git a/watchdog.js b/watchdog.js index eb725f8..e4f79bd 100644 --- a/watchdog.js +++ b/watchdog.js @@ -17,7 +17,7 @@ const { compareVersions } = require('./versions'); const { discordPayload, sendDiscord, sendTelegram } = require('./alerts'); const { simulateInstallCommand, aptInstallPlan, updateServices } = require('./apt_plan'); const { runSyncCheck } = require('./fluxd_chain'); -const { runCloudUiUpdate, CLOUDUI_UPDATE_TIMEOUT_MS } = require('./cloudui_update'); +const { runCloudUiUpdate, failureReason } = require('./cloudui_update'); const execFilePromise = promisify(execFile); @@ -226,10 +226,7 @@ function cloudUiApiBaseUrl() { async function updateCloudUI(apiBaseUrl) { const result = await runCloudUiUpdate({ fluxOsRootDir, apiBaseUrl }); if (!result.ok) { - let reason = `exited with code ${result.code}`; - if (result.timedOut) reason = `timed out after ${CLOUDUI_UPDATE_TIMEOUT_MS / 60_000} minutes`; - else if (result.error) reason = result.error.message; - console.log(`CloudUI update failed: ${reason}`); + console.log(`CloudUI update failed: ${failureReason(result)}`); const lastLines = result.output.trim().split('\n').slice(-5).join('\n'); if (lastLines) console.log(lastLines); } From 8422ac565ef43c8be1ed39c1817ab2d5c61c747a Mon Sep 17 00:00:00 2001 From: David White Date: Sun, 25 Oct 2026 06:27:03 +0000 Subject: [PATCH 4/7] fix(cloudui): a timed-out update is sent SIGTERM, and SIGKILL only after a grace period The update script removes its own files when it is stopped with SIGTERM, which SIGKILL does not allow. A timeout now signals the group with SIGTERM and kills it 10 seconds later if it is still running. The group is not killed when the first process exits after a timeout, because npm exits on SIGTERM while the script below it is still removing its files. Co-Authored-By: Claude Opus 5.5 --- cloudui_update.js | 23 ++++++++++++----- test/cloudui_update.test.js | 51 +++++++++++++++++++++++++++++++++++++ 2 files changed, 68 insertions(+), 6 deletions(-) diff --git a/cloudui_update.js b/cloudui_update.js index 3cba24c..0af69ba 100644 --- a/cloudui_update.js +++ b/cloudui_update.js @@ -2,8 +2,9 @@ * Runs FluxOS's CloudUI update (`npm run update:cloudui -- `). * * The update downloads a release tarball of about 55 MB, so the timeout is sized for a - * slow link. The update runs in its own process group and a timeout kills the whole - * group: killing only the first process leaves the download running on its own. + * slow link. The update runs in its own process group. A timeout sends the whole group + * SIGTERM, so the update can remove its own files, and SIGKILL once the grace period has + * passed: signalling only the first process leaves the download running on its own. * * The update's temporary files go in one scratch directory the watchdog owns * (`TMPDIR`), emptied before and after every run. A run cut short by the watchdog @@ -17,6 +18,7 @@ const os = require('os'); const path = require('node:path'); const CLOUDUI_UPDATE_TIMEOUT_MS = 10 * 60 * 1000; +const CLOUDUI_UPDATE_GRACE_MS = 10 * 1000; const CLOUDUI_SCRATCH_DIR = path.join(os.tmpdir(), 'fluxwatchdog-cloudui'); const MAX_OUTPUT_CHARS = 4000; @@ -24,9 +26,9 @@ function clearScratch(scratchDir) { fs.rmSync(scratchDir, { recursive: true, force: true }); } -function killGroup(pid) { +function signalGroup(pid, signal) { try { - process.kill(-pid, 'SIGKILL'); + process.kill(-pid, signal); } catch { // ESRCH: every process in the group has already exited. } @@ -37,6 +39,7 @@ function killGroup(pid) { * @param {string} options.fluxOsRootDir - FluxOS checkout the update runs in. * @param {string} options.apiBaseUrl - GitHub API host the update reads the release from. * @param {number} [options.timeoutMs] + * @param {number} [options.graceMs] - Time from SIGTERM to SIGKILL after a timeout. * @param {string} [options.scratchDir] - Directory given to the update as TMPDIR. * @param {string[]} [options.command] - Command and arguments; defaults to the npm script. * @returns {Promise<{ok: boolean, timedOut: boolean, code: number|null, @@ -46,6 +49,7 @@ function runCloudUiUpdate({ fluxOsRootDir, apiBaseUrl, timeoutMs = CLOUDUI_UPDATE_TIMEOUT_MS, + graceMs = CLOUDUI_UPDATE_GRACE_MS, scratchDir = CLOUDUI_SCRATCH_DIR, command = ['npm', 'run', 'update:cloudui', '--', apiBaseUrl], }) { @@ -57,11 +61,13 @@ function runCloudUiUpdate({ let timedOut = false; let spawnError = null; let settled = false; + let graceTimer = null; const finish = (code, signal) => { if (settled) return; settled = true; clearTimeout(timer); + clearTimeout(graceTimer); clearScratch(scratchDir); resolve({ ok: !timedOut && !spawnError && code === 0, @@ -88,7 +94,8 @@ function runCloudUiUpdate({ const timer = setTimeout(() => { timedOut = true; - killGroup(child.pid); + signalGroup(child.pid, 'SIGTERM'); + graceTimer = setTimeout(() => signalGroup(child.pid, 'SIGKILL'), graceMs); }, timeoutMs); child.on('error', (error) => { @@ -96,7 +103,10 @@ function runCloudUiUpdate({ finish(null, null); }); // Anything the update left running in its group is stopped once the update exits. - child.on('exit', () => killGroup(child.pid)); + // After a timeout the group is still removing its files, and the grace timer stops it. + child.on('exit', () => { + if (!timedOut) signalGroup(child.pid, 'SIGKILL'); + }); child.on('close', finish); }); } @@ -118,5 +128,6 @@ module.exports = { runCloudUiUpdate, failureReason, CLOUDUI_UPDATE_TIMEOUT_MS, + CLOUDUI_UPDATE_GRACE_MS, CLOUDUI_SCRATCH_DIR, }; diff --git a/test/cloudui_update.test.js b/test/cloudui_update.test.js index 65b94c3..bc4667e 100644 --- a/test/cloudui_update.test.js +++ b/test/cloudui_update.test.js @@ -72,6 +72,57 @@ test('a timeout kills every process the update started and removes its files', a assert.strictEqual(fs.existsSync(scratchDir), false); }); +test('a timeout lets the update remove its own files before the group is killed', async () => { + const { base, scratchDir } = tempDirs(); + const leftover = path.join(base, 'download.part'); + // The first process exits on SIGTERM at once, as npm does, while the script below it is + // still removing its download. + const script = `touch ${leftover}; trap "sleep 0.3; rm -f ${leftover}; exit 143" TERM; while :; do sleep 0.05; done`; + const result = await runCloudUiUpdate({ + fluxOsRootDir: base, + apiBaseUrl: 'https://api.github.com', + scratchDir, + timeoutMs: 500, + graceMs: 5000, + command: ['sh', '-c', `sh -c '${script}' & trap "exit 143" TERM; wait`], + }); + assert.strictEqual(result.timedOut, true); + assert.strictEqual(fs.existsSync(leftover), false); +}); + +test('a timeout kills an update that ignores SIGTERM once the grace period has passed', async () => { + const { base, scratchDir } = tempDirs(); + const pidFile = path.join(base, 'update.pid'); + const started = Date.now(); + const update = runCloudUiUpdate({ + fluxOsRootDir: base, + apiBaseUrl: 'https://api.github.com', + scratchDir, + timeoutMs: 300, + graceMs: 300, + command: ['sh', '-c', `trap "" TERM; echo $$ > ${pidFile}; while :; do sleep 0.05; done`], + }); + let deadline; + try { + // An update that is never killed would never settle; the deadline fails the test instead. + const result = await Promise.race([ + update, + new Promise((resolve) => { + deadline = setTimeout(() => resolve(null), 3000); + }), + ]); + assert.ok(result, 'the update was still running 3 s after it started'); + assert.strictEqual(result.timedOut, true); + assert.strictEqual(result.signal, 'SIGKILL'); + assert.ok(Date.now() - started >= 600); + assert.strictEqual(alive(Number(fs.readFileSync(pidFile, 'utf8'))), false); + } finally { + clearTimeout(deadline); + const pid = Number(fs.readFileSync(pidFile, 'utf8')); + if (alive(pid)) process.kill(-pid, 'SIGKILL'); + } +}); + test('stops a process the update left running after it exited', async () => { const { base, scratchDir } = tempDirs(); const pidFile = path.join(base, 'straggler.pid'); From fce86a352f8248a093e74557b27b52837b20995d Mon Sep 17 00:00:00 2001 From: David White Date: Sun, 25 Oct 2026 06:40:15 +0000 Subject: [PATCH 5/7] fix(cloudui): the update runs in the background, one at a time, with a six-hour limit The watchdog's loop starts the CloudUI update and goes on with its checks rather than waiting for a download that takes hours on a slow link. A check that finds an update still running does not start another. When the update ends, a failure is logged with its reason, and a success is checked against the release's hash. The time limit is six hours, a 60 MB download at under 3 KB/s, so it stops only a download that never finishes. Co-Authored-By: Claude Opus 5.5 --- cloudui_update.js | 37 +++++++++++++++++---- test/cloudui_update.test.js | 64 +++++++++++++++++++++++++++++++++++-- watchdog.js | 48 +++++++++++++++------------- 3 files changed, 118 insertions(+), 31 deletions(-) diff --git a/cloudui_update.js b/cloudui_update.js index 0af69ba..bb43f29 100644 --- a/cloudui_update.js +++ b/cloudui_update.js @@ -1,10 +1,12 @@ /** * Runs FluxOS's CloudUI update (`npm run update:cloudui -- `). * - * The update downloads a release tarball of about 55 MB, so the timeout is sized for a - * slow link. The update runs in its own process group. A timeout sends the whole group - * SIGTERM, so the update can remove its own files, and SIGKILL once the grace period has - * passed: signalling only the first process leaves the download running on its own. + * The update downloads a release tarball of about 60 MB, and a slow link takes hours, so + * the update runs in the background (`startCloudUiUpdate`), one at a time, and the + * timeout only stops a download that never finishes: 6 hours is 60 MB at under 3 KB/s. + * The update runs in its own process group. A timeout sends the whole group SIGTERM, so + * the update can remove its own files, and SIGKILL once the grace period has passed: + * signalling only the first process leaves the download running on its own. * * The update's temporary files go in one scratch directory the watchdog owns * (`TMPDIR`), emptied before and after every run. A run cut short by the watchdog @@ -17,11 +19,14 @@ const fs = require('fs'); const os = require('os'); const path = require('node:path'); -const CLOUDUI_UPDATE_TIMEOUT_MS = 10 * 60 * 1000; +const CLOUDUI_UPDATE_TIMEOUT_MS = 6 * 60 * 60 * 1000; const CLOUDUI_UPDATE_GRACE_MS = 10 * 1000; const CLOUDUI_SCRATCH_DIR = path.join(os.tmpdir(), 'fluxwatchdog-cloudui'); const MAX_OUTPUT_CHARS = 4000; +// The update in progress, if there is one. +let running = null; + function clearScratch(scratchDir) { fs.rmSync(scratchDir, { recursive: true, force: true }); } @@ -111,13 +116,32 @@ function runCloudUiUpdate({ }); } +/** + * Starts an update in the background unless one is already running, and calls onDone + * with its result when it ends. + * @param {object} options - As for runCloudUiUpdate. + * @param {function(object): void} onDone + * @returns {Promise|null} The started update, or null when one is already running. + */ +function startCloudUiUpdate(options, onDone) { + if (running) return null; + running = runCloudUiUpdate(options) + .then(onDone) + .catch((error) => console.log(`CloudUI update: ${error.message}`)) + .finally(() => { + running = null; + }); + + return running; +} + /** * Why an update that did not succeed failed, for the log. * @param {{timedOut: boolean, error: Error|null, signal: string|null, code: number|null}} result * @returns {string} */ function failureReason(result) { - if (result.timedOut) return `timed out after ${CLOUDUI_UPDATE_TIMEOUT_MS / 60_000} minutes`; + if (result.timedOut) return `timed out after ${CLOUDUI_UPDATE_TIMEOUT_MS / 3_600_000} hours`; if (result.error) return result.error.message; if (result.signal) return `killed by ${result.signal}`; @@ -126,6 +150,7 @@ function failureReason(result) { module.exports = { runCloudUiUpdate, + startCloudUiUpdate, failureReason, CLOUDUI_UPDATE_TIMEOUT_MS, CLOUDUI_UPDATE_GRACE_MS, diff --git a/test/cloudui_update.test.js b/test/cloudui_update.test.js index bc4667e..3d6eee0 100644 --- a/test/cloudui_update.test.js +++ b/test/cloudui_update.test.js @@ -4,7 +4,7 @@ const fs = require('fs'); const os = require('os'); const path = require('node:path'); -const { runCloudUiUpdate, failureReason } = require('../cloudui_update'); +const { runCloudUiUpdate, startCloudUiUpdate, failureReason } = require('../cloudui_update'); function tempDirs() { const base = fs.mkdtempSync(path.join(os.tmpdir(), 'cloudui-update-test-')); @@ -64,7 +64,7 @@ test('a timeout kills every process the update started and removes its files', a }); assert.strictEqual(result.ok, false); assert.strictEqual(result.timedOut, true); - assert.strictEqual(failureReason(result), 'timed out after 10 minutes'); + assert.strictEqual(failureReason(result), 'timed out after 6 hours'); const downloadPid = Number(fs.readFileSync(pidFile, 'utf8')); assert.ok(downloadPid > 0); await new Promise((r) => setTimeout(r, 200)); @@ -183,3 +183,63 @@ test('reports a command that cannot start', async () => { assert.strictEqual(failureReason(result), result.error.message); assert.strictEqual(fs.existsSync(scratchDir), false); }); + +test('starts an update in the background and returns before it ends', async () => { + const { base, scratchDir } = tempDirs(); + let result = null; + const started = startCloudUiUpdate( + { + fluxOsRootDir: base, + apiBaseUrl: 'https://api.github.com', + scratchDir, + command: ['sh', '-c', 'sleep 0.3; echo done'], + }, + (r) => { + result = r; + }, + ); + assert.ok(started); + assert.strictEqual(result, null); + await started; + assert.strictEqual(result.ok, true); + assert.match(result.output, /done/); +}); + +test('does not start a second update while one is running, and starts one after it ends', async () => { + const { base, scratchDir } = tempDirs(); + const runs = path.join(base, 'runs'); + const options = { + fluxOsRootDir: base, + apiBaseUrl: 'https://api.github.com', + scratchDir, + command: ['sh', '-c', `echo run >> ${runs}; sleep 0.3`], + }; + const first = startCloudUiUpdate(options, () => {}); + assert.ok(first); + assert.strictEqual( + startCloudUiUpdate(options, () => {}), + null, + ); + await first; + assert.strictEqual(fs.readFileSync(runs, 'utf8'), 'run\n'); + const next = startCloudUiUpdate(options, () => {}); + assert.ok(next); + await next; + assert.strictEqual(fs.readFileSync(runs, 'utf8'), 'run\nrun\n'); +}); + +test('an update whose onDone throws still lets the next one start', async () => { + const { base, scratchDir } = tempDirs(); + const options = { + fluxOsRootDir: base, + apiBaseUrl: 'https://api.github.com', + scratchDir, + command: ['sh', '-c', 'true'], + }; + await startCloudUiUpdate(options, () => { + throw new Error('onDone failed'); + }); + const next = startCloudUiUpdate(options, () => {}); + assert.ok(next); + await next; +}); diff --git a/watchdog.js b/watchdog.js index e4f79bd..db6bca4 100644 --- a/watchdog.js +++ b/watchdog.js @@ -17,7 +17,7 @@ const { compareVersions } = require('./versions'); const { discordPayload, sendDiscord, sendTelegram } = require('./alerts'); const { simulateInstallCommand, aptInstallPlan, updateServices } = require('./apt_plan'); const { runSyncCheck } = require('./fluxd_chain'); -const { runCloudUiUpdate, failureReason } = require('./cloudui_update'); +const { startCloudUiUpdate, failureReason } = require('./cloudui_update'); const execFilePromise = promisify(execFile); @@ -222,16 +222,20 @@ function cloudUiApiBaseUrl() { } } -// Runs FluxOS's CloudUI update, and logs why when it fails. -async function updateCloudUI(apiBaseUrl) { - const result = await runCloudUiUpdate({ fluxOsRootDir, apiBaseUrl }); - if (!result.ok) { - console.log(`CloudUI update failed: ${failureReason(result)}`); - const lastLines = result.output.trim().split('\n').slice(-5).join('\n'); - if (lastLines) console.log(lastLines); - } +// Starts FluxOS's CloudUI update in the background and returns at once. When the update +// ends, onSuccess runs if it succeeded, and why it failed is logged if it did not. +function updateCloudUI(apiBaseUrl, onSuccess) { + const started = startCloudUiUpdate({ fluxOsRootDir, apiBaseUrl }, (result) => { + if (!result.ok) { + console.log(`CloudUI update failed: ${failureReason(result)}`); + const lastLines = result.output.trim().split('\n').slice(-5).join('\n'); + if (lastLines) console.log(lastLines); - return result.ok; + return; + } + onSuccess(); + }); + if (!started) console.log('CloudUI update already running, not starting another.'); } async function checkCloudUI() { @@ -254,9 +258,7 @@ async function checkCloudUI() { return; } console.log(`checkCloudUI: FluxOS version ${version} >= 8.0.0. Downloading CloudUI...`); - if (await updateCloudUI(apiBaseUrl)) { - console.log('checkCloudUI: CloudUI download completed.'); - } + updateCloudUI(apiBaseUrl, () => console.log('checkCloudUI: CloudUI download completed.')); } else { console.log('checkCloudUI: FluxOS version < 8.0.0 or not detected. Skipping CloudUI download.'); } @@ -1097,17 +1099,17 @@ async function auto_update() { if (!cloudui_api_base_url) { console.log('No API host available, skipping the FluxCloud UI update.'); } else { - await updateCloudUI(cloudui_api_base_url); - } - await sleep(5 * 1_000); - let cloudui_lv = ''; - if (fs.existsSync(cloudui_local_version_file)) { - cloudui_lv = fs.readFileSync(cloudui_local_version_file, 'utf8').trim(); - } - if (cloudui_remote_hash == cloudui_lv) { - console.log('Update successfully.'); + updateCloudUI(cloudui_api_base_url, () => { + const cloudui_lv = fs.existsSync(cloudui_local_version_file) + ? fs.readFileSync(cloudui_local_version_file, 'utf8').trim() + : ''; + if (cloudui_remote_hash == cloudui_lv) { + console.log('FluxCloud UI updated successfully.'); + } else { + console.log('FluxCloud UI update ended, but the installed version is not the release.'); + } + }); } - await sleep(20 * 1_000); console.log(' '); } } From 5b39a52e9a0fb79b76cb7b38cdb31a95e8f27389 Mon Sep 17 00:00:00 2001 From: David White Date: Sun, 25 Oct 2026 09:05:49 +0000 Subject: [PATCH 6/7] fix(cloudui): a scratch directory the update cannot prepare is a failed update An error emptying or creating the scratch directory is returned as the update's result, with its reason, instead of being thrown before the update has started, so a background update reports it and the next one can start. Co-Authored-By: Claude Opus 5.5 --- cloudui_update.js | 24 ++++++++++++++++++----- test/cloudui_update.test.js | 38 +++++++++++++++++++++++++++++++++++++ 2 files changed, 57 insertions(+), 5 deletions(-) diff --git a/cloudui_update.js b/cloudui_update.js index bb43f29..4c4da86 100644 --- a/cloudui_update.js +++ b/cloudui_update.js @@ -58,14 +58,12 @@ function runCloudUiUpdate({ scratchDir = CLOUDUI_SCRATCH_DIR, command = ['npm', 'run', 'update:cloudui', '--', apiBaseUrl], }) { - clearScratch(scratchDir); - fs.mkdirSync(scratchDir, { recursive: true, mode: 0o700 }); - return new Promise((resolve) => { let output = ''; let timedOut = false; let spawnError = null; let settled = false; + let timer = null; let graceTimer = null; const finish = (code, signal) => { @@ -73,7 +71,11 @@ function runCloudUiUpdate({ settled = true; clearTimeout(timer); clearTimeout(graceTimer); - clearScratch(scratchDir); + try { + clearScratch(scratchDir); + } catch { + // Left in place; the next run cannot prepare it either and reports why. + } resolve({ ok: !timedOut && !spawnError && code === 0, timedOut, @@ -84,6 +86,18 @@ function runCloudUiUpdate({ }); }; + // A scratch directory that cannot be emptied or created fails the update before it + // starts. + try { + clearScratch(scratchDir); + fs.mkdirSync(scratchDir, { recursive: true, mode: 0o700 }); + } catch (error) { + spawnError = error; + finish(null, null); + + return; + } + const child = spawn(command[0], command.slice(1), { cwd: fluxOsRootDir, env: { ...process.env, TMPDIR: scratchDir }, @@ -97,7 +111,7 @@ function runCloudUiUpdate({ child.stdout.on('data', collect); child.stderr.on('data', collect); - const timer = setTimeout(() => { + timer = setTimeout(() => { timedOut = true; signalGroup(child.pid, 'SIGTERM'); graceTimer = setTimeout(() => signalGroup(child.pid, 'SIGKILL'), graceMs); diff --git a/test/cloudui_update.test.js b/test/cloudui_update.test.js index 3d6eee0..333b25c 100644 --- a/test/cloudui_update.test.js +++ b/test/cloudui_update.test.js @@ -243,3 +243,41 @@ test('an update whose onDone throws still lets the next one start', async () => assert.ok(next); await next; }); + +test('reports a scratch directory that cannot be created as a failed update, and runs nothing', async () => { + const { base } = tempDirs(); + const notADir = path.join(base, 'file'); + fs.writeFileSync(notADir, 'x'); + const ran = path.join(base, 'ran'); + const result = await runCloudUiUpdate({ + fluxOsRootDir: base, + apiBaseUrl: 'https://api.github.com', + scratchDir: path.join(notADir, 'scratch'), + command: ['sh', '-c', `touch ${ran}`], + }); + assert.strictEqual(result.ok, false); + assert.ok(result.error); + assert.strictEqual(failureReason(result), result.error.message); + assert.strictEqual(fs.existsSync(ran), false); +}); + +test('a background update whose scratch directory cannot be created ends with its failure', async () => { + const { base } = tempDirs(); + const notADir = path.join(base, 'file'); + fs.writeFileSync(notADir, 'x'); + const options = { + fluxOsRootDir: base, + apiBaseUrl: 'https://api.github.com', + scratchDir: path.join(notADir, 'scratch'), + command: ['sh', '-c', 'true'], + }; + let result = null; + await startCloudUiUpdate(options, (r) => { + result = r; + }); + assert.strictEqual(result.ok, false); + assert.ok(result.error); + const next = startCloudUiUpdate(options, () => {}); + assert.ok(next); + await next; +}); From 43cd2539d44dc6ecbc18f30a90a19e5a807480b4 Mon Sep 17 00:00:00 2001 From: David White Date: Sun, 25 Oct 2026 09:26:10 +0000 Subject: [PATCH 7/7] fix(cloudui): a timed-out update's reason states the limit it ran with The update's result carries its time limit, and the failure reason states that limit rather than the default one. Co-Authored-By: Claude Opus 5.5 --- cloudui_update.js | 25 ++++++++++++++++++++++--- test/cloudui_update.test.js | 17 +++++++++++++++-- 2 files changed, 37 insertions(+), 5 deletions(-) diff --git a/cloudui_update.js b/cloudui_update.js index 4c4da86..12ba46d 100644 --- a/cloudui_update.js +++ b/cloudui_update.js @@ -47,7 +47,7 @@ function signalGroup(pid, signal) { * @param {number} [options.graceMs] - Time from SIGTERM to SIGKILL after a timeout. * @param {string} [options.scratchDir] - Directory given to the update as TMPDIR. * @param {string[]} [options.command] - Command and arguments; defaults to the npm script. - * @returns {Promise<{ok: boolean, timedOut: boolean, code: number|null, + * @returns {Promise<{ok: boolean, timedOut: boolean, timeoutMs: number, code: number|null, * signal: string|null, error: Error|null, output: string}>} */ function runCloudUiUpdate({ @@ -79,6 +79,7 @@ function runCloudUiUpdate({ resolve({ ok: !timedOut && !spawnError && code === 0, timedOut, + timeoutMs, code, signal, error: spawnError, @@ -149,13 +150,31 @@ function startCloudUiUpdate(options, onDone) { return running; } +/** + * A duration in the largest whole unit that states it exactly. + * @param {number} ms + * @returns {string} + */ +function duration(ms) { + const units = [ + [3_600_000, 'hour'], + [60_000, 'minute'], + [1_000, 'second'], + ]; + const [size, name] = units.find(([unit]) => ms >= unit && ms % unit === 0) || [1, 'millisecond']; + const count = ms / size; + + return `${count} ${name}${count === 1 ? '' : 's'}`; +} + /** * Why an update that did not succeed failed, for the log. - * @param {{timedOut: boolean, error: Error|null, signal: string|null, code: number|null}} result + * @param {{timedOut: boolean, timeoutMs: number, error: Error|null, signal: string|null, + * code: number|null}} result * @returns {string} */ function failureReason(result) { - if (result.timedOut) return `timed out after ${CLOUDUI_UPDATE_TIMEOUT_MS / 3_600_000} hours`; + if (result.timedOut) return `timed out after ${duration(result.timeoutMs)}`; if (result.error) return result.error.message; if (result.signal) return `killed by ${result.signal}`; diff --git a/test/cloudui_update.test.js b/test/cloudui_update.test.js index 333b25c..a5053bb 100644 --- a/test/cloudui_update.test.js +++ b/test/cloudui_update.test.js @@ -4,7 +4,12 @@ const fs = require('fs'); const os = require('os'); const path = require('node:path'); -const { runCloudUiUpdate, startCloudUiUpdate, failureReason } = require('../cloudui_update'); +const { + runCloudUiUpdate, + startCloudUiUpdate, + failureReason, + CLOUDUI_UPDATE_TIMEOUT_MS, +} = require('../cloudui_update'); function tempDirs() { const base = fs.mkdtempSync(path.join(os.tmpdir(), 'cloudui-update-test-')); @@ -64,7 +69,7 @@ test('a timeout kills every process the update started and removes its files', a }); assert.strictEqual(result.ok, false); assert.strictEqual(result.timedOut, true); - assert.strictEqual(failureReason(result), 'timed out after 6 hours'); + assert.strictEqual(failureReason(result), 'timed out after 500 milliseconds'); const downloadPid = Number(fs.readFileSync(pidFile, 'utf8')); assert.ok(downloadPid > 0); await new Promise((r) => setTimeout(r, 200)); @@ -281,3 +286,11 @@ test('a background update whose scratch directory cannot be created ends with it assert.ok(next); await next; }); + +test('states the time limit an update ran with', () => { + const timedOut = (timeoutMs) => failureReason({ timedOut: true, timeoutMs }); + assert.strictEqual(timedOut(CLOUDUI_UPDATE_TIMEOUT_MS), 'timed out after 6 hours'); + assert.strictEqual(timedOut(60_000), 'timed out after 1 minute'); + assert.strictEqual(timedOut(90_000), 'timed out after 90 seconds'); + assert.strictEqual(timedOut(1_500), 'timed out after 1500 milliseconds'); +});