docker

package
v0.27.0 Latest Latest
Warning

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

Go to latest
Published: Nov 27, 2026 License: AGPL-3.0 Imports: 24 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package docker reads containers from a Docker Engine over its Unix socket: the container list, the details of one container, the Compose projects the containers belong to, the containers that use a path, one reading of a container's CPU and memory use, a container's logs as a stream of lines, and the actions start, stop and restart, with a wait until containers are healthy.

The application names the socket in Options.

On the first call a Client asks the Engine for its API version and uses the lower of that and MaxAPIVersion; the outcome of a success is kept in the Client, a failure is not.

Failures are an *Error with an output.Code: an unreachable socket is output.CodeUnreachable, a refused socket output.CodePermission, an expired deadline output.CodeTimeout, a cancelled context output.CodeRuntime wrapping context.Canceled, an unknown container output.CodeNotFound, an oversized or invalid answer output.CodeRuntime, and a malformed container reference output.CodeInvalidRequest. On Windows New returns an *Error that wraps errors.ErrUnsupported.

Logs returns a LogStream of lines with the Engine's timestamp and their source (stdout or stderr). Only the wait for the answer's headers is bounded by Options.Timeout; a following stream then ends with the context passed to Logs or with Close.

Start, Stop and Restart return nil once the Engine accepted the action; starting or stopping a container that is already in that state is not an error. A request may run for Options.Timeout plus the grace. WaitHealthy polls Inspect until each container runs and, if it has a health check, is healthy, or until WaitOptions.Deadline. It reports one WaitResult per reference, in order; a container that failed is a result with a WaitReason, not an error. An exited or missing container is final at once, a failing health check is watched until the deadline.

Always enforced

The package opens no TCP or TLS connection, uses no proxy and reads neither environment variables nor the contexts of other tools. The socket must be an absolute path. A request is bounded by Options.Timeout and a redirect is an error. A container reference must be a valid ID or name of at most 255 characters. Every answer except a log stream is read only up to a limit, and an oversized one is an output.CodeRuntime error. A list or a wait covers at most MaxContainers containers, and more is an error rather than a silent cut.

A server below MinAPIVersion, or one that reports no valid version, is refused. An *Error message never carries an answer body, a header or a value of the container. Environment variables of a container are returned by name only; the values are dropped while the answer is decoded.

The multiplexed framing of a log stream is checked strictly: an unknown source, a non-zero reserved byte, an oversized frame, a stream that ends inside a frame and a line without a valid timestamp are output.CodeRuntime errors, not a silent end. A line is cut at the line limit at a character boundary and marked Truncated, and invalid UTF-8 is replaced by U+FFFD. The delivery rate is enforced by backpressure: Next waits instead of dropping lines. Logs refuses negative limits, a limit above MaxLogLineBytes, a time before 1970 and an Until before Since. Logs adds no end of its own to a followed stream.

The grace period of Stop and Restart is at most MaxGrace and is rounded up to whole seconds; a negative or larger one is output.CodeInvalidRequest. WaitHealthy refuses an empty or repeated reference list and a negative deadline or interval, raises a shorter interval to MinWaitInterval and checks the deadline between polls, with one last poll at the deadline.

Access to the Docker socket is practically root access to the host. The application decides who may use a Client. Names, labels, images and paths in the answers, and log text, are text that images and users control; a caller masks them and their control characters before it shows them.

Options

  • Options.Timeout: bounds every request. Default: DefaultTimeout, 30 seconds.
  • LogOptions.Since: limits the stream to lines at or after a time; to follow only new lines, set it to time.Now with Follow. Default: from the start.
  • LogOptions.Until: limits the stream to lines at or before a time; with Follow the stream ends only when the Engine ends it. Default: no end.
  • LogOptions.Tail: limits the stream to the last n lines. Default: all lines.
  • LogOptions.Follow: keeps the stream open and delivers new lines until the context ends or the stream is closed. Default: the stream ends with the log.
  • LogOptions.MaxLineBytes: bounds the text of one line. Default: DefaultLogLineBytes, 16 KiB.
  • LogOptions.MaxLinesPerSecond: bounds the delivery rate. Default: DefaultLogLinesPerSecond, 1000.
  • The grace argument of Stop and Restart: how long the Engine waits for the container to stop. Default: zero selects the Engine's default.
  • WaitOptions.Deadline: bounds the whole wait. Default: DefaultWaitDeadline, 60 seconds.
  • WaitOptions.Interval: the pause between two polls. Default: DefaultWaitInterval, 1 second.

Index

Constants

View Source
const (
	MinAPIVersion = "1.41"
	MaxAPIVersion = "1.52"
)

The range of Engine API versions this package speaks. The version used is the lower of the server's and MaxAPIVersion; a server below MinAPIVersion is refused.

View Source
const (
	DefaultLogLineBytes      = 16 << 10
	MaxLogLineBytes          = 1 << 20
	DefaultLogLinesPerSecond = 1000
)

Bounds of a log stream. A zero LogOptions.MaxLineBytes or MaxLinesPerSecond selects the default.

