applecontainer

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Jun 17, 2026 License: MIT Imports: 23 Imported by: 0

README

🍎 applecontainer-go

Go Reference Go Report Card

applecontainer-go is a lightweight, testcontainers-go-style Go library designed to spin up Apple Container (container CLI) Linux containers as test dependencies on macOS.

Unlike Docker-based libraries, applecontainer-go integrates directly with the native Apple Silicon container virtualization engine, letting you boot up test dependencies like databases, web servers, and queues with near-zero overhead.


Table of Contents


Features

  • 🏎️ Fast Boot times: Harness macOS native container technology for minimal latency.
  • Familiar API: Modelled closely after testcontainers-go to ensure a minimal learning curve.
  • 🌐 Double Networking Modes: Choose between Bridged Direct IP and Host-Port mapping models.
  • ⏱️ Robust Wait Strategies: Built-in support for HTTP, listening ports, logs, SQL databases, executions, and file existence.
  • 🏗️ Build from Context: Support for building images on the fly via Containerfile / Dockerfile.
  • 🪝 Lifecycle Hooks: Attach custom execution callbacks to pre/post container build, creation, start, and termination phases.

Prerequisites

  • Host OS: macOS 26+ (Apple native container orchestration environment)
  • Architecture: Apple Silicon (M1, M2, M3, M4, or newer)
  • Dependency: The Apple native container CLI must be installed and active (e.g. /opt/homebrew/bin/container or /usr/local/bin/container).

Install

go get -u github.com/lynicis/applecontainer-go

Quickstart

Spin up an Nginx container with an HTTP wait strategy and get the endpoint:

package main

import (
	"context"
	"fmt"
	"net/http"
	"time"

	"github.com/lynicis/applecontainer-go"
	"github.com/lynicis/applecontainer-go/wait"
)

func main() {
	ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
	defer cancel()

	// Spin up Nginx in direct container IP mode
	c, err := applecontainer.Run(ctx, "nginx:alpine",
		applecontainer.WithExposedPorts("80"),
		applecontainer.WithWaitStrategy(wait.ForHTTP("/").WithPort("80")),
	)
	if err != nil {
		panic(err)
	}
	defer c.Terminate(ctx)

	// Fetch endpoint (resolves to direct container IP:80 by default)
	endpoint, err := c.Endpoint(ctx, "80")
	if err != nil {
		panic(err)
	}

	resp, err := http.Get("http://" + endpoint)
	if err != nil {
		panic(err)
	}
	defer resp.Body.Close()

	fmt.Printf("Nginx status: %s\n", resp.Status)
}

Networking Models

applecontainer-go supports two distinct networking architectures:

1. Direct IP Mode (Default)

In this mode, container virtual interfaces map directly onto the macOS host bridge.

  • You can communicate directly with the container's private bridge IP.
  • c.Host(ctx) resolves to the container's IP address.
  • c.Endpoint(ctx, port) matches the container's IP and port directly.
  • Limitation: No host ports are consumed, making it ideal for running many concurrent integration tests.
2. Host-Port Mapping Mode (Opt-in)

To bind container ports to ephemeral host ports on the localhost interface, enable this option using WithHostPortMapping(true).

  • Ephemeral host ports are automatically allocated and bound to the host network interface.
  • c.Host(ctx) resolves to "localhost".
  • c.Endpoint(ctx, port) resolves to localhost:<random_host_port>.
c, err := applecontainer.Run(ctx, "nginx:alpine",
	applecontainer.WithExposedPorts("80"),
	applecontainer.WithHostPortMapping(true),
	applecontainer.WithWaitStrategy(wait.ForHTTP("/").WithPort("80")),
)

Wait Strategies

A container isn't always fully initialized as soon as it starts. Wait strategies allow you to block execution until the dependency is ready.

Strategy Constructor Description
Listening Port wait.ForListeningPort(port) Checks if a TCP/UDP port is open and listening.
HTTP wait.ForHTTP(path) Performs HTTP requests and validates status codes/response body matchers.
Log Stream wait.ForLog(pattern) Scans stdout/stderr logs for a substring or regexp pattern.
Exec Command wait.ForExec(cmd) Executes a command inside the container repeatedly until exit code or outputs match.
SQL Database wait.ForSQL(port, driver, dburl) Verifies database availability using standard Go database/sql driver and query.
File Check wait.ForFile(path) Verifies file existence inside the container filesystem.
Container Health wait.ForHealth() Waits for the container state to be "running" with exit code 0.
All (Composite) wait.ForAll(strats...) Runs all provided wait strategies sequentially.
Any (Composite) wait.ForAny(strats...) Runs all provided wait strategies concurrently, succeeding when any one does.
Wait Strategy Examples
// Wait for Postgres using SQL driver pgx
dburl := func(host string, port int) string {
	return fmt.Sprintf("postgres://postgres:postgres@%s:%d/postgres?sslmode=disable", host, port)
}
waitPostgres := wait.ForSQL("5432", "pgx", dburl).WithQuery("SELECT 1")

