docker

package
v0.47.8 Latest Latest
Warning

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

Go to latest
Published: Oct 24, 2026 License: MIT Imports: 15 Imported by: 0

Documentation

Overview

Package docker provides Docker SDK client and operations.

Package docker provides a wrapper around the Docker API for bosun operations.

The Client type handles container lifecycle operations including listing, inspecting, starting, stopping, and collecting stats. The ComposeClient type manages docker-compose orchestration for stack deployments.

Interface Abstraction

The DockerAPI interface abstracts the Docker SDK, enabling mock injection for testing. Use NewTestableClient for test scenarios.

Example

client, err := docker.NewClient()
if err != nil {
    return err
}
defer client.Close()

containers, err := client.ListContainers(ctx, true)
for _, c := range containers {
    fmt.Printf("%s: %s\n", c.Name, c.Status)
}

Package docker provides Docker SDK client and operations.

Index

Constants

View Source
const MaxLogSize = 100 * 1024 * 1024

MaxLogSize is the maximum size of logs to read (100MB).

Variables

This section is empty.

Functions

This section is empty.

Types

type Client

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

Client wraps the Docker SDK client.

func NewClient

func NewClient() (*Client, error)

NewClient creates a new Docker client connection and validates daemon connectivity.

func NewClientWithAPI

func NewClientWithAPI(api DockerAPI) *Client

NewClientWithAPI creates a new Docker client with a custom API implementation. This is primarily used for testing with mock implementations.

func (*Client) Close

func (c *Client) Close() error

Close closes the Docker client connection.

func (*Client) CountContainers

func (c *Client) CountContainers(ctx context.Context) (running, total, unhealthy int, err error)

CountContainers returns counts of running, total, and unhealthy containers.

func (*Client) DiskUsage

func (c *Client) DiskUsage(ctx context.Context) (client.DiskUsageResult, error)

DiskUsage returns Docker system disk usage information.

The moby client computes usage per-category on demand; Volumes is requested explicitly so callers (e.g. the status dashboard) can read volume totals.

func (*Client) ExecContainer added in v0.25.0

func (c *Client) ExecContainer(ctx context.Context, name string, cmd []string) error

ExecContainer runs a command inside a running container and waits for completion. Returns an error if the command exits with a non-zero status.

func (*Client) Exists

func (c *Client) Exists(ctx context.Context, name string) (bool, error)

Exists checks if a container with the given name exists (running or stopped).

func (*Client) GetAllContainerStats

func (c *Client) GetAllContainerStats(ctx context.Context) ([]ContainerStats, error)

GetAllContainerStats returns stats for all running containers. Containers that fail to return stats are logged and skipped.

func (*Client) GetContainerByName

func (c *Client) GetContainerByName(ctx context.Context, name string) (*ContainerInfo, error)

GetContainerByName returns a container by its name.

func (*Client) GetContainerImage

func (c *Client) GetContainerImage(ctx context.Context, name string) (string, error)

GetContainerImage returns the image name for a running container.

func (*Client) GetContainerLogs

func (c *Client) GetContainerLogs(ctx context.Context, name string, tail int) (string, error)

GetContainerLogs returns the last n lines of logs from a container. Logs are limited to MaxLogSize (100MB) to prevent memory exhaustion.

func (*Client) GetContainerStats

func (c *Client) GetContainerStats(ctx context.Context, name string) (*ContainerStats, error)

GetContainerStats returns resource usage for a container.

func (*Client) Info

func (c *Client) Info(ctx context.Context) (system.Info, error)

Info returns system-wide information about the Docker daemon.

func (*Client) Inspect

func (c *Client) Inspect(ctx context.Context, name string) (*ContainerDetails, error)

Inspect returns detailed information about a container.

func (*Client) IsContainerRunning

func (c *Client) IsContainerRunning(ctx context.Context, name string) bool

IsContainerRunning checks if a container with the given name is running.

func (*Client) ListContainers

