diff --git a/docs/api.md b/docs/api.md index 14d69b81..7bb92de5 100644 --- a/docs/api.md +++ b/docs/api.md @@ -141,3 +141,5 @@ The worker settings panel exposes these controls with a warning acknowledgement. Management MCP exposes `workers.recovery.get`, `workers.recovery.set`, `workers.desired-state.set`, and `workers.emergency-stop` to platform administrators and to group administrators for ordinary workers in their live group subtree. The state and emergency tools require `confirmed:true`; mutation tools enforce worker protection locks. `admin-workspace.emergency-stop` is platform-only and requires the exact `workerId`. `groups.admin-workspace.emergency-stop` accepts an authorized `groupId`, confirmation, and any required lock password; it can target the bound group or a descendant, and never provisions a missing administrative workspace. Group membership and hierarchy are rechecked when executing, so sibling, ungrouped, foreign-owner and platform-administrative workers remain outside group scope. Guest GPU driver installation/repair remains the guest administrator's responsibility. A shared guest udev wait causing unrelated storage preparation to fail is a separate hypothesis requiring disposable reproduction; these controls do not replace drivers or weaken storage validation. + +Worker startup failures preserve a platform-authored phase such as `Docker storage preparation`, including native exec timeouts; raw guest output is excluded. Docker storage startup waits up to 30 seconds for its exact owned device instead of waiting for unrelated global udev events. Existing disk identity, filesystem and initialization authorization checks still apply. diff --git a/orchestrator/app/composables/useContainers.ts b/orchestrator/app/composables/useContainers.ts index 7a20792d..b536baf2 100644 --- a/orchestrator/app/composables/useContainers.ts +++ b/orchestrator/app/composables/useContainers.ts @@ -1,6 +1,8 @@ import type { ContainerInfo, CreateContainerRequest, UpdateContainerSettingsRequest } from '~/types'; +import { fetchErrorMessage } from '../utils/fetch-error'; export function useContainers() { + const toast = useToast(); const { data: containers, refresh } = useFetch('/api/containers', { key: 'workers', default: () => [], @@ -23,8 +25,13 @@ export function useContainers() { } async function restartContainer(id: string) { - await $fetch(`/api/containers/${id}/restart`, { method: 'POST' }); - await refresh(); + const notice = toast.add({ title: 'Starting worker', description: 'Waiting for storage preparation and worker readiness.', duration: 0 }); + try { + await $fetch(`/api/containers/${id}/restart`, { method: 'POST', retry: 0 }); + toast.add({ title: 'Worker started', description: 'Worker readiness confirmed.', color: 'success', duration: 5000 }); + } catch (error) { + toast.add({ title: 'Worker start not confirmed', description: fetchErrorMessage(error, 'Inspect runtime recovery for the failed startup phase before retrying.'), color: 'error', duration: 0 }); + } finally { toast.remove(notice.id); await refresh(); } } async function recoverContainer( diff --git a/orchestrator/server/utils/incus-worker-runtime.ts b/orchestrator/server/utils/incus-worker-runtime.ts index 6714c2fb..52cb366b 100644 --- a/orchestrator/server/utils/incus-worker-runtime.ts +++ b/orchestrator/server/utils/incus-worker-runtime.ts @@ -1453,7 +1453,9 @@ export class IncusWorkerRuntime { } private async checkedExec(name: string, command: string[], phase = "guest bootstrap"): Promise { - const result = await this.client.exec(name, command); + let result; + try { result = await this.client.exec(name, command); } + catch { throw new WorkerStartupError(phase); } if (result.returnCode !== 0) throw new WorkerStartupError(phase, result.returnCode); } @@ -1921,7 +1923,7 @@ export class IncusWorkerRuntime { await new Promise((resolve) => setTimeout(resolve, 500)); } if (!ready) { - useLogger().warn("[incus-worker] guest agent readiness deadline expired; startup unconfirmed, VM retained for recovery"); + useLogger().warn(`[incus-worker] ${opts.id}: guest agent readiness deadline expired; startup unconfirmed, VM retained for recovery`); throw new WorkerStartupError("guest agent readiness deadline"); } try { @@ -1978,6 +1980,7 @@ export class IncusWorkerRuntime { initialize: await storage.dockerInitializationAllowed(opts), }), { uid: 0, gid: 0, mode: 0o600 }); await this.checkedExec(name, ["systemctl", "unmask", "docker", "docker.socket", "containerd", "agentor-docker-storage"]); + useLogger().info(`[incus-worker] ${opts.id}: preparing Docker storage; worker service remains stopped until storage is verified`); await this.checkedExec(name, ["systemctl", "start", "agentor-docker-storage"], "Docker storage preparation"); await this.checkedExec(name, ["mountpoint", "-q", "/var/lib/docker"]); await storage.markDockerInitialized(opts); @@ -1988,12 +1991,13 @@ export class IncusWorkerRuntime { await this.checkedExec(name, ["systemctl", "mask", "docker", "docker.socket", "containerd"]); } recovery.assertStartAllowed?.(); + useLogger().info(`[incus-worker] ${opts.id}: starting worker service; readiness confirmation pending`); await this.checkedExec(name, ["systemctl", "start", "agentor-worker.service"], "worker service start"); - await this.checkedExec(name, ["systemctl", "is-active", "--quiet", "agentor-worker.service"]); + await this.checkedExec(name, ["systemctl", "is-active", "--quiet", "agentor-worker.service"], "worker service readiness"); const workerDeadline = Date.now() + 120_000; let workerReady = false; while (Date.now() < workerDeadline) { - await this.checkedExec(name, ["systemctl", "is-active", "--quiet", "agentor-worker.service"]); + await this.checkedExec(name, ["systemctl", "is-active", "--quiet", "agentor-worker.service"], "worker service readiness"); const result = await this.client.exec(name, ["grep", "-q", "^READY|", "/tmp/worker-events"]); if (result.returnCode === 0) { workerReady = true; break; } await new Promise((resolve) => setTimeout(resolve, 500)); @@ -2006,7 +2010,7 @@ export class IncusWorkerRuntime { try { await this.stop(opts, instance.config['volatile.uuid']); outcome = 'startup VM stopped; persistent data retained'; } catch { outcome = 'startup cleanup unconfirmed; operator recovery required'; } } - useLogger().warn(`[incus-worker] ${workerStartupFailure(error).message}; ${outcome}`); + useLogger().warn(`[incus-worker] ${opts.id}: ${workerStartupFailure(error).message}; ${outcome}`); throw error; } } diff --git a/tests/FEATURES.md b/tests/FEATURES.md index d7571b8d..b0107ab5 100644 --- a/tests/FEATURES.md +++ b/tests/FEATURES.md @@ -1521,3 +1521,5 @@ Terminal WebSocket attachment preserves only the latest validated early resize a - Operator desired-state controls remain available with an explicit warning when actual runtime state is unknown; desired and observed state remain distinct. - Emergency-stop intent is accepted during pending worker/platform/group lifecycle operations, preserves runtime identity/settlement fences and reports confirmation separately. - Equivalent REST/GUI/management MCP controls; group administrators are restricted to live descendant groups and member workers, while platform administrative shutdown is platform-only. + +Docker storage preparation waits only for the exact owned block-device identity, with a bounded deadline and retained filesystem/initialization safeguards. Native startup logs correlate storage/service phases and cleanup outcomes with the worker. Start/Retry shows a pending notification and a visible confirmed/failed result instead of leaving a rejected UI action unexplained. diff --git a/tests/TESTS.md b/tests/TESTS.md index f507526b..289542e7 100644 --- a/tests/TESTS.md +++ b/tests/TESTS.md @@ -652,3 +652,5 @@ Admin memory host-policy regression coverage now includes applied 6 GiB VM admis Recovery controls (#61): `api/worker-recovery-controls.spec.ts` covers finite limits, atomic durable reservations/reload, safe startup errors, REST/MCP confirmation and protection locks, global/group tool discovery, descendant authorization and revocation. `ui/worker-recovery-isolated.spec.ts` runs the actual production panel with HTTP fixtures to verify unknown-state warnings and retained counters. Native worker lifecycle and administrative transaction suites cover stop intent during in-flight/late-settling starts and native retry exhaustion. + +Storage startup regression coverage: `api/incus-docker-storage-startup.spec.ts` executes the real helper with isolated device/command fixtures for ready/delayed/missing/ambiguous disks, unauthorized initialization and incompatible filesystems. Unrelated udev activity cannot block an already identified disk. Native runtime coverage preserves a sanitized storage phase on transport timeout and forbids worker-service startup after that failure. `api/worker-start-feedback.spec.ts` verifies pending, failed and confirmed GUI notifications and status refresh. diff --git a/tests/api/incus-docker-storage-startup.spec.ts b/tests/api/incus-docker-storage-startup.spec.ts new file mode 100644 index 00000000..22b015ac --- /dev/null +++ b/tests/api/incus-docker-storage-startup.spec.ts @@ -0,0 +1,51 @@ +import { test, expect } from '@playwright/test'; +import { mkdtemp, readFile, writeFile, symlink, rm } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { spawnSync } from 'node:child_process'; + +async function runStorage(mode: 'ready' | 'delayed' | 'missing' | 'ambiguous' | 'unformatted' | 'wrong-filesystem') { + const root = await mkdtemp(join(tmpdir(), 'agentor-storage-wait-')); + try { + const source = await readFile(new URL('../../worker/vm/agentor-docker-storage.sh', import.meta.url), 'utf8'); + const disk = join(root, 'disk'), alias = join(root, 'alias'), second = join(root, 'second'); + await writeFile(join(root, 'config'), JSON.stringify({ serial: 'incus_docker', volume: 'fixture-docker', initialize: false })); + await symlink(disk, alias); + if (mode !== 'missing' && mode !== 'delayed') await writeFile(disk, 'preserved-fixture'); + if (mode === 'ambiguous') { await writeFile(join(root, 'other'), 'other-fixture'); await symlink(join(root, 'other'), second); } + const script = source.replace('/run/agentor/docker-storage.json', join(root, 'config')) + .replaceAll('/dev/disk/by-id/scsi-0QEMU_QEMU_HARDDISK_incus_docker', alias) + .replaceAll('/dev/disk/by-id/virtio-incus_docker', second).replaceAll('/var/lib/docker', join(root, 'mount')); + await writeFile(join(root, 'storage.sh'), script); + // Simulate block nodes and mount inspection without privileged devices or writes. + const environment = String.raw` +test() { if [[ "$1" == -b ]]; then [[ -f "$2" ]]; else builtin test "$@"; fi; } +stat() { printf '0:600\n'; } +udevadm() { echo unexpected-global-udev-wait >&2; return 99; } +lsblk() { printf 'disk\n'; } +blkid() { case "$FIXTURE_MODE" in unformatted) :;; wrong-filesystem) echo xfs;; *) echo ext4;; esac; } +mountpoint() { return 0; } +findmnt() { if [[ " $* " == *' FSTYPE '* ]]; then echo ext4; else printf '%s\n' "$FIXTURE_ROOT/disk"; fi; } +mount() { echo unexpected-mount >&2; return 98; } +mkfs.ext4() { echo unexpected-format >&2; return 97; } +wipefs() { echo unexpected-format-probe >&2; return 96; } +sleep() { if [[ "$FIXTURE_MODE" == delayed ]]; then printf preserved-fixture > "$FIXTURE_ROOT/disk"; SECONDS=$((SECONDS + 1)); else SECONDS=$((SECONDS + 31)); fi; } +`; + await writeFile(join(root, 'environment'), environment); + const result = spawnSync('bash', [join(root, 'storage.sh')], { encoding: 'utf8', timeout: 5000, + env: { ...process.env, BASH_ENV: join(root, 'environment'), FIXTURE_MODE: mode, FIXTURE_ROOT: root } }); + if (result.error) throw result.error; + expect(result.stderr).not.toMatch(/unexpected-global|unexpected-mount|unexpected-format/); + if (mode !== 'missing' && mode !== 'delayed') expect(await readFile(disk, 'utf8')).toBe('preserved-fixture'); + return result; + } finally { await rm(root, { recursive: true, force: true }); } +} +for (const mode of ['ready', 'delayed'] as const) test(`owned Docker disk ${mode}: unrelated udev activity does not block existing ext4 data`, async () => { + const result = await runStorage(mode); expect(result.status, result.stderr).toBe(0); + expect(result.stdout).toContain('storage preparation complete'); +}); +for (const [mode, message] of [['missing', 'absent after 30 seconds'], ['ambiguous', 'Ambiguous Docker block device'], + ['unformatted', 'Initialization not authorized'], ['wrong-filesystem', 'refusing to overwrite existing xfs']] as const) + test(`owned Docker disk ${mode}: stops without mounting or formatting`, async () => { + const result = await runStorage(mode); expect(result.status).toBe(1); expect(result.stderr).toContain(message); + }); diff --git a/tests/api/incus-worker-runtime.spec.ts b/tests/api/incus-worker-runtime.spec.ts index 119d51f3..1cb196e7 100644 --- a/tests/api/incus-worker-runtime.spec.ts +++ b/tests/api/incus-worker-runtime.spec.ts @@ -25,6 +25,7 @@ import { incusImageIdentity, sameIncusImageSource, validateIncusImageIdentity } import { IncusWorkerStorage } from '../../orchestrator/server/utils/incus-worker-storage'; import { backupInstallationId } from '../../orchestrator/server/utils/backup-installation'; import { ManagedVolumeStore } from '../../orchestrator/server/utils/managed-volume-store'; +import { workerStartupFailure } from '../../orchestrator/server/utils/worker-startup-error'; import { IncusManagedVolumeRuntime } from '../../orchestrator/server/utils/incus-managed-volume-runtime'; import { HostMountStore } from '../../orchestrator/server/utils/host-mount-store'; import { WorkerGroupStore } from '../../orchestrator/server/utils/worker-group-store'; @@ -1284,6 +1285,22 @@ test("Docker initialization authority is revoked before the worker can start", a expect(revoked).toBeLessThan(workerStart); }); +test('storage exec timeout retains its public phase without exposing transport details or starting the worker', async () => { + const { client, events } = fakeClient(); + const original = client.exec; + client.exec = async (...args: any[]) => { + if (args[1].join(' ') === 'systemctl start agentor-docker-storage') + throw Object.assign(new Error('private-transport-detail-and-secret'), { statusCode: 408 }); + return original(...args); + }; + const opts = options(); opts.dockerEnabled = opts.environmentJson.dockerEnabled = true; + const error = await new IncusWorkerRuntime(config, client as any).create(opts).catch(error => error); + expect(workerStartupFailure(error)).toMatchObject({ code: 'WORKER_BOOTSTRAP_FAILED', phase: 'Docker storage preparation' }); + expect(JSON.stringify(workerStartupFailure(error))).not.toContain('private-transport'); + expect(events.some(event => event.operation === 'exec' && event.args[1].join(' ') === 'systemctl start agentor-worker.service')).toBe(false); + expect(events.some(event => event.operation === 'stop')).toBe(true); +}); + test("shell configuration preserves literal quotes/newlines without executing substitutions", () => { const value = "quotes '\" and\n$(printf exploited) `printf exploited`"; const output = execFileSync("bash", ["-c", `${serializeIncusWorkerEnv({ VALUE: value })}\nprintf '%s' \"$VALUE\"`], { encoding: "utf8" }); diff --git a/tests/api/worker-start-feedback.spec.ts b/tests/api/worker-start-feedback.spec.ts new file mode 100644 index 00000000..2ab8a5b9 --- /dev/null +++ b/tests/api/worker-start-feedback.spec.ts @@ -0,0 +1,36 @@ +import { test, expect } from '@playwright/test'; +import { useContainers } from '../../orchestrator/app/composables/useContainers'; + +for (const fails of [false, true]) test(`worker start ${fails ? 'failure' : 'success'} visibly replaces its pending notice and refreshes status`, async () => { + const names = ['useToast', 'useFetch', 'usePolling', '$fetch']; + const previous = names.map(name => Object.getOwnPropertyDescriptor(globalThis, name)); + const notices: any[] = [], removed: string[] = [], requests: any[] = []; + let refreshes = 0, settle!: () => void; + const pending = new Promise((resolve, reject) => { + settle = () => fails ? reject({ data: { statusMessage: 'Incus worker bootstrap command failed during Docker storage preparation' } }) : resolve(); + }); + Object.assign(globalThis, { + useToast: () => ({ add: (notice: any) => { notices.push(notice); return { id: 'fixture-notice' }; }, remove: (id: string) => removed.push(id) }), + useFetch: () => ({ data: { value: [] }, refresh: async () => { refreshes++; } }), + usePolling: () => {}, + $fetch: (url: string, options: any) => { requests.push({ url, options }); return pending; }, + }); + try { + const operation = useContainers().restartContainer('fixture-worker'); + expect(notices[0]).toMatchObject({ title: 'Starting worker', duration: 0 }); + expect(notices[0].description).toContain('storage'); + expect(removed).toEqual([]); + settle(); await operation; + expect(requests).toEqual([{ url: '/api/containers/fixture-worker/restart', options: { method: 'POST', retry: 0 } }]); + expect(refreshes).toBe(1); + expect(notices).toHaveLength(2); + expect(removed).toEqual(['fixture-notice']); + expect(notices[1]).toMatchObject({ color: fails ? 'error' : 'success', title: fails ? 'Worker start not confirmed' : 'Worker started' }); + if (fails) expect(notices[1].description).toContain('Docker storage preparation'); + } finally { + for (const [index, name] of names.entries()) { + if (previous[index]) Object.defineProperty(globalThis, name, previous[index]!); + else delete (globalThis as any)[name]; + } + } +}); diff --git a/tests/playwright.modules.config.ts b/tests/playwright.modules.config.ts index 6cfa385d..9646c3d7 100644 --- a/tests/playwright.modules.config.ts +++ b/tests/playwright.modules.config.ts @@ -160,6 +160,8 @@ export default defineConfig({ "api/incus-worker-experience.spec.ts", "api/incus-derived-image.spec.ts", "api/incus-worker-runtime.spec.ts", + "api/incus-docker-storage-startup.spec.ts", + "api/worker-start-feedback.spec.ts", "api/incus-canonical-archive.spec.ts", "api/incus-offline-archive-helper.spec.ts", "api/incus-original-workspace-live.spec.ts", diff --git a/worker/vm/agentor-docker-storage.sh b/worker/vm/agentor-docker-storage.sh index 7e6adcf7..69ba9029 100644 --- a/worker/vm/agentor-docker-storage.sh +++ b/worker/vm/agentor-docker-storage.sh @@ -11,16 +11,23 @@ jq -e '.serial == "incus_docker" and (.volume | test("^[A-Za-z0-9_-]+-docker$")) # Only the exact serial of Incus device "docker", whose source is checked by # the orchestrator against worker-owned volume metadata. Never scan unused # disks or use /dev/sdb as authority. -udevadm settle +# Unrelated GPU/USB events can keep the global udev queue busy indefinitely. +echo "[agentor-docker-storage] Waiting up to 30 seconds for the owned Docker block device..." DOCKER_DISK="" -for id in /dev/disk/by-id/scsi-0QEMU_QEMU_HARDDISK_incus_docker /dev/disk/by-id/virtio-incus_docker; do - if [[ -b "$id" ]]; then - disk=$(readlink -f "$id") - [[ -z "$DOCKER_DISK" || "$DOCKER_DISK" == "$disk" ]] || fail "Ambiguous Docker block device" - DOCKER_DISK="$disk" +deadline=$((SECONDS + 30)) +while [[ -z "$DOCKER_DISK" ]]; do + for id in /dev/disk/by-id/scsi-0QEMU_QEMU_HARDDISK_incus_docker /dev/disk/by-id/virtio-incus_docker; do + if test -b "$id"; then + disk=$(readlink -f "$id") + [[ -z "$DOCKER_DISK" || "$DOCKER_DISK" == "$disk" ]] || fail "Ambiguous Docker block device" + DOCKER_DISK="$disk" + fi + done + if [[ -z "$DOCKER_DISK" ]]; then + ((SECONDS < deadline)) || fail "Owned Docker block device absent after 30 seconds; Docker startup stopped, existing data unchanged; inspect the Incus disk attachment" + sleep 1 fi done -[[ -n "$DOCKER_DISK" ]] || fail "Expected Incus Docker block device is absent" [[ "$(lsblk -dn -o TYPE "$DOCKER_DISK")" == disk ]] || fail "Expected a whole custom block volume" [[ "$(lsblk -n -o NAME "$DOCKER_DISK" | wc -l)" -eq 1 ]] || fail "Partitioned Docker volume needs explicit recovery" @@ -44,3 +51,5 @@ else mount -o defaults "$DOCKER_DISK" /var/lib/docker fi [[ "$(findmnt -n -o FSTYPE --target /var/lib/docker)" == ext4 ]] || fail "Docker storage must be native ext4" + +echo "[agentor-docker-storage] Owned ext4 Docker storage verified and mounted; storage preparation complete."