agent

package
v0.1.3 Latest Latest
Warning

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

Go to latest
Published: Nov 2, 2026 License: MIT Imports: 41 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 agent is the remote side of a job (spec 8.4), the same binary as the host side.

Index

Constants

View Source
const (
	VerdictNoFirewall = "FIREWALL NOT ACTIVE"
	VerdictNoEgress   = "EGRESS BROKEN"
)

The verdicts the self-test prints.

View Source
const (
	MarkBoot        = "__BITC_BOOT__"
	MarkBegin       = "__BITC_BEGIN__"
	MarkExit        = "__BITC_EXIT__"
	MarkSetupFailed = "__BITC_SETUP_FAILED__"
	MarkLost        = "__BITC_LOST__"
)
View Source
const (
	ProvisionExitRepo  = 71
	ProvisionExitInfra = 75
)

Exit codes of `__agent provision` besides 0: the repo's own failure and an infrastructure one. Anything else (64 bad input, a signal, 69, 126, 127) is read as infrastructure.

View Source
const MaxBootPayload = 8 << 20

MaxBootPayload is the largest boot payload body the agent accepts (8 MiB).

View Source
const ProvisionMarkerName = "provisioned.json"

ProvisionMarkerName is the marker file in the state root.

View Source
const SSHDSnippetText = "" /* 128-byte string literal not displayed */

SSHDSnippetText is the exact /etc/ssh/sshd_config.d/bitc.conf.

View Source
const SelfTestMarker = "/var/lib/bitc/selftest-failed"

SelfTestMarker is the file whose presence means the last self-test did not pass.

View Source
const SudoersText = "Defaults!/opt/bitc/sbin/bitc-gate !use_pty, !requiretty, !log_output, env_reset\n" +
	"bitc ALL=(root) NOPASSWD: /opt/bitc/sbin/bitc-gate\n"

SudoersText is the exact /etc/sudoers.d/bitc (providers delta C.5).

Variables

View Source
var (
	ErrTruncated = errors.New("truncated payload")
	ErrTooLarge  = errors.New("payload over 8 MiB")
	ErrBadArg    = errors.New("bad argument")
	ErrNotFound  = errors.New("not found")
	ErrOffset    = errors.New("offset beyond the end")
)
View Source
var ResultFiles = map[string]bool{"state.json": true, "out.log": true, "err.log": true, "artifacts.tar.gz": true, "result.json": true}

ResultFiles are the only names the results server serves.

Functions

func CanonNft

func CanonNft(j []byte) (string, error)

CanonNft canonicalises `nft -j list table inet bitc` output for comparison: handles and the metainfo object are dropped and set elements sorted; rule order is kept.

func EvalSelfTest

func EvalSelfTest(spec SelfTestSpec, res NetProbeResult) (lines, verdicts []string)

EvalSelfTest turns probe results into report lines and verdicts (none means the test passed). A target the probe did not report counts as blocked, which fails an Allow target.

func ExecVerb

func ExecVerb(args []string, stdout io.Writer, stderr io.Writer) int

ExecVerb runs `__agent [--root DIR] read|tail|list|teardown ...` and returns its exit code: 64 for a bad argument (nothing on stdout), 65 for an offset past the end, 66 when the job or file is not there, 69 for an error of the agent's own.

func FormatMarker

func FormatMarker(kind, nonce string, arg ...string) string

FormatMarker renders "<kind> <nonce>[ <arg>]".

func InstallJobSeccomp

func InstallJobSeccomp() error

InstallJobSeccomp sets PR_SET_NO_NEW_PRIVS and installs the filter for this architecture on every thread of the process (TSYNC); it is inherited by every child and cannot be removed.

func JobSeccompProgram

func JobSeccompProgram(goarch string) ([]unix.SockFilter, error)

JobSeccompProgram is the job seccomp filter for goarch ("amd64" or "arm64").

func List

func List(root string, w io.Writer) error

List prints one JSON line per job directory: its job id, phase (from state.json), whether the agent is alive and the exit code once there is one.

func Main

func Main(args []string, stdout io.Writer) int

Main is `bitc __agent`: stage 1 moves secrets out of the env and re-execs; stage 2 runs.

func MainIO

func MainIO(args []string, stdin io.Reader, stdout io.Writer) int

MainIO is Main with the input and the error stream explicit. Besides the environment boot it runs `--boot-stdin` (a length-prefixed payload on stdin, no listener) and the exec results verbs `read`, `tail`, `list` and `teardown` (providers delta X.1).

func NewServer

func NewServer(dir string, bearer []byte) (http.Handler, error)

NewServer serves GET|HEAD /v1/<name> with Range, only with Authorization: Bearer <hex B>; anything else is 404 without a body, other methods 405 (spec 8.4).