// Wait for a application server healthcheck endpoint
waitApp := wait.ForHTTP("/health").
	WithPort("8080").
	WithStatusCodeMatcher(func(code int) bool { return code == http.StatusOK })

// Wait for a log occurrence 3 times
waitLogs := wait.ForLog("server started").WithOccurrence(3)

Customizer Options

Customize the container configuration using functional options:

Customizer Option Type / Arguments Purpose
WithImage(img) string Defines the container image.
WithExposedPorts(ports...) ...string Ports exposed from the container (e.g. "80/tcp").
WithHostPortMapping(bool) bool Enables mapping exposed ports to host localhost ephemeral ports.
WithEnv(map) map[string]string Key-value environment variables.
WithCmd(cmd...) ...string Command parameters passed to the container.
WithEntrypoint(entry...) ...string Container entrypoint command.
WithNetworks(names...) ...string Custom network names to attach the container to.
WithVolumes(vols...) ...VolumeMount Directory volumes to mount.
WithTmpfs(map) map[string]string Mount tmpfs directories.
WithCPUs(cpus) float64 CPU allocation limits.
WithMemory(bytes) int64 Memory allocation limits.
WithWaitStrategy(strat) wait.Strategy Configures the default wait strategy with a default 60s timeout.
WithContainerfile(cf) FromContainerfile Build image from a context directory using Containerfile.
WithLifecycleHooks(hooks) ContainerLifecycleHooks Hooks to inject custom callbacks into lifecycle states.
WithLogConsumers(c...) ...LogConsumer Register consumers to receive stream container stdout/stderr.

Lifecycle Hooks

You can hook into different phases of the container's lifecycle:

hooks := applecontainer.ContainerLifecycleHooks{
	PreStarts: []applecontainer.ContainerHook{
		func(ctx context.Context, c applecontainer.Container) error {
			fmt.Println("Container is about to start!")
			return nil
		},
	},
	PostReadies: []applecontainer.ContainerHook{
		func(ctx context.Context, c applecontainer.Container) error {
			fmt.Println("Container is ready and wait strategies passed!")
			return nil
		},
	},
}

c, err := applecontainer.Run(ctx, "nginx:alpine",
	applecontainer.WithLifecycleHooks(hooks),
)

Networks and Volumes

Networks

Create and attach containers to custom networks to facilitate inter-container communication:

nw, err := applecontainer.NewNetwork(ctx,
	applecontainer.WithNetworkLabels(map[string]string{"type": "integration"}),
)
defer nw.Remove(ctx)

c1, err := applecontainer.Run(ctx, "nginx:alpine",
	applecontainer.WithNetwork([]string{"web-server"}, nw),
)
Volumes

Easily create volumes and mount them to containers to persist data across container lifecycles:

vol, err := applecontainer.NewVolume(ctx,
	applecontainer.WithVolumeSize("10G"),
)
defer vol.Remove(ctx)

c, err := applecontainer.Run(ctx, "postgres:alpine",
	applecontainer.WithVolumes(applecontainer.VolumeMount{
		Source: vol.Name(),
		Target: "/var/lib/postgresql/data",
	}),
)

Testing and Verification

Unit Tests

Unit tests use mocking and system CLI fakes and do not require the actual Apple container runtime environment.

go test ./...
Integration Tests

Integration tests run real container scenarios and require macOS with a running container CLI daemon.

APPLECONTAINER_INTEGRATION=1 go test -tags integration -v ./examples/...

Contributing

We welcome issues, bug reports, and pull requests to improve applecontainer-go.

  1. Fork the repository.
  2. Create your feature branch (git checkout -b feature/amazing-feature).
  3. Commit your changes (git commit -m 'Add amazing feature').
  4. Push to the branch (git push origin feature/amazing-feature).
  5. Open a Pull Request.

License

Distributed under the MIT License. See LICENSE for more information.

Documentation

