Documentation
¶
Overview ¶
Package traysup implements a hardened local process supervisor for GPU development pods.
A Supervisor manages a single worker process in an isolated process group (and optional separate UID/GID on Unix) behind a loopback-only HTTP control API. Every control endpoint—including read-only endpoints—requires a per-session random bearer token verified in constant time, an exact loopback Host header, no Origin header, and no cross-site Sec-Fetch-Site header.
Capability Tiers ¶
The supervisor starts with a fixed capability Tier that cannot be raised through the control API:
- TierObserve: read-only access to /status, /logs, /receipts, and /provenance.
- TierKernel (default): observe plus /pull into allowlisted directories, hot-patch, and start/stop/restart using a fixed launch profile.
- TierConfig: kernel plus allowlisted profile selection and flag overrides.
- TierCode: config plus free-form worker argv and environment variables.
Below TierCode, free-form argv and dangerous environment variables (LD_*, PYTHON*, PATH, CUDA_INJECTION*, *_PRELOAD, GCONV_PATH, HOSTALIASES, LOCPATH) are rejected.
CUDA Forward Compatibility ¶
The cuda_compat setting ("base", "13.4", or "13.5") prepends a forward-compat library directory to the worker environment only; the supervisor's own environment is never mutated. CheckLoadedLibCUDA parses /proc/<pid>/maps to verify that the loaded libcuda.so path matches the requested mode.
Kubernetes RBAC Boundary ¶
Port-forwarding to the loopback control API requires pods/portforward, which is a distinct Kubernetes RBAC subresource from pods/exec. Use RBACCheck and VerifyPortForwardExecBoundary to verify both subresources explicitly before treating port-forward access as exec-equivalent.
Telemetry and Receipts ¶
Each supervisor session has an immutable run_id, and each edit, patch, or restart attempt advances a monotonic generation_id independently of serving_generation_id. Every terminal attempt emits an unsampled Receipt with StageTimings (omitting unmeasured stages rather than reporting 0) and six SHA-256 Digests. Per-cell probe summaries are recorded as deduplicated ProbeCellEvent values with explicit comparability flags.
Basic usage:
sup, err := traysup.New(traysup.Config{
Tier: traysup.TierKernel,
ListenAddr: "127.0.0.1:8080",
TokenFile: "/run/traysup/token",
AllowPullDirs: []string{"/var/cache/traysup/overlay"},
})
if err != nil {
log.Fatal(err)
}
defer sup.Shutdown()
This package is outside the compatibility promise of github.com/tmc/lib/nvidia. Its API may change or be removed in patch releases.
Index ¶
- Constants
- Variables
- func ApplyCUDACompatEnv(env []string, compatDir string) []string
- func DurationMS(d time.Duration) *int64
- func FormatEventID(runID, testStep string) string
- func FormatTestStep(generationID int64, cell, repeat int) string
- func GenerateToken() (string, error)
- func IsDangerousEnvKey(key string) bool
- func IsLoopbackHost(hostHeader string) bool
- func NormalizeCUDACompat(raw string) (string, error)
- func ParseProcMapsLibCUDA(r io.Reader) []string
- func Redact(s, token string) string
- func ResolveCUDACompatDir(mode string, searchRoots []string) (string, error)
- func ValidateArgv(tier Tier, argv []string) error
- func ValidateEnv(tier Tier, env map[string]string) error
- func ValidateListenAddr(addr string, allowNonLoopback bool) error
- func VerifyPortForwardExecBoundary(c RBACCheck) error
- func WriteTokenFile(path, token string) error
- type CUDAProvenance
- type Config
- type CubinVetError
- type CubinVetFinding
- type CubinVetFunc
- type CubinVetReceipt
- type CubinVetter
- type Digests
- type ExecCubinVetter
- type Exporter
- type LaunchProfile
- type LogBuffer
- type LogStats
- type PatchRequest
- type ProbeCellEvent
- type PullRequest
- type PullResult
- type RBACCheck
- type Receipt
- type RollbackInfo
- type StageTimings
- type StatusSnapshot
- type StopRequest
- type Supervisor
- func (s *Supervisor) ApplyPatch(ctx context.Context, req PatchRequest) (Receipt, int, error)
- func (s *Supervisor) Handler() http.Handler
- func (s *Supervisor) ListenAndServe(ctx context.Context) error
- func (s *Supervisor) ProbeCellEvents() []ProbeCellEvent
- func (s *Supervisor) Pull(ctx context.Context, req PullRequest) (PullResult, error)
- func (s *Supervisor) Receipts() []Receipt
- func (s *Supervisor) RecordProbeCellEvent(ctx context.Context, ev ProbeCellEvent) (ProbeCellEvent, bool, error)
- func (s *Supervisor) Restart(ctx context.Context, req WorkerRequest) (Receipt, error)
- func (s *Supervisor) RunID() string
- func (s *Supervisor) Shutdown()
- func (s *Supervisor) Start(ctx context.Context, req WorkerRequest) (Receipt, error)
- func (s *Supervisor) Status() StatusSnapshot
- func (s *Supervisor) Tier() Tier
- func (s *Supervisor) Token() string
- type Tier
- type WorkerRequest
Examples ¶
Constants ¶
const ( // DefaultListenAddr is the default loopback-only control API bind address. DefaultListenAddr = "127.0.0.1:8080" // DefaultMaxRequestBodyBytes caps HTTP request bodies on mutating endpoints. DefaultMaxRequestBodyBytes int64 = 1 << 20 // 1 MiB )
const ( CUDACompatBase = "base" CUDACompat134 = "13.4" CUDACompat135 = "13.5" )
Supported CUDA forward-compatibility modes.
const ( SubresourcePodsPortForward = "pods/portforward" SubresourcePodsExec = "pods/exec" )
Kubernetes RBAC subresource names modeled distinctly by traysup.
Access to pods/portforward allows reaching the loopback-bound control API, whereas pods/exec allows arbitrary process execution inside the container. Callers must verify both subresources explicitly before treating a port-forward channel as exec-equivalent.
const ( // DefaultWatchdogTimeout is the default launch readiness/watchdog budget. DefaultWatchdogTimeout = 30 * time.Second // DefaultStopGracePeriod is the SIGTERM-to-SIGKILL grace window. DefaultStopGracePeriod = 5 * time.Second )
const DefaultMaxLogBytes int64 = 4 << 20 // 4 MiB
DefaultMaxLogBytes is the default local log ring-buffer byte cap.
const DefaultMaxPullBytes int64 = 64 << 20 // 64 MiB
DefaultMaxPullBytes is the default maximum artifact size accepted by /pull.
const RunKindDevloop = "devloop"
RunKindDevloop is the canonical run_kind value for devloop probe cell events.
Variables ¶
var ( // ErrPullPathDenied indicates that a /pull destination escaped the allowlisted roots. ErrPullPathDenied = errors.New("pull destination outside allowlisted directories") // ErrPullTooLarge indicates that a /pull payload exceeded MaxPullBytes. ErrPullTooLarge = errors.New("pull artifact exceeds size cap") // ErrDigestMismatch indicates that a /pull payload's SHA-256 did not match the request. ErrDigestMismatch = errors.New("pull artifact sha256 mismatch") )
var DefaultCubinVetChecks = []string{"features", "headroom", "resources"}
DefaultCubinVetChecks are the cudavet cubin checks run automatically before staging or patching a kernel slot onto a tray.
var ErrCUDACompatMismatch = errors.New("loaded libcuda.so does not match requested cuda_compat")
ErrCUDACompatMismatch indicates that the libcuda.so library mapped into a worker process does not match the requested cuda_compat mode.
var ErrDangerousEnv = errors.New("dangerous environment variable rejected")
ErrDangerousEnv indicates that a request supplied a prohibited environment variable below TierCode.
var ErrRBACNotExecEquivalent = errors.New("pods/portforward is not exec-equivalent without verified pods/exec")
ErrRBACNotExecEquivalent is returned by VerifyPortForwardExecBoundary when pods/portforward and pods/exec are not both explicitly verified.
var ErrTierDenied = errors.New("operation denied by supervisor tier")
ErrTierDenied indicates that an operation requires a higher Tier than the supervisor's fixed startup tier, or attempted to escalate the tier.
Functions ¶
func ApplyCUDACompatEnv ¶
ApplyCUDACompatEnv returns a copy of env with compatDir prepended to LD_LIBRARY_PATH. It never mutates the caller's slice or the current process environment.
func DurationMS ¶
DurationMS converts a monotonic duration to a non-nil millisecond pointer for StageTimings.
func FormatEventID ¶
FormatEventID returns the canonical deduplication key "<run_id>/<test_step>".
func FormatTestStep ¶
FormatTestStep formats a canonical test step identifier such as "g000042-c32-r01".
func GenerateToken ¶
GenerateToken returns a cryptographically random 32-byte lowercase hex token (64 hex characters).
func IsDangerousEnvKey ¶
IsDangerousEnvKey reports whether key is a loader, interpreter, or injection environment variable that is hard-denied below TierCode.
func IsLoopbackHost ¶
IsLoopbackHost reports whether an HTTP Host header is an exact loopback host: 127.0.0.1, 127.0.0.1:<port>, localhost, localhost:<port>, [::1], or [::1]:<port>.
func NormalizeCUDACompat ¶
NormalizeCUDACompat validates and normalizes raw to "base", "13.4", or "13.5". An empty string normalizes to "base".
func ParseProcMapsLibCUDA ¶
ParseProcMapsLibCUDA parses Linux /proc/<pid>/maps lines from r and returns the unique sorted file paths whose base name contains "libcuda.so".
func ResolveCUDACompatDir ¶
ResolveCUDACompatDir locates the forward-compat library directory containing libcuda.so.1 for mode ("13.4" or "13.5") under searchRoots. For "base", it returns ("", nil).
func ValidateArgv ¶
ValidateArgv checks free-form worker argv against the supervisor's tier. Below TierCode, free-form argv is rejected. At TierCode, an empty binary name is still rejected.
func ValidateEnv ¶
ValidateEnv checks env keys against the supervisor's tier. Below TierCode, any non-empty env map is rejected (free-form env requires TierCode), and any dangerous key returns an error wrapping ErrDangerousEnv.
func ValidateListenAddr ¶
ValidateListenAddr verifies that addr binds to a loopback interface unless allowNonLoopback is explicitly true.
func VerifyPortForwardExecBoundary ¶
VerifyPortForwardExecBoundary verifies that both pods/portforward and pods/exec have been checked and allowed before treating port-forward access as exec-equivalent.
func WriteTokenFile ¶
WriteTokenFile atomically writes token to path with 0600 permissions.
Types ¶
type CUDAProvenance ¶
type CUDAProvenance struct {
Requested string `json:"requested"`
CompatDir string `json:"compat_dir,omitempty"`
MappedLibCUDA []string `json:"mapped_libcuda,omitempty"`
Verified bool `json:"verified"`
MismatchReason string `json:"mismatch_reason,omitempty"`
CheckedAt string `json:"checked_at,omitempty"`
}
CUDAProvenance records the requested cuda_compat mode and the libcuda.so paths actually observed in the worker's /proc/<pid>/maps.
func CheckLoadedLibCUDA ¶
func CheckLoadedLibCUDA(mapsPath, requestedMode, compatDir string) (CUDAProvenance, error)
CheckLoadedLibCUDA parses mapsPath (typically /proc/<pid>/maps) and verifies that all mapped libcuda.so paths match requestedMode and compatDir.
func CheckLoadedLibCUDAFromReader ¶
func CheckLoadedLibCUDAFromReader(r io.Reader, requestedMode, compatDir string) (CUDAProvenance, error)
CheckLoadedLibCUDAFromReader parses /proc/<pid>/maps content from r and verifies that all mapped libcuda.so paths match requestedMode and compatDir.
Example ¶
package main
import (
"fmt"
"strings"
"github.com/tmc/lib/nvidia/x/host/traysup"
)
func main() {
maps := "7f000000-7f100000 r-xp 00000000 08:01 123 /opt/cuda-compat/13.4/libcuda.so.1\n"
prov, err := traysup.CheckLoadedLibCUDAFromReader(
strings.NewReader(maps),
traysup.CUDACompat134,
"/opt/cuda-compat/13.4",
)
fmt.Println(err == nil, prov.Verified, prov.Requested)
}
Output: true true 13.4
type Config ¶
type Config struct {
// Tier is the fixed capability tier (defaults to TierKernel).
Tier Tier
// ListenAddr is the HTTP bind address (defaults to 127.0.0.1:8080).
ListenAddr string
// AllowNonLoopback must be explicitly true to bind a non-loopback address.
AllowNonLoopback bool
// Token is the bearer token; if empty, a 32-byte random hex token is generated.
Token string
// TokenFile, if non-empty, is atomically written with mode 0600 at startup.
TokenFile string
// StateDir, if non-empty, receives generation.json stamps on start/restart/patch.
StateDir string
// AllowPullDirs lists the allowlisted destination roots for /pull.
AllowPullDirs []string
// MaxPullBytes caps the maximum size of a single /pull artifact.
MaxPullBytes int64
// MaxRequestBodyBytes caps HTTP request bodies on mutating endpoints.
MaxRequestBodyBytes int64
// MaxLogBytes caps the in-memory worker log ring buffer.
MaxLogBytes int64
// CUDACompatRoots lists directories searched for forward-compat libcuda.so.1.
CUDACompatRoots []string
// DefaultCUDACompat is the default cuda_compat mode ("base", "13.4", "13.5").
DefaultCUDACompat string
// Profiles defines allowlisted launch profiles keyed by name.
Profiles map[string]LaunchProfile
// DefaultProfile names the profile used when requests omit a profile.
DefaultProfile string
// BaseEnv overrides os.Environ() as the base worker environment when non-nil.
BaseEnv []string
// WorkerUID and WorkerGID optionally drop worker privileges on Unix.
WorkerUID *uint32
WorkerGID *uint32
// WatchdogTimeout bounds worker startup readiness and parity checks.
WatchdogTimeout time.Duration
// StopGracePeriod bounds the SIGTERM wait before SIGKILL.
StopGracePeriod time.Duration
// ReadinessCheck, if non-nil, verifies the worker is ready after launch.
ReadinessCheck func(ctx context.Context, gen int64) error
// ParityCheck, if non-nil, verifies numerical/output parity after launch or patch.
ParityCheck func(ctx context.Context, gen int64) error
// PatchHook, if non-nil, applies a hot-patch for /patch requests.
PatchHook func(ctx context.Context, gen int64, req PatchRequest) error
// CubinVetter validates KernelPath before ApplyPatch stages or books a tray.
// When nil, [ExecCubinVetter] runs "cudavet cubin -checks features,headroom,resources -json".
CubinVetter CubinVetter
// SkipCubinVet opts out of automatic cubin vetting for synthetic test payloads.
SkipCubinVet bool
// MapsPathFunc overrides /proc/<pid>/maps lookup (primarily for testing).
MapsPathFunc func(pid int) string
// HTTPClient is used by /pull for http(s) URLs.
HTTPClient *http.Client
// Exporter exports receipts and probe cell events from the supervisor UID.
Exporter Exporter
// Transport identifies the control transport recorded in receipts.
Transport string
}
Config configures a Supervisor. All security-critical settings (Tier, ListenAddr, AllowPullDirs, WorkerUID/GID) are fixed at construction time.
type CubinVetError ¶
type CubinVetError struct {
Receipt *CubinVetReceipt
Err error
}
CubinVetError reports a failed cubin preflight check along with its receipt.
func (*CubinVetError) Error ¶
func (e *CubinVetError) Error() string
func (*CubinVetError) Unwrap ¶
func (e *CubinVetError) Unwrap() error
type CubinVetFinding ¶
type CubinVetFinding struct {
Posn string `json:"posn"`
Check string `json:"check"`
Severity string `json:"severity"`
Kernel string `json:"kernel,omitempty"`
PC string `json:"pc,omitempty"`
Message string `json:"message"`
}
CubinVetFinding is one structured diagnostic emitted by "cudavet cubin -json".
type CubinVetFunc ¶
CubinVetFunc adapts a function to CubinVetter.
func (CubinVetFunc) VetCubin ¶
func (f CubinVetFunc) VetCubin(ctx context.Context, path string, checks []string) (*CubinVetReceipt, error)
VetCubin calls f(ctx, path, checks).
type CubinVetReceipt ¶
type CubinVetReceipt struct {
Status string `json:"status"` // "passed" or "failed"
Checks []string `json:"checks"`
File string `json:"file,omitempty"`
SHA256 string `json:"cubin_sha256,omitempty"`
SM int `json:"sm,omitempty"`
Target string `json:"target,omitempty"`
Findings []CubinVetFinding `json:"findings,omitempty"`
}
CubinVetReceipt records the outcome of running cubin preflight checks.
func (*CubinVetReceipt) BlockingFindings ¶
func (r *CubinVetReceipt) BlockingFindings() []CubinVetFinding
BlockingFindings returns the error-severity findings in r.
type CubinVetter ¶
type CubinVetter interface {
VetCubin(ctx context.Context, path string, checks []string) (*CubinVetReceipt, error)
}
CubinVetter checks a cubin file before a kernel slot is patched onto a tray.
type Digests ¶
type Digests struct {
ProbeSuite string `json:"probe_suite,omitempty"`
ReferenceOutputs string `json:"reference_outputs,omitempty"`
LaunchProfile string `json:"launch_profile,omitempty"`
Source string `json:"source,omitempty"`
Overlay string `json:"overlay,omitempty"`
Binary string `json:"binary,omitempty"`
}
Digests holds the six SHA-256 digests that identify a devloop generation's inputs and artifacts.
type ExecCubinVetter ¶
ExecCubinVetter runs "cudavet cubin -checks <checks> -json <path>" in a subprocess. If Binary is empty, "cudavet" is resolved via PATH.
func (ExecCubinVetter) VetCubin ¶
func (v ExecCubinVetter) VetCubin(ctx context.Context, path string, checks []string) (*CubinVetReceipt, error)
VetCubin invokes cudavet cubin on path with -json and the requested checks (defaulting to DefaultCubinVetChecks), failing closed on blocking findings or runner errors.
type Exporter ¶
type Exporter interface {
ExportReceipt(ctx context.Context, r Receipt) error
ExportProbeCell(ctx context.Context, e ProbeCellEvent) error
}
Exporter exports unsampled receipts and probe cell events from the supervisor process (supervisor UID, outside the worker UID). Implementations hold any collector credentials internally and never expose them to worker environments.
type LaunchProfile ¶
type LaunchProfile struct {
Argv []string `json:"argv"`
Env map[string]string `json:"env,omitempty"`
AllowedFlags []string `json:"allowed_flags,omitempty"`
CUDACompat string `json:"cuda_compat,omitempty"`
}
LaunchProfile defines an allowlisted worker command and optional flag allowlist used at TierKernel and TierConfig.
type LogBuffer ¶
type LogBuffer struct {
// contains filtered or unexported fields
}
LogBuffer is a bounded local ring buffer for raw worker logs and compiler output. Old entries are evicted when MaxBytes is exceeded, incrementing DroppedSpans and DroppedBytes.
func NewLogBuffer ¶
NewLogBuffer creates a LogBuffer capped at maxBytes.
func (*LogBuffer) Append ¶
Append adds line to the buffer, evicting oldest entries if needed to stay within the byte cap.
type LogStats ¶
type LogStats struct {
BufferedBytes int64 `json:"buffered_bytes"`
BufferedLines int `json:"buffered_lines"`
DroppedSpans int64 `json:"dropped_spans"`
DroppedBytes int64 `json:"dropped_bytes"`
}
LogStats reports local log buffer drop counters.
type PatchRequest ¶
type PatchRequest struct {
Kind string `json:"kind,omitempty"` // Empty and "kernel" require KernelPath. "generation" only advances the generation.
Who string `json:"who,omitempty"`
Tier string `json:"tier,omitempty"` // Always rejected with 403 if non-empty.
Argv []string `json:"argv,omitempty"` // Rejected below TierCode.
Env map[string]string `json:"env,omitempty"` // Rejected below TierCode.
OverlayDir string `json:"overlay_dir,omitempty"`
KernelPath string `json:"kernel_path,omitempty"`
Digests Digests `json:"digests,omitempty"`
}
PatchRequest is the JSON payload for POST /patch.
type ProbeCellEvent ¶
type ProbeCellEvent struct {
EventID string `json:"event_id"`
RunID string `json:"run_id"`
RunKind string `json:"run_kind"`
TestStep string `json:"test_step"`
StartGenerationID int64 `json:"start_generation_id"`
EndGenerationID int64 `json:"end_generation_id"`
ParityOK bool `json:"parity_ok"`
Denominator float64 `json:"denominator"`
Eligible bool `json:"eligible"`
IneligibleReason string `json:"ineligible_reason,omitempty"`
Warm bool `json:"warm"`
ProfilerOn bool `json:"profiler_on"`
SampleCount int `json:"sample_count"`
StageTimings StageTimings `json:"stage_timings"`
Digests Digests `json:"digests"`
TimestampRFC3339 string `json:"timestamp_rfc3339"`
}
ProbeCellEvent is an unsampled per-cell probe summary deduplicated by EventID.
func (*ProbeCellEvent) EvaluateComparability ¶
func (e *ProbeCellEvent) EvaluateComparability()
EvaluateComparability enforces comparability invariants on e and populates RunKind, EventID, Eligible, and IneligibleReason.
A cell is marked ineligible (Eligible=false) if:
- StartGenerationID <= 0 or StartGenerationID != EndGenerationID (generation changed mid-cell)
- !ParityOK (parity failed)
- Denominator <= 0 (denominator missing or zero)
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/host/traysup"
)
func main() {
ev := traysup.ProbeCellEvent{
RunID: "run1",
TestStep: traysup.FormatTestStep(42, 32, 1),
StartGenerationID: 42,
EndGenerationID: 42,
ParityOK: true,
Denominator: 100.0,
Warm: true,
SampleCount: 64,
}
ev.EvaluateComparability()
fmt.Println(ev.EventID, ev.RunKind, ev.Eligible)
}
Output: run1/g000042-c32-r01 devloop true
type PullRequest ¶
type PullRequest struct {
URL string `json:"url"`
DestRoot string `json:"dest_root,omitempty"`
Dest string `json:"dest"`
SHA256 string `json:"sha256"`
Executable bool `json:"executable,omitempty"`
}
PullRequest describes an artifact to fetch into an allowlisted directory.
type PullResult ¶
type PullResult struct {
Path string `json:"path"`
Bytes int64 `json:"bytes"`
SHA256 string `json:"sha256"`
}
PullResult reports the verified destination path, byte size, and SHA-256 digest.
type RBACCheck ¶
type RBACCheck struct {
Namespace string `json:"namespace"`
Pod string `json:"pod"`
PortForwardChecked bool `json:"portforward_checked"`
PortForwardAllowed bool `json:"portforward_allowed"`
ExecChecked bool `json:"exec_checked"`
ExecAllowed bool `json:"exec_allowed"`
}
RBACCheck records independently verified Kubernetes RBAC permissions for a pod's portforward and exec subresources.
func (RBACCheck) CanPortForward ¶
CanPortForward reports whether pods/portforward was checked and allowed.
func (RBACCheck) EquivalentToExec ¶
EquivalentToExec reports whether both pods/portforward and pods/exec were independently checked and allowed.
type Receipt ¶
type Receipt struct {
Who string `json:"who"`
Transport string `json:"transport"`
EffectiveTier Tier `json:"effective_tier"`
Op string `json:"op"`
Result string `json:"result"`
Error string `json:"error,omitempty"`
RunID string `json:"run_id"`
GenerationID int64 `json:"generation_id"`
ServingGenerationID int64 `json:"serving_generation_id"`
Rollback *RollbackInfo `json:"rollback,omitempty"`
CUDAProvenance *CUDAProvenance `json:"cuda_provenance,omitempty"`
CubinVet *CubinVetReceipt `json:"cubin_vet,omitempty"`
StageTimings StageTimings `json:"stage_timings"`
Digests Digests `json:"digests"`
TimestampRFC3339 string `json:"timestamp_rfc3339"`
}
Receipt is the single unsampled terminal audit record emitted for every control attempt (start, restart, patch, stop, pull, or rejected operation). It never contains bearer tokens or exporter credentials.
type RollbackInfo ¶
type RollbackInfo struct {
Attempted bool `json:"attempted"`
Restored int64 `json:"restored,omitempty"`
Digest string `json:"digest,omitempty"`
}
RollbackInfo records whether a failed attempt triggered a rollback to the last known good generation.
type StageTimings ¶
type StageTimings struct {
WallAnchorRFC3339 string `json:"wall_anchor_rfc3339"`
PullMS *int64 `json:"pull_ms,omitempty"`
PatchMS *int64 `json:"patch_ms,omitempty"`
StopMS *int64 `json:"stop_ms,omitempty"`
StartMS *int64 `json:"start_ms,omitempty"`
ReadyMS *int64 `json:"ready_ms,omitempty"`
ParityMS *int64 `json:"parity_ms,omitempty"`
RollbackMS *int64 `json:"rollback_ms,omitempty"`
TotalMS *int64 `json:"total_ms,omitempty"`
}
StageTimings records monotonic stage durations in milliseconds anchored to a wall-clock RFC3339 timestamp. Missing stages are nil pointers and omitted from JSON so an unmeasured stage is never serialized as 0.
func NewStageTimings ¶
func NewStageTimings() StageTimings
NewStageTimings initializes a StageTimings with the current UTC wall anchor.
type StatusSnapshot ¶
type StatusSnapshot struct {
RunID string `json:"run_id"`
Tier Tier `json:"tier"`
State string `json:"state"`
PID int `json:"pid,omitempty"`
GenerationID int64 `json:"generation_id"`
ServingGenerationID int64 `json:"serving_generation_id"`
CUDACompat string `json:"cuda_compat"`
CUDAProvenance *CUDAProvenance `json:"cuda_provenance,omitempty"`
DroppedSpans int64 `json:"dropped_spans"`
DroppedBytes int64 `json:"dropped_bytes"`
ReceiptCount int `json:"receipt_count"`
ProbeCellCount int `json:"probe_cell_count"`
}
StatusSnapshot is returned by GET /status. It never contains secrets.
type StopRequest ¶
type StopRequest struct {
Who string `json:"who,omitempty"`
Tier string `json:"tier,omitempty"` // Always rejected with 403 if non-empty.
}
StopRequest is the JSON payload for POST /stop.
type Supervisor ¶
type Supervisor struct {
// contains filtered or unexported fields
}
Supervisor manages a single worker process behind a hardened loopback HTTP control API.
func New ¶
func New(cfg Config) (*Supervisor, error)
New validates cfg and constructs a Supervisor. The tier and listen address policy are fixed at construction time.
func (*Supervisor) ApplyPatch ¶
func (s *Supervisor) ApplyPatch(ctx context.Context, req PatchRequest) (Receipt, int, error)
ApplyPatch applies a hot-patch, increments generation_id monotonically, stamps the generation into StateDir, verifies parity, and emits a receipt.
func (*Supervisor) Handler ¶
func (s *Supervisor) Handler() http.Handler
Handler returns the hardened HTTP control handler. Every endpoint—including read-only endpoints—is wrapped in the L3 authentication and header-hardening middleware.
func (*Supervisor) ListenAndServe ¶
func (s *Supervisor) ListenAndServe(ctx context.Context) error
ListenAndServe starts the loopback HTTP control server and blocks until ctx is cancelled or the server returns an error.
func (*Supervisor) ProbeCellEvents ¶
func (s *Supervisor) ProbeCellEvents() []ProbeCellEvent
ProbeCellEvents returns a copy of all deduplicated probe cell events recorded so far.
func (*Supervisor) Pull ¶
func (s *Supervisor) Pull(ctx context.Context, req PullRequest) (PullResult, error)
Pull downloads req.URL into an allowlisted directory, verifies its SHA-256 digest and size cap, and atomically renames it into place. On any failure, no partial file is left behind.
func (*Supervisor) Receipts ¶
func (s *Supervisor) Receipts() []Receipt
Receipts returns a copy of all unsampled terminal receipts emitted so far.
func (*Supervisor) RecordProbeCellEvent ¶
func (s *Supervisor) RecordProbeCellEvent(ctx context.Context, ev ProbeCellEvent) (ProbeCellEvent, bool, error)
RecordProbeCellEvent evaluates comparability, deduplicates by EventID, stores the event, and exports it via the configured Exporter. It returns true if the event was newly recorded, or false if it was a duplicate EventID.
func (*Supervisor) Restart ¶
func (s *Supervisor) Restart(ctx context.Context, req WorkerRequest) (Receipt, error)
Restart restarts the worker according to req and returns the terminal receipt.
func (*Supervisor) RunID ¶
func (s *Supervisor) RunID() string
RunID returns the immutable session identifier for this supervisor.
func (*Supervisor) Shutdown ¶
func (s *Supervisor) Shutdown()
Shutdown terminates any running worker process group.
func (*Supervisor) Start ¶
func (s *Supervisor) Start(ctx context.Context, req WorkerRequest) (Receipt, error)
Start launches the worker according to req and returns the terminal receipt.
func (*Supervisor) Status ¶
func (s *Supervisor) Status() StatusSnapshot
Status returns a point-in-time snapshot of the supervisor state.
func (*Supervisor) Tier ¶
func (s *Supervisor) Tier() Tier
Tier returns the immutable startup tier of this supervisor.
func (*Supervisor) Token ¶
func (s *Supervisor) Token() string
Token returns the session bearer token (intended for in-process callers and tests). The token is never logged or returned by any HTTP endpoint.
type Tier ¶
type Tier int
Tier is the fixed capability level of a Supervisor. Tiers are strictly ordered: TierObserve < TierKernel < TierConfig < TierCode. Once configured at startup, a supervisor's tier can never be raised via API.
const ( // TierObserve permits read-only inspection (/status, /logs, /receipts, /provenance). TierObserve Tier = iota + 1 // TierKernel permits observe plus kernel-patch, fixed-profile lifecycle, and allowlisted /pull. TierKernel // TierConfig permits kernel plus allowlisted profile and flag overrides. TierConfig // TierCode permits config plus free-form worker argv and environment variables. TierCode )
func ParseTier ¶
ParseTier parses a case-insensitive tier name ("observe", "kernel", "config", "code"). An empty string returns TierKernel.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/host/traysup"
)
func main() {
t, err := traysup.ParseTier("kernel")
if err != nil {
panic(err)
}
fmt.Println(t, t.Allows(traysup.TierObserve), t.Allows(traysup.TierCode))
}
Output: kernel true false
func (Tier) MarshalJSON ¶
MarshalJSON encodes t as its lowercase string name.
func (Tier) MarshalText ¶
MarshalText implements encoding.TextMarshaler.
func (*Tier) UnmarshalJSON ¶
UnmarshalJSON decodes a JSON string tier name.
func (*Tier) UnmarshalText ¶
UnmarshalText implements encoding.TextUnmarshaler.
type WorkerRequest ¶
type WorkerRequest struct {
Who string `json:"who,omitempty"`
Tier string `json:"tier,omitempty"` // Always rejected with 403 if non-empty.
Profile string `json:"profile,omitempty"`
Flags []string `json:"flags,omitempty"`
Argv []string `json:"argv,omitempty"`
Env map[string]string `json:"env,omitempty"`
CUDACompat string `json:"cuda_compat,omitempty"`
OverlayDir string `json:"overlay_dir,omitempty"`
Digests Digests `json:"digests,omitempty"`
}
WorkerRequest is the JSON payload for POST /start and POST /restart.