container

package
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Nov 17, 2026 License: Apache-2.0 Imports: 23 Imported by: 1 module, 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 container collects container metrics and events from the Docker Engine API (unix socket or Windows named pipe) and, on Linux, from cgroup v2 files for containerd and podman.

Index

Constants

View Source
const ComposeProjectLabel = "com.docker.compose.project"

ComposeProjectLabel is the label docker compose puts on every container of a project.

View Source
const ComposeServiceLabel = "com.docker.compose.service"

ComposeServiceLabel is the label docker compose puts the service name in.

View Source
const DefaultCgroupRoot = "/sys/fs/cgroup"

DefaultCgroupRoot is where cgroup v2 is mounted.

View Source
const ScopeSelf = "self"

ScopeSelf limits the Docker modules to the compose project of the agent's own container.

Variables

This section is empty.

Functions

func ApplyScope added in v0.4.0

func ApplyScope(ctx context.Context, module, scope string, labels *LabelSet, get func(string, any) error) error

ApplyScope sets labels to the own compose project when scope (or WT_AGENT_SCOPE) is self.

func CgroupsAvailable added in v0.3.4

func CgroupsAvailable() bool

CgroupsAvailable is true when no Docker socket exists but the cgroup root is readable: the agent then starts the cgroups module on its own.

func DefaultHost

func DefaultHost() string

DefaultHost is the engine endpoint when the local config names none.

func HasLabels

func HasLabels(have map[string]string, want LabelSet) bool

HasLabels reports whether have carries every key of want with one of its values.

func ImageIntegration added in v0.3.4

func ImageIntegration(image string) string

ImageIntegration maps an image reference (registry/name:tag@digest) to an integration name by its last path segment, or "".

func LabelFilter

func LabelFilter(labels LabelSet) []string

LabelFilter is the Engine API `label` filter for labels: sorted "k=v" values. The engine ANDs its filters, so a key with several accepted values is sent as "k" (present) and HasLabels does the any-of check.

func Learn added in v0.4.0

func Learn(id string, l Learned)

Learn remembers l for the container id (full id or a prefix of at least 12 characters).

func MatchedSummary added in v0.3.4

func MatchedSummary(cs []Info) string

MatchedSummary lists "name(id12)" of cs, sorted, for the startup and change log.

func ParseCPUStat

func ParseCPUStat(s string) (uint64, bool)

ParseCPUStat returns usage_usec of a cgroup v2 cpu.stat file, in nanoseconds.

func ParseIOStat added in v0.3.4

func ParseIOStat(s string) (read, write uint64)

ParseIOStat sums rbytes and wbytes over the devices of a cgroup v2 io.stat file.

func ParseMemoryStat

func ParseMemoryStat(s, key string) uint64

ParseMemoryStat returns the value of key in a cgroup v2 flat-keyed file such as memory.stat.

func ProjectsIn added in v0.4.0

func ProjectsIn(cs []Info) int

ProjectsIn counts the distinct compose projects among cs.

func PromName

func PromName(name string) string

PromName converts an OTLP metric name to a PromQL-safe one: every character outside [a-zA-Z0-9_:] becomes an underscore (container.cpu.usage -> container_cpu_usage).

func ResolveSelfScope added in v0.4.0

func ResolveSelfScope(ctx context.Context, module string, get func(path string, v any) error) (string, error)

ResolveSelfScope blocks until the agent's own compose project is known and returns it. It never returns without one except when ctx ends: scope self must not fall back to every container.

func Run

func Run(ctx context.Context, raw json.RawMessage, out sink.Sink) error

Run polls until ctx ends. A missing engine is not an error: the module keeps trying and the cgroup scan still reports.

func RunCgroups added in v0.3.4

func RunCgroups(ctx context.Context, raw json.RawMessage, out sink.Sink) error

RunCgroups reports containers from a (read-only) cgroup v2 mount, with no Docker socket.

func SelfContainerID added in v0.4.0

func SelfContainerID(cgroup, mountinfo string) string

SelfContainerID returns the agent's own container id from the text of /proc/self/cgroup (cgroup v1 "N:ctrl:/docker/<id>", v2 "0::/system.slice/docker-<id>.scope", cgroupfs or systemd, kubepods) or, failing that, /proc/self/mountinfo. "" when neither names one.

func SelfProject added in v0.4.0

func SelfProject(get func(path string, v any) error, cgroup, mountinfo, hostname string) (string, error)

