nodeswap

package
v0.209.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 8, 2026 License: Apache-2.0 Imports: 24 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package nodeswap is the one reusable engine behind every Windows fleet-node binary swap. It replaces the family of per-deploy, per-node .ps1 scripts (node-swap-<sha>.ps1, deploy-node-exe.ps1, fleet-node-restart.ps1 stitched together by hand each release) with a single, unit-tested sequence that every future deploy calls the same way.

It exists because of a real outage: the 2026-09-24 <node-a> 0.140.8 deploy ran its restart-and-verify phase over an interactive SSH session. Windows OpenSSH kills the whole remote process tree on disconnect (see docs/systems/node-swap.md and the windows-ssh-remote-ops-patterns house memory), so when the session dropped at the 120s mark the script had already swapped the binary but never reached its restart/verify/rollback lines — the node sat down for over two hours with nobody watching. This package's Run is meant to be launched DETACHED (see setup/windows-node- swap-launch.ps1), so an SSH drop mid-run cannot orphan a half-finished swap: the process keeps running, keeps writing its log and result file, and still reaches its own rollback path if something goes wrong.

Run is a pure sequence over the Deps seam: every OS operation (hashing, health reads, process enumeration, renames, tarball extraction, shelling out to Start/Stop-ScheduledTask or a restart script) is a function value, so the whole state machine — including every rollback branch — is unit-testable with fakes, with no real Windows box required.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Preflight

func Preflight(plan Plan, deps Deps) error

Preflight is what Run checks before it touches anything, without waiting or moving a file: the plan is valid and, when a restart is configured, no process on the target's name is one this process cannot read. A caller that stages a download first (the update verb) calls it before the download, so a swap that Run would refuse costs nothing.

Types

type Deps

type Deps struct {
	Hash               func(path string) (string, error)
	ReadHealth         func(ctx context.Context, url string) (HealthInfo, error)
	InspectGPULease    func(lockPath, stateDir string) (GPULeaseInfo, error)
	FindProcessesByExe func(exePath string) ([]ProcessInfo, error)
	// FindRunningByExe is the post-restart VERIFICATION finder: the processes
	// running exePath right now. It is separate from FindProcessesByExe
	// because the two answer different questions off Windows — a Linux swap
	// needs no holders stopped (FindProcessesByExe stays empty there), but its
	// verification must still find the restarted node (a /proc scan). nil =
	// use FindProcessesByExe (every Windows run and every fake-Deps test).
	FindRunningByExe func(exePath string) ([]ProcessInfo, error)
	StopProcess      func(pid int) error
	RenameFile       func(oldPath, newPath string) error
	RemoveAll        func(path string) error
	Exists           func(path string) bool
	MkdirAll         func(path string) error
	RunCommand       func(ctx context.Context, timeout time.Duration, command string) (string, error)
	ExtractTarGz     func(tarGzPath, destDir string) (filesWritten int, err error)
	Sleep            func(d time.Duration)
	Now              func() time.Time

	// CopyFile and IsCrossDeviceRenameErr back installNewBinary's fallback
	// for a same-directory-only rename: RenameFile(Staged, Target) fails
	// outright when the two paths are not on the same volume/filesystem
	// (Windows: a different drive letter — "The system cannot move the file
	// to a different disk drive"; Linux/macOS: EXDEV, "invalid cross-device
	// link"). The 2026-09-24 <node-a> rollout hit this staging the new exe at
	// C:\tmp\ against a D:\ target: the swap rolled back cleanly, but never
	// happened. IsCrossDeviceRenameErr classifies a RenameFile error as this
	// specific, recoverable shape (never any other failure); CopyFile
	// performs the byte-for-byte copy installNewBinary re-hashes before
	// trusting it. Either left nil (an older caller's Deps, or a test that
	// only exercises the same-device path) makes installNewBinary behave
	// exactly as before this fallback existed: the original rename error
	// surfaces unchanged, never a silent no-op.
	CopyFile               func(src, dst string) error
	IsCrossDeviceRenameErr func(err error) bool
}