Overview

Package applecontainer implements a testcontainers-go-style Go library for spinning up Apple Container CLI Linux containers as test dependencies.

Example Usage:

ctx := context.Background()
container, err := applecontainer.Run(ctx, "nginx:alpine",
	applecontainer.WithExposedPorts("80"),
	applecontainer.WithWaitStrategy(wait.ForHTTP("/")),
)
if err != nil {
	log.Fatalf("failed to run: %v", err)
}
defer container.Terminate(ctx)

endpoint, err := container.Endpoint(ctx, "80")
// HTTP request against endpoint...

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func CleanupContainer

func CleanupContainer(t testing.TB, c Container, opts ...TerminateOption)

CleanupContainer registers container termination during test cleanup.

func CleanupNetwork

func CleanupNetwork(t testing.TB, nw Network)

CleanupNetwork registers network deletion in t.Cleanup.

func GenericLabels

func GenericLabels() map[string]string

GenericLabels returns the default labels applied to all applecontainer test containers.

func Prune

func Prune(ctx context.Context) error

Prune runs 'container prune' to clean up unused containers, networks, and volumes.

func Reset

func Reset()

Reset clears the cached Config. For tests only.

func Run

func Run(ctx context.Context, img string, opts ...ContainerCustomizer) (*cliContainer, error)

Run creates, starts, and waits for a container using customizers.

func SessionID

func SessionID() string

SessionID returns a stable session identifier for the current test/run process.

func SkipIfProviderNotHealthy

func SkipIfProviderNotHealthy(t testing.TB)

SkipIfProviderNotHealthy checks the provider health and skips the test if not healthy.

func VersionCheck

func VersionCheck(ctx context.Context) (string, error)

VersionCheck runs `container --version`, parses the output, and verifies the version is >= 1.0.0. Called lazily on first Run().

Types

type CLIArgsModifier

type CLIArgsModifier func([]string) []string

CLIArgsModifier allows modifying the command line arguments sent to the CLI.

type Config

type Config struct {
	BinaryPath      string
	Debug           bool
	DefaultNetwork  string
	DefaultPlatform string
	HubImagePrefix  string
	PullTimeout     time.Duration
}

Config holds resolved configuration for the applecontainer-go library. Read once (sync.Once) from ~/.applecontainer.properties + env on first use.

func Read

func Read() Config

Read returns the singleton Config, reading ~/.applecontainer.properties and environment variables once. Env values override properties-file values.

type Configuration

type Configuration struct {
	CapAdd           []string          `json:"capAdd"`
	CapDrop          []string          `json:"capDrop"`
	CreationDate     string            `json:"creationDate"`
	DNS              DNS               `json:"dns"`
	ID               string            `json:"id"`
	Image            Image             `json:"image"`
	InitProcess      InitProcess       `json:"initProcess"`
	Labels           map[string]string `json:"labels"`
	Mounts           []InspectMount    `json:"mounts"`
	Networks         []NetworkConfig   `json:"networks"`
	Platform         Platform          `json:"platform"`
	PublishedPorts   []PublishedPort   `json:"publishedPorts"`
	PublishedSockets []json.RawMessage `json:"publishedSockets"`
	ReadOnly         bool              `json:"readOnly"`
	Resources        Resources         `json:"resources"`
	Rosetta          bool              `json:"rosetta"`
	RuntimeHandler   string            `json:"runtimeHandler"`
	SSH              bool              `json:"ssh"`
	StopSignal       string            `json:"stopSignal"`
	Sysctls          map[string]string `json:"sysctls"`
	UseInit          bool              `json:"useInit"`
	Virtualization   bool              `json:"virtualization"`
}

Configuration is the declared configuration of a container (the "configuration" object in inspect output). Named Configuration (not Config) to avoid colliding with the library Config singleton in config.go.

type Container

type Container interface {
	GetContainerID() string
	Endpoint(ctx context.Context, port string) (string, error)
	PortEndpoint(ctx context.Context, port string, proto string) (string, error)
	Host(context.Context) (string, error)
	MappedPort(ctx context.Context, port string) (int, error)
	ContainerIP(context.Context) (string, error)
	Inspect(context.Context) (*Inspect, error)
	State(context.Context) (*State, error)
	IsRunning() bool
	SessionID() string
	Start(context.Context) error
	Stop(context.Context, *time.Duration) error
	Terminate(ctx context.Context, opts ...TerminateOption) error
	Logs(context.Context) (io.ReadCloser, error)
	Exec(ctx context.Context, cmd []string, opts ...ProcessOption) (int, []byte, error)
	CopyToContainer(ctx context.Context, content []byte, containerPath string, mode int64) error
	CopyFileToContainer(ctx context.Context, hostPath, containerPath string, mode int64) error
	CopyFileFromContainer(ctx context.Context, path string) (io.ReadCloser, error)
	Networks(context.Context) ([]string, error)
}

