diff --git a/cloudui_update.js b/cloudui_update.js new file mode 100644 index 0000000..12ba46d --- /dev/null +++ b/cloudui_update.js @@ -0,0 +1,191 @@ +/** + * Runs FluxOS's CloudUI update (`npm run update:cloudui -- `). + * + * 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 + * 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 = 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 }); +} + +function signalGroup(pid, signal) { + try { + process.kill(-pid, signal); + } 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 {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, timeoutMs: number, code: number|null, + * signal: string|null, error: Error|null, output: string}>} + */ +function runCloudUiUpdate({ + fluxOsRootDir, + apiBaseUrl, + timeoutMs = CLOUDUI_UPDATE_TIMEOUT_MS, + graceMs = CLOUDUI_UPDATE_GRACE_MS, + scratchDir = CLOUDUI_SCRATCH_DIR, + command = ['npm', 'run', 'update:cloudui', '--', apiBaseUrl], +}) { + 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) => { + if (settled) return; + settled = true; + clearTimeout(timer); + clearTimeout(graceTimer); + try { + clearScratch(scratchDir); + } catch { + // Left in place; the next run cannot prepare it either and reports why. + } + resolve({ + ok: !timedOut && !spawnError && code === 0, + timedOut, + timeoutMs, + code, + signal, + error: spawnError, + output: output.slice(-MAX_OUTPUT_CHARS), + }); + }; + + // 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 }, + 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); + + timer = setTimeout(() => { + timedOut = true; + signalGroup(child.pid, 'SIGTERM'); + graceTimer = setTimeout(() => signalGroup(child.pid, 'SIGKILL'), graceMs); + }, timeoutMs); + + child.on('error', (error) => { + spawnError = error; + finish(null, null); + }); + // Anything the update left running in its group is stopped once the update exits. + // 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); + }); +} + +/** + * 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; +} + +/** + * 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, timeoutMs: number, error: Error|null, signal: string|null, + * code: number|null}} result + * @returns {string} + */ +function failureReason(result) { + 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}`; + + return `exited with code ${result.code}`; +} + +module.exports = { + runCloudUiUpdate, + startCloudUiUpdate, + 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 new file mode 100644 index 0000000..a5053bb --- /dev/null +++ b/test/cloudui_update.test.js @@ -0,0 +1,296 @@ +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, + startCloudUiUpdate, + failureReason, + CLOUDUI_UPDATE_TIMEOUT_MS, +} = 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); + 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)); + assert.strictEqual(alive(downloadPid), false); + 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'); + 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(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({ + 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(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; +}); + +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; +}); + +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'); +}); diff --git a/watchdog.js b/watchdog.js index a6c73d1..db6bca4 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 { startCloudUiUpdate, failureReason } = require('./cloudui_update'); const execFilePromise = promisify(execFile); @@ -221,6 +222,22 @@ function cloudUiApiBaseUrl() { } } +// 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; + } + onSuccess(); + }); + if (!started) console.log('CloudUI update already running, not starting another.'); +} + async function checkCloudUI() { const cloudUIDir = path.join(fluxOsRootDir, 'CloudUI'); if (fs.existsSync(cloudUIDir)) { @@ -241,10 +258,7 @@ 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.'); + 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 +1048,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 +1076,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,22 +1099,17 @@ 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 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(' '); } }