engineclient

package
v0.2.6 Latest Latest
Warning

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

Go to latest
Published: Oct 14, 2026 License: MIT Imports: 25 Imported by: 0

Documentation

Overview

Package engineclient owns the long-lived cavet-engine container for one repository: lifecycle, exec plumbing, report copy-out, and path translation (cli-spec §10). It knows Docker and paths; it never parses findings.

Index

Constants

This section is empty.

Variables

View Source
var ErrNoStamp = errors.New("advisory db not stamped")

ErrNoStamp reports an artifact volume without cavet-db.json: update-db has never swapped there, so the volume holds the engine image's baked copy.

Functions

func ContainerName

func ContainerName(root string) string

ContainerName derives the stable per-repository container name.

func ContainerToHost

func ContainerToHost(root, containerPath string) string

ContainerToHost maps a /workspace-relative container path back to the host.

func HostToContainer

func HostToContainer(root, hostPath string) string

HostToContainer maps a host path under the repository root into the container mount. Paths outside the mount map to "".

func RepoRelative

func RepoRelative(containerPath, target string) string

RepoRelative strips a scan target prefix (/workspace or /scan/<n>) from a container path, yielding a repository-relative slash path. Already-relative paths pass through with any leading slash trimmed.

func ResolveDB added in v0.2.3

func ResolveDB(ctx context.Context, a Artifact) (string, error)

ResolveDB returns the manifest digest ("sha256:...") for a, trying the repos in fallback order. Anonymous auth by default: both registries serve these repos publicly.

Types

type Artifact added in v0.2.3

type Artifact struct {
	Name        string   // "vuln" | "java-db" (state/config key)
	Repos       []string // registry repos, fallback order
	Tag         string   // schema tag
	MetaVersion int      // metadata.json Version trivy expects exactly
	LayerMedia  string   // the one accepted layer media type
	DBFile      string   // trivy.db | trivy-java.db, at the layer root
	Volume      string   // one named volume per artifact (copy-on-first-mount)
	CachePath   string   // container path the volume binds at
}

Artifact describes one advisory database the engine consumes: where to fetch it (repos in fallback order, mirror first like trivy itself), the shape to insist on, and where it lives in the engine.

func Artifacts added in v0.2.3

func Artifacts(variant string) []Artifact

Artifacts returns the advisory databases for an engine variant in update order: the vuln DB always, the java DB only in full (the core image has no java-db).

type Client

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

func New

func New(image, pinnedDigest, root, variant string) *Client

New builds a client. pinnedDigest may be empty in development (local image tag, no drift enforcement); production always pins (spec §3.4). variant ("core"|"full") selects the advisory volume binds (Artifacts).

func (*Client) BuildImage added in v0.2.0

func (c *Client) BuildImage(ctx context.Context, dockerfilePath, contextDir, tag, target string, output io.Writer) error

BuildImage builds tag from the dockerfile at dockerfilePath (absolute or contextDir-relative) with contextDir as the build context by execing `docker buildx build --load`. The daemon API's /build endpoint with BuildKit wedges indefinitely on large builds on Docker Desktop for Windows (verified by a standalone probe with zero cavet code; the CLI path completes the same build, ~9 minutes cold cache), so the CLI is the one deliberate exception to this package's SDK-only daemon access. target names a build stage for multi-stage Dockerfiles; empty means the Dockerfile default (the last stage). output receives the child's combined stdout/stderr live (nil means discard); buildx runs with --progress=plain so that stream is parseable and timestamped. The context is sent by buildx per standard Docker semantics: .dockerignore is the exclusion mechanism. On failure the error carries only the tail of the output.

func (*Client) CopyOut

func (c *Client) CopyOut(ctx context.Context, containerPath string) ([]byte, error)

CopyOut retrieves a single file's bytes from the container. Reports are megabytes at worst (spike §5); read into memory and discard (cli-spec §10.3).

func (*Client) CopyToContainer added in v0.2.0

func (c *Client) CopyToContainer(ctx context.Context, srcPath, dstPath string) error

CopyToContainer copies one host file (srcPath) into the engine container at dstPath (an absolute container path such as /scan/image-0.tar), mirroring CopyOut. The container-side parent directory must already exist: the daemon extracts a tar into the destination's directory, so the file travels as a tar entry named after dstPath's base (docker cp wire convention).

func (*Client) EnsureRunning

func (c *Client) EnsureRunning(ctx context.Context) error

EnsureRunning guarantees a healthy container: create if absent, restart if stopped (transparently, spec §7.1), verify the digest first. Digest drift is a hard stop, never silent scanning on a stale engine (cli-spec §10.2).

func (*Client) Exec

func (c *Client) Exec(ctx context.Context, cmd []string) (ExecResult, error)

Exec runs cmd in the container with stdout/stderr demultiplexed. Workdir is /workspace. Exit codes are data (gitleaks exits 1 on leaks — cli-spec §7); transport errors are the only error returns.

func (*Client) ExecRoot added in v0.2.3

func (c *Client) ExecRoot(ctx context.Context, cmd []string) (ExecResult, error)

ExecRoot runs cmd as root (uid/gid 0) regardless of the container's own user: Windows-host containers already run as root, Linux-host containers run uid:gid and need the per-exec override for the advisory swap to rename files in the volumes (db.go). Workdir and exit-code semantics match Exec.

func (*Client) ImageDigest

func (c *Client) ImageDigest(ctx context.Context, ref string) (string, error)

ImageDigest returns the image's registry digest when it has one (locally built images have none) — the pin `cavet init` records.

func (*Client) ImagePresent

func (c *Client) ImagePresent(ctx context.Context) error

ImagePresent reports whether the engine image exists locally.

func (*Client) Name

func (c *Client) Name() string

func (*Client) NextScanDir