Container defines the interface for interacting with a container.

type ContainerCustomizer

type ContainerCustomizer interface {
	Customize(req *ContainerRequest) error
}

ContainerCustomizer defines the interface for customizing a ContainerRequest.

func WithAdditionalLifecycleHooks

func WithAdditionalLifecycleHooks(hooks ContainerLifecycleHooks) ContainerCustomizer

WithAdditionalLifecycleHooks is an alias to WithLifecycleHooks.

func WithAdditionalWaitStrategy

func WithAdditionalWaitStrategy(s wait.Strategy) ContainerCustomizer

WithAdditionalWaitStrategy appends an additional wait strategy.

func WithAlwaysPull

func WithAlwaysPull(alwaysPull bool) ContainerCustomizer

WithAlwaysPull sets image always-pull flag.

func WithArch

func WithArch(arch string) ContainerCustomizer

WithArch sets architecture.

func WithCLIArgsModifier

func WithCLIArgsModifier(modifier CLIArgsModifier) ContainerCustomizer

WithCLIArgsModifier chains or sets custom argument modifiers.

func WithCPUs

func WithCPUs(cpus float64) ContainerCustomizer

WithCPUs sets the number of CPUs allocated to the container.

func WithCapAdd

func WithCapAdd(capAdd ...string) ContainerCustomizer

WithCapAdd appends capabilities to add.

func WithCapDrop

func WithCapDrop(capDrop ...string) ContainerCustomizer

WithCapDrop appends capabilities to drop.

func WithCmd

func WithCmd(cmd ...string) ContainerCustomizer

WithCmd sets the command line arguments.

func WithCmdArgs

func WithCmdArgs(args ...string) ContainerCustomizer

WithCmdArgs appends command line arguments.

func WithContainerfile

func WithContainerfile(cf FromContainerfile) ContainerCustomizer

WithContainerfile sets options for building from a Containerfile.

func WithDNS

func WithDNS(dns ...string) ContainerCustomizer

WithDNS appends custom DNS servers.

func WithDNSDomain

func WithDNSDomain(domain string) ContainerCustomizer

WithDNSDomain sets custom DNS search domain.

func WithDNSSearch

func WithDNSSearch(search ...string) ContainerCustomizer

WithDNSSearch appends DNS search domains.

func WithEntrypoint

func WithEntrypoint(entrypoint ...string) ContainerCustomizer

WithEntrypoint overrides the entrypoint.

func WithEntrypointArgs

func WithEntrypointArgs(args ...string) ContainerCustomizer

WithEntrypointArgs sets the command line arguments.

func WithEnv

func WithEnv(env map[string]string) ContainerCustomizer

WithEnv merges environment variables.

func WithEnvFile

func WithEnvFile(filePath string) ContainerCustomizer

WithEnvFile stubs loading variables from an env file.

func WithExposedPorts

func WithExposedPorts(ports ...string) ContainerCustomizer

WithExposedPorts exposes ports.

func WithFiles

func WithFiles(files ...ContainerFile) ContainerCustomizer

WithFiles appends files to copy to container.

func WithHostPortMapping

func WithHostPortMapping(mapping bool) ContainerCustomizer

WithHostPortMapping toggles host port mapping.

func WithImage

func WithImage(image string) ContainerCustomizer

WithImage sets the image reference to run.

func WithInit

func WithInit(init bool) ContainerCustomizer

WithInit enables or disables init mode inside container.

func WithLabels

func WithLabels(labels map[string]string) ContainerCustomizer

WithLabels merges labels.

func WithLifecycleHooks

func WithLifecycleHooks(hooks ContainerLifecycleHooks) ContainerCustomizer

WithLifecycleHooks appends lifecycle hooks.

func WithLogConsumers

func WithLogConsumers(consumers ...LogConsumer) ContainerCustomizer

WithLogConsumers registers log consumers.

func WithLogger

func WithLogger(logger any) ContainerCustomizer

WithLogger stubs logger configuration.

func WithMemory