func (c *Client) ListContainers(ctx context.Context, runningOnly bool) ([]ContainerInfo, error)

ListContainers returns all containers (running and stopped).

func (*Client) Logs

func (c *Client) Logs(ctx context.Context, name string, tail int, follow bool) (io.ReadCloser, error)

Logs returns a reader for container logs (streaming).

IMPORTANT: The caller MUST close the returned io.ReadCloser when done to avoid goroutine leaks. If following logs (follow=true), the reader will block until the context is cancelled or the container stops.

For non-streaming use cases, prefer GetContainerLogs which handles cleanup automatically.

func (*Client) Ping

func (c *Client) Ping(ctx context.Context) error

Ping tests the connection to the Docker daemon.

func (*Client) Raw

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

Raw returns the underlying Docker client for advanced operations.

func (*Client) Remove

func (c *Client) Remove(ctx context.Context, name string, force bool) error

Remove removes a container.

func (*Client) RemoveContainer

func (c *Client) RemoveContainer(ctx context.Context, name string) error

RemoveContainer forcefully removes a container by name.

func (*Client) RestartContainer

func (c *Client) RestartContainer(ctx context.Context, name string, timeout ...int) error

RestartContainer restarts a container by name with the given timeout (seconds). The timeout controls the grace period between SIGTERM and SIGKILL during the stop phase.

func (*Client) Start

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

Start starts a stopped container.

func (*Client) StopContainer added in v0.20.0

func (c *Client) StopContainer(ctx context.Context, name string, timeout int) error

StopContainer gracefully stops a container with the given timeout.

type ComposeClient

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

ComposeClient handles docker compose operations.

func NewComposeClient

func NewComposeClient(file, project string) (*ComposeClient, error)

NewComposeClient creates a new compose client for the given compose file and project name. The project name ensures consistent container namespacing and proper orphan detection. Returns an error if the compose file does not exist.

func (*ComposeClient) Down

func (c *ComposeClient) Down(ctx context.Context) error

Down stops and removes services defined in the compose file.

func (*ComposeClient) DownWithTimeout added in v0.27.0

func (c *ComposeClient) DownWithTimeout(ctx context.Context, timeoutSeconds int) error

DownWithTimeout stops and removes services with a custom shutdown timeout. The timeout is the grace period (in seconds) between SIGTERM and SIGKILL for each container.

func (*ComposeClient) Ps

func (c *ComposeClient) Ps(ctx context.Context) (string, error)

Ps runs docker compose ps and returns the raw output.

func (*ComposeClient) Restart

func (c *ComposeClient) Restart(ctx context.Context, services ...string) error

Restart restarts services defined in the compose file.

func (*ComposeClient) Status

func (c *ComposeClient) Status(ctx context.Context) ([]ServiceStatus, error)

Status returns the status of services in the compose file.

func (*ComposeClient) Up

func (c *ComposeClient) Up(ctx context.Context, services ...string) error

Up starts services defined in the compose file.

type ContainerDetails

type ContainerDetails struct {
	ID                  string // Short (12-character) ID for display and state.
	FullID              string // Full daemon ID; use it to act on exactly the inspected container.
	Name                string
	Image               string
	State               string
	Status              string
	Health              string
	HealthFailingStreak int
	HealthLog           *HealthCheckLog // Last health check result (nil if no health checks)
	Ports               []PortBinding
	Networks            []string
	Volumes             []string
	Environment         []string
	Labels              map[string]string
	Created             time.Time
	Started             time.Time
	RestartCount        int
	Platform            string
	Driver              string
}

ContainerDetails holds detailed container information.

type ContainerInfo

type ContainerInfo struct {
	ID      string
	Name    string
	Image   string
	Status  string
	State   string
	Health  string
	Created time.Time
	Uptime  string
	Ports   []string
	Labels  map[string]string
}

ContainerInfo holds summary information about a container.

type ContainerStats

type ContainerStats struct {
	Name       string
	CPUPercent float64
	MemUsage   uint64
	MemLimit   uint64
	MemPercent float64
}