func NftTemplate

func NftTemplate() string

NftTemplate returns the ruleset template with its three placeholders (for the setup script test).

func PackArtifacts

func PackArtifacts(workdir string, paths []string, w io.Writer) error

PackArtifacts tars regular files and dirs under the declared paths that exist (symlinks are neither followed nor stored); an empty archive when none exist (spec 8.4 step 6).

func ParseSlots

func ParseSlots(s string) ([]int, bool)

ParseSlots parses "1" or "1+2+3" (ascending, no repeats, each 1..64).

func Provision

func Provision(o ProvisionOptions, ps ProvisionSpec) int

Provision installs the packages and tools, creates the job user and the state root and writes the marker. It prints its progress on o.Stdout and returns 0, ProvisionExitRepo or ProvisionExitInfra. The last line of a failure is `setup step <name> failed: <why>`.

func ReadFile

func ReadFile(root, job, file string, off int64, w io.Writer) error

ReadFile writes file of job from offset off to w. Only the result files are served, never a .part, a link or anything else (the exec twin of the results server's rules, spec 8.4).

func RenderNft

func RenderNft(c HostConf, uids []int) (string, error)

RenderNft renders the C.8.7 ruleset for conf and the slot users' uids.

func Run

func Run(ctx context.Context, o Options, s Spec, sec Secrets) int

Run is stage 2: one job, then serve until torn down (spec 8.4 steps 2-7).

func RunFirewallSelfTest

func RunFirewallSelfTest(e HostEnv, spec SelfTestSpec, out io.Writer) int

RunFirewallSelfTest probes with e.NetProbe, prints the report to out and keeps the marker (under e.Root) in step with the result. It returns 0 for a pass and 69 for anything else.

func RunSlot

func RunSlot(env SlotRunEnv, slots []int, name, nonce string, stdin io.Reader, stdout io.Writer) int

RunSlot is `slot-boot --run` against env: the handoff, then (for an upload) the bundle, then stage 2.

func SelfTestFailed

func SelfTestFailed(root string) bool

SelfTestFailed reports whether the marker exists under root.

func Stub

func Stub(url, sum string) string

Stub is the start script (spec 8.4 step 1): fetch the agent with curl or wget (else install curl), verify its sha256, exec it. It keeps the spec env for stage 1 but runs its own tools under a fixed PATH. BITC_STUB_DIR is for the stub's own unit test only.

func StubBuild

func StubBuild(cloneURL, ref, commit, sum string) string

StubBuild is the start script for agent = { source = "build" } (spec 8.4 step 1). In the pinned golang image, as root, it fetches the one agent ref from cloneURL with the deploy key (the BITC_DEPLOY_KEY env var, pinned hosts from BITC_KNOWN_HOSTS, the same set the agent uses), shreds the key at once, checks out and verifies commit, builds with the recipe in buildrecipe.sh, and execs the result only if its sha256 equals sum, under umask 022 (the stub itself runs under 077 for the key; the agent must create 0755 dirs the job user can traverse). BITC_STUB_DIR is for the stub's own unit test only.

func StubInstall

func StubInstall(url, sum string) string

StubInstall is the provisioning script of the exec delivery (sprites-provider.md 3 step 1): fetch the agent over https, verify its sha256 and install it root 0755 at $BITC_INSTALL_DIR/bitc (default /opt/bitc/bin; the variable is for the unit test only). It does not run it: the host starts every agent exec itself, through the sha check (J4). Nothing job specific is in it.

func Tail

func Tail(ctx context.Context, root, job string, o TailOptions, w io.Writer) error

Tail streams agent.log, out.log and err.log of job from the given offsets, with heartbeats, until result.json exists, the agent has exited (it does so right after its EXIT marker) and everything is sent (then Done), or the agent is gone without a result (a heartbeat with alive=false, then Done).

func Teardown

func Teardown(root, job string, w io.Writer) error

Teardown kills the job's process group and the agent, each only if its recorded identity (pid and start time) still matches, then removes the job's directory. It prints `torn <job>`, or `gone` when there was no such job.

func ValidateAllowTarget

func ValidateAllowTarget(v string, testTargets bool) error

ValidateAllowTarget checks one --allow value, host:port with the IPv6 host in brackets. The host may be a DNS name or a literal address; a literal private (RFC1918), loopback, link-local, CGNAT (100.64/10), 198.18/15, unspecified, multicast or IPv6 ULA address is refused unless testTargets (--allow-test-targets) is set, as is localhost. The documentation ranges (203.0.113/24, 2001:db8::/32) are not private.

Types

type BootPayload

type BootPayload struct {
	Spec        string `json:"spec"`
	Deadline    int64  `json:"deadline"`
	DeployKey   string `json:"deploy_key"`
	Provider    string `json:"provider"`
	ResourceID  string `json:"resource_id"`
	ScopedKey   string `json:"scoped_key"`
	APIBase     string `json:"api_base"`
	ResultsRoot string `json:"results_root,omitempty"` // --boot-stdin only; default /run/bitc
	// KeepAlive asks for a Tasks API task held for the job (--boot-stdin on Sprites only).
	KeepAlive *KeepAlive  `json:"keep_alive,omitempty"`
	Code      *CodeUpload `json:"code,omitempty"`
}

BootPayload is what stage 1 hands stage 2 on fd 3 (spec 8.4 step 1). The environment path builds it from BITC_*; --boot-stdin reads it from a length-prefixed frame on stdin.

func ReadBootPayload

func ReadBootPayload(r io.Reader) (BootPayload, error)

ReadBootPayload reads one frame. EOF before the declared length, a zero length or unparsable JSON is ErrTruncated: the agent starts nothing (spec 8.4, providers delta C.5).

func (BootPayload) Frame

func (p BootPayload) Frame() ([]byte, error)

Frame is the boot payload frame: an 8-byte big-endian length, then that many bytes of JSON.

func (BootPayload) WithoutKey

func (p BootPayload) WithoutKey() (BootPayload, string)

WithoutKey returns the payload with the deploy key taken out, and the key. Stage 1 keeps the rest in the memfd that survives the re-exec and passes the key in a second one that stage 2 reads and closes before any repo code runs.

type BusyError

type BusyError struct{ Slot int }

BusyError: a slot's lease is still ahead.

func (*BusyError) Error

func (e *BusyError) Error() string

type CodeUpload

type CodeUpload struct {
	Kind   string `json:"kind"`
	Len    int64  `json:"len"`
	SHA256 string `json:"sha256"`
	Ref    string `json:"ref"`
}

CodeUpload says that exactly Len bytes of a git bundle (SHA256 is its hash, Ref the ref it carries) follow the frame on the same stream. ssh upload transport only.

type ConnResult

type ConnResult int

ConnResult is what a connect from a job's side of the LAN block did.

const (
	ConnBlocked ConnResult = iota // timed out, EPERM or unreachable: the block works
	ConnRefused                   // an RST came back: the packet got through
	ConnOpen                      // the connection completed
)

type Duration

type Duration time.Duration

Duration marshals as a Go duration string.

func (Duration) MarshalJSON

func (d Duration) MarshalJSON() ([]byte, error)

func (*Duration) UnmarshalJSON

func (d *Duration) UnmarshalJSON(b []byte) error

type Finding

type Finding struct{ Level, ID, Msg string }

Finding is one line of `check-host`: ok, warn or fail, the check id and a message.

func CheckHost

func CheckHost(e HostEnv) []Finding

CheckHost runs C.8 items 1-4 and 6-11, and 5 and 12 (and the swap and login-wrapper lines) when e.Doctor. The first failing finding is what the agent reports at job start.

func GitItems

func GitItems(e HostEnv) []Finding

GitItems are the two doctor items the controller's ssh-git rule judges for the upload transport: ssh-git-version, the text of `git --version` of the git the stage-2 code step runs (found on the agent's PATH, like every step), and ssh-git-changelog, the first line of the package changelog under e.Root that names CVE-2024-32002 (empty when there is none). The judgement itself stays controller-side. A host whose git cannot be run prints neither item.