func WithMemory(memory int64) ContainerCustomizer

WithMemory sets the memory limit in bytes.

func WithMounts

func WithMounts(mounts ...Mount) ContainerCustomizer

WithMounts appends container mounts.

func WithName

func WithName(name string) ContainerCustomizer

WithName sets container name.

func WithNetwork

func WithNetwork(aliases []string, nw Network) ContainerCustomizer

WithNetwork attaches the container to an existing network with network aliases.

func WithNetworkName

func WithNetworkName(network string) ContainerCustomizer

WithNetworkName sets container network name.

func WithNetworks

func WithNetworks(networks ...string) ContainerCustomizer

WithNetworks appends container networks.

func WithNewNetwork

func WithNewNetwork(ctx context.Context, aliases []string, opts ...NetworkOption) ContainerCustomizer

WithNewNetwork creates a network and attaches the container to it.

func WithNoDNS

func WithNoDNS(noDNS bool) ContainerCustomizer

WithNoDNS disables auto DNS injection.

func WithOS

func WithOS(os string) ContainerCustomizer

WithOS sets target OS.

func WithPlatform

func WithPlatform(platform string) ContainerCustomizer

WithPlatform sets platform.

func WithReadOnlyRootfs

func WithReadOnlyRootfs(readOnly bool) ContainerCustomizer

WithReadOnlyRootfs sets readonly root filesystem flag.

func WithRosetta

func WithRosetta(rosetta bool) ContainerCustomizer

WithRosetta enables Rosetta 2 emulation.

func WithShmSize

func WithShmSize(shmSize int64) ContainerCustomizer

WithShmSize sets shared memory size.

func WithTmpfs

func WithTmpfs(tmpfs map[string]string) ContainerCustomizer

WithTmpfs merges tmpfs mounts.

func WithUlimits

func WithUlimits(ulimits ...Ulimit) ContainerCustomizer

WithUlimits appends ulimit configurations.

func WithUser

func WithUser(user string) ContainerCustomizer

WithUser sets the user name or UID.

func WithVolumes

func WithVolumes(volumes ...VolumeMount) ContainerCustomizer

WithVolumes appends volume mounts.

func WithWaitStrategy

func WithWaitStrategy(s wait.Strategy) ContainerCustomizer

WithWaitStrategy sets the wait strategy, wrapping it in wait.ForAll with a 60s timeout.

func WithWaitStrategyAndDeadline

func WithWaitStrategyAndDeadline(s wait.Strategy, deadline time.Duration) ContainerCustomizer

WithWaitStrategyAndDeadline sets the wait strategy and its deadline.

func WithWaitingFor

func WithWaitingFor(s wait.Strategy) ContainerCustomizer

WithWaitingFor sets the wait strategy.

func WithWorkingDir

func WithWorkingDir(workingDir string) ContainerCustomizer

WithWorkingDir sets the working directory.

type ContainerFile

type ContainerFile struct {
	HostFilePath      string `json:"hostFilePath"`
	ContainerFilePath string `json:"containerFilePath"`
	FileMode          int64  `json:"fileMode"`
}

ContainerFile represents a file to be copied into the container.

type ContainerHook

type ContainerHook func(ctx context.Context, c Container) error

ContainerHook defines a hook triggered with the container.

type ContainerLifecycleHooks

type ContainerLifecycleHooks struct {
	PreBuilds      []ContainerRequestHook
	PostBuilds     []ContainerRequestHook
	PreCreates     []ContainerRequestHook
	PostCreates    []ContainerRequestHook
	PreStarts      []ContainerHook
	PostStarts     []ContainerHook
	PostReadies    []ContainerHook
	PreStops       []ContainerHook
	PostStops      []ContainerHook
	PreTerminates  []ContainerHook
	PostTerminates []ContainerHook
}

ContainerLifecycleHooks defines hooks during container lifecycle phases.

type ContainerProvider

type ContainerProvider interface {
	CreateContainer(ctx context.Context, req *ContainerRequest) (*cliContainer, error)
	StartContainer(ctx context.Context, c *cliContainer) error
	StopContainer(ctx context.Context, id string, timeout *time.Duration) error
	KillContainer(ctx context.Context, id string, signal string) error
	DeleteContainer(ctx context.Context, id string, force bool) error
	InspectContainer(ctx context.Context, id string) (*Inspect, error)
	ContainerLogs(ctx context.Context, id string, follow bool, n int) (io.ReadCloser, error)
	ExecContainer(ctx context.Context, id string, cmd []string, opts ...ProcessOption) (int, []byte, error)
	CopyToContainer(ctx context.Context, id, containerPath string, content []byte, mode int64) error
	CopyFileFromContainer(ctx context.Context, id, path string) (io.ReadCloser, error)
	ImagePull(ctx context.Context, ref string, opts ...PullOption) error
	ImageInspect(ctx context.Context, ref string) (*ImageInspect, error)
	Health(ctx context.Context) error
	Close() error
}