SelfProject inspects only the agent's own container (by id, else by hostname, which Docker sets to the short id) and returns its compose project label. get is a GET-and-decode on the engine.

func ServiceFromName added in v0.4.0

func ServiceFromName(name string) string

ServiceFromName guesses the compose service from a container name "<project>-<service>-<n>" (or with underscores): the name without its trailing replica number. The project prefix cannot be told from a dash in the service name, so the guess keeps it unless a compose.service label arrived with the record.

func WantsSelf added in v0.4.0

func WantsSelf(scope string) (bool, error)

WantsSelf is true when scope (a module's `scope` key) or WT_AGENT_SCOPE asks for `self`. Any other non-empty value is an error, never "all".

Types

type CG

type CG struct {
	ID         string
	Path       string // relative to the cgroup root, with a leading /
	CPUUsageNS uint64
	MemBytes   uint64
	// MemLimit is memory.max (0: unlimited); the rest are plain readings (Has* false when the file is absent).
	MemLimit, MemAnon, MemFile uint64
	IORead, IOWrite            uint64
	Pids                       uint64
	HasPids, HasIO             bool
	OOMKills                   uint64 // memory.events oom_kill
}

CG is one container's cgroup reading.

func ScanCgroups

func ScanCgroups(root string) []CG

ScanCgroups walks root (at most 8 levels, at most maxContainers hits) for container scopes and reads their CPU time and working-set memory (memory.current minus inactive_file).

type CgroupFilter added in v0.4.0

type CgroupFilter struct {
	// Parent keeps only cgroups under a directory of this name (a systemd slice "wt-x.slice" or a
	// cgroupfs path "/wt-x"): the `cgroup_parent` of the compose services.
	Parent string
	// Include (when non-empty) and Exclude are path.Match globs on the cgroup path and on the
	// container name when one is known. `*` does not cross `/`.
	Include, Exclude []string
	// IDs (when non-nil) keeps only these container ids (the engine's matched containers).
	IDs map[string]bool
	// Labels (when set) keeps only containers whose learned labels (from forwarded logs) match;
	// a container nothing is learned about yet is skipped, never reported by default.
	Labels LabelSet
}

CgroupFilter selects which container cgroups the socket-free scan reports. The zero value reports all of them. Paths are relative to the cgroup root with a leading "/", e.g. /system.slice/docker-<id>.scope or /wt-myapp.slice/docker-<id>.scope.

func (*CgroupFilter) Match added in v0.4.0

func (f *CgroupFilter) Match(cgPath, id, name string, labels map[string]string) bool

Match reports whether the cgroup at cgPath (container id, name when known) is reported.

type CgroupsConfig added in v0.3.4

type CgroupsConfig struct {
	Enabled    *bool  `json:"enabled"`
	Interval   string `json:"interval"`    // default 30s, at least 5s
	CgroupRoot string `json:"cgroup_root"` // default WT_AGENT_CGROUP_ROOT or /sys/fs/cgroup
	// Parent keeps only cgroups under this slice or path (compose `cgroup_parent`); env WT_AGENT_CGROUP_PARENT.
	Parent string `json:"parent"`
	// Include/Exclude are glob patterns on the cgroup path (and container name when known); see CgroupFilter.
	Include []string `json:"include"`
	Exclude []string `json:"exclude"`
	// Scope "self" (with the engine socket mounted) keeps only containers of the agent's own compose project.
	Scope string `json:"scope"`
	// Labels keeps only containers whose log-driver labels (logs.forward) match, like container.labels.
	Labels LabelSet `json:"labels"`
	// NamesFrom "off" stops naming and labelling containers from forwarded log records (default: used).
	NamesFrom string `json:"names_from"`
	// Health are extra probe targets; containers are also probed through their wt.health label.
	Health []HealthConfig `json:"health"`
}

CgroupsConfig is the `cgroups` module's config; the root is local-file only.

type Config

type Config struct {
	Enabled    *bool  `json:"enabled"`
	Interval   string `json:"interval"`    // default 30s, at least 5s
	DockerHost string `json:"docker_host"` // default: the platform's engine socket
	CgroupRoot string `json:"cgroup_root"` // default /sys/fs/cgroup on Linux; "off" disables
	Events     *bool  `json:"events"`      // default true
	// Labels limit the engine's containers and events to those carrying every label, each with one of its values (a string or a list; sent as a
	// server-side filter). Set, they also turn the cgroup scan off: it cannot see labels.
	Labels LabelSet `json:"labels"`
	// RequireLabels makes empty Labels collect nothing instead of every container (shared hosts).
	RequireLabels bool `json:"require_labels"`
	// Scope "self" (or WT_AGENT_SCOPE=self) sets Labels to the compose project of the agent's own
	// container, read by inspecting only that container. Unresolvable: nothing is collected.
	Scope string `json:"scope"`
	// Services maps a compose service name to the service, environment and version its
	// containers report when they carry no label or OTEL env of their own. Local file only.
	Services map[string]ServiceMap `json:"services"`
}

Config is the container module's config. Only Enabled and Interval can be set remotely; DockerHost and CgroupRoot are local-file only.

type Docker

type Docker struct {
	HTTP   *http.Client
	Labels LabelSet
}

Docker is a minimal Engine API client. The endpoint comes only from the agent's local file. Labels, when set, are sent as a server-side filter on list and events, so the engine never returns containers without every one of them (and List re-checks them).

func NewDocker

func NewDocker(endpoint string) (*Docker, error)

NewDocker accepts unix:///path and npipe:////./pipe/name endpoints.

func (*Docker) Env

func (d *Docker) Env(ctx context.Context, id string) ([]string, error)

Env returns the container's environment (NAME=value) from the engine.

func (*Docker) Events

func (d *Docker) Events(ctx context.Context, since time.Time, out sink.Sink) error

Events streams container events as log records until ctx ends or the stream breaks.

func (*Docker) Get added in v0.4.0

func (d *Docker) Get(ctx context.Context) func(string, any) error

Get is d's GET-and-decode bound to ctx, for ResolveSelfScope.

func (*Docker) List

func (d *Docker) List(ctx context.Context) ([]Info, error)

List returns the running containers (at most maxContainers).

func (*Docker) Stats

func (d *Docker) Stats(ctx context.Context, id string) (Stats, error)

Stats takes one sample (no streaming, no server-side wait).

type HealthConfig added in v0.4.0

type HealthConfig struct {
	Name     string `json:"name"`
	Target   string `json:"target"`
	Interval string `json:"interval"` // default 30s, at least 5s
	Timeout  string `json:"timeout"`  // default 5s, at most 30s
	Status   string `json:"status"`   // expected http status ("200", "2xx"); default any below 400
}

HealthConfig is one static `cgroups.health` entry (local file only).

type HealthTarget added in v0.4.0

type HealthTarget struct {
	Name     string // container or service the series is reported for
	URL      string // http://host:port/path, https://..., or tcp://host:port
	Interval time.Duration
	Timeout  time.Duration
	// Status is the expected http status: "200", or a class such as "2xx"; empty means below 400.
	Status string
}

HealthTarget is one probe the agent runs itself over the compose network (socket-free health).

func ParseHealth added in v0.4.0

func ParseHealth(name, service string, labels map[string]string) (HealthTarget, bool, error)

ParseHealth builds the target of a `wt.health` label value. The host may be empty (the container name) or the container's own name or compose service: a label comes from whoever can start containers, so it can never aim the agent at another host. Static config (trusted) passes any host through ParseHealthTarget.

func ParseHealthTarget added in v0.4.0

func ParseHealthTarget(name, target, interval, timeout, defHost, status string) (HealthTarget, error)

ParseHealthTarget parses a target URL; an empty host becomes defHost.

func StaticHealth added in v0.4.0

func StaticHealth(cfg []HealthConfig) ([]HealthTarget, error)

StaticHealth parses `cgroups.health`.

type Identity

type Identity struct{ Service, Environment, Version string }

Identity is the application a container runs, as the product shows it.

func ResolveIdentity

func ResolveIdentity(env []string, labels map[string]string, byCompose map[string]ServiceMap, name string) Identity

ResolveIdentity picks service.name, per W62, from the first non-empty of: the container's OTEL_SERVICE_NAME / OTEL_RESOURCE_ATTRIBUTES service.name env, a com.watchtower.service label, the agent.yaml compose-service map, the compose service name, then the container name. The environment and version resolve likewise (env, label, map). name is the last-resort service so a scraped container never inherits the agent's own service.name (wt-agent); pass "" for none.

func (Identity) Resource

func (i Identity) Resource() map[string]string

Resource returns the OTLP resource attributes (unprefixed) for the identity; nil when unknown. wt.internal=false overrides the agent's own marker (the agent resource carries wt.internal=true).

type Info

type Info struct {
	ID    string
	Name  string
	Image string
	// State is docker's state word (running, paused, restarting, exited, ...).
	State string
	// Labels are the container labels (watchtower.dev/* drive autodiscovery, see labels.go).
	Labels map[string]string
	// IP is the lowest network address; Ports the distinct private ports, ascending.
	IP    string
	Ports []int
}

Info is one listed container.

type LabelSet added in v0.4.0

type LabelSet map[string][]string

LabelSet is a label requirement: every key must be present with one of its values. In config a value is a string or a list of strings (any of).

func (*LabelSet) UnmarshalJSON added in v0.4.0

func (l *LabelSet) UnmarshalJSON(b []byte) error

UnmarshalJSON accepts `{"k": "v"}` and `{"k": ["a", "b"]}`.

type LabelTarget

type LabelTarget struct {
	ID, Name, IP, Path, Integration string
	Port                            int
}

LabelTarget is a container that opted in to scraping with the same keys as the pod annotations (watchtower.dev/scrape, port, path, integration), set as Docker labels.

func IntegrationTargets added in v0.3.4

func IntegrationTargets(cs []Info, byImage bool) []LabelTarget

IntegrationTargets returns running containers that name an integration with the label watchtower.integration (optionally watchtower.port), or, with byImage, are recognised by image. Credentials are never read from here: the agent's own file holds the base config (see modules_autodiscover.go). Containers that already opt in with watchtower.dev/scrape are left to LabelTargets.

func LabelTargets

func LabelTargets(cs []Info) []LabelTarget

LabelTargets returns the running containers whose labels opt in. Labels are untrusted input from whoever can start containers, so they only choose a port and path on the container's own IP.

type Learned added in v0.4.0

type Learned struct {
	Name    string
	Service string
	Labels  map[string]string
}

Learned is what the socket-free log forwarder (logs.forward) learned about a container from the records its Docker log driver sends: name, compose service and the labels the driver attached (log-opt labels / labels-regex). It names and labels the cgroup series.

func Lookup added in v0.4.0

func Lookup(id string) (Learned, bool)

Lookup returns what was learned about the container id.

type Poller

type Poller struct {

	// Services maps compose service names to identities (Config.Services).
	Services map[string]ServiceMap
	// Filter limits CollectCgroups (nil: every container cgroup).
	Filter *CgroupFilter
	// NoLearned ignores names and labels learned from forwarded logs.
	NoLearned bool
	// StaticHealth are extra probe targets (cgroups.health).
	StaticHealth []HealthTarget
	// contains filtered or unexported fields
}

Poller turns successive samples into cores-used gauges.

func (*Poller) Collect

func (p *Poller) Collect(ctx context.Context, d *Docker, out sink.Sink) ([]Info, error)

Collect samples every listed container and writes container.cpu.usage (cores in use, from the change since the last pass; none on the first) and container.memory.usage (bytes).

func (*Poller) CollectCgroups

func (p *Poller) CollectCgroups(root string, known map[string]bool, out sink.Sink)

CollectCgroups reports containers the Engine API did not list (known holds ids already reported) and adds the ids it reports to known. The name is the env-file name, else the one learned from forwarded logs, else the short id; learned labels feed the identity and the Filter. It also emits start/die/oom events, container.restarts and container.oom_kills.

func (*Poller) Health added in v0.4.0

func (p *Poller) Health(ctx context.Context, out sink.Sink, targets []HealthTarget, attrs func(HealthTarget) map[string]string)

Health probes the targets that are due and emits container.health (1 healthy, 0 not), container.health.latency (ms) with source=probe, and a container.event record on every change (the names Docker's health_status events use). It runs inside the module tick, so an interval shorter than the module interval is rounded up to it.

func (*Poller) ProbeLearned added in v0.4.0

func (p *Poller) ProbeLearned(ctx context.Context, out sink.Sink, reported map[string]bool)

ProbeLearned probes the static targets and the wt.health label of every reported container.

func (*Poller) Prune

func (p *Poller) Prune(seen map[string]bool)

Prune forgets containers that are no longer reported.

type ServiceMap

type ServiceMap struct {
	Service     string `json:"service"`
	Environment string `json:"environment"`
	Version     string `json:"version"`
}

ServiceMap names the service a compose service stands for (agent.yaml, modules.container.services).

type Stats

type Stats struct {
	CPUTotalNS uint64 // cumulative CPU time
	MemUsage   uint64 // working set: usage minus reclaimable page cache
	At         time.Time
}

Stats is the part of /containers/{id}/stats that the agent uses.

Jump to

Keyboard shortcuts

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