func (Finding) String

func (f Finding) String() string

type Frame

type Frame struct {
	File  string `json:"file,omitempty"`
	Off   int64  `json:"off,omitempty"`
	Data  []byte `json:"data,omitempty"`
	HB    bool   `json:"hb,omitempty"`
	Alive *bool  `json:"alive,omitempty"`
	Done  bool   `json:"done,omitempty"`
}

Frame is one line of `__agent tail`: data of a result file at an offset (Off is omitted when 0), a heartbeat carrying whether the agent is alive, or the final done.

type HostConf

type HostConf struct {
	Slots         int
	Resolver      string
	Gateway       string
	Netns         bool
	MemoryPerSlot int64 // bytes; 0 means no memory.max
	SecretPaths   []string
	MaxBundle     int64 // bytes; 0 means the 1 GiB default
}

HostConf is /etc/bitc/host.conf (providers delta C.5): what the agent and the setup script share about one ssh host.

func ParseHostConf

func ParseHostConf(b []byte) (HostConf, error)

ParseHostConf parses key=value lines ('#' comments, blank lines ignored). Keys: slots (1-64), resolver and gateway (IPv4 literals), netns (true|false, default true; false needs slots=1), memory_per_slot (bytes, or with a KiB/MiB/GiB/TiB suffix), max_bundle (the same sizes, at most 8GiB; optional, default 1GiB), secret_paths (absolute paths separated by spaces).