Deps is the OS/network seam. Every field is a plain function so Run is fully unit-testable with fakes; DefaultDeps (deps.go, plus the platform-suffixed deps_windows.go / deps_other.go files) wires the real implementations.

func DefaultDeps

func DefaultDeps() Deps

DefaultDeps wires the real, cross-platform half of Deps. The two platform-specific fields — FindProcessesByExe and StopProcess, which need CIM/Win32_Process on Windows and have no equivalent this package implements on other OSes — are filled in by platformDeps (deps_windows.go / deps_other.go), matching the repo's existing _windows.go / crossplatform_lint_test.go convention.

type FleetKeyCheck

type FleetKeyCheck struct {
	// Config is the path of the config the caller read.
	Config string
	// Present is true when that config holds a non-empty fleet_auth_token.
	Present bool
}

FleetKeyCheck is whether the node's config holds a fleet_auth_token, and which config that was. The value itself is never read out into the plan.

type GPULeaseInfo

type GPULeaseInfo struct {
	Held   bool
	Reason string
	// Leases is every live lease with the cards it sits on (empty Devices = the whole node).
	// A caller that fills only Held and Reason (every Deps written before leases carried
	// cards) is read as one whole-node lease.
	Leases []GPULeaseOnCards
}

GPULeaseInfo is the minimal GPU-lease signal a standalone node's swap needs before touching the binary — a package-local mirror of gpulease.Info (Held/Reason only) so this package and its tests never need the full gpulease.Info shape or a real lease directory.

type GPULeaseOnCards

type GPULeaseOnCards struct {
	Epoch  uint64
	Class  string
	Reason string
	// PID is the process that holds the lease (the `gpu reserve` wrapper, or the MCP server or
	// fleet node when it took the lease in-process), 0 when unknown. It is how a deploy tells a
	// lease held by a process it is about to stop from one on another card it can leave alone.
	PID int
	// Devices are the cards the lease sits on, as lease ids (lower-cased GPU UUIDs). Empty is
	// the whole node.
	Devices []string
}

GPULeaseOnCards is one live GPU lease as the standalone wait reads it.

type Generation

type Generation struct {
	OldExe, NewExe string
	// Flip points the live link at the new build (toNew true) or back at the previous one (false).
	Flip func(toNew bool) error
}

Generation is the link flip of a Plan. OldExe and NewExe are the executables behind the link before and after, as paths a running process reports for itself (the link resolved): the stop and the verification find the process by them, since the OS names the generation directory, not the link.

type HealthInfo

type HealthInfo struct {
	OK          bool
	NodeID      string
	Version     string
	RunningJobs int
	QueuedJobs  int
}

HealthInfo is the subset of GET /fleet/health this package reasons about.

type Logger

type Logger struct {
	// contains filtered or unexported fields
}

Logger is the minimal --log sink: every step and every rollback action is appended here as it happens, so a caller polling mid-run (or after a simulated SSH drop) sees real progress, not just the final result file.

func NewLogger

func NewLogger(w func(line string)) *Logger

NewLogger wraps a write func (nodeswap_cmd.go supplies one that appends to a file and optionally echoes to stderr).

func (*Logger) Printf

func (l *Logger) Printf(format string, args ...any)

type Outcome