ContainerStats holds resource usage statistics.

type DockerAPI

type DockerAPI interface {
	// Ping tests the connection to the Docker daemon.
	Ping(ctx context.Context, options client.PingOptions) (client.PingResult, error)

	// ContainerList returns a list of containers.
	ContainerList(ctx context.Context, options client.ContainerListOptions) (client.ContainerListResult, error)

	// ContainerInspect returns detailed information about a container.
	ContainerInspect(ctx context.Context, containerID string, options client.ContainerInspectOptions) (client.ContainerInspectResult, error)

	// ContainerLogs returns logs from a container.
	ContainerLogs(ctx context.Context, containerID string, options client.ContainerLogsOptions) (client.ContainerLogsResult, error)

	// ContainerStart starts a stopped container.
	ContainerStart(ctx context.Context, containerID string, options client.ContainerStartOptions) (client.ContainerStartResult, error)

	// ContainerStop stops a container with a grace period.
	ContainerStop(ctx context.Context, containerID string, options client.ContainerStopOptions) (client.ContainerStopResult, error)

	// ContainerRestart restarts a container.
	ContainerRestart(ctx context.Context, containerID string, options client.ContainerRestartOptions) (client.ContainerRestartResult, error)

	// ContainerRemove removes a container.
	ContainerRemove(ctx context.Context, containerID string, options client.ContainerRemoveOptions) (client.ContainerRemoveResult, error)

	// ContainerStats returns container resource usage statistics.
	ContainerStats(ctx context.Context, containerID string, options client.ContainerStatsOptions) (client.ContainerStatsResult, error)

	// ExecCreate creates an exec instance in a container.
	ExecCreate(ctx context.Context, containerID string, options client.ExecCreateOptions) (client.ExecCreateResult, error)

	// ExecAttach attaches to an exec instance and returns a connection.
	ExecAttach(ctx context.Context, execID string, options client.ExecAttachOptions) (client.ExecAttachResult, error)

	// ExecInspect returns information about an exec instance.
	ExecInspect(ctx context.Context, execID string, options client.ExecInspectOptions) (client.ExecInspectResult, error)

	// DiskUsage returns Docker system disk usage information.
	DiskUsage(ctx context.Context, options client.DiskUsageOptions) (client.DiskUsageResult, error)

	// Info returns system-wide information about the Docker daemon.
	Info(ctx context.Context, options client.InfoOptions) (client.SystemInfoResult, error)

	// Close closes the client connection.
	Close() error
}

DockerAPI defines the interface for Docker client operations. This interface enables mocking for unit tests without requiring a running Docker daemon.

The method set mirrors the moby split-module client (github.com/moby/moby/client) so that *client.Client satisfies it directly. Every method takes an options struct and returns a *Result wrapper, matching the moby client conventions.

type HealthCheckLog added in v0.15.0

type HealthCheckLog struct {
	ExitCode int
	Output   string
}

HealthCheckLog holds the last health check result for a container.

type PortBinding

type PortBinding struct {
	ContainerPort string
	HostPort      string
	Protocol      string
}

PortBinding represents a container port binding.

type ServiceStatus

type ServiceStatus struct {
	Name    string
	State   string
	Status  string
	Ports   string
	Running bool
}

ServiceStatus represents the status of a docker compose service.

type TestableClient

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

TestableClient is a variant of Client that accepts a DockerAPI interface. This allows injecting mocks for testing.

func NewTestableClient

func NewTestableClient(api DockerAPI) *TestableClient

NewTestableClient creates a new testable Docker client with the given API implementation.

func (*TestableClient) API

func (c *TestableClient) API() DockerAPI

API returns the underlying Docker API for advanced operations.

func (*TestableClient) Close

func (c *TestableClient) Close() error

Close closes the Docker client connection.

Directories

Path Synopsis
Package dockertest provides test utilities for the docker package.
Package dockertest provides test utilities for the docker package.

Jump to

Keyboard shortcuts

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