engine

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Jun 27, 2026 License: MIT Imports: 18 Imported by: 0

Documentation

Overview

Package engine orchestrates a compose project against the container runtime: creating networks and volumes, then starting/stopping service containers in dependency order.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func DependencyOrder

func DependencyOrder(p *types.Project) ([]string, error)

DependencyOrder returns service names sorted so that every service appears after all services it depends_on. Independent services are ordered alphabetically for deterministic behavior. It returns an error if the depends_on graph contains a cycle.

func ParsePort

func ParsePort(arg string) (int, string, error)

ParsePort splits a "PORT[/PROTO]" argument into its numeric port and protocol.

Types

type BuildOptions

type BuildOptions struct {
	BuildArgs        []string // extra KEY=VALUE build args (override compose)
	NoCache          bool     // force --no-cache
	Pull             bool     // force --pull
	Quiet            bool     // -q/--quiet
	Memory           string   // -m/--memory
	WithDependencies bool     // also build the named services' dependencies
	Push             bool     // push each built image after building
}

BuildOptions overrides build settings from the CLI (`docker compose build`).

type ContainerStatus

type ContainerStatus struct {
	Name    string
	Service string
	Status  string
	Image   string
	Ports   string
}

ContainerStatus is the runtime state of one expected service container.

type CreateOptions

type CreateOptions struct {
	Scale         map[string]int
	NoBuild       bool   // skip building images for services with a build section
	Pull          string // "always" pulls images before creating
	RemoveOrphans bool   // remove containers for services not in the compose file
	ForceRecreate bool   // recreate existing containers even if unchanged
	NoRecreate    bool   // leave existing containers in place even if changed
	QuietPull     bool   // suppress pull progress
}

CreateOptions controls Create.

type DownOptions

type DownOptions struct {
	// RemoveVolumes also deletes the project's named volumes.
	RemoveVolumes bool
	// RemoveOrphans removes containers for services not in the compose file.
	RemoveOrphans bool
	// Timeout overrides each container's shutdown grace period (seconds).
	Timeout *int
	// RemoveImages removes service images: "all" (every image) or "local"
	// (only images with no custom name, i.e. locally built). Empty = keep.
	RemoveImages string
}

DownOptions controls the behavior of Down.

type Engine

type Engine struct {
	Runner runner.Runner
	// Out receives human-readable progress messages.
	Out io.Writer
	// Now returns the current time; injectable for tests. Defaults to time.Now.
	Now func() time.Time
	// Sleep pauses for d or until ctx is cancelled; injectable for tests.
	Sleep func(ctx context.Context, d time.Duration) error
	// StateDir is where fruitbox writes generated per-container files
	// (e.g. /etc/hosts, /etc/hostname). Defaults to <tmp>/fruitbox.
	StateDir string
}

Engine orchestrates a compose project against the container runtime.

func New

func New(r runner.Runner, out io.Writer) *Engine

New returns an Engine using the given runner and progress writer.

func (*Engine) Attach

func (e *Engine) Attach(ctx context.Context, p *types.Project, service string, index int) error

Attach attaches to a running service container's standard streams.

func (*Engine) Build

func (e *Engine) Build(ctx context.Context, p *types.Project, names []string, opts BuildOptions) error

Build builds images for the named services that declare a build section (or all such services when names is empty).

func (*Engine) Copy

func (e *Engine) Copy(ctx context.Context, p *types.Project, src, dest string, index int, all bool) error

Copy copies files between the host and a service container. Either src or dest may be of the form "SERVICE:PATH"; that side is resolved to the service's container name before delegating to `container cp`. When all is set, the copy is applied to every replica of the referenced service.

func (*Engine) Create

func (e *Engine) Create(ctx context.Context, p *types.Project, opts CreateOptions) error

Create creates the project's networks, volumes and service containers without starting them (compose `create`).

func (*Engine) Down

func (e *Engine) Down(ctx context.Context, p *types.Project, opts DownOptions) error

Down stops and removes the project's service containers in reverse dependency order, then removes its networks (and optionally volumes/images).

func (*Engine) Events

func (e *Engine) Events(ctx context.Context, p *types.Project, maxPolls int, jsonOut bool) error

Events streams synthesized container lifecycle events for the project until the context is cancelled. maxPolls bounds the number of polls (0 = infinite); it exists primarily so tests terminate deterministically. When jsonOut is set, each event is emitted as a JSON object (matching `docker compose events --json`) instead of a text line.

func (*Engine) Exec

func (e *Engine) Exec(ctx context.Context, p *types.Project, service string, command []string, opts ExecOptions) error