ContainerProvider defines the interface for managing container lifecycles.

type ContainerRequest

type ContainerRequest struct {
	Image             string
	FromContainerfile FromContainerfile
	AlwaysPull        bool
	Platform          string
	Arch              string
	OS                string
	Cmd               []string
	Entrypoint        []string
	Env               map[string]string
	WorkingDir        string
	User              string
	Init              bool
	ExposedPorts      []string
	HostPorts         map[string]int
	Networks          []string
	NetworkAliases    map[string][]string
	DNS               []string
	DNSDomain         string
	DNSSearch         []string
	NoDNS             bool
	Volumes           []VolumeMount
	Mounts            []Mount
	Tmpfs             map[string]string
	ShmSize           int64
	ReadOnlyRootfs    bool
	Files             []ContainerFile
	CPUs              float64
	Memory            int64
	CapAdd            []string
	CapDrop           []string
	Ulimits           []Ulimit
	Rosetta           bool
	Name              string
	Labels            map[string]string
	WaitingFor        WaitingFor
	LifecycleHooks    ContainerLifecycleHooks
	LogConsumerCfg    *LogConsumerCfg
	HostPortMapping   bool
	CLIArgsModifier   CLIArgsModifier
}

ContainerRequest represents the parameters for creating a container.

func (*ContainerRequest) Validate

func (req *ContainerRequest) Validate() error

Validate validates the container request parameters.

type ContainerRequestHook

type ContainerRequestHook func(ctx context.Context, req *ContainerRequest) error

ContainerRequestHook defines a hook triggered with the container request.

type CustomizeRequestOption

type CustomizeRequestOption func(req *ContainerRequest) error

CustomizeRequestOption is a function type that implements ContainerCustomizer.

func (CustomizeRequestOption) Customize

func (f CustomizeRequestOption) Customize(req *ContainerRequest) error

Customize calls the underlying function to customize the request.

type DNS

type DNS struct {
	Nameservers   []string `json:"nameservers"`
	Options       []string `json:"options"`
	SearchDomains []string `json:"searchDomains"`
}

DNS is the configured DNS for a container.

type Descriptor

type Descriptor struct {
	Digest    string `json:"digest"`
	MediaType string `json:"mediaType"`
	Size      int64  `json:"size"`
}

Descriptor is the OCI image descriptor.

type FromContainerfile

type FromContainerfile struct {
	Context   string             `json:"context"`
	File      string             `json:"file"`
	BuildArgs map[string]*string `json:"buildArgs"`
	Tags      []string           `json:"tags"`
	Target    string             `json:"target"`
	Platform  string             `json:"platform"`
	NoCache   bool               `json:"noCache"`
	Pull      bool               `json:"pull"`
	Secrets   map[string]string  `json:"secrets"`
	KeepImage bool               `json:"keepImage"`
}

FromContainerfile contains options for building an image from a Containerfile.

type Image

type Image struct {
	Descriptor Descriptor `json:"descriptor"`
	Reference  string     `json:"reference"`
}

Image is the image reference plus its descriptor.

type ImageInspect

type ImageInspect struct {
	ID string
}

ImageInspect represents metadata of an image.

type InitProcess

type InitProcess struct {
	Arguments          []string          `json:"arguments"`
	Environment        []string          `json:"environment"`
	Executable         string            `json:"executable"`
	Rlimits            []json.RawMessage `json:"rlimits"`
	SupplementalGroups []int             `json:"supplementalGroups"`
	Terminal           bool              `json:"terminal"`
	User               User              `json:"user"`
	WorkingDirectory   string            `json:"workingDirectory"`
}

InitProcess is the configured init process of the container.

type Inspect

type Inspect struct {
	ID            string        `json:"id"`
	Configuration Configuration `json:"configuration"`
	State         `json:"status"`
}

Inspect is the parsed result of `container inspect <id>` and `container list --format json`. State is embedded so its fields (Networks, Status, StartedDate) are reachable directly on Inspect.

