docker

package
v1.0.2 Latest Latest
Warning

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

Go to latest
Published: Oct 23, 2026 License: MIT Imports: 35 Imported by: 0

Documentation

Overview

Package docker provides an adapter for the official Docker SDK.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrNilExecConfig is returned when an ExecConfig pointer is nil.
	ErrNilExecConfig = errors.New("exec: nil ExecConfig")
	// ErrNoExecOutputWriter is returned when Run is invoked in non-TTY mode
	// with both stdout and stderr nil. stdcopy.StdCopy panics in that case
	// the moment it has output to dispatch.
	ErrNoExecOutputWriter = errors.New("exec: non-TTY mode requires at least one of stdout or stderr")
)

Sentinel errors for input validation. Defined as static values so callers can use errors.Is for branching and to satisfy err113 lint guidance.

View Source
var ErrHTTPSRequiresUsableCertMaterial = errors.New("https:// has TLS material configured but it is unreadable or invalid")

ErrHTTPSRequiresUsableCertMaterial is returned by NewClientWithConfig when DOCKER_HOST uses the explicit-TLS scheme `https://` AND TLS material is configured (DOCKER_CERT_PATH or ClientConfig.TLSCertPath) but resolveTLSConfig fails to load it (typo in path, unreadable cert.pem, malformed ca.pem, secrets not yet populated, broken volume mount).

Without this gate, applyDockerTLS would emit slog.Warn and leave TLSClientConfig nil; the SDK would then dial with Go's default TLS — the system CA pool, NO client certificate — silently downgrading what the operator declared as mTLS into an unauthenticated TLS handshake.

Asymmetry vs ErrTCPTLSRequiresCertMaterial: tcp+tls:// REQUIRES material even when nothing is set (the scheme is an explicit mTLS opt-in). https:// is fail-open when no material is configured (operator legitimately relies on the system CA bundle); we only fail closed when material IS configured but unloadable. This is the silent-downgrade vector closed by #653.

View Source
var ErrMissingDockerHostScheme = errors.New("missing DOCKER_HOST scheme")

ErrMissingDockerHostScheme is returned when DOCKER_HOST is non-empty but has no "://" separator (e.g. "127.0.0.1:2375"). Distinct from ErrUnsupportedDockerHostScheme so operators can tell "I forgot the scheme" from "I used a scheme that isn't supported."

View Source
var ErrNilContainerConfig = errors.New("container: nil ContainerConfig")

ErrNilContainerConfig is returned by ContainerServiceAdapter.Create when the supplied *domain.ContainerConfig is nil. Production callers always pass a non-nil config (the executor builds it eagerly), so this is defense-in-depth — but the previous code dereferenced `config.HostConfig` / `config.NetworkConfig` unconditionally and would panic on a hand-rolled nil. Returning a typed sentinel keeps the failure branchable via errors.Is and consistent with ErrNilExecConfig.

View Source
var ErrNilDockerClient = errors.New("docker adapter: nil SDK client")

ErrNilDockerClient is returned by any *ServiceAdapter method when the embedded Docker SDK client is nil. The supported wiring (`NewClient` / `NewClientWithConfig`, then accessing the per-service adapters via the `*Client` accessor methods) always returns adapters with a non-nil embedded client, so this is reachable only through hand-rolled adapter values (`&ContainerServiceAdapter{}` and friends) — typically a test fixture or a wiring bug. Returning a typed error converts what would otherwise be a `nil pointer dereference` panic in a hot goroutine into an actionable, branchable failure that callers can route via `errors.Is`.

View Source
var ErrTCPTLSRequiresCertMaterial = errors.New("tcp+tls:// requires TLS material")

ErrTCPTLSRequiresCertMaterial is returned by NewClientWithConfig when DOCKER_HOST uses the explicit-TLS scheme `tcp+tls://` but no TLS material is configured (no DOCKER_CERT_PATH / DOCKER_TLS_VERIFY env vars and no ClientConfig.TLSCertPath / TLSVerify overrides).

Without this gate the SDK would dial TLS using Go's stdlib defaults — system CA bundle, NO client certificate — silently downgrading what the operator declared as mTLS into an unauthenticated TLS handshake. This is the analog, for tcp+tls://, of the silent plain-TCP downgrade closed by #612 / #625; tracked in #627.