func (HostConf) BundleCap

func (c HostConf) BundleCap() int64

BundleCap is the largest bundle this host takes.

type HostEnv

type HostEnv struct {
	Root   string // "" is the real root
	Conf   HostConf
	Doctor bool // also run items 5 and 12
	// Exec runs a command with stdin and returns its stdout.
	Exec func(stdin, name string, args ...string) ([]byte, error)
	// Owner returns the owning uid and gid of fi.
	Owner func(fi os.FileInfo) (uid, gid int)
	// OpenAs tries to open path read-only as uid:gid with no groups.
	OpenAs func(uid, gid uint32, path string) error
	// NetProbe runs item 5's connects and DNS query as the first slot user, in a job network
	// namespace when Conf.Netns, else in the VM's own.
	NetProbe func(targets []string) (NetProbeResult, error)
	// SeccompProbe runs item 12's calls as the first slot user under the job filter; it returns
	// "<call> <ERRNO>" lines.
	SeccompProbe func() ([]string, error)
	Environ      func() []string
	// LoginProbe runs bitc-login as the login user with SSH_AUTH_SOCK set and returns its exit
	// status (doctor only; 64 is right).
	LoginProbe func() (int, error)
	// Self is the agent binary the probes start (NewHostEnvFor sets it).
	Self string
}

HostEnv is everything check-host reads or runs, so tests can point it at a fake tree.

func NewHostEnv

func NewHostEnv(conf HostConf, doctor bool) HostEnv

NewHostEnv is check-host's view of the real host.

func NewHostEnvFor

func NewHostEnvFor(conf HostConf, doctor bool, self string) HostEnv

NewHostEnvFor is NewHostEnv with the agent binary that doctor's helper processes (the network and seccomp probes, which run as a slot user) are started from.

type JobNS

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

JobNS is a running holder.

func StartJobNS

func StartJobNS(c JobNSConf) (*JobNS, error)

StartJobNS creates the cgroup, starts the holder, joins it to the cgroup and wires the network.

func (*JobNS) Close

func (n *JobNS) Close()

Close ends the holder, which ends the namespaces and every process in them.

func (*JobNS) Wrap

func (n *JobNS) Wrap(c *exec.Cmd) error

Wrap rewrites c (a command prepared for the job: Path, Args, Env, Dir) into the nsenter and job-exec form. The job's environment travels on an inherited memfd, never in the argv or in the env of the root processes in between.

type JobNSConf

type JobNSConf struct {
	Slot     int
	Uid, Gid int
	Conf     HostConf
	ToolsDir string // a host path made visible read-only at the same path
	Self     string // the agent binary
	Probe    bool   // doctor's probe namespace: slot 0, no cgroup, no slot dirs
}

JobNSConf describes one job's namespaces.

type KeepAlive

type KeepAlive struct {
	Expire Duration `json:"expire"`
	Renew  Duration `json:"renew"`
}

KeepAlive is the lifetime of the keep-alive task and how often it is renewed.

type KeepAliveConf

type KeepAliveConf struct {
	Sock          string
	Expire, Renew time.Duration
}

KeepAliveConf is the keep-alive task (sprites-provider.md 2.3): Sock is the Tasks API unix socket, the task lives Expire past its last renewal and is renewed every Renew. The API shape (POST /v1/tasks {"expire"}, POST /v1/tasks/<id> to renew, DELETE /v1/tasks/<id>) is assumed until probe 9.17.

type Marker

type Marker struct{ Kind, Arg, Class, Line string }

Marker is one parsed marker. For MarkSetupFailed, Arg is the step name, Class "repo" or "infra" ("" when missing or unparsable: the host treats that as infra) and Line the first error line (spec 8.4 step 4).

func ParseMarker

func ParseMarker(line, nonce string) (Marker, bool)

ParseMarker: a marker counts only with this job's nonce (spec 8.4).

type NetProbeResult

type NetProbeResult struct {
	Connect map[string]ConnResult // by "host:port"
	DNSErr  error
}

NetProbeResult is what item 5 learns as a slot user in the host's job network mode.

type NotLeasedError

type NotLeasedError struct {
	Slot int
	Name string
}

NotLeasedError: the slot's owner is not the caller.

func (*NotLeasedError) Error

func (e *NotLeasedError) Error() string

type Options