type InspectMount

type InspectMount struct {
	Destination string           `json:"destination"`
	Options     []string         `json:"options"`
	Source      string           `json:"source"`
	Type        InspectMountType `json:"type"`
}

InspectMount is one entry under configuration.mounts. Apple Container encodes the mount driver as a tagged union (e.g. {"virtiofs": {}}); the known virtiofs variant is captured and other drivers are retained as raw messages.

type InspectMountType

type InspectMountType struct {
	VirtioFS json.RawMessage `json:"virtiofs,omitempty"`
}

InspectMountType holds the mount driver variant. VirtioFS is the only captured variant; its inner object is kept as a raw message so unseen fields do not break parsing.

type ListEntry

type ListEntry = Inspect

ListEntry is an alias for Inspect: `container list --format json` returns the same JSON array shape as `container inspect`.

type Log

type Log struct {
	LogType string
	Content []byte
}

Log represents a log message.

type LogConsumer

type LogConsumer interface {
	Accept(Log)
}

LogConsumer defines the interface for consuming container logs.

type LogConsumerCfg

type LogConsumerCfg struct {
	Consumers []LogConsumer
}

LogConsumerCfg holds log consumer settings.

type Mount

type Mount struct {
	Type     MountType `json:"type"`
	Source   string    `json:"source"`
	Target   string    `json:"target"`
	ReadOnly bool      `json:"readOnly"`
}

Mount represents a container mount configuration.

type MountType

type MountType string

MountType defines the type of mount.

const (
	MountTypeBind   MountType = "bind"
	MountTypeVolume MountType = "volume"
	MountTypeTmpfs  MountType = "tmpfs"
)

type Network

type Network interface {
	Remove(ctx context.Context) error
	Name() string
}

Network represents a container network.

func NewNetwork

func NewNetwork(ctx context.Context, opts ...NetworkOption) (Network, error)

NewNetwork creates a network.

type NetworkConfig

type NetworkConfig struct {
	Network string         `json:"network"`
	Options map[string]any `json:"options"`
}

NetworkConfig is one entry under configuration.networks (the declared network attachment, without a runtime IP). Options is an open map because the keys vary (hostname, mtu, ...).

type NetworkInfo

type NetworkInfo struct {
	Hostname    string `json:"hostname"`
	IPv4Address string `json:"ipv4Address"`
	IPv4Gateway string `json:"ipv4Gateway"`
	IPv6Address string `json:"ipv6Address"`
	MacAddress  string `json:"macAddress"`
	MTU         int    `json:"mtu"`
	Network     string `json:"network"`
}

NetworkInfo is one entry under status.networks carrying the assigned IP.

func (NetworkInfo) IPv4

func (n NetworkInfo) IPv4() string

IPv4 returns the IPv4 address without the CIDR suffix (e.g. "192.168.64.7" from "192.168.64.7/24"). If there is no "/", the value is returned as-is.

type NetworkOption

type NetworkOption func(*NetworkRequest)

NetworkOption sets network request parameters.

func WithEnableIPv6

func WithEnableIPv6(enable bool) NetworkOption

WithEnableIPv6 sets IPv6 enable flag.

func WithInternal

func WithInternal(internal bool) NetworkOption

WithInternal sets internal network flag.

func WithNetworkDriver

func WithNetworkDriver(driver string) NetworkOption

WithNetworkDriver sets network driver.

func WithNetworkLabels

func WithNetworkLabels(labels map[string]string) NetworkOption

WithNetworkLabels sets labels on the network.

func WithNetworkNameOption

func WithNetworkNameOption(name string) NetworkOption

WithNetworkNameOption sets the network name.

func WithSubnet

func WithSubnet(subnet string) NetworkOption

WithSubnet sets the network subnet.

func WithSubnetV6

func WithSubnetV6(subnet string) NetworkOption

WithSubnetV6 sets the IPv6 subnet.

type NetworkRequest

type NetworkRequest struct {
	Name       string
	Driver     string
	Internal   bool
	EnableIPv6 bool
	Subnet     string
	SubnetV6   string
	Labels     map[string]string
}

NetworkRequest configuration.

type Platform

type Platform struct {
	Architecture string `json:"architecture"`
	OS           string `json:"os"`
}

Platform is the target OS/architecture.

type ProcessOption

type ProcessOption func(*processOptions)

ProcessOption is a functional option for container execution.

func WithExecEnv

func WithExecEnv(env []string) ProcessOption

