From 68d7321716cde3ce6617bd161d2dfd814caa25d2 Mon Sep 17 00:00:00 2001 From: Neil Date: Mon, 16 Nov 2026 16:21:16 -0800 Subject: [PATCH] fix(wsl): reclaim a dead installer's orcad lock in seconds via a guest kernel lock --- .../install/orcad-host-transport.ts | 2 + .../orcad-remote-install-lock-holder.test.ts | 139 +++++++++++ .../install/orcad-remote-install.ts | 86 +++++-- .../remote-install-lock-boot-identity.ts | 79 ++++++ .../install/remote-install-lock-commands.ts | 107 +++----- ...emote-install-lock-holder-commands.test.ts | 232 ++++++++++++++++++ .../remote-install-lock-holder-commands.ts | 144 +++++++++++ .../remote-install-lock-holder-takeover.ts | 69 ++++++ .../remote-install-lock-holder.test.ts | 99 ++++++++ .../install/remote-install-lock-holder.ts | 108 ++++++++ .../install/remote-install-lock-wait.test.ts | 151 ++++++++++++ .../install/remote-install-lock.ts | 51 +++- .../wsl-orcad-host-transport-loops.test.ts | 18 ++ .../wsl/orcad/wsl-orcad-host-transport.ts | 128 +++++----- 14 files changed, 1249 insertions(+), 164 deletions(-) create mode 100644 src/main/managed-server/install/orcad-remote-install-lock-holder.test.ts create mode 100644 src/main/managed-server/install/remote-install-lock-boot-identity.ts create mode 100644 src/main/managed-server/install/remote-install-lock-holder-commands.test.ts create mode 100644 src/main/managed-server/install/remote-install-lock-holder-commands.ts create mode 100644 src/main/managed-server/install/remote-install-lock-holder-takeover.ts create mode 100644 src/main/managed-server/install/remote-install-lock-holder.test.ts create mode 100644 src/main/managed-server/install/remote-install-lock-holder.ts create mode 100644 src/main/managed-server/install/remote-install-lock-wait.test.ts diff --git a/src/main/managed-server/install/orcad-host-transport.ts b/src/main/managed-server/install/orcad-host-transport.ts index c30380754f9..0a571f6223c 100644 --- a/src/main/managed-server/install/orcad-host-transport.ts +++ b/src/main/managed-server/install/orcad-host-transport.ts @@ -18,6 +18,8 @@ export type OrcadHostTransport = RemoteInstallTransport & { readonly orcadLaunchEnv?: ( launch: OrcadLaunchEnvRequest ) => Promise + /** WSL only: a transport whose every host command first runs the POSIX `fence` statement. */ + readonly withCommandFence?: (fence: string) => OrcadHostTransport } /** The slot being launched; entries only its own build understands must check the version. */ diff --git a/src/main/managed-server/install/orcad-remote-install-lock-holder.test.ts b/src/main/managed-server/install/orcad-remote-install-lock-holder.test.ts new file mode 100644 index 00000000000..69bdfe3c00e --- /dev/null +++ b/src/main/managed-server/install/orcad-remote-install-lock-holder.test.ts @@ -0,0 +1,139 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' +import type { OrcadHostTransport } from './orcad-host-transport' + +type HolderInstallState = { + events: string[] + uploadConn: unknown + holderAvailable: boolean + loseHolderDuringUpload: boolean + loseHolder: () => void + acquireOptions: { probeExitedHolder?: boolean } | null +} + +const state = vi.hoisted((): HolderInstallState => ({ + events: [], + uploadConn: null, + holderAvailable: true, + loseHolderDuringUpload: false, + loseHolder: () => {}, + acquireOptions: null +})) + +vi.mock('./orcad-remote-node-runtime', () => ({ ensureRemoteOrcadNodeRuntime: async () => {} })) +vi.mock('./remote-versioned-install', () => ({ + isRemoteInstallComplete: async () => false, + abandonInstall: async (conn: { fenced?: string }) => { + state.events.push(`abandon:${conn.fenced ? 'fenced' : 'plain'}`) + return true + }, + finalizeInstall: async (conn: { fenced?: string }) => { + state.events.push(`finalize:${conn.fenced ? 'fenced' : 'plain'}`) + } +})) +vi.mock('./remote-install-transfers', () => ({ + uploadRemoteInstallDirectory: async ( + conn: unknown, + _local: unknown, + _remote: unknown, + _host: unknown, + options: { signal?: AbortSignal } + ) => { + state.uploadConn = conn + if (state.loseHolderDuringUpload) { + state.loseHolder() + await Promise.resolve() + options.signal?.throwIfAborted() + } + }, + writeRemoteInstallFile: async () => {} +})) +vi.mock('../../ssh/remote-exec/remote-exec-command', async (importOriginal) => ({ + ...(await importOriginal()), + execCommand: async () => '' +})) +vi.mock('./remote-install-lock', () => ({ + acquireInstallLock: async ( + _conn: unknown, + _dir: unknown, + _host: unknown, + options: { probeExitedHolder?: boolean } + ) => { + state.acquireOptions = options + } +})) +vi.mock('./remote-install-lock-holder', () => ({ + startInstallLockHolder: async () => { + if (!state.holderAvailable) { + return null + } + let resolveLost: () => void = () => {} + const lost = new Promise((resolve) => (resolveLost = resolve)) + state.loseHolder = resolveLost + return { lost, release: () => state.events.push('release') } + } +})) +vi.mock('../activation/orcad-held-fence-tokens', () => ({ + rememberHeldOrcadFence: () => {}, + forgetHeldOrcadFence: () => {} +})) + +const { installOrcadBundle } = await import('./orcad-remote-install') +const { getRemoteHostPlatform } = await import('../../ssh/remote-host/ssh-remote-platform') + +function wslConn(): OrcadHostTransport { + const conn: OrcadHostTransport = Object.create(null) + return Object.assign(conn, { + withCommandFence: (fence: string) => Object.assign(Object.create(null), { fenced: fence }) + }) +} + +function install(conn: OrcadHostTransport, localWslHost = true) { + return installOrcadBundle( + { + conn, + host: getRemoteHostPlatform('linux-x64'), + localOrcadDir: '/tmp/orcad', + target: 'linux-x64-glibc', + nodeRuntimeArchive: async () => '/tmp/node.tar.xz', + localWslHost + }, + '0.1.0+aa01', + '/home/u/.orca-remote/orcad-0.1.0+aa01' + ) +} + +describe('installOrcadBundle flock-backed install lock on WSL', () => { + beforeEach(() => { + state.events = [] + state.uploadConn = null + state.holderAvailable = true + state.loseHolderDuringUpload = false + state.acquireOptions = null + }) + + it('fences every install command on the holder and releases it after cleanup', async () => { + await expect(install(wslConn())).resolves.toBe('uploaded') + expect(state.acquireOptions?.probeExitedHolder).toBe(true) + expect(state.uploadConn).toMatchObject({ fenced: expect.stringContaining('flock -s -n 7') }) + expect(state.events).toEqual(['finalize:fenced', 'abandon:fenced', 'release']) + }) + + it('stops the install when its holder exits mid-install', async () => { + state.loseHolderDuringUpload = true + await expect(install(wslConn())).rejects.toThrow('The install lock holder exited.') + expect(state.events).toEqual(['abandon:fenced', 'release']) + }) + + it('keeps an unbacked lock where the distro cannot hold one', async () => { + state.holderAvailable = false + await expect(install(wslConn())).resolves.toBe('uploaded') + expect(state.uploadConn).not.toHaveProperty('fenced') + expect(state.events).toEqual(['finalize:plain', 'abandon:plain']) + }) + + it('leaves SSH installs unbacked and unprobed', async () => { + await expect(install(wslConn(), false)).resolves.toBe('uploaded') + expect(state.acquireOptions?.probeExitedHolder).toBeUndefined() + expect(state.uploadConn).not.toHaveProperty('fenced') + }) +}) diff --git a/src/main/managed-server/install/orcad-remote-install.ts b/src/main/managed-server/install/orcad-remote-install.ts index 32bd15be4e9..f5014e9a488 100644 --- a/src/main/managed-server/install/orcad-remote-install.ts +++ b/src/main/managed-server/install/orcad-remote-install.ts @@ -17,6 +17,9 @@ import type { OrcadHostTransport } from './orcad-host-transport' import { joinRemotePath, type RemoteHostPlatform } from '../../ssh/remote-host/ssh-remote-platform' import { ORCAD_INSTALL_MODEL } from './remote-install-model' import { acquireInstallLock, type InstallLockWait } from './remote-install-lock' +import { installLockFenceStatement } from './remote-install-lock-holder-commands' +import { startInstallLockHolder, type InstallLockHolder } from './remote-install-lock-holder' +import { RELAY_INSTALL_LOCK_NAME } from '../../../shared/remote-runtime/relay/relay-install-lock-name' import { ORCAD_FENCE_OWNER_FILENAME } from '../activation/orcad-activation-fence-scope' import { forgetHeldOrcadFence, rememberHeldOrcadFence } from '../activation/orcad-held-fence-tokens' import { exitedOwnLockProof } from '../activation/orcad-exited-own-lock' @@ -93,6 +96,7 @@ export async function installOrcadBundle( // SSH keeps its bounded wait: a slow live upload elsewhere never refreshes the lock's age. ...(options.localWslHost ? { + probeExitedHolder: true, waitThroughStaleTakeover: true, onWait: (wait: InstallLockWait) => { waited = true @@ -106,60 +110,94 @@ export async function installOrcadBundle( } let preserveInstallLock = false + let holder: InstallLockHolder | null = null + let conn: OrcadHostTransport = options.conn + let signal = options.signal try { + const held = await holdInstallLock(options, remoteDir, owner) + if (held) { + ;({ holder, conn, signal } = held) + } // A sibling may have completed deployment while this client waited for the lock. if ( - await isRemoteInstallComplete(options.conn, ORCAD_INSTALL_MODEL, remoteDir, options.host, { - signal: options.signal + await isRemoteInstallComplete(conn, ORCAD_INSTALL_MODEL, remoteDir, options.host, { + signal }) ) { return 'reused' } - await uploadRemoteInstallDirectory( - options.conn, - options.localOrcadDir, - remoteDir, - options.host, - { - signal: options.signal - } - ) + await uploadRemoteInstallDirectory(conn, options.localOrcadDir, remoteDir, options.host, { + signal + }) if (options.host.os !== 'win32') { await execCommand( - options.conn, + conn, executablePermissionsCommand(options.host, remoteDir, options.target), { wrapCommand: options.host.commandDialect !== 'powershell', - signal: options.signal + signal } ) } await writeRemoteInstallFile( - options.conn, + conn, options.host, joinRemotePath(options.host, remoteDir, ORCAD_INSTALL_MODEL.versionFilename), fullVersion, - { signal: options.signal } + { signal } ) - await finalizeInstall(options.conn, remoteDir, options.host, { - signal: options.signal, - releaseLock: false - }) + await finalizeInstall(conn, remoteDir, options.host, { signal, releaseLock: false }) return 'uploaded' } catch (error) { preserveInstallLock = isUnconfirmedSshCommandTermination(error) throw error } finally { - if (!preserveInstallLock) { - // Retain ownership proof if interrupted cleanup cannot confirm lock removal. - // Token-checked: a cleanup that runs after a takeover leaves the successor's lock alone. - if (await abandonInstall(options.conn, remoteDir, options.host, owner)) { - forgetHeldOrcadFence(token) + try { + if (!preserveInstallLock) { + // Retain ownership proof if interrupted cleanup cannot confirm lock removal. + // Token-checked: a cleanup that runs after a takeover leaves the successor's lock alone. + if (await abandonInstall(conn, remoteDir, options.host, owner)) { + forgetHeldOrcadFence(token) + } } + } finally { + // After cleanup: a lock left behind is then reclaimable once its last fenced command ends. + holder?.release() } } } +/** WSL: back the lock with a guest kernel lock so a contender can prove this install gone, and + * fence every install command on it. Null keeps today's unbacked lock. */ +async function holdInstallLock( + options: { + conn: OrcadHostTransport + host: RemoteHostPlatform + localWslHost?: boolean + signal?: AbortSignal + }, + remoteDir: string, + owner: { fileName: string; token: string } +): Promise<{ holder: InstallLockHolder; conn: OrcadHostTransport; signal: AbortSignal } | null> { + const withFence = options.conn.withCommandFence + if (!options.localWslHost || !withFence || options.host.os === 'win32') { + return null + } + const lockDir = joinRemotePath(options.host, remoteDir, RELAY_INSTALL_LOCK_NAME) + const holder = await startInstallLockHolder(options.conn, lockDir, owner, options.signal) + if (!holder) { + return null + } + // A holder lost mid-install ends this install: its lock is now reclaimable. + const lost = new AbortController() + void holder.lost.then(() => lost.abort(new Error('The install lock holder exited.'))) + return { + holder, + conn: withFence.call(options.conn, installLockFenceStatement(lockDir, owner)), + signal: options.signal ? AbortSignal.any([options.signal, lost.signal]) : lost.signal + } +} + export function executablePermissionsCommand( host: RemoteHostPlatform, directory: string, diff --git a/src/main/managed-server/install/remote-install-lock-boot-identity.ts b/src/main/managed-server/install/remote-install-lock-boot-identity.ts new file mode 100644 index 00000000000..b6567edb246 --- /dev/null +++ b/src/main/managed-server/install/remote-install-lock-boot-identity.ts @@ -0,0 +1,79 @@ +import { quotePosixShell } from '../../../shared/shell/launch/shell-argument-quoting' +import type { RemoteHostPlatform } from '../../ssh/remote-host/ssh-remote-platform' + +/** Install lock boot marker: a lock from a previous boot is reclaimable at once. */ +const INSTALL_LOCK_BOOT_ID_NAME = '.boot-id' + +export function posixCurrentBootIdentityAssignment( + host: RemoteHostPlatform, + variableName: string +): string { + if (host.os === 'darwin') { + return `${variableName}=$(sysctl -n kern.boottime 2>/dev/null | sed -n 's/^.*{ sec = \\([0-9][0-9]*\\),.*$/darwin:\\1/p');` + } + return [ + `${variableName}=;`, + 'kernel_boot_id=$(cat /proc/sys/kernel/random/boot_id 2>/dev/null) || kernel_boot_id=;', + `pid1_start_ticks=$(sed 's/^.*) //' /proc/1/stat 2>/dev/null | awk '{ print $20 }') || pid1_start_ticks=;`, + `if [ -n "$kernel_boot_id" ] && [ -n "$pid1_start_ticks" ]; then ${variableName}="linux:$kernel_boot_id:$pid1_start_ticks"; fi;` + ].join(' ') +} + +export function posixReadBootIdentity(lockDir: string, variableName: string): string { + const markerPath = quotePosixShell(`${lockDir}/${INSTALL_LOCK_BOOT_ID_NAME}`) + return [ + `${variableName}=$(head -c 128 ${markerPath} 2>/dev/null | tr -d '\\r\\n') || ${variableName}=;`, + `if ! printf '%s\\n' "$${variableName}" | grep -Eq '^(linux:[0-9a-fA-F-]{1,64}:[0-9]{1,32}|darwin:[0-9]{1,32})$'; then ${variableName}=; fi;` + ].join(' ') +} + +export function posixWriteBootIdentity(lockDir: string, variableName: string): string { + const markerPath = quotePosixShell(`${lockDir}/${INSTALL_LOCK_BOOT_ID_NAME}`) + const markerTempPrefix = quotePosixShell(`${lockDir}/${INSTALL_LOCK_BOOT_ID_NAME}.tmp`) + return [ + `if [ -n "$${variableName}" ]; then`, + `boot_marker_tmp=${markerTempPrefix}.$$;`, + `if printf '%s\\n' "$${variableName}" > "$boot_marker_tmp" 2>/dev/null; then mv "$boot_marker_tmp" ${markerPath} 2>/dev/null || rm -f "$boot_marker_tmp"; else rm -f "$boot_marker_tmp"; fi;`, + 'fi;' + ].join(' ') +} + +export function windowsCurrentBootIdentityStatements(variableName: string): string[] { + return [ + `${variableName} = $null`, + 'try {', + '$operatingSystem = Get-CimInstance -ClassName Win32_OperatingSystem -ErrorAction Stop', + '$bootTicks = ([DateTime]$operatingSystem.LastBootUpTime).ToUniversalTime().Ticks', + `${variableName} = "win32:$bootTicks"`, + '} catch {}' + ] +} + +export function windowsReadBootIdentityStatements( + lockVariable: string, + valueVariable: string +): string[] { + return [ + `${valueVariable} = $null`, + 'try {', + `$bootMarker = Join-Path ${lockVariable} '${INSTALL_LOCK_BOOT_ID_NAME}'`, + '$bootMarkerItem = Get-Item -LiteralPath $bootMarker -ErrorAction Stop', + `if ($bootMarkerItem.Length -le 128) { ${valueVariable} = [System.IO.File]::ReadAllText($bootMarker).Trim() }`, + `if (${valueVariable} -notmatch '^win32:[0-9]{1,32}$') { ${valueVariable} = $null }`, + '} catch {}' + ] +} + +export function windowsWriteBootIdentityStatement( + lockVariable: string, + valueVariable: string +): string { + return [ + `if (-not [string]::IsNullOrWhiteSpace(${valueVariable})) {`, + `$bootMarkerPath = Join-Path ${lockVariable} '${INSTALL_LOCK_BOOT_ID_NAME}'`, + '$bootMarkerTemp = "$bootMarkerPath.tmp.$PID.$([Guid]::NewGuid().ToString(\'N\'))"', + 'try { [System.IO.File]::WriteAllText($bootMarkerTemp, ' + + `${valueVariable}); [System.IO.File]::Move($bootMarkerTemp, $bootMarkerPath) } catch {} finally { Remove-Item -LiteralPath $bootMarkerTemp -Force -ErrorAction SilentlyContinue }`, + '}' + ].join('; ') +} diff --git a/src/main/managed-server/install/remote-install-lock-commands.ts b/src/main/managed-server/install/remote-install-lock-commands.ts index 0ef64799e05..968d9bad436 100644 --- a/src/main/managed-server/install/remote-install-lock-commands.ts +++ b/src/main/managed-server/install/remote-install-lock-commands.ts @@ -6,8 +6,18 @@ import { type RemoteHostPlatform } from '../../ssh/remote-host/ssh-remote-platform' import * as exitedOwnerSteal from './remote-install-lock-exited-owner' - -const INSTALL_LOCK_BOOT_ID_NAME = '.boot-id' +import { + posixCurrentBootIdentityAssignment, + posixReadBootIdentity, + posixWriteBootIdentity, + windowsCurrentBootIdentityStatements, + windowsReadBootIdentityStatements, + windowsWriteBootIdentityStatement +} from './remote-install-lock-boot-identity' +import { + posixHolderStealParts, + type InstallLockHolderExit +} from './remote-install-lock-holder-commands' export function acquireInstallLockParentCommand( host: RemoteHostPlatform, @@ -100,10 +110,19 @@ export function tryStealInstallLockCommand( lockDir: string, staleAfterSeconds: number, owner?: InstallLockOwnerFile, - exitedOwner?: exitedOwnerSteal.InstallLockExitedOwner + exitedOwner?: exitedOwnerSteal.InstallLockExitedOwner, + /** POSIX only: a flock-backed lock generation whose holder a probe found gone. */ + exitedHolder?: InstallLockHolderExit ): string { if (!isWindowsRemoteHost(host)) { - return posixStealInstallLockCommand(host, lockDir, staleAfterSeconds, owner, exitedOwner) + return posixStealInstallLockCommand( + host, + lockDir, + staleAfterSeconds, + owner, + exitedOwner, + exitedHolder + ) } return windowsStealInstallLockCommand(lockDir, staleAfterSeconds, owner, exitedOwner) } @@ -113,9 +132,11 @@ function posixStealInstallLockCommand( lockDir: string, staleAfterSeconds: number, owner?: InstallLockOwnerFile, - exitedOwner?: exitedOwnerSteal.InstallLockExitedOwner + exitedOwner?: exitedOwnerSteal.InstallLockExitedOwner, + exitedHolder?: InstallLockHolderExit ): string { const escapedLockDir = quotePosixShell(lockDir) + const holder = posixHolderStealParts(lockDir, owner, exitedHolder) const escapedStealLockPrefix = quotePosixShell(`${lockDir}.steal`) return [ posixCurrentBootIdentityAssignment(host, 'current_boot_id'), @@ -124,7 +145,8 @@ function posixStealInstallLockCommand( 'if [ -n "$recorded_boot_id" ] && [ -n "$current_boot_id" ] && [ "$recorded_boot_id" != "$current_boot_id" ]; then rebooted=1; fi;', `${posixLockIdentityAssignment(lockDir, 'lock_key')} && mtime=\${lock_key%%:*} && now=$(date +%s) && age=$((now - mtime)) || age=0;`, exitedOwnerSteal.posixCheck(lockDir, exitedOwner, 'age', 'exited'), - `if [ "\${age:-0}" -le ${staleAfterSeconds} ] 2>/dev/null && [ "$rebooted" != 1 ] && [ "$exited" != 1 ]; then echo BUSY; else`, + ...(holder.check ? [holder.check] : []), + `if [ "\${age:-0}" -le ${staleAfterSeconds} ] 2>/dev/null && [ "$rebooted" != 1 ] && [ "$exited" != 1 ]${holder.gate}; then echo BUSY; else`, `steal_root=${escapedStealLockPrefix};`, 'steal_generation=0;', 'steal="$steal_root.$steal_generation";', @@ -144,13 +166,14 @@ function posixStealInstallLockCommand( 'current_rebooted=0;', 'if [ -n "$current_recorded_boot_id" ] && [ -n "$current_boot_id" ] && [ "$current_recorded_boot_id" != "$current_boot_id" ]; then current_rebooted=1; fi;', exitedOwnerSteal.posixClaimCheck(lockDir, exitedOwner, posixLockIdentityAssignment), - `if [ "$current_key" = "$lock_key" ] && { [ "\${current_age:-0}" -gt ${staleAfterSeconds} ] 2>/dev/null || [ "$current_rebooted" = 1 ] || [ "$current_exited" = 1 ]; }; then`, + ...(holder.claimCheck ? [holder.claimCheck] : []), + `if [ "$current_key" = "$lock_key" ] && { [ "\${current_age:-0}" -gt ${staleAfterSeconds} ] 2>/dev/null || [ "$current_rebooted" = 1 ] || [ "$current_exited" = 1 ]${holder.claim}; }; then`, `lock_tombstone=${escapedLockDir}.tombstone.$$.$(date +%s);`, `if [ ! -e "$lock_tombstone" ] && mv ${escapedLockDir} "$lock_tombstone" 2>/dev/null; then`, `if mkdir ${escapedLockDir} 2>/dev/null; then`, posixWriteBootIdentity(lockDir, 'current_boot_id'), ...posixWriteOwner(lockDir, owner), - 'if [ "$current_rebooted" = 1 ]; then echo REBOOT_OK; elif [ "$current_exited" = 1 ]; then echo EXITED_OWNER_OK; else echo OK; fi;', + `if [ "$current_rebooted" = 1 ]; then echo REBOOT_OK; elif [ "$current_exited" = 1 ]; then echo EXITED_OWNER_OK;${holder.reason} else echo OK; fi;`, 'else echo BUSY; fi; else echo BUSY; fi;', 'else echo BUSY; fi;', 'else echo BUSY; fi; fi' @@ -229,74 +252,6 @@ function windowsStealInstallLockCommand( ) } -function posixCurrentBootIdentityAssignment( - host: RemoteHostPlatform, - variableName: string -): string { - if (host.os === 'darwin') { - return `${variableName}=$(sysctl -n kern.boottime 2>/dev/null | sed -n 's/^.*{ sec = \\([0-9][0-9]*\\),.*$/darwin:\\1/p');` - } - return [ - `${variableName}=;`, - 'kernel_boot_id=$(cat /proc/sys/kernel/random/boot_id 2>/dev/null) || kernel_boot_id=;', - `pid1_start_ticks=$(sed 's/^.*) //' /proc/1/stat 2>/dev/null | awk '{ print $20 }') || pid1_start_ticks=;`, - `if [ -n "$kernel_boot_id" ] && [ -n "$pid1_start_ticks" ]; then ${variableName}="linux:$kernel_boot_id:$pid1_start_ticks"; fi;` - ].join(' ') -} - -function posixReadBootIdentity(lockDir: string, variableName: string): string { - const markerPath = quotePosixShell(`${lockDir}/${INSTALL_LOCK_BOOT_ID_NAME}`) - return [ - `${variableName}=$(head -c 128 ${markerPath} 2>/dev/null | tr -d '\\r\\n') || ${variableName}=;`, - `if ! printf '%s\\n' "$${variableName}" | grep -Eq '^(linux:[0-9a-fA-F-]{1,64}:[0-9]{1,32}|darwin:[0-9]{1,32})$'; then ${variableName}=; fi;` - ].join(' ') -} - -function posixWriteBootIdentity(lockDir: string, variableName: string): string { - const markerPath = quotePosixShell(`${lockDir}/${INSTALL_LOCK_BOOT_ID_NAME}`) - const markerTempPrefix = quotePosixShell(`${lockDir}/${INSTALL_LOCK_BOOT_ID_NAME}.tmp`) - return [ - `if [ -n "$${variableName}" ]; then`, - `boot_marker_tmp=${markerTempPrefix}.$$;`, - `if printf '%s\\n' "$${variableName}" > "$boot_marker_tmp" 2>/dev/null; then mv "$boot_marker_tmp" ${markerPath} 2>/dev/null || rm -f "$boot_marker_tmp"; else rm -f "$boot_marker_tmp"; fi;`, - 'fi;' - ].join(' ') -} - -function windowsCurrentBootIdentityStatements(variableName: string): string[] { - return [ - `${variableName} = $null`, - 'try {', - '$operatingSystem = Get-CimInstance -ClassName Win32_OperatingSystem -ErrorAction Stop', - '$bootTicks = ([DateTime]$operatingSystem.LastBootUpTime).ToUniversalTime().Ticks', - `${variableName} = "win32:$bootTicks"`, - '} catch {}' - ] -} - -function windowsReadBootIdentityStatements(lockVariable: string, valueVariable: string): string[] { - return [ - `${valueVariable} = $null`, - 'try {', - `$bootMarker = Join-Path ${lockVariable} '${INSTALL_LOCK_BOOT_ID_NAME}'`, - '$bootMarkerItem = Get-Item -LiteralPath $bootMarker -ErrorAction Stop', - `if ($bootMarkerItem.Length -le 128) { ${valueVariable} = [System.IO.File]::ReadAllText($bootMarker).Trim() }`, - `if (${valueVariable} -notmatch '^win32:[0-9]{1,32}$') { ${valueVariable} = $null }`, - '} catch {}' - ] -} - -function windowsWriteBootIdentityStatement(lockVariable: string, valueVariable: string): string { - return [ - `if (-not [string]::IsNullOrWhiteSpace(${valueVariable})) {`, - `$bootMarkerPath = Join-Path ${lockVariable} '${INSTALL_LOCK_BOOT_ID_NAME}'`, - '$bootMarkerTemp = "$bootMarkerPath.tmp.$PID.$([Guid]::NewGuid().ToString(\'N\'))"', - 'try { [System.IO.File]::WriteAllText($bootMarkerTemp, ' + - `${valueVariable}); [System.IO.File]::Move($bootMarkerTemp, $bootMarkerPath) } catch {} finally { Remove-Item -LiteralPath $bootMarkerTemp -Force -ErrorAction SilentlyContinue }`, - '}' - ].join('; ') -} - function posixLockAgeSecondsAssignment(lockDir: string): string { return `${posixLockMtimeSecondsAssignment(lockDir, 'mtime')} && now=$(date +%s) && age=$((now - mtime))` } diff --git a/src/main/managed-server/install/remote-install-lock-holder-commands.test.ts b/src/main/managed-server/install/remote-install-lock-holder-commands.test.ts new file mode 100644 index 00000000000..8b5901b8b2b --- /dev/null +++ b/src/main/managed-server/install/remote-install-lock-holder-commands.test.ts @@ -0,0 +1,232 @@ +// Run the holder, fence, probe and steal scripts in /bin/sh against a real kernel lock. +import { spawn, spawnSync, type ChildProcessWithoutNullStreams } from 'node:child_process' +import { mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, describe, expect, it } from 'vitest' +import { tryStealInstallLockCommand } from './remote-install-lock-commands' +import { + INSTALL_LOCK_HOLDER_FILENAME, + installLockFenceStatement, + installLockHolderCommand, + installLockHolderExitedProbeCommand, + parseInstallLockHolderExit +} from './remote-install-lock-holder-commands' +import { getRemoteHostPlatform } from '../../ssh/remote-host/ssh-remote-platform' + +const host = getRemoteHostPlatform('linux-x64') +const OWNER = '.orca-fence-owner' +const first = { fileName: OWNER, token: 't-first' } +const second = { fileName: OWNER, token: 't-second' } +const hasFlock = + process.platform !== 'win32' && spawnSync('/bin/sh', ['-c', 'command -v flock']).status === 0 + +const roots: string[] = [] +const children: ChildProcessWithoutNullStreams[] = [] +afterEach(() => { + for (const child of children.splice(0)) { + child.kill('SIGKILL') + } + for (const root of roots.splice(0)) { + rmSync(root, { recursive: true, force: true }) + } +}) + +function lockOwnedBy(token: string): string { + const root = mkdtempSync(join(tmpdir(), 'orca-lock-holder-')) + roots.push(root) + const lock = join(root, '.install-lock') + mkdirSync(lock) + writeFileSync(join(lock, OWNER), token) + return lock +} + +function sh(command: string, env?: NodeJS.ProcessEnv): { code: number | null; stdout: string } { + const result = spawnSync('/bin/sh', ['-c', command], { encoding: 'utf8', env }) + return { code: result.status, stdout: result.stdout.trim() } +} + +function start(command: string, env?: NodeJS.ProcessEnv): ChildProcessWithoutNullStreams { + const child = spawn('/bin/sh', ['-c', command], { env }) + children.push(child) + return child +} + +function line(child: ChildProcessWithoutNullStreams, expected: string): Promise { + return new Promise((resolve) => { + let out = '' + const onData = (chunk: Buffer): void => { + out += chunk.toString() + if (out.split('\n').includes(expected)) { + child.stdout.off('data', onData) + resolve(true) + } + } + child.stdout.on('data', onData) + child.once('exit', () => resolve(out.split('\n').includes(expected))) + }) +} + +function exited(child: ChildProcessWithoutNullStreams): Promise { + return child.exitCode !== null + ? Promise.resolve(child.exitCode) + : new Promise((resolve) => child.once('exit', (code) => resolve(code))) +} + +async function holdLock(lock: string): Promise { + const holder = start(installLockHolderCommand(lock, first)) + expect(await line(holder, 'HOLDER_READY')).toBe(true) + holder.stdin.write('mark\n') + expect(await line(holder, 'HOLDER_HELD')).toBe(true) + return holder +} + +const probe = (lock: string): string => sh(installLockHolderExitedProbeCommand(lock, OWNER)).stdout + +function stealAs(lock: string, seen: ReturnType): string { + return sh(tryStealInstallLockCommand(host, lock, 20 * 60, second, undefined, seen ?? undefined)) + .stdout +} + +describe.skipIf(!hasFlock)('flock-backed install lock, run for real', () => { + it('keeps a live holder from being taken over, then reclaims it once the holder exits', async () => { + const lock = lockOwnedBy('t-first') + const holder = await holdLock(lock) + expect(readFileSync(join(lock, INSTALL_LOCK_HOLDER_FILENAME), 'utf8')).toBe('held') + expect(probe(lock)).toBe('') + // Even a forged proof cannot take a lock whose holder still holds it. + const lockKey = sh(`stat -c %Y:%i '${lock}'`).stdout + expect(stealAs(lock, { dirKey: lockKey, token: 't-first' })).toBe('BUSY') + + holder.stdin.end() + expect(await exited(holder)).toBe(0) + const seen = parseInstallLockHolderExit(probe(lock)) + expect(seen).toEqual({ dirKey: lockKey, token: 't-first' }) + expect(stealAs(lock, seen)).toBe('HOLDER_EXITED_OK') + expect(readFileSync(join(lock, OWNER), 'utf8')).toBe('t-second') + // The successor's fresh lock is unmarked until its own holder marks it. + expect(probe(lock)).toBe('') + }) + + it('treats a killed holder as gone', async () => { + const lock = lockOwnedBy('t-first') + const holder = await holdLock(lock) + holder.kill('SIGKILL') + await exited(holder) + expect(parseInstallLockHolderExit(probe(lock))?.token).toBe('t-first') + }) + + it('waits for a fenced command the dead owner left running', async () => { + const lock = lockOwnedBy('t-first') + const holder = await holdLock(lock) + const fence = installLockFenceStatement(lock, first) + const straggler = start(`${fence} echo STARTED; sleep 2`) + expect(await line(straggler, 'STARTED')).toBe(true) + holder.stdin.end() + await exited(holder) + expect(probe(lock)).toBe('') + expect(await exited(straggler)).toBe(0) + expect(parseInstallLockHolderExit(probe(lock))).not.toBeNull() + }) + + it('fails a displaced owner fenced command', async () => { + const lock = lockOwnedBy('t-first') + const holder = await holdLock(lock) + expect(sh(`${installLockFenceStatement(lock, first)} echo RAN`).stdout).toBe('RAN') + holder.stdin.end() + await exited(holder) + expect(stealAs(lock, parseInstallLockHolderExit(probe(lock)))).toBe('HOLDER_EXITED_OK') + const late = sh(`${installLockFenceStatement(lock, first)} echo RAN`) + expect(late).toEqual({ code: 75, stdout: '' }) + }) + + it('never marks the lock when the desktop closes stdin before answering', async () => { + const lock = lockOwnedBy('t-first') + const holder = start(installLockHolderCommand(lock, first)) + expect(await line(holder, 'HOLDER_READY')).toBe(true) + holder.stdin.end() + await exited(holder) + expect(readFileSync(join(lock, INSTALL_LOCK_HOLDER_FILENAME), 'utf8')).toBe('') + expect(probe(lock)).toBe('') + }) + + it('refuses to back a lock another owner holds', async () => { + const lock = lockOwnedBy('t-other') + const holder = start(installLockHolderCommand(lock, first)) + expect(await line(holder, 'HOLDER_READY')).toBe(false) + expect(await exited(holder)).toBe(0) + }) + + it('lets only one of several concurrent contenders take a gone holder', async () => { + const lock = lockOwnedBy('t-first') + const holder = await holdLock(lock) + holder.stdin.end() + await exited(holder) + const seen = parseInstallLockHolderExit(probe(lock)) ?? undefined + const command = tryStealInstallLockCommand(host, lock, 20 * 60, second, undefined, seen) + const outputs = await Promise.all( + Array.from( + { length: 6 }, + () => + new Promise((resolve) => { + let out = '' + const child = start(command) + child.stdout.on('data', (chunk: Buffer) => (out += chunk.toString())) + child.once('exit', () => resolve(out.trim())) + }) + ) + ) + expect(outputs.filter((output) => output === 'HOLDER_EXITED_OK')).toHaveLength(1) + }) + + it('keeps a fenced command own stderr', async () => { + const lock = lockOwnedBy('t-first') + const holder = await holdLock(lock) + const result = spawnSync( + '/bin/sh', + ['-c', `${installLockFenceStatement(lock, first)} echo oops >&2`], + { + encoding: 'utf8' + } + ) + expect(result.stderr.trim()).toBe('oops') + holder.stdin.end() + }) + + it('leaves a live flock-backed lock to the age rules for a contender without proof', async () => { + const lock = lockOwnedBy('t-first') + const holder = await holdLock(lock) + holder.stdin.end() + await exited(holder) + // An older build sees only a fresh lock directory. + expect(stealAs(lock, null)).toBe('BUSY') + }) + + it('leaves an unmarked lock to the age rules', () => { + const lock = lockOwnedBy('t-first') + expect(probe(lock)).toBe('') + expect(stealAs(lock, null)).toBe('BUSY') + }) + + it('degrades to an unbacked lock where flock is missing', async () => { + const lock = lockOwnedBy('t-first') + const bin = join(lock, '..', 'bin') + mkdirSync(bin) + const cat = sh('command -v cat').stdout + symlinkSync(cat, join(bin, 'cat')) + const holder = start(installLockHolderCommand(lock, first), { PATH: bin }) + expect(await line(holder, 'HOLDER_READY')).toBe(false) + expect(await exited(holder)).toBe(0) + }) +}) + +describe('steal without a holder proof', () => { + it('carries no flock clauses, as on SSH and in older builds', () => { + const lock = '/l/.install-lock' + expect(tryStealInstallLockCommand(host, lock, 20 * 60, second)).not.toMatch(/holder|flock/u) + const proofWithoutOwner = { dirKey: '1:2', token: 't-first' } + expect( + tryStealInstallLockCommand(host, lock, 20 * 60, undefined, undefined, proofWithoutOwner) + ).not.toMatch(/holder|flock/u) + }) +}) diff --git a/src/main/managed-server/install/remote-install-lock-holder-commands.ts b/src/main/managed-server/install/remote-install-lock-holder-commands.ts new file mode 100644 index 00000000000..c52bfd70096 --- /dev/null +++ b/src/main/managed-server/install/remote-install-lock-holder-commands.ts @@ -0,0 +1,144 @@ +import { quotePosixShell } from '../../../shared/shell/launch/shell-argument-quoting' +import type { InstallLockOwnerFile } from './remote-install-lock-commands' + +/** Inside the mkdir lock: shared-flocked by the owner's holder and every fenced command; its + * content marks the lock flock-backed. Old builds never write it, so their locks keep today's rules. */ +export const INSTALL_LOCK_HOLDER_FILENAME = '.holder-flock' +const HOLDER_MARKER = 'held' + +export const INSTALL_LOCK_HOLDER_READY = 'HOLDER_READY' +export const INSTALL_LOCK_HOLDER_MARK = 'mark' +export const INSTALL_LOCK_HOLDER_HELD = 'HOLDER_HELD' +const HOLDER_EXITED = 'HOLDER_EXITED' +// Busybox flock has no -w, so shared waits poll; a contender's exclusive probe is momentary. +const SHARED_LOCK_ATTEMPTS = 10 + +/** Identifies one lock generation: the lock dir's mtime:inode plus the token its owner wrote. */ +export type InstallLockHolderExit = { dirKey: string; token: string } + +function holderPath(lockDir: string): string { + return `${lockDir.replace(/\/+$/u, '')}/${INSTALL_LOCK_HOLDER_FILENAME}` +} + +function ownerPath(lockDir: string, ownerFileName: string): string { + return `${lockDir.replace(/\/+$/u, '')}/${ownerFileName}` +} + +function sharedLockLoop(fd: number): string { + return ( + `held_tries=0; until flock -s -n ${fd} 2>/dev/null; do held_tries=$((held_tries + 1)); ` + + `[ "$held_tries" -ge ${SHARED_LOCK_ATTEMPTS} ] && exit 75; sleep 1; done;` + ) +} + +/** Long-lived POSIX holder of a shared kernel lock inside `lockDir`, kept until its stdin closes. + * It marks the lock only after the desktop answers READY, so a holder the desktop gave up on + * (stdin closed) can never leave a marker behind. */ +export function installLockHolderCommand(lockDir: string, owner: InstallLockOwnerFile): string { + const ownerFile = quotePosixShell(`./${owner.fileName}`) + const token = quotePosixShell(owner.token) + const holder = quotePosixShell(`./${INSTALL_LOCK_HOLDER_FILENAME}`) + const ownsLock = `[ "$(cat ${ownerFile} 2>/dev/null)" = ${token} ]` + return [ + // cwd pins this lock's inode, so a takeover that renames it cannot redirect the marker. + `cd ${quotePosixShell(lockDir)} 2>/dev/null && ${ownsLock} || exit 0;`, + 'command -v flock >/dev/null 2>&1 || exit 0;', + `{ command exec 9>>${holder}; } 2>/dev/null || exit 0;`, + sharedLockLoop(9).replace('exit 75', 'exit 0'), + // A filesystem that grants a second description an exclusive lock cannot prove anything. + `if ( exec 8<${holder} && flock -x -n 8 ) 2>/dev/null; then exit 0; fi;`, + `${ownsLock} || exit 0;`, + `echo ${INSTALL_LOCK_HOLDER_READY};`, + `IFS= read -r holder_go && [ "$holder_go" = ${INSTALL_LOCK_HOLDER_MARK} ] && ${ownsLock} || exit 0;`, + `printf ${HOLDER_MARKER} >&9 || exit 0;`, + `echo ${INSTALL_LOCK_HOLDER_HELD};`, + // One process keeps fd 9 (the lock); stdin EOF means the desktop let go or died. + 'exec cat >/dev/null' + ].join(' ') +} + +/** Prefix for every command an owner with a live holder runs: a shared lock on the holder file + * that lasts the whole command (children included), then proof the lock still names `owner`. + * A contender's exclusive lock therefore succeeds only once the holder and every command are gone. */ +export function installLockFenceStatement(lockDir: string, owner: InstallLockOwnerFile): string { + return [ + // Grouped so the redirect failure is quiet without silencing the command's own stderr. + `{ command exec 7<${quotePosixShell(holderPath(lockDir))}; } 2>/dev/null || exit 75;`, + sharedLockLoop(7), + `[ "$(cat ${quotePosixShell(ownerPath(lockDir, owner.fileName))} 2>/dev/null)" = ${quotePosixShell(owner.token)} ] || exit 75;` + ].join(' ') +} + +/** True (exit 0) when the lock at `lockPath` is marked flock-backed and nothing holds its file. */ +function posixHolderGoneTest(lockPath: string, fd: number): string { + const holder = quotePosixShell(holderPath(lockPath)) + return ( + `[ "$(head -c 16 ${holder} 2>/dev/null)" = ${HOLDER_MARKER} ] && ` + + `( exec ${fd}<${holder} && flock -x -n ${fd} ) 2>/dev/null` + ) +} + +/** Prints `HOLDER_EXITED ` only when one lock generation is flock-backed and + * nothing holds it; unmarked, held, or flock-less locks print nothing. */ +export function installLockHolderExitedProbeCommand( + lockDir: string, + ownerFileName: string +): string { + const lock = quotePosixShell(lockDir) + const owner = quotePosixShell(ownerPath(lockDir, ownerFileName)) + const identity = (variable: string): string => + `${variable}=$(stat -c %Y:%i ${lock} 2>/dev/null || stat -f %m:%i ${lock} 2>/dev/null)` + return [ + `${identity('before_key')} || exit 0;`, + `before_owner=$(head -c 128 ${owner} 2>/dev/null) || exit 0;`, + `${posixHolderGoneTest(lockDir, 8)} || exit 0;`, + `${identity('after_key')} || exit 0;`, + `[ "$before_key" = "$after_key" ] && [ "$(head -c 128 ${owner} 2>/dev/null)" = "$before_owner" ] || exit 0;`, + `echo "${HOLDER_EXITED} $before_key $before_owner"` + ].join(' ') +} + +const PROBE_LINE = /^HOLDER_EXITED (\d+:\d+) ([A-Za-z0-9-]{1,128})$/u + +export function parseInstallLockHolderExit(output: string): InstallLockHolderExit | null { + const match = PROBE_LINE.exec(output.trim().split(/\r?\n/u).at(-1) ?? '') + return match ? { dirKey: match[1], token: match[2] } : null +} + +/** Pieces of the POSIX steal for a probed-gone holder; all empty without proof, so the steal + * stays byte-identical to builds without flock-backed locks. */ +export type HolderStealParts = { + check: string + gate: string + claimCheck: string + claim: string + reason: string +} + +export function posixHolderStealParts( + lockDir: string, + owner: InstallLockOwnerFile | undefined, + exit: InstallLockHolderExit | undefined +): HolderStealParts { + if (!owner || !exit) { + return { check: '', gate: '', claimCheck: '', claim: '', reason: '' } + } + const holder = quotePosixShell(holderPath(lockDir)) + const ownedBy = `[ "$(cat ${quotePosixShell(ownerPath(lockDir, owner.fileName))} 2>/dev/null)" = ${quotePosixShell(exit.token)} ]` + const sameGeneration = (key: string): string => `[ "$${key}" = ${quotePosixShell(exit.dirKey)} ]` + return { + // Cheap pre-mutex gate: the named generation still looks gone. + check: `holder_exited=0; if ${sameGeneration('lock_key')} && ${ownedBy} && ${posixHolderGoneTest(lockDir, 8)}; then holder_exited=1; fi;`, + gate: ' && [ "$holder_exited" != 1 ]', + // Inside the steal mutex: fd 6's exclusive lock lasts to the end of the steal, so no fenced + // command of the old owner can start while the lock is replaced. + claimCheck: [ + 'current_holder_exited=0;', + `if ${sameGeneration('current_key')} && { command exec 6<${holder}; } 2>/dev/null; then`, + `if flock -x -n 6 2>/dev/null && [ "$(head -c 16 ${holder} 2>/dev/null)" = ${HOLDER_MARKER} ] && ${ownedBy}; then current_holder_exited=1; fi;`, + 'fi;' + ].join(' '), + claim: ' || [ "$current_holder_exited" = 1 ]', + reason: ' elif [ "$current_holder_exited" = 1 ]; then echo HOLDER_EXITED_OK;' + } +} diff --git a/src/main/managed-server/install/remote-install-lock-holder-takeover.ts b/src/main/managed-server/install/remote-install-lock-holder-takeover.ts new file mode 100644 index 00000000000..f642a79e4e7 --- /dev/null +++ b/src/main/managed-server/install/remote-install-lock-holder-takeover.ts @@ -0,0 +1,69 @@ +import type { RemoteInstallTransport } from './remote-install-transport' +import { execHostCommand } from '../../ssh/remote-exec/remote-host-exec' +import { isUnconfirmedSshCommandTermination } from '../../ssh/remote-exec/remote-exec-command' +import type { RemoteHostPlatform } from '../../ssh/remote-host/ssh-remote-platform' +import { + tryStealInstallLockCommand, + type InstallLockOwnerFile +} from './remote-install-lock-commands' +import { + installLockHolderExitedProbeCommand, + parseInstallLockHolderExit, + type InstallLockHolderExit +} from './remote-install-lock-holder-commands' + +/** A contender's view of a flock-backed lock across probes; one per acquire attempt. */ +export type HolderTakeoverState = { gone: InstallLockHolderExit | null } + +async function answered(work: Promise, fallback: string): Promise { + try { + return await work + } catch (error) { + if (isUnconfirmedSshCommandTermination(error)) { + throw error + } + return fallback + } +} + +/** Steal output once the same lock generation read gone on two probes, else null. The steal + * itself rechecks under its mutex with the holder file exclusively locked. */ +export async function tryTakeOverExitedHolder( + conn: RemoteInstallTransport, + host: RemoteHostPlatform, + lockDir: string, + owner: InstallLockOwnerFile, + state: HolderTakeoverState, + staleAfterSeconds: number, + signal?: AbortSignal +): Promise { + const seen = parseInstallLockHolderExit( + await answered( + execHostCommand(conn, host, installLockHolderExitedProbeCommand(lockDir, owner.fileName), { + signal + }), + '' + ) + ) + const confirmed = + seen !== null && state.gone?.dirKey === seen.dirKey && state.gone.token === seen.token + state.gone = seen + if (!confirmed) { + return null + } + const steal = await answered( + execHostCommand( + conn, + host, + tryStealInstallLockCommand(host, lockDir, staleAfterSeconds, owner, undefined, seen), + { signal } + ), + 'BUSY' + ) + signal?.throwIfAborted() + if (steal.trim().endsWith('OK')) { + state.gone = null + return steal + } + return null +} diff --git a/src/main/managed-server/install/remote-install-lock-holder.test.ts b/src/main/managed-server/install/remote-install-lock-holder.test.ts new file mode 100644 index 00000000000..49c282a71d4 --- /dev/null +++ b/src/main/managed-server/install/remote-install-lock-holder.test.ts @@ -0,0 +1,99 @@ +import { Duplex, PassThrough } from 'node:stream' +import { describe, expect, it, vi } from 'vitest' +import type { RemoteCommandChannel, RemoteInstallTransport } from './remote-install-transport' +import { + InstallLockHolderUnconfirmedError, + startInstallLockHolder +} from './remote-install-lock-holder' + +const owner = { fileName: '.orca-fence-owner', token: 't-1' } +// Lets the holder attach its listeners once the exec resolves. +const attached = (): Promise => new Promise((resolve) => setImmediate(resolve)) + +function fakeHolder(): { + conn: RemoteInstallTransport + say: (line: string) => void + exit: () => void + written: string[] + closed: () => boolean +} { + const written: string[] = [] + // Writes are what the desktop sends the holder; pushes are what the holder prints. + const channel = new Duplex({ + read() {}, + write(chunk: Buffer, _encoding, done) { + written.push(chunk.toString()) + done() + } + }) + let closed = false + const remote: RemoteCommandChannel = Object.assign(channel, { + stdin: new PassThrough(), + stderr: new PassThrough(), + close: () => { + closed = true + } + }) + const conn: RemoteInstallTransport = Object.assign(Object.create(null), { + exec: async () => remote + }) + return { + conn, + say: (line) => channel.push(`${line}\n`), + exit: () => channel.emit('close'), + written, + closed: () => closed + } +} + +describe('startInstallLockHolder', () => { + it('marks only after READY, then reports a holder lost before release', async () => { + const host = fakeHolder() + const started = startInstallLockHolder(host.conn, '/l', owner) + await attached() + expect(host.written).toEqual([]) + host.say('HOLDER_READY') + await vi.waitFor(() => expect(host.written).toEqual(['mark\n'])) + host.say('HOLDER_HELD') + const holder = await started + let lost = false + void holder?.lost.then(() => (lost = true)) + host.exit() + await vi.waitFor(() => expect(lost).toBe(true)) + }) + + it('does not report loss after its own release', async () => { + const host = fakeHolder() + const started = startInstallLockHolder(host.conn, '/l', owner) + await attached() + host.say('HOLDER_READY') + host.say('HOLDER_HELD') + const holder = await started + let lost = false + void holder?.lost.then(() => (lost = true)) + holder?.release() + host.exit() + await attached() + expect(lost).toBe(false) + expect(host.closed()).toBe(true) + }) + + it('keeps the lock unbacked when the holder exits before READY', async () => { + const host = fakeHolder() + const started = startInstallLockHolder(host.conn, '/l', owner) + await attached() + host.exit() + await expect(started).resolves.toBeNull() + expect(host.written).toEqual([]) + }) + + it('gives up the install when a marked holder never confirms', async () => { + const host = fakeHolder() + const started = startInstallLockHolder(host.conn, '/l', owner) + await attached() + host.say('HOLDER_READY') + await vi.waitFor(() => expect(host.written).toEqual(['mark\n'])) + host.exit() + await expect(started).rejects.toBeInstanceOf(InstallLockHolderUnconfirmedError) + }) +}) diff --git a/src/main/managed-server/install/remote-install-lock-holder.ts b/src/main/managed-server/install/remote-install-lock-holder.ts new file mode 100644 index 00000000000..e15622346a6 --- /dev/null +++ b/src/main/managed-server/install/remote-install-lock-holder.ts @@ -0,0 +1,108 @@ +import type { RemoteInstallTransport } from './remote-install-transport' +import type { InstallLockOwnerFile } from './remote-install-lock-commands' +import { + INSTALL_LOCK_HOLDER_HELD, + INSTALL_LOCK_HOLDER_MARK, + INSTALL_LOCK_HOLDER_READY, + installLockHolderCommand +} from './remote-install-lock-holder-commands' + +const HOLDER_ANSWER_TIMEOUT_MS = 15_000 + +/** A guest process keeping the install lock flock-backed; `lost` settles if it exits before release. */ +export type InstallLockHolder = { lost: Promise; release(): void } + +export class InstallLockHolderUnconfirmedError extends Error { + constructor() { + super('The install lock holder did not confirm it marked the lock; giving up this install.') + this.name = 'InstallLockHolderUnconfirmedError' + } +} + +/** Null when the host cannot back the lock (no flock, no exclusive locks, lock not ours): the + * lock stays unmarked, so contenders keep today's rules. Throws only when the lock may be + * marked but this client cannot keep its holder alive. */ +export async function startInstallLockHolder( + conn: RemoteInstallTransport, + lockDir: string, + owner: InstallLockOwnerFile, + signal?: AbortSignal +): Promise { + signal?.throwIfAborted() + const channel = await conn.exec(installLockHolderCommand(lockDir, owner), { signal }) + let stdout = '' + let released = false + let closed = false + let notify: () => void = () => {} + const closedOrLine = (): void => notify() + const onData = (chunk: Buffer | string): void => { + stdout += chunk.toString() + closedOrLine() + } + const onClose = (): void => { + closed = true + closedOrLine() + } + channel.on('data', onData) + channel.on('close', onClose) + channel.on('error', onClose) + channel.stderr.on('data', () => {}) + const waitFor = (line: string): Promise => + new Promise((resolve) => { + const check = (): void => { + if (stdout.split(/\r?\n/u).includes(line)) { + finish(true) + } else if (closed || signal?.aborted) { + finish(false) + } + } + const timer = setTimeout(() => finish(false), HOLDER_ANSWER_TIMEOUT_MS) + const finish = (answered: boolean): void => { + clearTimeout(timer) + signal?.removeEventListener('abort', check) + notify = () => {} + resolve(answered) + } + notify = check + signal?.addEventListener('abort', check, { once: true }) + check() + }) + const close = (): void => { + channel.off('data', onData) + channel.close() + } + + // Closing stdin before `mark` means the holder exits on EOF without ever marking the lock. + if (!(await waitFor(INSTALL_LOCK_HOLDER_READY))) { + close() + signal?.throwIfAborted() + return null + } + channel.write(`${INSTALL_LOCK_HOLDER_MARK}\n`) + if (!(await waitFor(INSTALL_LOCK_HOLDER_HELD))) { + close() + signal?.throwIfAborted() + throw new InstallLockHolderUnconfirmedError() + } + channel.off('data', onData) + channel.resume() + const lost = new Promise((resolve) => { + const settle = (): void => { + if (!released) { + resolve() + } + } + if (closed) { + settle() + } + channel.once('close', settle) + channel.once('error', settle) + }) + return { + lost, + release: () => { + released = true + channel.close() + } + } +} diff --git a/src/main/managed-server/install/remote-install-lock-wait.test.ts b/src/main/managed-server/install/remote-install-lock-wait.test.ts new file mode 100644 index 00000000000..d4d24a3032e --- /dev/null +++ b/src/main/managed-server/install/remote-install-lock-wait.test.ts @@ -0,0 +1,151 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import type { RemoteInstallTransport } from './remote-install-transport' +import type { InstallLockWait } from './remote-install-lock' + +// A held install lock answered by command shape; its age follows the faked clock. +const lock: { createdAt: number; stolen: boolean; holderGoneAt: number | null; probes: number } = { + createdAt: 0, + stolen: false, + holderGoneAt: null, + probes: 0 +} +vi.mock('../../ssh/remote-exec/remote-host-exec', () => ({ + execHostCommand: async (_conn: unknown, _host: unknown, command: string) => { + const ageSec = Math.floor((Date.now() - lock.createdAt) / 1000) + const holderGone = lock.holderGoneAt !== null && Date.now() >= lock.holderGoneAt + if (command.includes('echo HOLDER_EXITED_OK')) { + lock.stolen = holderGone + return holderGone ? 'HOLDER_EXITED_OK' : 'BUSY' + } + if (command.includes('echo "HOLDER_EXITED')) { + lock.probes += 1 + return holderGone ? 'HOLDER_EXITED 1794874229:262443 t-dead\n' : '' + } + if (command.includes('.steal')) { + // Mirrors the host's rule: stale only once older than the threshold. + lock.stolen = ageSec > 20 * 60 + return lock.stolen ? 'OK' : 'BUSY' + } + if (command.includes('echo "$age"')) { + return `${ageSec}\n` + } + if (command.includes('if mkdir')) { + return 'BUSY' + } + return '' + } +})) + +const { acquireInstallLock, RemoteInstallLockBusyError } = await import('./remote-install-lock') + +// The mocked exec never reads the transport. +const conn: RemoteInstallTransport = Object.create(null) + +async function settle(promise: Promise, maxMs: number): Promise<'done' | Error> { + let outcome: 'done' | Error | null = null + promise.then( + () => (outcome = 'done'), + (error: Error) => (outcome = error) + ) + for (let elapsed = 0; outcome === null && elapsed < maxMs; elapsed += 1_000) { + await vi.advanceTimersByTimeAsync(1_000) + } + return outcome ?? new Error('still waiting') +} + +describe('acquireInstallLock waiting on a held lock', () => { + beforeEach(() => { + vi.useFakeTimers({ now: new Date('2026-11-16T06:44:00Z') }) + vi.spyOn(console, 'info').mockImplementation(() => {}) + vi.spyOn(console, 'warn').mockImplementation(() => {}) + lock.stolen = false + lock.holderGoneAt = null + lock.probes = 0 + }) + afterEach(() => { + vi.useRealTimers() + vi.restoreAllMocks() + }) + + it('reports when takeover becomes possible and waits for it past the step timeout', async () => { + // A relaunch 1 minute after the lock was taken: the old 15-minute wait expired before takeover. + lock.createdAt = Date.now() - 60_000 + const waits: InstallLockWait[] = [] + const acquired = acquireInstallLock(conn, '/home/u/.orca-remote/orcad-1', undefined, { + relayGcClaim: false, + waitThroughStaleTakeover: true, + onWait: (wait) => waits.push(wait) + }) + expect(await settle(acquired, 25 * 60_000)).toBe('done') + expect(lock.stolen).toBe(true) + expect(waits[0]).toEqual({ takeoverInMs: 19 * 60_000, givesUpInMs: 20 * 60_000 }) + // Taken at the first recheck after the lock turned stale, about 20 minutes after it was made. + expect(Date.now() - lock.createdAt).toBeLessThanOrEqual(21 * 60_000 + 1_000) + }) + + it('a relaunch takes over when the lock turns stale, not a full wait after it started', async () => { + // Four minutes in: a fresh 15-minute wait would end a minute before the lock turns stale. + lock.createdAt = Date.now() - 4 * 60_000 + const start = Date.now() + const acquired = acquireInstallLock(conn, '/home/u/.orca-remote/orcad-1', undefined, { + relayGcClaim: false, + waitThroughStaleTakeover: true + }) + expect(await settle(acquired, 25 * 60_000)).toBe('done') + expect(Date.now() - start).toBeGreaterThan(15 * 60_000) + expect(Date.now() - start).toBeLessThanOrEqual(17 * 60_000 + 1_000) + }) + + it('takes over a fresh flock-backed lock seconds after its holder is seen gone twice', async () => { + lock.createdAt = Date.now() - 60_000 + lock.holderGoneAt = Date.now() + 30_000 + const start = Date.now() + const acquired = acquireInstallLock(conn, '/home/u/.orca-remote/orcad-1', undefined, { + relayGcClaim: false, + waitThroughStaleTakeover: true, + owner: { fileName: '.orca-fence-owner', token: 't-next' }, + probeExitedHolder: true + }) + expect(await settle(acquired, 2 * 60_000)).toBe('done') + expect(lock.stolen).toBe(true) + // First gone reading at 30s, confirmed by the next probe 5s later. + expect(Date.now() - start).toBeGreaterThanOrEqual(35_000) + expect(Date.now() - start).toBeLessThanOrEqual(41_000) + }) + + it('never probes without an owner token to bind the proof to', async () => { + lock.createdAt = Date.now() - 19 * 60_000 + lock.holderGoneAt = Date.now() + const acquired = acquireInstallLock(conn, '/home/u/.orca-remote/orcad-1', undefined, { + relayGcClaim: false, + waitThroughStaleTakeover: true, + probeExitedHolder: true + }) + expect(await settle(acquired, 5 * 60_000)).toBe('done') + expect(lock.probes).toBe(0) + }) + + it('stops at the cap when a holder keeps refreshing the lock, and stops promising takeover', async () => { + const start = Date.now() + const refresh = setInterval(() => (lock.createdAt = Date.now()), 60_000) + lock.createdAt = start + const waits: InstallLockWait[] = [] + const acquired = acquireInstallLock(conn, '/home/u/.orca-remote/orcad-1', undefined, { + relayGcClaim: false, + waitThroughStaleTakeover: true, + onWait: (wait) => waits.push(wait) + }) + try { + expect(await settle(acquired, 30 * 60_000)).toBeInstanceOf(RemoteInstallLockBusyError) + expect(Date.now() - start).toBeGreaterThan(20 * 60_000) + expect(Date.now() - start).toBeLessThanOrEqual(22 * 60_000 + 1_000) + } finally { + clearInterval(refresh) + } + expect(waits[0]?.takeoverInMs).toBe(20 * 60_000) + // Once takeover would land after the cap, the wait says when it gives up instead. + const last = waits.at(-1) + expect(last?.takeoverInMs).toBeNull() + expect(last?.givesUpInMs).toBeLessThanOrEqual(60_000) + }) +}) diff --git a/src/main/managed-server/install/remote-install-lock.ts b/src/main/managed-server/install/remote-install-lock.ts index 32203e7feb8..d5010acb9bf 100644 --- a/src/main/managed-server/install/remote-install-lock.ts +++ b/src/main/managed-server/install/remote-install-lock.ts @@ -11,8 +11,13 @@ import { type InstallLockOwnerFile } from './remote-install-lock-commands' import type { InstallLockExitedOwner } from './remote-install-lock-exited-owner' +import { + tryTakeOverExitedHolder, + type HolderTakeoverState +} from './remote-install-lock-holder-takeover' import { getRemoteHostPlatform, + isWindowsRemoteHost, joinRemotePath, type RemoteHostPlatform } from '../../ssh/remote-host/ssh-remote-platform' @@ -24,6 +29,8 @@ const INSTALL_LOCK_POLL_MS = 1_000 const INSTALL_LOCK_STALE_RECHECK_MS = 60_000 // Give holders at least one full install step before the waiter gives up. const INSTALL_LOCK_TIMEOUT_MS = REMOTE_INSTALL_TIMEOUT_MS +// A gone holder must read gone twice this far apart before takeover. +const INSTALL_LOCK_HOLDER_PROBE_MS = 5_000 // A holder's step may outlive its timeout; leave room before takeover. export const INSTALL_LOCK_STALE_MS = 20 * 60_000 export const INSTALL_LOCK_STALE_SECONDS = INSTALL_LOCK_STALE_MS / 1000 @@ -99,6 +106,8 @@ export async function acquireInstallLock( waitThroughStaleTakeover?: boolean /** Reported at each stale recheck while another holder keeps the lock. */ onWait?: (wait: InstallLockWait) => void + /** POSIX: take over a flock-backed lock whose holder and fenced commands are all gone. */ + probeExitedHolder?: boolean } ): Promise { const lockDir = joinRemotePath(host, remoteRelayDir, options?.lockName ?? RELAY_INSTALL_LOCK_NAME) @@ -128,6 +137,9 @@ export async function acquireInstallLock( let lastCommandError: unknown let lastStaleCheckAt = Number.NEGATIVE_INFINITY let lastWaitLogAt = Number.NEGATIVE_INFINITY + let lastHolderProbeAt = Number.NEGATIVE_INFINITY + const holderTakeover: HolderTakeoverState = { gone: null } + const probedOwner = options?.probeExitedHolder ? options.owner : undefined while (true) { // Recover crashed GC claims rather than polling them forever. if (relayGcClaim) { @@ -154,6 +166,28 @@ export async function acquireInstallLock( // Retried until the bounded wait expires: one refused channel is not a verdict. lastCommandError = err } + if ( + probedOwner && + !isWindowsRemoteHost(host) && + Date.now() - lastHolderProbeAt >= INSTALL_LOCK_HOLDER_PROBE_MS + ) { + lastHolderProbeAt = Date.now() + const steal = await tryTakeOverExitedHolder( + conn, + host, + lockDir, + probedOwner, + holderTakeover, + INSTALL_LOCK_STALE_SECONDS, + options?.signal + ) + if (steal) { + console.warn(`[ssh] Stealing ${stealReason(steal)} install lock at ${lockDir}`) + if (await keptAfterGcRecheck()) { + return + } + } + } if ( options?.allowStaleTakeover !== false && Date.now() - lastStaleCheckAt >= INSTALL_LOCK_STALE_RECHECK_MS @@ -178,11 +212,7 @@ export async function acquireInstallLock( ) options?.signal?.throwIfAborted() if (steal.trim().endsWith('OK')) { - const reason = steal.trim().endsWith('REBOOT_OK') - ? 'previous-boot' - : steal.trim().endsWith('EXITED_OWNER_OK') - ? 'exited-owner' - : 'stale' + const reason = stealReason(steal) if (exitedOwner && reason === 'exited-owner') { options?.exitedOwner?.reclaimed(exitedOwner.token) } @@ -227,6 +257,17 @@ export async function acquireInstallLock( } } +function stealReason(steal: string): string { + const result = steal.trim() + if (result.endsWith('REBOOT_OK')) { + return 'previous-boot' + } + if (result.endsWith('EXITED_OWNER_OK')) { + return 'exited-owner' + } + return result.endsWith('HOLDER_EXITED_OK') ? 'exited-holder' : 'stale' +} + export type InstallLockExitedOwnerProof = { /** The token a provably exited holder wrote into `lockDir`, or null when none is proven. */ find(lockDir: string): Promise diff --git a/src/main/wsl/orcad/wsl-orcad-host-transport-loops.test.ts b/src/main/wsl/orcad/wsl-orcad-host-transport-loops.test.ts index 615893291f7..102666711a8 100644 --- a/src/main/wsl/orcad/wsl-orcad-host-transport-loops.test.ts +++ b/src/main/wsl/orcad/wsl-orcad-host-transport-loops.test.ts @@ -64,6 +64,24 @@ describe.runIf(posix)('WSL transport command loops', () => { expect(specs[1]?.args?.[5]).toContain('cat') }) + it('runs a fence before every command of a fenced transport, sharing its loop', async () => { + const { transport, specs } = localTransport() + const fenced = transport.withCommandFence?.('[ -n "$FENCE_OK" ] || exit 75;') + if (!fenced) { + throw new Error('WSL transport has no command fence') + } + await expect(execCommand(fenced, 'echo loop')).rejects.toThrow(/exit 75/) + expect( + await execCommand(transport.withCommandFence?.('FENCE_OK=1;') ?? fenced, 'echo loop') + ).toBe('loop\n') + await expect( + execCommand(fenced, 'cat', { stdin: Readable.from([Buffer.from('piped')]) }) + ).rejects.toThrow(/exit 75/) + // The unfenced transport is unchanged, and all stdin-free commands shared one loop. + expect(await execCommand(transport, 'echo plain')).toBe('plain\n') + expect(specs.filter((spec) => spec.args?.[6] === 'orca-wsl-exec-loop')).toHaveLength(1) + }) + it('falls back to one wsl.exe per command when the loop cannot start', async () => { const specs: PipedProcessSpec[] = [] const transport = createWslOrcadHostTransport({ diff --git a/src/main/wsl/orcad/wsl-orcad-host-transport.ts b/src/main/wsl/orcad/wsl-orcad-host-transport.ts index 44fecee5b1f..175353d8bbb 100644 --- a/src/main/wsl/orcad/wsl-orcad-host-transport.ts +++ b/src/main/wsl/orcad/wsl-orcad-host-transport.ts @@ -79,64 +79,74 @@ export function createWslOrcadHostTransport( spawnLoop: (marker) => spawnWsl(['sh', '-c', WSL_COMMAND_LOOP_SCRIPT, WSL_COMMAND_LOOP_ARGV0, marker]) }) - const transport: WslOrcadHostTransport = { - // wrapCommand is SSH-only; WSL starts sh directly without a login shell. - async exec(command: string, execOptions?: SshExecOptions): Promise { - if (execOptions?.signal?.aborted || options.signal?.aborted) { - throw createSshOperationAbortError() - } - const child = spawnWsl(['sh', '-c', command]) - const channel = wrapWslCommandProcess(child) - const endOnAbort = (): void => { - channel.destroy(createSshOperationAbortError()) - } - options.signal?.addEventListener('abort', endOnAbort, { once: true }) - channel.once('close', () => options.signal?.removeEventListener('abort', endOnAbort)) - // Reject spawn failure while opening the channel, matching SSH, rather than as a later stream error. - const spawnError = (error: Error): void => { - channel.destroy(error) - } - channel.on('error', spawnError) - try { - await once(child, 'spawn') - } finally { - channel.off('error', spawnError) - } - return channel - }, - async execWithClosedStdin(command, execOptions) { - return ( - (await loops?.run(command, execOptions?.signal)) ?? transport.exec(command, execOptions) - ) - }, - dispose: () => loops?.dispose(), - // Without systemd, nohup children die with wsl.exe; launch orcad in a new session. - orcadLaunchDetach: 'setsid', - // D1b-2: bind launches to the registration the guest cannot read itself. - // An idle orcad alone keeps the distro running, so it exits sooner here than on SSH. - orcadLaunchEnv: async () => { - const id = await (options.readDistroRegistryId ?? readWslDistroRegistryIdShared)( - target.distro - ) - return [ - ...(id ? [[ORCAD_WSL_DISTRO_GUID_ENV, id] as const] : []), - [ORCAD_IDLE_TIMEOUT_ENV, String(WSL_ORCAD_IDLE_EXIT_TIMEOUT_MS)] - ] - }, - usesSystemSshTransport: () => false, - // One transport, one wsl.exe lane: nothing underneath is ever replaced. - getConnectGeneration: () => 0, - getTarget: () => target, - writeFile: (remotePath, contents, fileOptions) => - writeStringViaExecStdin(transport, remotePath, contents, { signal: fileOptions?.signal }), - uploadDirectory: (localDir, remoteDir, fileOptions) => - uploadDirectoryIntoWsl( - transport, - localDir, - options.uploadSource === 'guest-mount' ? wslGuestSourcePath(localDir, target.distro) : null, - remoteDir, - { signal: fileOptions?.signal } - ) + // A fence runs before every guest command of a derived transport; the loops stay shared. + const build = (fence: string | null): WslOrcadHostTransport => { + const fenced = (command: string): string => (fence ? `${fence} ${command}` : command) + const transport: WslOrcadHostTransport = { + // wrapCommand is SSH-only; WSL starts sh directly without a login shell. + async exec(command: string, execOptions?: SshExecOptions): Promise { + if (execOptions?.signal?.aborted || options.signal?.aborted) { + throw createSshOperationAbortError() + } + const child = spawnWsl(['sh', '-c', fenced(command)]) + const channel = wrapWslCommandProcess(child) + const endOnAbort = (): void => { + channel.destroy(createSshOperationAbortError()) + } + options.signal?.addEventListener('abort', endOnAbort, { once: true }) + channel.once('close', () => options.signal?.removeEventListener('abort', endOnAbort)) + // Reject spawn failure while opening the channel, matching SSH, rather than as a later stream error. + const spawnError = (error: Error): void => { + channel.destroy(error) + } + channel.on('error', spawnError) + try { + await once(child, 'spawn') + } finally { + channel.off('error', spawnError) + } + return channel + }, + async execWithClosedStdin(command, execOptions) { + return ( + (await loops?.run(fenced(command), execOptions?.signal)) ?? + transport.exec(command, execOptions) + ) + }, + // The base transport owns the loops; a fenced one shares them. + dispose: () => (fence ? undefined : loops?.dispose()), + withCommandFence: (next) => build(next), + // Without systemd, nohup children die with wsl.exe; launch orcad in a new session. + orcadLaunchDetach: 'setsid', + // D1b-2: bind launches to the registration the guest cannot read itself. + // An idle orcad alone keeps the distro running, so it exits sooner here than on SSH. + orcadLaunchEnv: async () => { + const id = await (options.readDistroRegistryId ?? readWslDistroRegistryIdShared)( + target.distro + ) + return [ + ...(id ? [[ORCAD_WSL_DISTRO_GUID_ENV, id] as const] : []), + [ORCAD_IDLE_TIMEOUT_ENV, String(WSL_ORCAD_IDLE_EXIT_TIMEOUT_MS)] + ] + }, + usesSystemSshTransport: () => false, + // One transport, one wsl.exe lane: nothing underneath is ever replaced. + getConnectGeneration: () => 0, + getTarget: () => target, + writeFile: (remotePath, contents, fileOptions) => + writeStringViaExecStdin(transport, remotePath, contents, { signal: fileOptions?.signal }), + uploadDirectory: (localDir, remoteDir, fileOptions) => + uploadDirectoryIntoWsl( + transport, + localDir, + options.uploadSource === 'guest-mount' + ? wslGuestSourcePath(localDir, target.distro) + : null, + remoteDir, + { signal: fileOptions?.signal } + ) + } + return transport } - return transport + return build(null) }