Exec runs a command in a replica of a service's container, interactively wired to the process stdio (or detached when opts.Detach is set).

func (*Engine) Export

func (e *Engine) Export(ctx context.Context, p *types.Project, service, output string, index int) error

Export writes a service container's filesystem to a tar archive via `container export`.

func (*Engine) Images

func (e *Engine) Images(p *types.Project) []ImageInfo

Images returns the image used by each service, sorted by service name.

func (*Engine) Kill

func (e *Engine) Kill(ctx context.Context, p *types.Project, names []string, signal string, removeOrphans bool) error

Kill sends a signal to the named services' containers (default SIGKILL), optionally also removing orphan containers afterward.

func (*Engine) ListProjects

func (e *Engine) ListProjects(ctx context.Context) ([]ProjectSummary, error)

ListProjects scans all containers and groups them by compose project label, returning one summary per project, sorted by name.

func (*Engine) LockProject

func (e *Engine) LockProject(project string) (func(), error)

LockProject acquires an exclusive, advisory, cross-process lock for a project so that two mutating fruitbox commands (e.g. two `up`s, or `up` and `down`) cannot race into half-created/half-removed state. It returns a release function, or an error if another process already holds the lock.

The lock must be acquired ONCE per command at the CLI boundary — never per engine method — because the orchestrator calls other engine methods internally and a second flock from the same process (different fd) would deadlock.

Crash recovery is automatic: flock is released by the kernel when the holding process dies (its fd is closed), so a crashed command never leaves a held lock. The lock FILE is deliberately NOT unlinked on release — unlinking it would reintroduce a race where a waiter holds the lock on the now-removed inode while a new process creates a fresh file and locks it independently (two holders). A lingering zero-byte lock file is harmless.

func (*Engine) Logs

func (e *Engine) Logs(ctx context.Context, p *types.Project, services []string, opts LogOptions) error

Logs streams logs for the named services (or all services when none are given), multiplexing every container's output concurrently with a colored, per-service prefix (like docker compose).

func (*Engine) Orphans

func (e *Engine) Orphans(ctx context.Context, p *types.Project) []ContainerStatus

Orphans returns the project's orphan containers as status records, for `ps --orphans`.

func (*Engine) Pause

func (e *Engine) Pause(ctx context.Context, p *types.Project, names []string) error

Pause suspends the named services' containers by sending SIGSTOP, since the runtime exposes no freezer; Unpause resumes them with SIGCONT.

func (*Engine) Port

func (e *Engine) Port(p *types.Project, service string, private int, protocol string) (string, error)

Port resolves the published host port for a service's container port. It returns an error if no matching published port exists.

func (*Engine) Ps

func (e *Engine) Ps(ctx context.Context, p *types.Project) ([]ContainerStatus, error)

Ps returns the status of every container the project expects, in dependency order, enriched with the live image/ports/status from the runtime. Containers that have not been created report status "not created" and their configured image.

func (*Engine) Pull

func (e *Engine) Pull(ctx context.Context, p *types.Project, names []string, opts PullOptions) error

Pull pulls the images referenced by the named services (or all services).

func (*Engine) Push

func (e *Engine) Push(ctx context.Context, p *types.Project, names []string, opts PushOptions) error

Push pushes the images of the named services (or all) to their registries.

func (*Engine) Restart

func (e *Engine) Restart(ctx context.Context, p *types.Project, names []string, timeout *int) error

Restart restarts containers for the named services (stop then start). A non-nil timeout overrides the stop grace period.

func (*Engine) Rm

func (e *Engine) Rm(ctx context.Context, p *types.Project, names []string, opts RmOptions) error

Rm removes stopped service containers (compose `rm`).

func (*Engine) RunOneOff

func (e *Engine) RunOneOff(ctx context.Context, p *types.Project, service string, opts RunOneOffOptions) error

RunOneOff starts dependencies (unless NoDeps) and then runs a single one-off container for the named service, mirroring `docker compose run`.

func (*Engine) Scale

func (e *Engine) Scale(ctx context.Context, p *types.Project, scale map[string]int) error

Scale brings the given services to the requested replica counts by starting missing replicas and removing surplus ones.

func (*Engine) Start

func (e *Engine) Start(ctx context.Context, p *types.Project, names []string, opts StartOptions) error

Start starts existing (stopped) containers for the named services.

func (*Engine) Stats

func (e *Engine) Stats(ctx context.Context, p *types.Project, opts StatsOptions) error

Stats streams resource usage for the project's containers by delegating to `container stats`.