WithExecEnv sets the environment variables for exec command execution.

func WithExecUser

func WithExecUser(user string) ProcessOption

WithExecUser sets the user for exec command execution.

func WithExecWorkingDir

func WithExecWorkingDir(dir string) ProcessOption

WithExecWorkingDir sets the working directory for exec command execution.

type PublishedPort

type PublishedPort struct {
	ContainerPort int    `json:"containerPort"`
	Count         int    `json:"count"`
	HostAddress   string `json:"hostAddress"`
	HostPort      int    `json:"hostPort"`
	Proto         string `json:"proto"`
}

PublishedPort is one entry under configuration.publishedPorts.

type PullOption

type PullOption func(*pullOptions)

PullOption is a functional option for image pulling.

type Resources

type Resources struct {
	CPUOverhead   int   `json:"cpuOverhead"`
	CPUs          int   `json:"cpus"`
	MemoryInBytes int64 `json:"memoryInBytes"`
}

Resources is the resource allocation for the container.

type State

type State struct {
	Networks    []NetworkInfo `json:"networks"`
	StartedDate string        `json:"startedDate"`
	Status      string        `json:"state"`
	ExitCode    int           `json:"exitCode"`
}

State is the runtime status of a container (the "status" object).

type StatsEntry

type StatsEntry struct {
	BlockReadBytes   int64  `json:"blockReadBytes"`
	BlockWriteBytes  int64  `json:"blockWriteBytes"`
	CPUUsageUsec     int64  `json:"cpuUsageUsec"`
	ID               string `json:"id"`
	MemoryLimitBytes int64  `json:"memoryLimitBytes"`
	MemoryUsageBytes int64  `json:"memoryUsageBytes"`
	NetworkRxBytes   int64  `json:"networkRxBytes"`
	NetworkTxBytes   int64  `json:"networkTxBytes"`
	NumProcesses     int    `json:"numProcesses"`
}

StatsEntry is one element of `container stats --format json --no-stream`.

type StdoutLogConsumer

type StdoutLogConsumer struct{}

StdoutLogConsumer prints container logs directly to stdout.

func (*StdoutLogConsumer) Accept

func (s *StdoutLogConsumer) Accept(l Log)

Accept writes the log content followed by a newline to stdout.

type TerminateOption

type TerminateOption func(*terminateOptions)

TerminateOption is a functional option for container termination.

type Ulimit

type Ulimit struct {
	Name string `json:"name"`
	Soft int64  `json:"soft"`
	Hard int64  `json:"hard"`
}

Ulimit represents resource limit settings.

type User

type User struct {
	ID UserID `json:"id"`
}

User is the user specification containing the uid/gid id.

type UserID

type UserID struct {
	GID int `json:"gid"`
	UID int `json:"uid"`
}

UserID is the uid/gid pair identifying the container user.

type Volume

type Volume interface {
	Remove(ctx context.Context) error
	Name() string
}

Volume represents a container volume.

func NewVolume

func NewVolume(ctx context.Context, opts ...VolumeOption) (Volume, error)

NewVolume creates a volume.

type VolumeMount

type VolumeMount struct {
	Source   string `json:"source"`
	Target   string `json:"target"`
	ReadOnly bool   `json:"readOnly"`
}

VolumeMount represents a volume mount.

type VolumeOption

type VolumeOption func(*VolumeRequest)

VolumeOption sets volume request parameters.

func WithVolumeLabels

func WithVolumeLabels(labels map[string]string) VolumeOption

WithVolumeLabels sets labels on the volume.

func WithVolumeNameOption

func WithVolumeNameOption(name string) VolumeOption

WithVolumeNameOption sets the volume name.

func WithVolumeOpt

func WithVolumeOpt(key, val string) VolumeOption

WithVolumeOpt adds options to the volume creation.

func WithVolumeSize

func WithVolumeSize(size string) VolumeOption

WithVolumeSize sets the size of the volume.

type VolumeRequest

type VolumeRequest struct {
	Name    string
	Size    string
	Labels  map[string]string
	Options map[string]string
}

VolumeRequest configuration.

type WaitingFor

type WaitingFor = wait.Strategy

WaitingFor is an alias for wait.Strategy.

Directories

Path Synopsis
Package log provides a minimal logger interface for applecontainer-go, ported from testcontainers-go's log package.
Package log provides a minimal logger interface for applecontainer-go, ported from testcontainers-go's log package.

Jump to

Keyboard shortcuts

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