View Source
const (
	DefaultWaitDeadline = 60 * time.Second
	DefaultWaitInterval = time.Second
	MinWaitInterval     = 100 * time.Millisecond
)

Bounds of WaitHealthy. A zero WaitOptions.Deadline or Interval selects the default; a shorter Interval is raised to MinWaitInterval.

View Source
const DefaultTimeout = 30 * time.Second

DefaultTimeout bounds a request when Options.Timeout is zero.

View Source
const (
	MaxContainers = 1024
)

Limits on what is read from the Engine and on how many containers List inspects.

View Source
const (
	// MaxGrace bounds the grace period of Stop and Restart.
	MaxGrace = time.Hour
)

Variables

View Source
var ErrUnsupportedAPIVersion = errors.New("docker: engine API version is not supported")

ErrUnsupportedAPIVersion is the cause of the Error returned when the server speaks a version below MinAPIVersion.

Functions

func Group

func Group(cs []Container) (projects []Project, loose []Container)

Group splits cs by the Compose project label. Containers with the same project name and working directory form one Project, whose config files are those of its first container (by name) that has any. Containers without a project label are returned as loose. Both results are sorted, and cs is not changed.

Types

type Client

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

Client talks to one Engine over its Unix socket. It is safe for concurrent use.

func New

func New(opts Options) (*Client, error)

New returns a Client for the socket in opts. It does not connect.

func (*Client) Close

func (c *Client) Close()

Close releases idle connections. The Client stays usable.

func (*Client) Inspect

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

Inspect returns the details of a container named by ID or name. Status of the result is empty.

func (*Client) List

func (c *Client) List(ctx context.Context) ([]Container, error)

List returns all containers, also stopped ones, sorted by name. It inspects each container for its health, start time and restart count.

func (*Client) Logs

func (c *Client) Logs(ctx context.Context, ref string, opts LogOptions) (*LogStream, error)

Logs opens the log of a container named by ID or name. Lines carry the Engine's timestamp and their source; a container with a terminal has a single stream, reported as SourceStdout. A line of one source that spans several frames is joined. The stream ends with io.EOF when the log ends, or never with Follow. Request timeouts apply to the answer's headers only: afterwards the context and Close end the stream.

func (*Client) Restart

func (c *Client) Restart(ctx context.Context, ref string, grace time.Duration) error

Restart stops a container as Stop does and starts it again.

func (*Client) Start

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

Start starts a stopped container. A container that already runs is not an error.

func (*Client) Stats

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

Stats reads the resource use of a container once. The request asks for two samples, so the reading covers the interval between them. A stopped container yields zero values if the Engine answers so.

func (*Client) Stop

func (c *Client) Stop(ctx context.Context, ref string, grace time.Duration) error

Stop stops a container: the Engine signals it and kills it after grace. Zero grace selects the Engine's default, a negative or larger than MaxGrace one is output.CodeInvalidRequest, and a fraction of a second is rounded up. A container that is already stopped is not an error.

func (*Client) UsingPath

func (c *Client) UsingPath(ctx context.Context, dir string) ([]Details, error)

UsingPath returns the containers that use dir: a mount source or the Compose working directory is dir or lies below it. dir must be absolute.

func (*Client) WaitHealthy

func (c *Client) WaitHealthy(ctx context.Context, refs []string, opts WaitOptions) ([]WaitResult, error)

WaitHealthy polls the containers until each one runs and, if it has a health check, is healthy, or until the deadline. A container that is exited or dead, or not found, is final at once and not polled again; a failing health check is watched until the deadline because it can recover. The deadline is checked between polls, so a poll in flight finishes first (bounded by Options.Timeout), and one last poll runs at the deadline. A container that failed is reported in the results; the error is only for an invalid call, a failing Engine and a cancelled context. refs must be non-empty, valid, distinct as written and at most MaxContainers.

type Container

type Container struct {
	ID    string
	Name  string // without the leading slash
	Image string
	// State is the Engine's state word, such as running or exited.
	State string
	// Status is the Engine's human readable text; empty in Details.
	Status string
	// Health is empty without a health check, otherwise starting, healthy or unhealthy.
	Health       string
	StartedAt    time.Time // zero if the container never started
	RestartCount int
	Labels       map[string]string
}

Container is one container as List reports it. All text comes from the Engine and its images and is not trustworthy: a caller masks it before it shows it.

type Details

type Details struct {
	Container
	Ports    []Port
	Mounts   []Mount
	Networks []Network
	EnvNames []string
}

Details is a Container with what Inspect adds. It holds the names of the environment variables but has no place for their values.

func (Details) UsesPath

func (d Details) UsesPath(dir string) bool

UsesPath reports whether a mount source or the Compose working directory of d is dir or lies below it. Paths are compared lexically as cleaned slash paths, with a boundary at a separator, so /srv/app does not include /srv/apple. Symbolic links are not resolved. A relative dir matches nothing.

type Error