func (*Engine) Stop

func (e *Engine) Stop(ctx context.Context, p *types.Project, names []string, timeout *int) error

Stop stops running containers for the named services without removing them, honoring each service's stop_signal and stop_grace_period. A non-nil timeout overrides the grace period (--time).

func (*Engine) Supervise

func (e *Engine) Supervise(ctx context.Context, p *types.Project, names []string, opts SuperviseOptions) error

Supervise watches the containers of the named services and restarts them according to their policy when they exit. It returns when every watched container has reached a terminal state, the context is cancelled, or (for --abort-on-*) the first qualifying exit, after stopping the rest. It is intended for a foreground `up`.

func (*Engine) Top

func (e *Engine) Top(ctx context.Context, p *types.Project, names []string, psArgs []string) error

Top lists the running processes of each of the project's containers by running `ps` inside them via `container exec`. Apple's runtime has no native `top`, so fruitbox executes ps in-container, matching `docker compose top`.

func (*Engine) Unpause

func (e *Engine) Unpause(ctx context.Context, p *types.Project, names []string) error

Unpause resumes paused containers by sending SIGCONT.

func (*Engine) Up

func (e *Engine) Up(ctx context.Context, p *types.Project, opts UpOptions) error

Up creates the project's networks and volumes, then starts every service container in dependency order. Services with a build section are built first.

func (*Engine) VolumeNames

func (e *Engine) VolumeNames(p *types.Project) []string

VolumeNames returns the resolved runtime names of the project's named volumes, sorted (for `compose volumes`).

func (*Engine) Wait

func (e *Engine) Wait(ctx context.Context, p *types.Project, names []string) (int, error)

Wait blocks until the named services' containers have stopped, returning the exit code of the last container to finish.

func (*Engine) Watch

func (e *Engine) Watch(ctx context.Context, p *types.Project, maxPolls int, opts WatchOptions) error

Watch implements `compose watch`: it (by default) brings the project up, then monitors each service's develop.watch triggers and applies sync/restart/ rebuild actions on change. maxPolls bounds the number of polling rounds (0 = run until cancelled); it exists so tests terminate deterministically.

type Event

type Event struct {
	Name   string
	Action string // create, start, die, destroy
}

Event is a synthesized container lifecycle event.

type ExecOptions

type ExecOptions struct {
	Interactive bool
	TTY         bool
	Detach      bool
	Index       int
	User        string
	WorkingDir  string
	Env         []string
}

ExecOptions controls the behavior of Exec.

type ExitError

type ExitError struct{ Code int }

ExitError carries a container exit code so a foreground `up` can propagate it as the process exit status (used by --exit-code-from / --abort-on-*).

func (ExitError) Error

func (e ExitError) Error() string

type ImageInfo

type ImageInfo struct {
	Service string
	Image   string
}

ImageInfo describes the image a service uses.

type LogOptions

type LogOptions struct {
	// Follow streams new output (--follow).
	Follow bool
	// Tail is the number of lines from the end ("all" or "" for everything).
	Tail string
	// Index selects a single replica (1-based); 0 means all replicas.
	Index int
	// NoPrefix omits the per-service line prefix (--no-log-prefix).
	NoPrefix bool
	// NoColor disables ANSI color in the prefix (--no-color).
	NoColor bool
	// Timestamps prepends an RFC3339 timestamp to each line (--timestamps).
	Timestamps bool
}

LogOptions controls log retrieval.

type ProjectSummary

type ProjectSummary struct {
	Name           string
	ContainerCount int
	RunningCount   int
}

ProjectSummary aggregates the containers of one compose project found in the runtime.

type PullOptions

type PullOptions struct {
	Quiet           bool   // suppress progress logs
	IncludeDeps     bool   // also pull transitive dependencies of the named services
	IgnoreFailures  bool   // continue when an individual pull fails
	IgnoreBuildable bool   // skip services that have a build section
	Policy          string // pull policy: "never" skips; "always"/"missing"/"" pull
}

PullOptions controls Pull.

type PushOptions

type PushOptions struct {
	Quiet          bool // suppress progress logs
	IncludeDeps    bool // also push dependencies of the named services
	IgnoreFailures bool // continue when an individual push fails
}

PushOptions controls Push.

type RmOptions

type RmOptions struct {
	Force   bool // also remove running containers
	Stop    bool // stop containers before removing
	Volumes bool // also remove anonymous volumes attached to the containers
}

RmOptions controls Rm.

type RunOneOffOptions

