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
- func ApplyScope(ctx context.Context, module, scope string, labels *LabelSet, ...) error
- func CgroupsAvailable() bool
- func DefaultHost() string
- func HasLabels(have map[string]string, want LabelSet) bool
- func ImageIntegration(image string) string
- func LabelFilter(labels LabelSet) []string
- func Learn(id string, l Learned)
- func MatchedSummary(cs []Info) string
- func ParseCPUStat(s string) (uint64, bool)
- func ParseIOStat(s string) (read, write uint64)
- func ParseMemoryStat(s, key string) uint64
- func ProjectsIn(cs []Info) int
- func PromName(name string) string
- func ResolveSelfScope(ctx context.Context, module string, get func(path string, v any) error) (string, error)
- func Run(ctx context.Context, raw json.RawMessage, out sink.Sink) error
- func RunCgroups(ctx context.Context, raw json.RawMessage, out sink.Sink) error
- func SelfContainerID(cgroup, mountinfo string) string
- func SelfProject(get func(path string, v any) error, cgroup, mountinfo, hostname string) (string, error)
- func ServiceFromName(name string) string
- func WantsSelf(scope string) (bool, error)
- type CG
- type CgroupFilter
- type CgroupsConfig
- type Config
- type Docker
- func (d *Docker) Env(ctx context.Context, id string) ([]string, error)
- func (d *Docker) Events(ctx context.Context, since time.Time, out sink.Sink) error
- func (d *Docker) Get(ctx context.Context) func(string, any) error
- func (d *Docker) List(ctx context.Context) ([]Info, error)
- func (d *Docker) Stats(ctx context.Context, id string) (Stats, error)
- type HealthConfig
- type HealthTarget
- type Identity
- type Info
- type LabelSet
- type LabelTarget
- type Learned
- type Poller
- func (p *Poller) Collect(ctx context.Context, d *Docker, out sink.Sink) ([]Info, error)
- func (p *Poller) CollectCgroups(root string, known map[string]bool, out sink.Sink)
- func (p *Poller) Health(ctx context.Context, out sink.Sink, targets []HealthTarget, ...)
- func (p *Poller) ProbeLearned(ctx context.Context, out sink.Sink, reported map[string]bool)
- func (p *Poller) Prune(seen map[string]bool)
- type ServiceMap
- type Stats
Constants ¶
const ComposeProjectLabel = "com.docker.compose.project"
ComposeProjectLabel is the label docker compose puts on every container of a project.
const ComposeServiceLabel = "com.docker.compose.service"
ComposeServiceLabel is the label docker compose puts the service name in.
const DefaultCgroupRoot = "/sys/fs/cgroup"
DefaultCgroupRoot is where cgroup v2 is mounted.
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 ImageIntegration ¶ added in v0.3.4
ImageIntegration maps an image reference (registry/name:tag@digest) to an integration name by its last path segment, or "".
func LabelFilter ¶
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
Learn remembers l for the container id (full id or a prefix of at least 12 characters).
func MatchedSummary ¶ added in v0.3.4
MatchedSummary lists "name(id12)" of cs, sorted, for the startup and change log.
func ParseCPUStat ¶
ParseCPUStat returns usage_usec of a cgroup v2 cpu.stat file, in nanoseconds.
func ParseIOStat ¶ added in v0.3.4
ParseIOStat sums rbytes and wbytes over the devices of a cgroup v2 io.stat file.
func ParseMemoryStat ¶
ParseMemoryStat returns the value of key in a cgroup v2 flat-keyed file such as memory.stat.
func ProjectsIn ¶ added in v0.4.0
ProjectsIn counts the distinct compose projects among cs.
func PromName ¶
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 ¶
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
RunCgroups reports containers from a (read-only) cgroup v2 mount, with no Docker socket.
func SelfContainerID ¶ added in v0.4.0
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
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.
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 ¶
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.
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 ¶
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 (*Docker) Events ¶
Events streams container events as log records until ctx ends or the stream breaks.
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
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.
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
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
UnmarshalJSON accepts `{"k": "v"}` and `{"k": ["a", "b"]}`.
type LabelTarget ¶
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
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.
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 ¶
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 ¶
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
ProbeLearned probes the static targets and the wt.health label of every reported container.
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).