type Error struct {
	Code    output.Code
	Message string
	// contains filtered or unexported fields
}

Error is a failed operation. Message never carries an answer body, a header or a value of the container; Unwrap yields only a cause that carries none either, such as a context error.

func (*Error) Error

func (e *Error) Error() string

func (*Error) Unwrap

func (e *Error) Unwrap() error

Unwrap returns the cause, or nil.

type LogLine

type LogLine struct {
	Time      time.Time
	Source    Source
	Text      string // without the line end; invalid UTF-8 is replaced by U+FFFD
	Truncated bool   // the line was longer than MaxLineBytes and the rest was dropped
}

LogLine is one line of a container's output. Text is untrusted: a caller masks control characters before it shows it.

type LogOptions

type LogOptions struct {
	// Since limits the stream to lines at or after this time; zero means from the start. To follow only
	// new lines, set Follow with Since to time.Now().
	Since time.Time
	// Until limits the stream to lines at or before this time; zero means without an end. With Follow the
	// stream ends when the Engine ends it; Logs adds no end of its own.
	Until time.Time
	// Tail limits the stream to the last n lines; zero means all lines.
	Tail int
	// Follow keeps the stream open and delivers new lines until the context ends or the stream is closed.
	Follow bool
	// MaxLineBytes bounds the text of one line. A longer line is cut at a character boundary and marked
	// Truncated. Zero means DefaultLogLineBytes; more than MaxLogLineBytes is refused.
	MaxLineBytes int
	// MaxLinesPerSecond bounds the delivery rate. Next waits instead of dropping lines. Zero means
	// DefaultLogLinesPerSecond; a negative value is refused.
	MaxLinesPerSecond int
}

LogOptions selects and bounds the lines Logs returns. The zero value reads every line from the start without following.

type LogStream

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

LogStream delivers log lines in order. Next must not be called concurrently with itself; Close may be called at any time from any goroutine.

func (*LogStream) Close

func (s *LogStream) Close() error

Close ends the stream and unblocks a pending Next. It is safe to call more than once.

func (*LogStream) Next

func (s *LogStream) Next() (LogLine, error)

Next returns the next line, or io.EOF at the end of the log. After an error every call returns it again.

type Mount

type Mount struct {
	Type        string
	Name        string // volume name, if any
	Source      string
	Destination string
	ReadOnly    bool
}

Mount is a mount of a container. Type is volume, bind, tmpfs or another type the Engine reports.

type Network

type Network struct {
	Name      string
	IPAddress string
}

Network is a network a container is attached to.

type Options

type Options struct {
	// Socket is the absolute path of the Engine's Unix socket. It is required; nothing is read from the
	// environment or from other tools' configuration.
	Socket string
	// Timeout bounds every request. Zero means DefaultTimeout.
	Timeout time.Duration
}

Options configures a Client.

type Port

type Port struct {
	PrivatePort int
	PublicPort  int
	Protocol    string
	HostIP      string
}

Port is a port of a container; PublicPort and HostIP are zero or empty if it is not published.

type Project

type Project struct {
	Name        string
	WorkingDir  string
	ConfigFiles []string
	Containers  []Container
}

Project is the set of containers of one Compose project, taken from their labels.

type Source

type Source string

Source is the output stream a log line was written to.

const (
	SourceStdout Source = "stdout"
	SourceStderr Source = "stderr"
)

type Stats

type Stats struct {
	// CPUPercent is the share of all CPUs as Docker shows it: 100 per fully used CPU, so it may exceed 100.
	CPUPercent float64
	// MemoryUsed is the memory in use without the reclaimable page cache.
	MemoryUsed  uint64
	MemoryLimit uint64
}

Stats is a single reading of a container's resource use.

type WaitOptions

type WaitOptions struct {
	// Deadline bounds the whole wait. Zero means DefaultWaitDeadline; negative is output.CodeInvalidRequest.
	Deadline time.Duration
	// Interval is the pause between two polls. Zero means DefaultWaitInterval.
	Interval time.Duration
}

WaitOptions configures WaitHealthy.

type WaitReason

type WaitReason string

WaitReason says why a container was not healthy when WaitHealthy ended.

const (
	ReasonNotFound   WaitReason = "not-found"
	ReasonExited     WaitReason = "exited"      // exited or dead; not waited for any longer
	ReasonRestarting WaitReason = "restarting"  // still restarting at the deadline
	ReasonNotRunning WaitReason = "not-running" // created or paused at the deadline
	ReasonUnhealthy  WaitReason = "unhealthy"   // health check failing at the deadline
	ReasonStarting   WaitReason = "starting"    // health check not yet passed at the deadline
)

The reasons of a WaitResult that is not OK.

type WaitResult

type WaitResult struct {
	Ref string
	// Name is the container's name; empty if it was not found. It is the Engine's text and not trustworthy.
	Name string
	OK   bool
	// Reason is empty if OK.
	Reason WaitReason
}

WaitResult is the outcome for one container, in the order of the references passed to WaitHealthy.

Jump to

Keyboard shortcuts

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