type Options struct {
	Stdout      io.Writer
	ResultsRoot string
	ToolsRoot   string
	WorkRoot    string
	System      System
	HTTP        *http.Client
	Listener    net.Listener
	NoServe     bool // tests: do not block serving at the end
	Deadline    time.Time
	SelfDelete  func(ctx context.Context) error
	// StateRoot holds the provision marker (no-listener mode only): a Run whose spec matches it
	// skips its own package and tool installs. SelfSHA is the agent's sha256 (default: /proc/self/exe).
	StateRoot string
	SelfSHA   func() (string, error)
	// KeyRoot is where the deploy key lives in no-listener mode: a tmpfs System.MountTmpfs mounts there.
	KeyRoot string
	// KeepAlive, when set, holds a Tasks API task for the whole job (sprites-provider.md 2.3).
	KeepAlive *KeepAliveConf
	// HostCheck, when set, runs right after BOOT: an error is an infra setup failure named
	// host-check (the ssh host's C.8 re-check, providers delta C.5 step 6).
	HostCheck func() error
	// AfterCommand, when set, runs once the job's command has ended and before its results are
	// collected (the ssh host kills every process the job left behind).
	AfterCommand func()
	// Code, when set, makes the code step an ssh upload: the commit comes from the git bundle
	// WorkRoot/.bitc-upload/code.bundle, not from a clone (providers delta, upload transport).
	Code *CodeUpload
	// UploadLock is the host-wide upload.lock the checkout guard and the checkout run under.
	UploadLock string
	// Upload holds the statfs seam of the checkout guard (the other fields are the root side's).
	Upload UploadEnv
	// CodeTimeout limits each git command of the code step (default 10 minutes).
	CodeTimeout time.Duration
}

Options are the agent's environment.

type PlainSystem

type PlainSystem struct{}

PlainSystem runs everything as the current user (tests and the RunPod fake; only with Spec.Unprivileged, which the host sets only when its [test] table is present).

func (PlainSystem) Chown

func (PlainSystem) Chown(string, int, int) error

func (PlainSystem) Cmd

func (PlainSystem) Cmd(argv []string, _ bool, _, _ int) *exec.Cmd

func (PlainSystem) EnsureJobUser

func (PlainSystem) EnsureJobUser() (int, int, string, error)

func (PlainSystem) InstallPackages

func (PlainSystem) InstallPackages([]string) error

func (PlainSystem) MountTmpfs

func (PlainSystem) MountTmpfs(string) (func() error, error)

func (PlainSystem) SetOOMScoreAdj

func (PlainSystem) SetOOMScoreAdj() error

type ProvisionMarker

type ProvisionMarker struct {
	AgentSHA256 string   `json:"agent_sha256"`
	Packages    []string `json:"packages"`
	Tools       []Tool   `json:"tools"`
}

ProvisionMarker records what provisioning installed; Run skips its own installs when it matches.

type ProvisionOptions

type ProvisionOptions struct {
	Stdout               io.Writer
	System               System
	ToolsRoot, StateRoot string
	HTTP                 *http.Client
	SelfSHA              func() (string, error) // the running agent's sha256 (default: hash the executable)
}

ProvisionOptions are the agent's environment for provisioning.

type ProvisionSpec

type ProvisionSpec struct {
	Packages     []string `json:"packages,omitempty"`
	Tools        []Tool   `json:"tools,omitempty"`
	Unprivileged bool     `json:"unprivileged,omitempty"`
	TestRoot     string   `json:"test_root,omitempty"`
}

ProvisionSpec is the whole input of `__agent provision` (sprites-provider.md 3): the repo's packages and tools and nothing that belongs to one job. Unprivileged and TestRoot are for the host's [test] runs only, as in Spec.

func ReadProvisionSpec

func ReadProvisionSpec(r io.Reader) (ProvisionSpec, error)

ReadProvisionSpec reads one frame.

func (ProvisionSpec) Frame

func (p ProvisionSpec) Frame() ([]byte, error)

Frame is the length-prefixed JSON the host writes on stdin (the boot payload's framing).

type RealSlotSys

type RealSlotSys struct {
	Log io.Writer
}

RealSlotSys runs the teardown steps of C.5 step 8 as root on the real host.

func (RealSlotSys) ClearScheduling

func (r RealSlotSys) ClearScheduling(slot, uid int) error

ClearScheduling removes the uid's crontab and at jobs and its linger file (cron.allow and at.allow should make all three impossible; a doctor failure too).

func (RealSlotSys) DropNet

func (r RealSlotSys) DropNet(slot int) error

DropNet ends the job's namespace holder and deletes bv<slot>.

func (RealSlotSys) KillSlot

func (RealSlotSys) KillSlot(slot, uid int) error

KillSlot kills the slot's cgroup and then every process of the uid until none is left.

func (RealSlotSys) Recreate

func (RealSlotSys) Recreate(slot, uid, gid int) error

Recreate wipes the slot's job dirs and recreates them 0700 owned by the slot user, and removes the per-job files the agent leaves in the slot dir.

func (RealSlotSys) RemoveIPC

func (RealSlotSys) RemoveIPC(uid int) error

RemoveIPC removes the SysV segments, queues and semaphores the uid owns in this namespace.

func (RealSlotSys) RemoveStray

func (RealSlotSys) RemoveStray(slot, uid int) (int, error)

RemoveStray deletes every file the uid owns on any local filesystem (xdev) outside the slot dirs, and returns how many it removed.

func (RealSlotSys) UID

func (RealSlotSys) UID(slot int) (int, int, error)

UID is the uid and gid of bitc-s<slot>.

func (RealSlotSys) UnmountKey

func (RealSlotSys) UnmountKey(slot int) error

UnmountKey unmounts the slot's deploy-key tmpfs if one is mounted.

type RealSystem

type RealSystem struct{}

RealSystem runs as root in the pod.

func (RealSystem) Chown

func (RealSystem) Chown(path string, uid, gid int) error

func (RealSystem) Cmd

func (RealSystem) Cmd(argv []string, asRoot bool, uid, gid int) *exec.Cmd

func (RealSystem) EnsureJobUser

func (RealSystem) EnsureJobUser() (int, int, string, error)

func (RealSystem) InstallPackages

func (RealSystem) InstallPackages(names []string) error

func (RealSystem) MountTmpfs

func (RealSystem) MountTmpfs(dir string) (func() error, error)

func (RealSystem) SetOOMScoreAdj

func (RealSystem) SetOOMScoreAdj() error

type ResultFile

type ResultFile struct {
	Exit            int    `json:"exit"`
	OutBytes        int64  `json:"out_bytes"`
	ErrBytes        int64  `json:"err_bytes"`
	OutSHA256       string `json:"out_sha256"`
	ErrSHA256       string `json:"err_sha256"`
	ArtifactsSHA256 string `json:"artifacts_sha256"`
	MAC             string `json:"mac"`
}

ResultFile is result.json in the pod (spec 8.4 step 6).

func Sign

func Sign(k []byte, r ResultFile) ResultFile

func VerifyResult

func VerifyResult(k []byte, raw []byte) (ResultFile, error)

VerifyResult accepts result.json only if its MAC verifies under K.

type Results

type Results struct {
	Dir string
	// contains filtered or unexported fields
}

Results is /run/bitc/<job>/ on container disk (root, 0700; .part then rename).

func NewResults

func NewResults(root, job string) (*Results, error)

func (*Results) Bind

func (r *Results) Bind(k []byte, job, nonce string)

Bind gives WriteState the key, job id and attempt nonce it signs with.

func (*Results) Commit

func (r *Results) Commit(name string) error

func (*Results) Create

func (r *Results) Create(name string) (*os.File, error)

func (*Results) Finish

func (r *Results) Finish(k []byte, exit int, workdir string, artifacts []string) (ResultFile, error)

Finish commits out.log and err.log, packs artifacts and writes the MACed result.json.

func (*Results) WriteState

func (r *Results) WriteState(phase string, exit *int) error

WriteState writes state.json: {phase, exit, job, nonce, seq, ts, mac}; the MAC is under K (domain "bitc-state-v1") and seq grows with every write. An unbound Results refuses.

type Secrets

type Secrets struct {
	DeployKey string
}

Secrets are the values moved out of the env at boot.

type SelfTestSpec

type SelfTestSpec struct{ Block, Allow []string }

SelfTestSpec lists what must fail (Block) and what must work (Allow), as host:port.

func DefaultSelfTestSpec

func DefaultSelfTestSpec(conf HostConf, router, controller string, allow []string) SelfTestSpec

DefaultSelfTestSpec is the owner's list: the LAN router on 80 and 443 (router, default 192.168.1.1), the controller-facing LAN address on 22 (controller, required: the verb refuses to run without it), the VM's gateway, a ULA, a link-local, a 100.64/10 and a 198.18/15 sample must fail; github.com:22 and registry.npmjs.org:443 must work, unless allow (the --allow targets, validated by ValidateAllowTarget) names the reachable targets instead. allow never touches Block or the firewall rules: it only changes what the test expects to reach. The VM's own addresses (the namespace host end 10.203.0.1:22 and the VM's interface addresses) must fail too: with the firewall inactive the VM's own sshd answers, so they cannot pass vacuously the way a router that does not exist on this LAN can.

type Service

type Service struct {
	Name         string   `json:"name"`
	RunAs        string   `json:"run_as"`
	Argv         []string `json:"argv"`
	Ready        []string `json:"ready"`
	ReadyTimeout Duration `json:"ready_timeout"`
}

type SlotHost

type SlotHost struct {
	Root string
	Conf HostConf
	Now  func() time.Time
	Sys  SlotSys
	Log  io.Writer
}

SlotHost is the host's slot state under Root.

func (*SlotHost) Handoff

func (h *SlotHost) Handoff(slots []int, name, nonce string, read func() (job string, deadline time.Time, err error)) error

Handoff checks under the slots' mutexes that they are leased to name with nonce, calls read for the job's id and deadline, then extends the lease to that deadline (C.5 step 5).

func (*SlotHost) Owners

func (h *SlotHost) Owners() (map[int]*SlotOwner, error)

Owners returns the owner of every slot (nil for a free one).

func (*SlotHost) Prepare

func (h *SlotHost) Prepare(slots []int, name, nonce, tag string, lease time.Duration) error

Prepare leases the slots to name (all or none) and cleans each (C.5 step 3).

func (*SlotHost) ReceiveUpload

func (h *SlotHost) ReceiveUpload(env UploadEnv, slots []int, c CodeUpload, deadline time.Time, src io.Reader) (err error)

ReceiveUpload is the root side after the handoff: under the host-wide upload lock it checks the space, kills the slot, creates work/.bitc-upload and streams exactly c.Len bytes of src into code.bundle, all fd-relative. Whatever goes wrong, the upload dir is gone when it returns.

func (*SlotHost) Release

func (h *SlotHost) Release(slots []int, name string) error

Release is Teardown for the agent's own end of life: only if name still owns the slots.

func (*SlotHost) ResultsDir

func (h *SlotHost) ResultsDir() string

ResultsDir is where the agent keeps one directory per job.

func (*SlotHost) StateDir

func (h *SlotHost) StateDir() string

StateDir is /var/lib/bitc under the host's root.

func (*SlotHost) Teardown

func (h *SlotHost) Teardown(slots []int, name string) (string, error)

Teardown frees the slots owned by name; it returns "torn", or "gone" when none was (C.3.6: a stale cleanup never touches a later job that leased the same slot).

type SlotOwner

type SlotOwner struct {
	Name       string `json:"name"`
	Nonce      string `json:"nonce"`
	Tag        string `json:"tag,omitempty"`
	Job        string `json:"job,omitempty"`
	Created    int64  `json:"created"`
	LeaseUntil int64  `json:"lease_until"`
}

SlotOwner is slots/<i>/owner (providers delta C.3.1).

type SlotRunEnv

type SlotRunEnv struct {
	Host   *SlotHost
	Upload UploadEnv
	// Start launches stage 2 with the payload (without the key) and the key; nil starts the real one.
	Start func(p BootPayload, key string) error
}

SlotRunEnv is what `slot-boot --run` works against; the zero Upload and a nil Start are the real host, tests inject the rest.

type SlotSys

type SlotSys interface {
	UID(slot int) (uid, gid int, err error)
	KillSlot(slot, uid int) error
	DropNet(slot int) error
	ClearScheduling(slot, uid int) error
	RemoveIPC(uid int) error
	RemoveStray(slot, uid int) (int, error)
	UnmountKey(slot int) error
	Recreate(slot, uid, gid int) error
}

SlotSys is every destructive action of a slot's teardown steps (C.5 step 8), so the lease logic can be tested without root.

type SlotSystem

type SlotSystem struct {
	Conf     HostConf
	Slots    []int
	Self     string
	ToolsDir string
	Sys      RealSlotSys
	// contains filtered or unexported fields
}

SlotSystem is the System of an ssh host's job (providers delta C.5): the job runs as the slot's user, inside the job namespaces, and nothing is installed (packages are only checked). The namespaces start with the first command, so provisioning and the key fetch run outside.

func (*SlotSystem) Chown

func (s *SlotSystem) Chown(path string, uid, gid int) error

Chown changes ownership of the whole tree at path (links themselves, never their targets).

func (*SlotSystem) Close

func (s *SlotSystem) Close()

Close ends the namespaces.

func (*SlotSystem) Cmd

func (s *SlotSystem) Cmd(argv []string, asRoot bool, uid, gid int) *exec.Cmd

Cmd prepares argv for the job user; the namespace wrapping happens in FinishCmd, when the caller has set Dir and Env. A root command is refused: ssh hosts run no root steps.

func (*SlotSystem) EnsureJobUser

func (s *SlotSystem) EnsureJobUser() (int, int, string, error)

func (*SlotSystem) FinishCmd

func (s *SlotSystem) FinishCmd(c *exec.Cmd)

FinishCmd starts the job's namespaces on first use and rewrites c to run inside them.

func (*SlotSystem) InstallPackages

func (s *SlotSystem) InstallPackages(names []string) error

InstallPackages never installs: a package that is not there is the host's gap (infra).

func (*SlotSystem) MountTmpfs

func (s *SlotSystem) MountTmpfs(dir string) (func() error, error)

func (*SlotSystem) Reap

func (s *SlotSystem) Reap()

Reap kills what the job left behind: the cgroup and every process of the slot user.

func (*SlotSystem) SetOOMScoreAdj

func (s *SlotSystem) SetOOMScoreAdj() error

type Spec

type Spec struct {
	Job          string    `json:"job"`
	Pool         string    `json:"pool"`
	Argv         []string  `json:"argv"`
	Cwd          string    `json:"cwd"`
	Env          []string  `json:"env"`
	CloneURL     string    `json:"clone_url"`
	Ref          string    `json:"ref"`
	Sha          string    `json:"sha"`
	KnownHosts   string    `json:"known_hosts"`
	Timeout      Duration  `json:"timeout"`
	Packages     []string  `json:"packages,omitempty"`
	Tools        []Tool    `json:"tools,omitempty"`
	Setup        []Step    `json:"setup,omitempty"`
	Services     []Service `json:"services,omitempty"`
	RootSteps    bool      `json:"root_steps"`
	Artifacts    []string  `json:"artifacts,omitempty"`
	Port         int       `json:"port"`
	Bearer       string    `json:"bearer"`                 // hex B
	MacKey       string    `json:"mac_key"`                // hex K
	Nonce        string    `json:"nonce"`                  // hex M
	Unprivileged bool      `json:"unprivileged,omitempty"` // host [test] only
	TestRoot     string    `json:"test_root,omitempty"`    // the RunPod fake's per-pod dir
}

Spec is what the host sends in BITC_SPEC (base64 JSON). Secrets B and K travel here and in nothing else; the agent moves them out of its environment at boot.

func DecodeSpec

func DecodeSpec(v string) (Spec, error)

DecodeSpec parses a BITC_SPEC value.

func (Spec) Encode

func (s Spec) Encode() (string, error)

Encode is the BITC_SPEC value.

type State

type State struct {
	Phase string `json:"phase"`
	Exit  *int   `json:"exit,omitempty"`
	Job   string `json:"job"`
	Nonce string `json:"nonce"`
	Seq   int64  `json:"seq"`
	TS    int64  `json:"ts"`
	MAC   string `json:"mac"`
}

State is state.json: the phase, bound to one job and one attempt (nonce M), ordered by Seq and MACed with K like result.json (spec 8.4).

func SignState

func SignState(k []byte, s State) State

func VerifyState

func VerifyState(k []byte, raw []byte, job, nonce string) (State, error)

VerifyState accepts state.json only if its MAC verifies under K and it names this job and this attempt's nonce.

type Step

type Step struct {
	Name  string   `json:"name"`
	RunAs string   `json:"run_as"`
	Argv  []string `json:"argv"`
}

type System

type System interface {
	SetOOMScoreAdj() error
	InstallPackages(names []string) error
	EnsureJobUser() (uid, gid int, home string, err error)
	Chown(path string, uid, gid int) error
	// Cmd prepares argv to run as root (asRoot) or as the job user.
	Cmd(argv []string, asRoot bool, uid, gid int) *exec.Cmd
	// MountTmpfs mounts a fresh private tmpfs on dir (created 0700) and returns the unmount; the
	// deploy key of the exec delivery lives only there (sprites-provider.md 4, 6.4).
	MountTmpfs(dir string) (unmount func() error, err error)
}

System is every root action, so tests can run the agent as a plain user.

type TailOptions

type TailOptions struct {
	Offsets         map[string]int64
	Heartbeat, Poll time.Duration
}

TailOptions: Offsets are the host's resume points by file name (agent.log, out.log, err.log); Heartbeat is the interval of the alive frames, Poll how often the files are re-read.

type Tool

type Tool struct{ Name, URL, SHA256 string }

type UploadEnv

type UploadEnv struct {
	// Statfs reports the bytes available to the agent and the free inodes under path.
	Statfs func(path string) (avail, filesFree uint64, err error)
	// Now is the clock the overall deadline is computed from.
	Now func() time.Time
	// Idle and Overall override the 30 s read idle timeout and the 10 min overall limit.
	Idle, Overall time.Duration
	// Raced runs between mkdirat and openat of the upload dir (tests swap the dir there).
	Raced func()
	// Fchown replaces fchown(2) on the upload dir and bundle.
	Fchown func(fd, uid, gid int) error
	// OwnerUID is the uid that must own the new dir and that it is chowned to (0 on a host).
	OwnerUID int
}

UploadEnv holds the seams of the upload paths (root side and stage 2). The zero value is the real host.

Directories

Path Synopsis
Package agenttest is a fixture that drives agent.Run in-process as a plain user against a local git repository, for the agent's own tests and the conformance suite.
Package agenttest is a fixture that drives agent.Run in-process as a plain user against a local git repository, for the agent's own tests and the conformance suite.

Jump to

Keyboard shortcuts

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