Documentation
¶
Overview ¶
Package docker reads containers from a Docker Engine over its Unix socket: the container list, the details of one container with its health check, 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, the container events of the Engine as a stream, 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.
Events returns an EventStream of the Engine's container events, optionally of one Compose project; the Engine applies the filter. It never reconnects. To resume after the stream ended, pass the Time of the last Event as EventOptions.Since. The Engine keeps only a short history of recent events, a few hundred counted over all object types before any filter; an older one is gone, and a gap is not visible in the stream. After a resume the application reads the current state again. The Engine includes an event with exactly the time of Since, so the last event can arrive a second time.
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 or event 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 health check of a container is the opposite: its command and the output of its latest runs are returned as the Engine reports them, unmasked, and can hold passwords. A health check result keeps at most MaxHealthResults runs, the latest, and each output is cut at MaxHealthOutputBytes at a character boundary, marked Truncated, with invalid UTF-8 replaced by U+FFFD.
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.
An event stream is read line by line up to a size limit. An oversized line, invalid JSON, an event without a time and an event that is not a container event are output.CodeRuntime errors, because JSON cannot be cut. The Engine ending the stream between two events is io.EOF; an end inside an event is an output.CodeRuntime error. An error stays: every later Next returns it. The delivery rate is enforced by backpressure, as in a log stream. Events refuses a Project other than lowercase letters, digits, '-' and '_', a Since before 1970 and negative or too large limits, before it sends a request.
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, health check commands and outputs, log text, and the Action and Attributes of an event are text that images and users control; Action and Attributes can hold command lines, for example for exec_create. An *Error never carries them. 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.
- EventOptions.Project: limits the stream to the containers of one Compose project. Default: all containers.
- EventOptions.Since: replays buffered events at or after a time before new ones. Default: new events only.
- EventOptions.MaxEventBytes: bounds the JSON text of one event. Default: DefaultEventBytes, 64 KiB; the maximum is MaxEventBytes, 1 MiB.
- EventOptions.MaxEventsPerSecond: bounds the delivery rate. Default: DefaultEventsPerSecond, 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
- Variables
- func Group(cs []Container) (projects []Project, loose []Container)
- type Client
- func (c *Client) Close()
- func (c *Client) Events(ctx context.Context, opts EventOptions) (*EventStream, error)
- func (c *Client) Inspect(ctx context.Context, ref string) (Details, error)
- func (c *Client) List(ctx context.Context) ([]Container, error)
- func (c *Client) Logs(ctx context.Context, ref string, opts LogOptions) (*LogStream, error)
- func (c *Client) Restart(ctx context.Context, ref string, grace time.Duration) error
- func (c *Client) Start(ctx context.Context, ref string) error
- func (c *Client) Stats(ctx context.Context, ref string) (Stats, error)
- func (c *Client) Stop(ctx context.Context, ref string, grace time.Duration) error
- func (c *Client) UsingPath(ctx context.Context, dir string) ([]Details, error)
- func (c *Client) WaitHealthy(ctx context.Context, refs []string, opts WaitOptions) ([]WaitResult, error)
- type Container
- type Details
- type Error
- type Event
- type EventOptions
- type EventStream
- type HealthCheck
- type HealthResult
- type LogLine
- type LogOptions
- type LogStream
- type Mount
- type Network
- type Options
- type Port
- type Project
- type Source
- type Stats
- type WaitOptions
- type WaitReason
- type WaitResult
Constants ¶
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.
const ( DefaultEventBytes = 64 << 10 MaxEventBytes = 1 << 20 DefaultEventsPerSecond = 1000 )
Bounds of an event stream. A zero EventOptions.MaxEventBytes or MaxEventsPerSecond selects the default.
const ( // MaxHealthOutputBytes bounds the output of one HealthResult; a longer output is cut at a character // boundary and marked Truncated. MaxHealthOutputBytes = 4 << 10 // MaxHealthResults bounds HealthCheck.Results; of more, the latest are kept. MaxHealthResults = 5 )
Limits on the health check results in Details.
const ( DefaultLogLineBytes = 16 << 10 MaxLogLineBytes = 1 << 20 DefaultLogLinesPerSecond = 1000 )
Bounds of a log stream. A zero LogOptions.MaxLineBytes or MaxLinesPerSecond selects the default.
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.
const DefaultTimeout = 30 * time.Second
DefaultTimeout bounds a request when Options.Timeout is zero.
const (
MaxContainers = 1024
)
Limits on what is read from the Engine and on how many containers List inspects.
const ( // MaxGrace bounds the grace period of Stop and Restart. MaxGrace = time.Hour )
Variables ¶
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 ¶
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 (*Client) Close ¶
func (c *Client) Close()
Close releases idle connections. The Client stays usable.
func (*Client) Events ¶ added in v0.32.0
func (c *Client) Events(ctx context.Context, opts EventOptions) (*EventStream, error)
Events opens the stream of container events, limited to one Compose project if opts.Project is set. The stream ends with io.EOF when the Engine ends it between two events. Request timeouts apply to the answer's headers only: afterwards the context and Close end the stream. Events never reconnects.
func (*Client) Inspect ¶
Inspect returns the details of a container named by ID or name. Status of the result is empty.
func (*Client) List ¶
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 ¶
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) Start ¶
Start starts a stopped container. A container that already runs is not an error.
func (*Client) Stats ¶
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 ¶
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 ¶
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
HealthCheck *HealthCheck
}
Details is a Container with what Inspect adds. It holds the names of the environment variables but has no place for their values. HealthCheck is nil without a health check.
func (Details) UsesPath ¶
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 ¶
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.
type Event ¶ added in v0.32.0
type Event struct {
Time time.Time
Type string // always "container"
Action string // for example "start", "die" or "health_status: healthy"
ActorID string // the container ID
Attributes map[string]string
}
Event is one container event of the Engine. Action and Attributes are untrusted: they can carry command lines, labels and other text that images and users control.
type EventOptions ¶ added in v0.32.0
type EventOptions struct {
// Project limits the stream to the containers of one Compose project; empty means all containers. Only
// lowercase letters, digits, '-' and '_' are accepted.
Project string
// Since replays buffered events at or after this time before it streams new ones; zero means new
// events only. Pass the time of the last event received to resume after the stream ended.
Since time.Time
// MaxEventBytes bounds the JSON text of one event. A larger event ends the stream with an error. Zero
// means DefaultEventBytes; more than MaxEventBytes is refused.
MaxEventBytes int
// MaxEventsPerSecond bounds the delivery rate. Next waits instead of dropping events. Zero means
// DefaultEventsPerSecond; a negative value is refused.
MaxEventsPerSecond int
}
EventOptions selects and bounds the events Events returns. The zero value streams the events of all containers that happen from now on.
type EventStream ¶ added in v0.32.0
type EventStream struct {
// contains filtered or unexported fields
}
EventStream delivers container events in order. Next must not be called concurrently with itself; Close may be called at any time from any goroutine.
func (*EventStream) Close ¶ added in v0.32.0
func (s *EventStream) Close() error
Close ends the stream and unblocks a pending Next. It is safe to call more than once.
func (*EventStream) Next ¶ added in v0.32.0
func (s *EventStream) Next() (Event, error)
Next returns the next event, or io.EOF when the Engine ended the stream between two events. After an error every call returns it again.
type HealthCheck ¶ added in v0.30.0
type HealthCheck struct {
// Test is the command as the Engine stores it, such as ["CMD-SHELL", "curl -f http://localhost/"].
Test []string
// Interval, Timeout, StartPeriod and StartInterval are zero if the Engine's default applies.
// StartInterval needs API version 1.44 and is zero below it.
Interval, Timeout, StartPeriod, StartInterval time.Duration
Retries int
// FailingStreak is the number of consecutive failures.
FailingStreak int
// Results are the latest results, oldest first, at most MaxHealthResults; empty before the first run.
Results []HealthResult
}
HealthCheck is the health check of a container: its definition and its latest results. Test and the results' Output come from the container and its image, are not masked and can hold passwords after the Engine resolved variables; a caller masks them before it shows them.
type HealthResult ¶ added in v0.30.0
HealthResult is one run of a health check. Start and End are zero if the Engine reports none or an invalid time.
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.
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 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 ¶
Port is a port of a container; PublicPort and HostIP are zero or empty if it is not published.
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.