Documentation
¶
Overview ¶
Package handoff implements graceful binary upgrades for CUDA processes, combining listener file-descriptor inheritance with CUDA Virtual Memory Management (VMM) POSIX file-descriptor slab handoff.
An Upgrader coordinates a parent process and its replacement child over an anonymous AF_UNIX control socketpair inherited across exec (or an optional 0600-permissioned Unix domain socket). On Upgrader.Upgrade, the parent transfers a JSON Manifest together with duplicated listener FDs and VMM POSIX_FD handles via SCM_RIGHTS.
The child adopts every listener and slab before signaling Upgrader.Ready. Adoption is fail-closed: a virtual-address collision under RequireSameVA, a device UUID or granularity mismatch, an FD count mismatch, or a corrupt manifest causes the child to unmap and release all partial state, report the error to the parent, and exit non-zero while the parent continues serving without interruption.
Basic usage:
u, err := handoff.New(handoff.Options{})
if err != nil {
log.Fatal(err)
}
defer u.Close()
ln, err := u.Listen("tcp", "127.0.0.1:8080")
if err != nil {
log.Fatal(err)
}
if err := u.Ready(); err != nil {
log.Fatal(err)
}
// Serve on ln until <-u.Exit().
This package is outside the compatibility promise of github.com/tmc/lib/nvidia. Its API may change or be removed in patch releases.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/cuda/handoff"
)
func main() {
u, err := handoff.New(handoff.Options{RunID: "example-run"})
if err != nil {
panic(err)
}
defer u.Close()
ln, err := u.Listen("tcp", "127.0.0.1:0")
if err != nil {
panic(err)
}
defer ln.Close()
if err := u.Ready(); err != nil {
panic(err)
}
fmt.Printf("child=%v gen=%d run=%s\n", u.IsChild(), u.GenerationID(), u.RunID())
}
Output: child=false gen=0 run=example-run
Index ¶
- Constants
- Variables
- type ListenerSpec
- type Manifest
- type MappedSlab
- type Options
- type SlabAccess
- type SlabMode
- type SlabSpec
- type Upgrader
- func (u *Upgrader) AdoptedSlab(name string) (*MappedSlab, bool)
- func (u *Upgrader) Close() error
- func (u *Upgrader) Exit() <-chan struct{}
- func (u *Upgrader) GenerationID() uint64
- func (u *Upgrader) IsChild() bool
- func (u *Upgrader) Listen(network, addr string) (net.Listener, error)
- func (u *Upgrader) Ready() error
- func (u *Upgrader) RegisterSlab(spec SlabSpec, exportFD int) error
- func (u *Upgrader) RunID() string
- func (u *Upgrader) Stop()
- func (u *Upgrader) Upgrade(ctx context.Context) error
- type VMM
Examples ¶
Constants ¶
const ( // ManifestVersion is the wire format version of [Manifest]. ManifestVersion = 1 // EnvControlFD is the environment variable carrying the inherited control // socket file descriptor number from parent to child. EnvControlFD = "CUDA_HANDOFF_FD" // EnvParentPID is the environment variable carrying the parent process ID // expected by the child during handoff adoption. EnvParentPID = "CUDA_HANDOFF_PPID" )
Variables ¶
var ( // ErrVACollision reports that a [RequireSameVA] slab could not be reserved // at its original virtual address. ErrVACollision = errors.New("handoff: virtual address collision") // ErrDeviceMismatch reports that the target device ordinal or UUID does not // match the handoff manifest. ErrDeviceMismatch = errors.New("handoff: device mismatch") // ErrGranularityMismatch reports that a slab's size or granularity does not // match the target device's VMM granularity. ErrGranularityMismatch = errors.New("handoff: granularity mismatch") // ErrFDCountMismatch reports that the number of file descriptors received // via SCM_RIGHTS does not match the manifest. ErrFDCountMismatch = errors.New("handoff: fd count mismatch") // ErrInvalidManifest reports a corrupt, unsupported, or invalid manifest. ErrInvalidManifest = errors.New("handoff: invalid manifest") // ErrUpgradeInProgress reports that [Upgrader.Upgrade] is already running. ErrUpgradeInProgress = errors.New("handoff: upgrade already in progress") // ErrClosed reports an operation on a closed [Upgrader]. ErrClosed = errors.New("handoff: upgrader closed") // ErrAlreadyReady reports that [Upgrader.Ready] was called more than once. ErrAlreadyReady = errors.New("handoff: already ready") // ErrChildExited reports that the child process exited before signaling ready. ErrChildExited = errors.New("handoff: child exited before ready") )
Functions ¶
This section is empty.
Types ¶
type ListenerSpec ¶
type ListenerSpec struct {
Name string `json:"name"`
Network string `json:"network"`
Addr string `json:"addr"`
FD int `json:"-"`
}
ListenerSpec describes a network listener handed off to a child process.
type Manifest ¶
type Manifest struct {
Version int `json:"version"`
RunID string `json:"run_id"`
GenerationID uint64 `json:"generation_id"`
ParentPID int `json:"parent_pid"`
Listeners []ListenerSpec `json:"listeners,omitempty"`
Slabs []SlabSpec `json:"slabs,omitempty"`
}
Manifest is the JSON wire payload transferred alongside SCM_RIGHTS FDs.
type MappedSlab ¶
type MappedSlab struct {
Name string
DeviceOrdinal int
DeviceUUID string
BaseVA uint64
RequestedVA uint64
Size uint64
Granularity uint64
Mode SlabMode
Access SlabAccess
SHA256 string
FD int
// contains filtered or unexported fields
}
MappedSlab represents a VMM slab adopted and mapped by a child process. Call MappedSlab.Close when finished to unmap the VA range, free the VA reservation, and close the duplicated POSIX FD.
func (*MappedSlab) Close ¶
func (s *MappedSlab) Close() error
Close unmaps the slab, frees its VA reservation, and closes its duplicated POSIX FD. Close is safe to call multiple times.
type Options ¶
type Options struct {
// UpgradeTimeout bounds how long [Upgrader.Upgrade] waits for the child
// process to signal [Upgrader.Ready]. Defaults to 30s when <= 0.
UpgradeTimeout time.Duration
// ExecPath is the binary executed on [Upgrader.Upgrade]. Defaults to
// [os.Executable] when empty.
ExecPath string
// Args are the command-line arguments passed to the child process
// (excluding argv[0]). Defaults to os.Args[1:] when nil.
Args []string
// Env is the environment passed to the child process. Defaults to
// [os.Environ] when nil. Handoff control variables are always stamped.
Env []string
// RunID identifies a logical server instance across upgrade generations.
// Generated randomly on a fresh parent if empty.
RunID string
// VMM provides CUDA Virtual Memory Management operations. Defaults to
// [DefaultVMM] when nil.
VMM VMM
// ControlFD optionally overrides [EnvControlFD] when > 0, allowing
// in-process socketpair handoff without exec.
ControlFD int
// ExpectedParentPID optionally overrides [EnvParentPID] when ControlFD > 0.
// When 0 and ControlFD > 0, parent PID verification is skipped.
ExpectedParentPID int
// ControlSocketPath optionally binds an AF_UNIX listener with 0600
// permissions. When empty (the default), Upgrade uses an anonymous
// socketpair inherited across exec.
ControlSocketPath string
}
Options configures an Upgrader.
type SlabAccess ¶
type SlabAccess int
SlabAccess controls the GPU page protection applied to a mapped VMM slab.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/cuda/handoff"
)
func main() {
fmt.Println(handoff.AccessReadOnly, handoff.AccessReadWrite)
}
Output: read_only read_write
const ( // AccessReadOnly maps the slab with PROT_READ only (default for weight slabs). AccessReadOnly SlabAccess = iota // AccessReadWrite maps the slab with PROT_READ|PROT_WRITE (for KV-cache pools). AccessReadWrite )
func (SlabAccess) MarshalJSON ¶
func (a SlabAccess) MarshalJSON() ([]byte, error)
MarshalJSON encodes a as its canonical string name.
func (SlabAccess) String ¶
func (a SlabAccess) String() string
String returns the canonical name of a.
func (*SlabAccess) UnmarshalJSON ¶
func (a *SlabAccess) UnmarshalJSON(b []byte) error
UnmarshalJSON decodes a from its canonical string name.
type SlabMode ¶
type SlabMode int
SlabMode controls whether a VMM slab must map at its original virtual address.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/cuda/handoff"
)
func main() {
fmt.Println(handoff.RequireSameVA, handoff.AllowRelocate)
}
Output: require_same_va allow_relocate
const ( // RequireSameVA requires the child to reserve the exact BaseVA from the // parent. If the driver cannot satisfy the reservation, adoption fails closed. RequireSameVA SlabMode = iota // AllowRelocate treats BaseVA as a hint and accepts a different virtual // address if the original range is occupied. AllowRelocate )
func (SlabMode) MarshalJSON ¶
MarshalJSON encodes m as its canonical string name.
func (*SlabMode) UnmarshalJSON ¶
UnmarshalJSON decodes m from its canonical string name.
type SlabSpec ¶
type SlabSpec struct {
Name string `json:"name"`
DeviceOrdinal int `json:"device_ordinal"`
DeviceUUID string `json:"device_uuid"`
BaseVA uint64 `json:"base_va"`
Size uint64 `json:"size"`
Granularity uint64 `json:"granularity"`
Mode SlabMode `json:"mode"`
Access SlabAccess `json:"access"`
SHA256 string `json:"sha256,omitempty"`
FD int `json:"-"`
}
SlabSpec describes a resident CUDA VMM memory slab to hand off to a child.
type Upgrader ¶
type Upgrader struct {
// contains filtered or unexported fields
}
Upgrader manages listener and CUDA VMM slab handoff across graceful binary upgrades.
func New ¶
New creates an Upgrader. If the process was spawned by a parent's Upgrader.Upgrade (detected via EnvControlFD or Options.ControlFD), New receives the manifest and SCM_RIGHTS FDs, validates every listener and VMM slab, and maps all slabs before returning.
If any adoption step fails, New rolls back all partial mappings and closes all received FDs, sends the error to the parent, and returns a non-nil error.
func (*Upgrader) AdoptedSlab ¶
func (u *Upgrader) AdoptedSlab(name string) (*MappedSlab, bool)
AdoptedSlab returns the mapped VMM slab adopted during New under name.
func (*Upgrader) Close ¶
Close releases all resources owned by the Upgrader, including duplicated slab export FDs, unclaimed adopted listeners, and any unclosed adopted slabs.
func (*Upgrader) Exit ¶
func (u *Upgrader) Exit() <-chan struct{}
Exit returns a channel that is closed when a replacement child signals Upgrader.Ready or when Upgrader.Stop / Upgrader.Close is called.
func (*Upgrader) GenerationID ¶
GenerationID returns the zero-based upgrade generation (0 for a fresh parent).
func (*Upgrader) IsChild ¶
IsChild reports whether this Upgrader adopted state from a parent process.
func (*Upgrader) Listen ¶
Listen returns a handed-off listener matching (network, addr) if one was adopted from the parent, or binds a fresh listener otherwise. The returned listener is automatically registered for subsequent upgrades.
func (*Upgrader) Ready ¶
Ready signals the parent process that this child has adopted all listeners and VMM slabs and passed startup/parity checks. Calling Ready on a fresh parent is a no-op.
func (*Upgrader) RegisterSlab ¶
RegisterSlab registers a resident VMM slab and its exported POSIX FD to be handed off during Upgrader.Upgrade. The Upgrader duplicates exportFD with FD_CLOEXEC so the caller retains independent ownership of exportFD.
func (*Upgrader) Stop ¶
func (u *Upgrader) Stop()
Stop signals the process to stop accepting new work and drain.
func (*Upgrader) Upgrade ¶
Upgrade spawns a replacement child binary, transfers the manifest, listener FDs, and VMM POSIX_FD handles via SCM_RIGHTS, and waits for the child to call Upgrader.Ready.
On success, Upgrade closes Upgrader.Exit and returns nil. If the child fails validation, crashes, or exceeds UpgradeTimeout/ctx before Ready, Upgrade aborts cleanly and returns an error while leaving this parent live and able to retry later.
type VMM ¶
type VMM interface {
DeviceUUID(deviceOrdinal int) (string, error)
Granularity(deviceOrdinal int) (uint64, error)
ImportPOSIXFD(fd int) (uint64, error)
AddressReserve(size, alignment, requestedBaseVA uint64) (uint64, error)
Map(va, size, handle uint64) error
SetAccess(va, size uint64, deviceOrdinal int, access SlabAccess) error
Unmap(va, size uint64) error
AddressFree(va, size uint64) error
ReleaseHandle(handle uint64) error
}
VMM abstracts the CUDA Virtual Memory Management driver operations required to import, reserve, map, protect, and release GPU memory slabs.
func DefaultVMM ¶
func DefaultVMM() VMM
DefaultVMM returns a VMM backed by the Linux CUDA driver API via purego.