type Outcome struct {
	OK               bool         `json:"ok"`
	DryRun           bool         `json:"dry_run"`
	StartedAt        time.Time    `json:"started_at"`
	FinishedAt       time.Time    `json:"finished_at"`
	DurationSec      float64      `json:"duration_sec"`
	Steps            []StepResult `json:"steps"`
	Error            string       `json:"error,omitempty"`
	RolledBack       bool         `json:"rolled_back"`
	RollbackOK       bool         `json:"rollback_ok,omitempty"`
	OldSHA256        string       `json:"old_sha256,omitempty"`
	NewSHA256        string       `json:"new_sha256,omitempty"`
	BackupPath       string       `json:"backup_path,omitempty"`
	RenderSwapped    bool         `json:"render_swapped,omitempty"`
	RenderBackupPath string       `json:"render_backup_path,omitempty"`
	FinalPID         int          `json:"final_pid,omitempty"`
	FinalImageSHA256 string       `json:"final_image_sha256,omitempty"`
	HealthVersion    string       `json:"health_version,omitempty"`
	// Cards are the cards the deploy declared it touches (Plan.Cards); absent for a whole-node
	// deploy. LeasesLeftAlone names each live GPU lease the standalone wait did NOT wait for
	// because it sits on other cards, so the record says what the swap ran beside.
	Cards           []string `json:"cards,omitempty"`
	LeasesLeftAlone []string `json:"leases_left_alone,omitempty"`
}

Outcome is the full, JSON-serializable record of one run — written to the --result file so a caller who launched this detached can poll for it over a fresh connection after an SSH drop.

func Run

func Run(ctx context.Context, plan Plan, deps Deps, log *Logger) Outcome

Run executes the full swap sequence. It never panics on a bad Plan; every failure is returned inside Outcome (OK=false, Error set) so a caller can always write the result file, even when Run's own precondition checks reject the Plan before touching anything.

type Plan