func (c *Client) NextScanDir() string

NextScanDir allocates a fresh staging directory inside the container. The name mixes the clock (unique across processes — the container outlives CLI invocations, so a bare counter would collide across commands) with a local counter (Windows clock granularity can repeat adjacent nanoseconds — measured). Dirs die with the container (cli-spec §6).

func (*Client) Ping

func (c *Client) Ping(ctx context.Context) error

Ping reports whether a Docker daemon is reachable.

func (*Client) Prune

func (c *Client) Prune(ctx context.Context, all bool) ([]PruneEntry, error)

Prune classifies every cavet-* container and force-removes the ones the classification marks for removal. HostConfig.Binds (not the summary's Mounts) is the source of truth: Docker Desktop rewrites mount sources to in-VM paths, while Binds keeps the host path as created. Containers outside the cavet- prefix are invisible to prune, and the calling repository's own container is never touched.

func (*Client) Pull

func (c *Client) Pull(ctx context.Context, ref string) (io.ReadCloser, error)

Pull streams the image from its registry. Progress reporting is the caller's job; drain the reader to completion or the pull aborts.

func (*Client) ReadDBInfo added in v0.2.3

func (c *Client) ReadDBInfo(ctx context.Context) (DBInfo, error)

ReadDBInfo reads the live vuln DB identity: the volume stamp when update-db has run there, else the baked metadata.json (CopyOut, like ReadDBStamp). Successful reads are cached on the client, so the scan path reads the container once per run whatever it feeds (findings join, header line); a failed read is not cached and surfaces to the caller.

func (*Client) ReadDBStamp added in v0.2.3

func (c *Client) ReadDBStamp(ctx context.Context, a Artifact) (DBStamp, error)

ReadDBStamp returns the stamp from a's volume. A missing file maps to ErrNoStamp (the baked era); the caller renders it.

func (*Client) Remove

func (c *Client) Remove(ctx context.Context) error

Remove force-removes the container; the container holds no unique state (cli-spec §5 engine stop).

func (*Client) RemoveImage added in v0.2.0

func (c *Client) RemoveImage(ctx context.Context, ref string) error

RemoveImage force-removes ref; a missing image is not an error so scan teardown stays idempotent.

func (*Client) SaveImage added in v0.2.0

func (c *Client) SaveImage(ctx context.Context, ref, destPath string) error

SaveImage streams ref from the daemon to destPath as a tar, creating parent directories (mirrors how report paths are laid out).

func (*Client) Status

func (c *Client) Status(ctx context.Context) (running, healthy bool, imageID string, err error)

Status reports container state without side effects. healthy means the healthcheck currently passes (warm).

func (*Client) UpdateDB added in v0.2.3

func (c *Client) UpdateDB(ctx context.Context, a Artifact, digest string) (Swap, error)

UpdateDB runs the staged swap: fetch and verify into a host temp dir, copy the files into <CachePath>/db.next inside the volume, then one root exec renames trivy.db, then metadata.json, then the stamp into place and removes the staging dir. Renames stay inside the volume (cross-device rename fails EXDEV); db before metadata keeps trivy's consistency check sane mid-swap (W0 spike: verified clean under concurrent scans). Nothing is staged until fetch+verify pass; the swap is verified afterwards.

func (*Client) VolumeExists added in v0.2.3

func (c *Client) VolumeExists(ctx context.Context, volume string) (bool, error)

VolumeExists reports whether a named volume exists on the host. update-db uses it as the java-db trigger: a host that never ran a full-variant container has no java-db volume and never fetches the java DB.

type DBInfo added in v0.2.3

type DBInfo struct {
	Digest    string
	UpdatedAt time.Time // advisories date (metadata.json)
	Source    string    // "managed" | "baked"
}

DBInfo is the vuln DB's live identity for scan-time surfaces (PR B): what the scan's findings were matched against. Digest is empty in the baked era (the engine image's copy carries no manifest digest record); Source is "managed" after update-db, "baked" before.

type DBStamp added in v0.2.3

type DBStamp struct {
	Artifact  string    `json:"artifact"`
	Digest    string    `json:"digest"`
	UpdatedAt time.Time `json:"updatedAt"`
	SwappedAt time.Time `json:"swappedAt"`
}

DBStamp is cavet-db.json inside an artifact volume: what is live and how it got there. Written by UpdateDB, read back by ReadDBStamp.

type ExecResult

type ExecResult struct {
	Stdout []byte
	Stderr []byte
	Code   int
}

ExecResult carries a container command's captured streams and exit code.

type PruneAction

type PruneAction string

PruneAction is prune's decision for one cavet-* container, phrased for the report line the CLI prints.

const (
	PruneRemovedOrphan PruneAction = "removed as orphan"           // bind source no longer exists on the host
	PruneRemovedAll    PruneAction = "removed (--all)"             // --all, not the calling repository's
	PruneKept          PruneAction = "kept, root exists"           // nothing to do
	PruneKeptSelf      PruneAction = "kept, current repository"    // never touched, --all included
	PruneSkippedNoBind PruneAction = "skipped, no /workspace bind" // conservative on ambiguity
	PruneSkippedStat   PruneAction = "skipped, root stat failed"   // ambiguity is never a removal
)

type PruneEntry

type PruneEntry struct {
	Name   string
	Root   string // host path bound at /workspace; "" when there is none
	Action PruneAction
}

PruneEntry is one cavet-* container and what prune decided about it.

type Swap added in v0.2.3

type Swap struct {
	Digest    string    // resolved manifest digest (sha256:...)
	UpdatedAt time.Time // advisories date from metadata.json
	SwappedAt time.Time
	Bytes     int64 // compressed layer size
}

Swap records one successful UpdateDB for the caller's bookkeeping.

Jump to

Keyboard shortcuts

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