`tcp://` and `https://` remain fail-open (tcp:// is ambiguous; https:// follows the upstream SDK's documented fail-open-with-warning posture).

View Source
var ErrUnsupportedDockerHostScheme = errors.New("unsupported DOCKER_HOST scheme")

ErrUnsupportedDockerHostScheme is returned when a DOCKER_HOST value uses a URL scheme that this adapter does not support. The error message lists the supported schemes so operators get an actionable failure at startup instead of an opaque dial error later.

Supported schemes (case-insensitive): unix, tcp, tcp+tls, http, https, npipe. Notably unsupported: ssh, fd. See docs/TROUBLESHOOTING.md.

Tracking: https://github.com/netresearch/ofelia/issues/609

Functions

func EncodeAuthConfig

func EncodeAuthConfig(auth domain.AuthConfig) (string, error)

EncodeAuthConfig encodes an auth config for use in API calls.

func ExtractRegistry added in v0.16.0

func ExtractRegistry(image string) string

ExtractRegistry extracts the registry hostname from an image reference. Uses the canonical docker/distribution/reference parser for robustness.

Types

type Client

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

Client implements ports.DockerClient using the official Docker SDK.

func NewClient

func NewClient() (*Client, error)

NewClient creates a new Docker client from environment variables.

func NewClientWithConfig

func NewClientWithConfig(config *ClientConfig) (*Client, error)

NewClientWithConfig creates a new Docker client with custom configuration.

The effective Docker host is resolved in this order:

  1. config.Host (if non-empty)
  2. DOCKER_HOST environment variable
  3. client.DefaultDockerHost

The host's URL scheme is validated against the allow-list (see schemeHandlers) and normalized to lowercase. Unsupported schemes (ssh://, fd://, etc.) return ErrUnsupportedDockerHostScheme.

The DOCKER_HOST environment variable is consulted at most once per call. This is the contract from issue #617: a single resolveDockerHost seam avoids the SDK-vs-transport disagreement that caused #605 / #606 / #607 / #609 when two readers raced on env.

func (*Client) Close

func (c *Client) Close() error

Close closes the client.

func (*Client) Containers

func (c *Client) Containers() ports.ContainerService

Containers returns the container service.

func (*Client) Events

func (c *Client) Events() ports.EventService

Events returns the event service.

func (*Client) Exec

func (c *Client) Exec() ports.ExecService

Exec returns the exec service.

func (*Client) Images

func (c *Client) Images() ports.ImageService

Images returns the image service.

func (*Client) Networks

func (c *Client) Networks() ports.NetworkService

Networks returns the network service.

func (*Client) SDK

func (c *Client) SDK() *client.Client

SDK returns the underlying Docker SDK client. This should only be used for operations not covered by the ports interface.

func (*Client) Services

func (c *Client) Services() ports.SwarmService

Services returns the Swarm service.

func (*Client) System

func (c *Client) System() ports.SystemService

System returns the system service.

type ClientConfig

type ClientConfig struct {
	// Host is the Docker host address (e.g., "unix:///var/run/docker.sock")
	Host string

	// Version is the API version (empty for auto-negotiation)
	Version string

	// HTTPHeaders are custom HTTP headers (optional)
	HTTPHeaders map[string]string

	// Connection pool settings
	MaxIdleConns        int
	MaxIdleConnsPerHost int
	MaxConnsPerHost     int
	IdleConnTimeout     time.Duration

	// Timeout settings
	DialTimeout           time.Duration
	ResponseHeaderTimeout time.Duration

	// NegotiateTimeout bounds the initial Docker API version negotiation that
	// runs once at client creation. Without a bound, NegotiateAPIVersion uses
	// context.Background() and can block forever when the Docker daemon is
	// reachable but unresponsive (e.g. a socket proxy whose upstream is wedged),
	// hanging Ofelia at startup with no diagnostic output.
	//
	// The Docker SDK swallows ping errors silently, so this timeout does not
	// change correctness on successful paths - it only bounds the failure case.
	//
	// Set to 0 to inherit the default (see DefaultConfig). Use a small value
	// to fail fast in tests; production typically wants 10-30s.
	NegotiateTimeout time.Duration

	// TLSCertPath is the directory containing TLS material (ca.pem, cert.pem,
	// key.pem) for HTTPS Docker hosts. When empty, the DOCKER_CERT_PATH
	// environment variable is consulted instead. If both are empty, no TLS
	// configuration is applied (mirroring docker/docker's
	// WithTLSClientConfigFromEnv).
	TLSCertPath string

	// TLSVerify controls whether the server certificate is verified for HTTPS
	// Docker hosts. When nil, the DOCKER_TLS_VERIFY environment variable is
	// consulted: any non-empty value enables verification (mirroring
	// docker/docker's WithTLSClientConfigFromEnv).
	TLSVerify *bool
}

ClientConfig contains configuration for the Docker client.

func DefaultConfig

func DefaultConfig() *ClientConfig

DefaultConfig returns a default configuration.

type ConfigAuthProvider added in v0.16.0

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

ConfigAuthProvider implements ports.AuthProvider using Docker's config.json. It reads credentials fresh on each call to support dynamic credential updates (e.g., short-lived tokens from AWS ECR, GCR).

func NewConfigAuthProvider added in v0.16.0

func NewConfigAuthProvider() *ConfigAuthProvider

NewConfigAuthProvider creates a new auth provider.

func NewConfigAuthProviderWithOptions added in v0.16.0

func NewConfigAuthProviderWithOptions(configDir string, logger *slog.Logger) *ConfigAuthProvider

NewConfigAuthProviderWithOptions creates an auth provider with options.

func (*ConfigAuthProvider) GetAuthConfig added in v0.16.0

func (p *ConfigAuthProvider) GetAuthConfig(registry string) (domain.AuthConfig, error)

GetAuthConfig returns auth configuration for a registry.

func (*ConfigAuthProvider) GetEncodedAuth added in v0.16.0

func (p *ConfigAuthProvider) GetEncodedAuth(registry string) (string, error)

GetEncodedAuth returns base64-encoded auth for a registry.

type ContainerServiceAdapter

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

ContainerServiceAdapter implements ports.ContainerService using Docker SDK.

func (*ContainerServiceAdapter) Attach

Attach attaches to a container.

func (*ContainerServiceAdapter) CopyLogs

func (s *ContainerServiceAdapter) CopyLogs(
	ctx context.Context, containerID string, stdout, stderr io.Writer, opts domain.LogOptions,
) error

CopyLogs copies container logs to writers.

func (*ContainerServiceAdapter) Create

Create creates a new container.

Returns ErrNilContainerConfig (no panic) if config is nil — the previous code dereferenced config.HostConfig / config.NetworkConfig unconditionally. See #632 / #626.

func (*ContainerServiceAdapter) Inspect

func (s *ContainerServiceAdapter) Inspect(ctx context.Context, containerID string) (*domain.Container, error)

Inspect returns container information.

func (*ContainerServiceAdapter) Kill

func (s *ContainerServiceAdapter) Kill(ctx context.Context, containerID string, signal string) error

Kill sends a signal to a container.

func (*ContainerServiceAdapter) List

List lists containers.

func (*ContainerServiceAdapter) Logs

func (s *ContainerServiceAdapter) Logs(ctx context.Context, containerID string, opts domain.LogOptions) (io.ReadCloser, error)

Logs returns container logs.

func (*ContainerServiceAdapter) Pause

func (s *ContainerServiceAdapter) Pause(ctx context.Context, containerID string) error

Pause pauses a container.

func (*ContainerServiceAdapter) Remove

func (s *ContainerServiceAdapter) Remove(ctx context.Context, containerID string, opts domain.RemoveOptions) error

Remove removes a container.

func (*ContainerServiceAdapter) Rename

func (s *ContainerServiceAdapter) Rename(ctx context.Context, containerID string, newName string) error

Rename renames a container.

func (*ContainerServiceAdapter) Start

func (s *ContainerServiceAdapter) Start(ctx context.Context, containerID string) error

Start starts a container.

func (*ContainerServiceAdapter) Stop

func (s *ContainerServiceAdapter) Stop(ctx context.Context, containerID string, opts domain.StopOptions) error

Stop stops a container.

func (*ContainerServiceAdapter) Unpause

func (s *ContainerServiceAdapter) Unpause(ctx context.Context, containerID string) error

Unpause unpauses a container.

func (*ContainerServiceAdapter) Wait

func (s *ContainerServiceAdapter) Wait(ctx context.Context, containerID string) (<-chan domain.WaitResponse, <-chan error)

Wait waits for a container to stop.

type EventServiceAdapter

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

EventServiceAdapter implements ports.EventService using Docker SDK. This implementation uses context-based cancellation for safe channel management.

func (*EventServiceAdapter) Subscribe

func (s *EventServiceAdapter) Subscribe(ctx context.Context, filter domain.EventFilter) (<-chan domain.Event, <-chan error)

Subscribe subscribes to Docker events. The returned channels are closed when the context is canceled or an error occurs. The caller should NOT close these channels.

If the embedded SDK client is nil (defense-in-depth), both channels are closed synchronously after pushing ErrNilDockerClient on errCh — no goroutine is launched.

func (*EventServiceAdapter) SubscribeWithCallback

func (s *EventServiceAdapter) SubscribeWithCallback(
	ctx context.Context,
	filter domain.EventFilter,
	callback ports.EventCallback,
) error

SubscribeWithCallback subscribes to events with a callback.

type ExecServiceAdapter

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

ExecServiceAdapter implements ports.ExecService using Docker SDK.

func (*ExecServiceAdapter) Create

func (s *ExecServiceAdapter) Create(ctx context.Context, containerID string, config *domain.ExecConfig) (string, error)

Create prepares an exec instance inside containerID and returns its exec ID. It only creates the instance — nothing runs until Start is called with that ID, and detaching is likewise decided there, not here.

Returns ErrNilDockerClient when the adapter holds no SDK client, ErrNilExecConfig when config is nil, and a domain-mapped error (convertError) for Docker API failures. config.ConsoleSize is forwarded only when config.Tty is set; see consoleSize.

func (*ExecServiceAdapter) Inspect

func (s *ExecServiceAdapter) Inspect(ctx context.Context, execID string) (*domain.ExecInspect, error)

Inspect returns exec information.

func (*ExecServiceAdapter) Run

func (s *ExecServiceAdapter) Run(
	ctx context.Context, containerID string, config *domain.ExecConfig, stdout, stderr io.Writer,
) (int, error)

Run executes a command in a container and waits for it to complete.

func (*ExecServiceAdapter) Start

Start starts an exec instance.

type ImageServiceAdapter

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

ImageServiceAdapter implements ports.ImageService using Docker SDK.

func (*ImageServiceAdapter) Exists

func (s *ImageServiceAdapter) Exists(ctx context.Context, imageRef string) (bool, error)

Exists checks if an image exists locally.

func (*ImageServiceAdapter) Inspect

func (s *ImageServiceAdapter) Inspect(ctx context.Context, imageID string) (*domain.Image, error)

Inspect returns image information.

func (*ImageServiceAdapter) List

List lists images.

func (*ImageServiceAdapter) Pull

Pull pulls an image from a registry.

func (*ImageServiceAdapter) PullAndWait

func (s *ImageServiceAdapter) PullAndWait(ctx context.Context, opts domain.PullOptions) error

PullAndWait pulls an image and waits for completion.

func (*ImageServiceAdapter) Remove

func (s *ImageServiceAdapter) Remove(ctx context.Context, imageID string, force, pruneChildren bool) error

Remove removes an image.

func (*ImageServiceAdapter) Tag

func (s *ImageServiceAdapter) Tag(ctx context.Context, source, target string) error

Tag tags an image.

type NetworkServiceAdapter

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

NetworkServiceAdapter implements ports.NetworkService using Docker SDK.

func (*NetworkServiceAdapter) Connect

func (s *NetworkServiceAdapter) Connect(ctx context.Context, networkID, containerID string, config *domain.EndpointSettings) error

Connect connects a container to a network.

func (*NetworkServiceAdapter) Create

Create creates a network.

func (*NetworkServiceAdapter) Disconnect

func (s *NetworkServiceAdapter) Disconnect(ctx context.Context, networkID, containerID string, force bool) error

Disconnect disconnects a container from a network.

func (*NetworkServiceAdapter) Inspect

func (s *NetworkServiceAdapter) Inspect(ctx context.Context, networkID string) (*domain.Network, error)

Inspect returns network information.

func (*NetworkServiceAdapter) List

List lists networks.

func (*NetworkServiceAdapter) Remove

func (s *NetworkServiceAdapter) Remove(ctx context.Context, networkID string) error

Remove removes a network.

type SwarmServiceAdapter

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

SwarmServiceAdapter implements ports.SwarmService using Docker SDK.

func (*SwarmServiceAdapter) Create

Create creates a new Swarm service.

func (*SwarmServiceAdapter) Inspect

func (s *SwarmServiceAdapter) Inspect(ctx context.Context, serviceID string) (*domain.Service, error)

Inspect returns service information.

func (*SwarmServiceAdapter) List

List lists services.

func (*SwarmServiceAdapter) ListTasks

ListTasks lists tasks.

func (*SwarmServiceAdapter) Remove

func (s *SwarmServiceAdapter) Remove(ctx context.Context, serviceID string) error

Remove removes a service.

func (*SwarmServiceAdapter) WaitForServiceTasks

func (s *SwarmServiceAdapter) WaitForServiceTasks(ctx context.Context, serviceID string, timeout time.Duration) ([]domain.Task, error)

WaitForServiceTasks waits for all service tasks to reach a terminal state.

func (*SwarmServiceAdapter) WaitForTask

func (s *SwarmServiceAdapter) WaitForTask(ctx context.Context, taskID string, timeout time.Duration) (*domain.Task, error)

WaitForTask waits for a task to reach a terminal state.

type SystemServiceAdapter

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

SystemServiceAdapter implements ports.SystemService using Docker SDK.

func (*SystemServiceAdapter) DiskUsage

func (s *SystemServiceAdapter) DiskUsage(ctx context.Context) (*domain.DiskUsage, error)

DiskUsage returns disk usage information.

func (*SystemServiceAdapter) Info

Info returns system information.

func (*SystemServiceAdapter) Ping

Ping pings the Docker server.

func (*SystemServiceAdapter) Version

Version returns version information.

Jump to

Keyboard shortcuts

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