type Plan struct {
	// Staged is the path to the already-staged new binary. Target is the
	// live binary it replaces.
	Staged string
	Target string

	// ExpectedSHA256 is the hex sha256 the staged binary must hash to before
	// anything is touched. SkipHashCheck exists for tests and dry runs of the
	// plumbing only — production callers always set ExpectedSHA256.
	ExpectedSHA256 string
	SkipHashCheck  bool

	// BackupSuffix names the backup file: "<Target>.bak-<BackupSuffix>".
	// Defaults to a timestamp when empty.
	BackupSuffix string

	// HealthURL is this node's own /fleet/health. Empty means a standalone
	// node with no fleet-serve endpoint (the <node-e> pattern): the
	// fleet-serve idle-wait and the health half of post-restart verification
	// are both skipped — instead the GPU LEASE is waited on (GPULockPath/
	// GPUStateDir below), since a standalone node has no queue depth to read
	// but can still be mid-render under a caller's own `gpu reserve`. PID +
	// image-hash verification still runs whenever a restart mechanism is
	// configured, regardless of which wait path applied.
	HealthURL        string
	WaitIdleTimeout  time.Duration // default 10m
	IdlePollInterval time.Duration // default 5s

	// GPULockPath / GPUStateDir override the GPU lease directory a STANDALONE
	// node (HealthURL == "") waits to clear before swapping — the check the
	// deploy record for d5207011 notes the operator had to do by hand ("gpu
	// status" before and right before the swap). Empty = the harness's own
	// built-in defaults (internal/gpulease.LeaseDir), the same resolution
	// `local-offload gpu status` uses. Ignored when HealthURL is set (a
	// fleet-serve node's own wait-idle already covers this).
	GPULockPath string
	GPUStateDir string

	// Cards are the cards this deploy touches, as GPU UUIDs (the lease ids a lease records,
	// compared case-insensitively; the node-swap command resolves an index or a UUID prefix
	// against the card table before a plan gets here, and refuses an entry that places on no
	// card). Empty = the whole node, and every GPU lease holds the standalone wait, exactly as
	// before. The OPERATOR says which cards, never the tool: a binary swap touches the exe and
	// the processes it may stop, not a card. With cards named, a lease holds the deploy when it
	// sits on one of them, names no cards (the whole node), or is held by a process the deploy
	// would stop (the fleet node, an MCP helper: both take a lease in-process while they render,
	// the lease records its holder's pid, and stopping that process ends the lease on whatever
	// card it sits). The rest are left alone and recorded (Outcome.LeasesLeftAlone). If the
	// processes running the image cannot be listed, nothing is narrowed. Cards with a health URL
	// is refused (validatePlan): that wait is the job count, which is node-wide, because a
	// restart of fleet-serve cuts every job the node is running, whichever card it runs on.
	Cards []string

	// Exactly one of RestartTaskName / RestartCommand should be set for a
	// fleet node; both empty means a standalone binary-only swap (no restart
	// at all — the <node-e> case named in the task).
	//
	// RestartTaskName: a Windows scheduled task Stop/Start wraps the swap
	// (the <node-a> "\offload-fleet-node" pattern).
	//
	// RestartCommand: an arbitrary command that performs its own stop+launch
	// (<node-b>'s fleet-node-restart.ps1, which launches via WMI/CIM because
	// this box has no scheduled task for fleet-serve). Run does not trust its
	// exit code alone — verifyRunning re-derives PID/hash/health
	// independently after it returns.
	RestartTaskName string
	RestartCommand  string
	RestartTimeout  time.Duration // default 60s, applied to RunCommand for the restart step

	VerifyTimeout      time.Duration // default 90s
	VerifyPollInterval time.Duration // default 2s

	// RenderTarball/RenderDir make the render-tree swap (tarball + backup +
	// extract + hash-verify) an OPTION alongside the binary swap, same as
	// every deploy record's render-tree step.
	RenderTarball      string
	RenderDir          string
	RenderBackupSuffix string

	// ProcessMatch is the substring a fleet-serve command line must contain
	// (default "fleet-serve"). MCPMatch identifies an idle MCP-server helper
	// sharing the same exe (default " mcp") — the Windows-only class of
	// holder documented in the 2026-09-24 <node-e> deploy: an idle `... mcp`
	// process can hold an OS-level handle on the exe and block the rename
	// even with no active job. Only a process matching MCPMatch and NOT also
	// matching ProcessMatch is ever stopped to clear a rename; any other
	// holder is reported, never touched.
	ProcessMatch string
	MCPMatch     string

	// DryRun validates the hash and (if HealthURL is set) reads health once,
	// then stops — no file or process is touched.
	DryRun bool

	// NoRollback is for tests exercising the failure path itself; production
	// callers never set it.
	NoRollback bool

	// FleetKey is what the caller read of the config the node's fleet-serve reads; nil = not checked.
	FleetKey *FleetKeyCheck

	// Generation, when set, replaces the file swap (steps 4 and 5: backup-rename and install) for a build that is
	// reached through a junction or symlink: the new build already sits in its own write-once directory, so the
	// swap is re-pointing the link, and a rollback re-points it back. Staged is the new executable, Target the
	// live path through the link; everything else (hash check, idle wait, stop, restart, verification) is the
	// same code. The update verb uses it for llama-swap laid out like every engine (docs/systems/update.md).
	Generation *Generation
}

Plan is every input to one node-swap run. It is plain data (no live handles), so it can be captured verbatim into the result file and used to reconstruct exactly what a run was asked to do.

type ProcessInfo

type ProcessInfo struct {
	PID            int
	CommandLine    string
	ExecutablePath string
	// Unreadable: a process with the target's file name whose path and command line the OS
	// would not give this process (Windows: it runs elevated or as another account, and CIM
	// returns both empty). Nothing can tell whether it is the node, so a swap that stops and
	// restarts the node refuses on it (refuseUnreadableHolders).
	Unreadable bool
}

ProcessInfo is one CIM/Win32_Process row: enough to identify a holder and decide whether it is safe to stop.

type StepResult

type StepResult struct {
	Name   string    `json:"name"`
	OK     bool      `json:"ok"`
	Detail string    `json:"detail,omitempty"`
	At     time.Time `json:"at"`
}

StepResult is one line of the run's audit trail.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL