Documentation
¶
Overview ¶
Package agent is the remote side of a job (spec 8.4), the same binary as the host side.
Index ¶
- Constants
- Variables
- func CanonNft(j []byte) (string, error)
- func EvalSelfTest(spec SelfTestSpec, res NetProbeResult) (lines, verdicts []string)
- func ExecVerb(args []string, stdout io.Writer, stderr io.Writer) int
- func FormatMarker(kind, nonce string, arg ...string) string
- func InstallJobSeccomp() error
- func JobSeccompProgram(goarch string) ([]unix.SockFilter, error)
- func List(root string, w io.Writer) error
- func Main(args []string, stdout io.Writer) int
- func MainIO(args []string, stdin io.Reader, stdout io.Writer) int
- func NewServer(dir string, bearer []byte) (http.Handler, error)
- func NftTemplate() string
- func PackArtifacts(workdir string, paths []string, w io.Writer) error
- func ParseSlots(s string) ([]int, bool)
- func Provision(o ProvisionOptions, ps ProvisionSpec) int
- func ReadFile(root, job, file string, off int64, w io.Writer) error
- func RenderNft(c HostConf, uids []int) (string, error)
- func Run(ctx context.Context, o Options, s Spec, sec Secrets) int
- func RunFirewallSelfTest(e HostEnv, spec SelfTestSpec, out io.Writer) int
- func RunSlot(env SlotRunEnv, slots []int, name, nonce string, stdin io.Reader, ...) int
- func SelfTestFailed(root string) bool
- func Stub(url, sum string) string
- func StubBuild(cloneURL, ref, commit, sum string) string
- func StubInstall(url, sum string) string
- func Tail(ctx context.Context, root, job string, o TailOptions, w io.Writer) error
- func Teardown(root, job string, w io.Writer) error
- func ValidateAllowTarget(v string, testTargets bool) error
- type BootPayload
- type BusyError
- type CodeUpload
- type ConnResult
- type Duration
- type Finding
- type Frame
- type HostConf
- type HostEnv
- type JobNS
- type JobNSConf
- type KeepAlive
- type KeepAliveConf
- type Marker
- type NetProbeResult
- type NotLeasedError
- type Options
- type PlainSystem
- func (PlainSystem) Chown(string, int, int) error
- func (PlainSystem) Cmd(argv []string, _ bool, _, _ int) *exec.Cmd
- func (PlainSystem) EnsureJobUser() (int, int, string, error)
- func (PlainSystem) InstallPackages([]string) error
- func (PlainSystem) MountTmpfs(string) (func() error, error)
- func (PlainSystem) SetOOMScoreAdj() error
- type ProvisionMarker
- type ProvisionOptions
- type ProvisionSpec
- type RealSlotSys
- func (r RealSlotSys) ClearScheduling(slot, uid int) error
- func (r RealSlotSys) DropNet(slot int) error
- func (RealSlotSys) KillSlot(slot, uid int) error
- func (RealSlotSys) Recreate(slot, uid, gid int) error
- func (RealSlotSys) RemoveIPC(uid int) error
- func (RealSlotSys) RemoveStray(slot, uid int) (int, error)
- func (RealSlotSys) UID(slot int) (int, int, error)
- func (RealSlotSys) UnmountKey(slot int) error
- type RealSystem
- func (RealSystem) Chown(path string, uid, gid int) error
- func (RealSystem) Cmd(argv []string, asRoot bool, uid, gid int) *exec.Cmd
- func (RealSystem) EnsureJobUser() (int, int, string, error)
- func (RealSystem) InstallPackages(names []string) error
- func (RealSystem) MountTmpfs(dir string) (func() error, error)
- func (RealSystem) SetOOMScoreAdj() error
- type ResultFile
- type Results
- func (r *Results) Bind(k []byte, job, nonce string)
- func (r *Results) Commit(name string) error
- func (r *Results) Create(name string) (*os.File, error)
- func (r *Results) Finish(k []byte, exit int, workdir string, artifacts []string) (ResultFile, error)
- func (r *Results) WriteState(phase string, exit *int) error
- type Secrets
- type SelfTestSpec
- type Service
- type SlotHost
- func (h *SlotHost) Handoff(slots []int, name, nonce string, ...) error
- func (h *SlotHost) Owners() (map[int]*SlotOwner, error)
- func (h *SlotHost) Prepare(slots []int, name, nonce, tag string, lease time.Duration) error
- func (h *SlotHost) ReceiveUpload(env UploadEnv, slots []int, c CodeUpload, deadline time.Time, src io.Reader) (err error)
- func (h *SlotHost) Release(slots []int, name string) error
- func (h *SlotHost) ResultsDir() string
- func (h *SlotHost) StateDir() string
- func (h *SlotHost) Teardown(slots []int, name string) (string, error)
- type SlotOwner
- type SlotRunEnv
- type SlotSys
- type SlotSystem
- func (s *SlotSystem) Chown(path string, uid, gid int) error
- func (s *SlotSystem) Close()
- func (s *SlotSystem) Cmd(argv []string, asRoot bool, uid, gid int) *exec.Cmd
- func (s *SlotSystem) EnsureJobUser() (int, int, string, error)
- func (s *SlotSystem) FinishCmd(c *exec.Cmd)
- func (s *SlotSystem) InstallPackages(names []string) error
- func (s *SlotSystem) MountTmpfs(dir string) (func() error, error)
- func (s *SlotSystem) Reap()
- func (s *SlotSystem) SetOOMScoreAdj() error
- type Spec
- type State
- type Step
- type System
- type TailOptions
- type Tool
- type UploadEnv
Constants ¶
const ( VerdictNoFirewall = "FIREWALL NOT ACTIVE" VerdictNoEgress = "EGRESS BROKEN" )
The verdicts the self-test prints.
const ( MarkBoot = "__BITC_BOOT__" MarkBegin = "__BITC_BEGIN__" MarkExit = "__BITC_EXIT__" MarkSetupFailed = "__BITC_SETUP_FAILED__" MarkLost = "__BITC_LOST__" )
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.
const MaxBootPayload = 8 << 20
MaxBootPayload is the largest boot payload body the agent accepts (8 MiB).
const ProvisionMarkerName = "provisioned.json"
ProvisionMarkerName is the marker file in the state root.
const SSHDSnippetText = "" /* 128-byte string literal not displayed */
SSHDSnippetText is the exact /etc/ssh/sshd_config.d/bitc.conf.
const SelfTestMarker = "/var/lib/bitc/selftest-failed"
SelfTestMarker is the file whose presence means the last self-test did not pass.
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 ¶
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") )
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
Main is `bitc __agent`: stage 1 moves secrets out of the env and re-execs; stage 2 runs.
func MainIO ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 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 ¶
SelfTestFailed reports whether the marker exists under root.
func Stub ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 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 ¶
Duration marshals as a Go duration string.
func (Duration) MarshalJSON ¶
func (*Duration) UnmarshalJSON ¶
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 ¶
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 ¶
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.
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 ¶
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).
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 ¶
NewHostEnv is check-host's view of the real host.
type JobNS ¶
type JobNS struct {
// contains filtered or unexported fields
}
JobNS is a running holder.
func StartJobNS ¶
StartJobNS creates the cgroup, starts the holder, joins it to the cgroup and wires the network.
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 KeepAliveConf ¶
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 ¶
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 ¶
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) 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 ¶
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) 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 ¶
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 SlotHost ¶
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) Prepare ¶
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 ¶
Release is Teardown for the agent's own end of life: only if name still owns the slots.
func (*SlotHost) ResultsDir ¶
ResultsDir is where the agent keeps one directory per job.
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) 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.
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).
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 ¶
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 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.
Source Files
¶
- agent.go
- boot.go
- boot_stdin.go
- exec.go
- fds.go
- host_check.go
- host_conf.go
- host_nft.go
- host_ns.go
- host_seccomp.go
- host_selftest.go
- host_slot.go
- host_sys.go
- host_system.go
- host_verbs.go
- keepalive.go
- mac.go
- markers.go
- path.go
- provision.go
- results.go
- server.go
- setup.go
- spec.go
- stub.go
- stubbuild.go
- system.go
- upload.go
- upload_stage2.go
- wire.go
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. |