type RunOneOffOptions struct {
	// Command overrides the service command for this run.
	Command []string
	// Detach runs the one-off container in the background.
	Detach bool
	// Remove deletes the container after it exits (default true for run).
	Remove bool
	// NoDeps skips starting the service's dependencies.
	NoDeps bool
	// Name overrides the generated one-off container name.
	Name string
	// Interactive/TTY wire the container to the terminal.
	Interactive bool
	TTY         bool
	// Env are additional environment variables (KEY=VALUE) for this run.
	Env []string

	// Override flags mirroring `docker compose run`.
	Entrypoint    string   // --entrypoint
	EntrypointSet bool     // whether --entrypoint was provided (allows clearing)
	User          string   // --user
	WorkDir       string   // --workdir
	Labels        []string // --label KEY=VALUE
	Volumes       []string // --volume specs
	Publish       []string // --publish specs
	CapAdd        []string // --cap-add
	CapDrop       []string // --cap-drop
	ServicePorts  bool     // --service-ports: map the service's declared ports
	Build         bool     // --build: build image before running
	RemoveOrphans bool     // --remove-orphans
	Pull          string   // --pull: "always" pulls the image before running
	EnvFromFile   []string // --env-from-file: files of KEY=VALUE env entries
	Quiet         bool     // --quiet: suppress progress/warnings
	QuietBuild    bool     // --quiet-build
	QuietPull     bool     // --quiet-pull
}

RunOneOffOptions controls a one-off `run` invocation.

type StartOptions

type StartOptions struct {
	Wait        bool // block until healthcheck'd services are healthy
	WaitTimeout int  // bound for Wait (seconds); 0 = unbounded
}

StartOptions controls Start.

type StatsOptions

type StatsOptions struct {
	NoStream bool   // --no-stream: print one snapshot and exit
	Format   string // --format: table|json|yaml
}

StatsOptions controls Stats.

type SuperviseOptions

type SuperviseOptions struct {
	// AbortOnExit stops all containers when any one exits.
	AbortOnExit bool
	// AbortOnFailure stops all containers when any one exits non-zero.
	AbortOnFailure bool
	// ExitCodeFrom returns the exit code of this service's container (and
	// implies AbortOnExit).
	ExitCodeFrom string
}

SuperviseOptions controls foreground supervision (`up` without -d).

type UpOptions

type UpOptions struct {
	// Detach starts service containers in the background.
	Detach bool
	// NoBuild skips building images for services with a build section.
	NoBuild bool
	// Scale overrides the replica count per service name (compose --scale).
	Scale map[string]int
	// RemoveOrphans removes containers for services not in the compose file.
	RemoveOrphans bool
	// NoStart creates containers (and resources) without starting them.
	NoStart bool
	// Pull is the pull policy: "always" pulls every image before starting.
	Pull string
	// Wait blocks until started services are healthy/running before returning.
	Wait bool
	// WaitTimeout bounds Wait (seconds); 0 means no bound.
	WaitTimeout int
	// ForceRecreate recreates containers even if their config is unchanged.
	ForceRecreate bool
	// NoRecreate leaves existing containers in place even if their config changed.
	NoRecreate bool
	// Services restricts the up to these services (empty = all). Their
	// dependencies are included unless NoDeps is set.
	Services []string
	// NoDeps starts only the selected services, not their dependencies.
	NoDeps bool
	// Timeout overrides the stop grace period (seconds) when recreating.
	Timeout *int
	// QuietBuild / QuietPull suppress build / pull progress.
	QuietBuild bool
	QuietPull  bool
	// AbortOnExit stops all containers (foreground) when any one exits.
	AbortOnExit bool
	// AbortOnFailure stops all containers (foreground) when any one fails.
	AbortOnFailure bool
	// ExitCodeFrom returns this service's exit code from a foreground up.
	ExitCodeFrom string
	// AlwaysRecreateDeps force-recreates dependency containers too.
	AlwaysRecreateDeps bool
	// Attach restricts foreground log streaming to these services (empty = all
	// started). NoAttach excludes services. AttachDependencies also streams the
	// logs of dependency services.
	Attach             []string
	NoAttach           []string
	AttachDependencies bool
	// Foreground log formatting (mirrors `logs`).
	NoLogPrefix   bool
	NoColor       bool
	LogTimestamps bool
}

UpOptions controls the behavior of Up.

type WatchOptions

type WatchOptions struct {
	NoUp  bool // don't build & start services before watching
	Quiet bool // suppress build/sync progress logs
	Prune bool // remove synced files from the container when deleted from source
}

WatchOptions controls Watch.

Jump to

Keyboard shortcuts

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