k8s

package
v0.3.1 Latest Latest
Warning

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

Go to latest
Published: Nov 10, 2026 License: Apache-2.0 Imports: 52 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 k8s is the Kubernetes side of wt-agent: a node agent (DaemonSet: kubelet usage metrics, pod logs, scrape discovery) and a cluster agent (one elected Deployment replica: object state metrics, events, spec-change history). Both use client-go with read-only RBAC and never read Secret objects or the env of any pod spec.

Index

Constants

View Source
const AdPrefix = "ad.watchtower.dev/"

AdPrefix is the autodiscovery-checks annotation namespace:

ad.watchtower.dev/<container>.checks: '{"redis":{"instances":[{"host":"%%host%%","port":"%%port%%"}]}}'

The value maps an integration module name to its config; %%host%% becomes the pod IP and %%port%% the container's first declared port. No env or secret is ever substituted.

View Source
const AnnPrefix = "watchtower.dev/"

AnnPrefix is the pod annotation namespace the agent reads (autodiscovery).

View Source
const (
	AnnRightsize = AnnPrefix + "rightsize"
)

Rightsizing (INF-005, Datadog Kubernetes Autoscaling / VPA parity): the opt-in `k8s_rightsize` module reads the project's recommendations (GET /v1/projects/{prj}/k8s-rightsizing) and patches container requests of the workloads that opted in with the annotation

watchtower.dev/rightsize: Auto | TriggerRollout | Disabled   (absent = Disabled)

TriggerRollout patches the pod template at once (the controller rolls the pods out). Auto waits until the owner rolls the workload out anyway (a new generation not yet observed, or pods still being updated) and joins that rollout, so Watchtower never restarts pods on its own. Every patch is bounded (at most halve or double per step, never below 10m CPU / 32Mi), needs medium or high confidence, waits a cooldown per workload, and is audited as a Kubernetes Event on the workload and an INFO log record `k8s.rightsize.applied` exported to Watchtower.

Variables

View Source
var DefaultTiming = Timing{LeaseDuration: 15 * time.Second, RenewDeadline: 10 * time.Second, RetryPeriod: 2 * time.Second}

DefaultTiming is client-go's usual 15 s / 10 s / 2 s.

View Source
var ErrEtcdNeedsClientCert = errors.New("controlplane: etcd targets need etcd_client_cert_secret (tls.crt, tls.key, ca.crt)")

ErrEtcdNeedsClientCert is returned when etcd targets are listed without a client certificate.

Functions

func CadvisorAttrs

func CadvisorAttrs(labels map[string]string, node, cluster string) (res, point map[string]string, ok bool)

CadvisorAttrs turns one container_* series' labels into resource attributes plus the point attributes that stay on the series (interface, device, cpu ...). ok is false for series that belong to no workload (the root cgroup) or to the pause container.

func Chain

func Chain(ctx context.Context, ns string, refs []metav1.OwnerReference, look Lookup) []metav1.OwnerReference

Chain walks pod -> owner -> owner...: a ReplicaSet continues to its Deployment and a Job to its CronJob (through look); any other owner kind ends the chain. The first element is the direct owner.

func ControlPlaneURLs

func ControlPlaneURLs(pods []*corev1.Pod, component string) []string

ControlPlaneURLs resolves a control-plane component ("scheduler", "controller-manager", "etcd") to the metrics URLs of its kube-system static pods (label component=<name>), on the pod IP and kubeadm's default port. Pods that are not running are skipped.

func Duration

func Duration(s string, def, floor time.Duration) time.Duration

Duration parses s, falling back to def and never going below floor.

func Emit

func Emit(out sink.Sink, s *Summary, nodeRes map[string]string, podRes func(PodRef) map[string]string, at time.Time)

Emit turns a summary into k8s.node.*, k8s.pod.* and k8s.container.* usage metrics. podRes gives the resource attributes of a pod (enrichment); nodeRes those of the node. Container names are point attributes; everything about the owning object is on the resource.

The pod uid and, when podRes names it, the workload uid (k8s.parent.id) are also point attributes: series labels keep only point attributes, and the explorer joins usage to pods and sums it per workload by them (INF-009). k8s.parent.id stays off the resource, where only the cluster agent names a parent.

func EmitCadvisor

func EmitCadvisor(out sink.Sink, fams map[string]*dto.MetricFamily, node, cluster string, at time.Time)

EmitCadvisor forwards the container_* families under their original names (so cAdvisor dashboards work) with the workload on the resource.

func IndexContainers

func IndexContainers(pods []*corev1.Pod) map[string]ContainerRef

IndexContainers maps runtime container ids (the 64-hex id without the `containerd://` scheme) of the given pods to their pod.

func Manifest

func Manifest(obj any) string

Manifest renders an object as the informer keeps it (already trimmed by Trim: no env, command, args, volumes or foreign annotations) as YAML with sorted keys, without status and resource version, so two versions differ only where the spec or labels did (INF-004). Cut to maxManifest bytes; "" when the object does not marshal.

func NetpolAttrs

func NetpolAttrs(sp *netv1.NetworkPolicySpec) map[string]string

NetpolAttrs describes a NetworkPolicy spec as the facts logged on change: its types, rule counts and a short digest of the whole spec, so any edit to a rule shows up.

func NodeProps

func NodeProps(n *corev1.Node) map[string]string

NodeProps are a node's entity properties for the node page: every condition the kubelet or a node-problem-detector reports (k8s.node.condition.<Type> = True/False/Unknown) and the allocatable CPU (cores) and memory (bytes).

func OwnerAttrs

func OwnerAttrs(chain []metav1.OwnerReference) map[string]string

OwnerAttrs is k8s.<kind>.name for each owner in the chain (resource attributes). Owners are named but never given a .uid here: the worker makes an entity of every k8s.<kind>.uid it sees, and an owner's entity must come only from the owner's own state metrics, which carry its spec.

func ParseCRI

func ParseCRI(line string) (at time.Time, stream, text string, partial, ok bool)

ParseCRI splits one CRI log line. partial is true for a "P" (continued) line.

func ParsePodLogPath

func ParsePodLogPath(dir, path string) (ns, pod, uid, container string, ok bool)

ParsePodLogPath splits <dir>/<ns>_<pod>_<uid>/<container>/<n>.log.

func PodAttrs

func PodAttrs(ctx context.Context, cluster string, pod *corev1.Pod, look Lookup) map[string]string

PodAttrs are the resource attributes every record about a pod carries (INF-007): cluster, namespace, pod, node and the owner chain. No `wt.*` key is ever set.

func ResourceProps

func ResourceProps(kind string, spec *corev1.PodSpec, n int32) map[string]string

ResourceProps are the container requests and limits of a pod spec summed and times n pods, as entity properties k8s.<kind>.{cpu,memory}.{request,limit} (cores, bytes), so the explorer can show usage against them. A sum is left out when any container lacks the value; those containers are named in k8s.<kind>.requests_missing / .limits_missing (the risk checks).

func RunCluster

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

RunCluster runs the cluster agent: wins the Lease, then (only while leading) watches the cluster and reports state metrics, events and spec changes. Replicas that do not hold the Lease stay idle.

func RunElected

func RunElected(ctx context.Context, cs kubernetes.Interface, ns, name, id string, tm Timing, lead func(context.Context) error) error

RunElected competes for the Lease name in ns (coordination.k8s.io; RBAC: get and update on the pre-created lease) and calls lead only while this replica holds it; lead's context ends when leadership is lost or ctx ends. If lead returns an error while still leading, the Lease is released (the election context is cancelled, ReleaseOnCancel) and the replica waits one lease duration before competing again, so a standby can take over. After losing, the replica competes again until ctx ends. At most one replica runs lead at a time (up to one lease duration of overlap is possible after a network partition, which is why everything lead sends is at-least-once safe).

func RunExtMetrics

func RunExtMetrics(ctx context.Context, raw json.RawMessage) error

RunExtMetrics serves until ctx ends.

func RunNode

func RunNode(ctx context.Context, raw json.RawMessage, stateDir string, out sink.Sink) error

RunNode runs the node agent against the in-cluster API until ctx ends.

func RunRightsize

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

RunRightsize runs the module on the elected replica until ctx ends.

func SelectorMatchers

func SelectorMatchers(sel string) (string, error)

SelectorMatchers turns a Kubernetes label selector (equality, set and existence requirements) into PromQL matchers. Values are quoted for a PromQL string; keys must be label names.

func SpecAttrs

func SpecAttrs(kind string, spec *corev1.PodSpec, replicas *int32, labels map[string]string) map[string]string

SpecAttrs are the spec facts the worker records in entity history when they change, as resource attributes of the object: k8s.<kind>.spec.{image,replicas,resources,labels}. Values are deterministic (declared container order, sorted labels) and cut to maxSpecAttr bytes.

func Trim

func Trim(obj any) (any, error)

Trim is the cache.TransformFunc for every informer of this package. Unknown types pass through unchanged (tombstones included).

func WorkloadOf

func WorkloadOf(ctx context.Context, p *corev1.Pod, look Lookup) (string, string)

WorkloadOf is the kind and uid of the pod's workload (a ReplicaSet collapsed to its Deployment, a Job to its CronJob); "" when the pod has none.

Types

type CPUStats

type CPUStats struct {
	UsageNanoCores       *uint64 `json:"usageNanoCores"`
	UsageCoreNanoSeconds *uint64 `json:"usageCoreNanoSeconds"`
}

The kubelet's /stats/summary document, reduced to the fields the agent reports. Numbers are pointers because the kubelet omits what it cannot measure.

type CheckTarget

type CheckTarget struct {
	Namespace string
	Pod       string
	UID       string
	PodIP     string
	Container string
	Module    string
	Config    map[string]any // the module's config with the templates resolved
}

CheckTarget binds one integration module to one container of a running pod.

func DiscoverChecks

func DiscoverChecks(pods []*corev1.Pod) []CheckTarget

DiscoverChecks returns the module bindings declared through ad.watchtower.dev annotations on running pods with an IP, sorted by namespace, pod, container and module. An annotation that names a missing container, is oversized or is not a JSON object of objects is skipped.

type ClusterConfig

type ClusterConfig struct {
	Enabled      *bool  `json:"enabled"`
	Interval     string `json:"interval"` // state metrics, default 60s, at least 10s
	ClusterName  string `json:"cluster_name"`
	Namespace    string `json:"namespace"`  // of the Lease; default the pod's own
	LeaseName    string `json:"lease_name"` // default wt-cluster-agent
	Identity     string `json:"identity"`   // default $POD_NAME, then the hostname
	Events       *bool  `json:"events"`     // default true
	EventsPerSec int    `json:"events_per_sec"`
	// ControlPlane scrapes API server, scheduler, controller manager and etcd metrics (leader only).
	ControlPlane *ControlPlaneConfig `json:"controlplane"`
	// contains filtered or unexported fields
}

ClusterConfig is the cluster agent's config. Only Enabled and Interval can be set remotely.

type ContainerRef

type ContainerRef struct {
	Namespace, Pod, Container string
	// Workload is the controlling object as kind/name; a ReplicaSet with a pod-template-hash is
	// folded into its Deployment so flows group by what users deploy.
	Workload string
}

ContainerRef is the pod a running container belongs to (for eBPF flow attribution, INF-038).

func ContainerByID

func ContainerByID(id string) (ContainerRef, bool)

ContainerByID looks a container id up in the node agent's latest pod list (false before the first poll, off-cluster, or for containers that are not pods').

type ContainerStats

type ContainerStats struct {
	Name   string    `json:"name"`
	CPU    *CPUStats `json:"cpu"`
	Memory *MemStats `json:"memory"`
	Rootfs *FSStats  `json:"rootfs"`
}

The kubelet's /stats/summary document, reduced to the fields the agent reports. Numbers are pointers because the kubelet omits what it cannot measure.

type ControlPlane

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

ControlPlane scrapes the control-plane endpoints.

func NewControlPlane

func NewControlPlane(cfg ControlPlaneConfig, apiURL, cluster string, resolve func(string) []string) (*ControlPlane, error)

NewControlPlane builds the scraper; it fails when etcd targets lack a client certificate.

func (*ControlPlane) Scrape

func (c *ControlPlane) Scrape(ctx context.Context, out sink.Sink, at time.Time)

Scrape reports apiserver_*, etcd_*, scheduler_*, workqueue_* ... series under their original names with `component` as a point attribute, plus `up` per target. One failing target never stops the others.

type ControlPlaneConfig

type ControlPlaneConfig struct {
	Enabled *bool `json:"enabled"`
	// Targets: "scheduler", "controller-manager" (resolved to the kube-system static pods) or a
	// full https URL.
	Targets []string `json:"targets"`
	// EtcdTargets: https URLs such as https://10.0.0.5:2379/metrics, or "etcd" (static pods).
	EtcdTargets []string `json:"etcd_targets"`
	// EtcdClientCertSecret is the directory the etcd client Secret is mounted at (tls.crt,
	// tls.key, ca.crt). The agent never reads Secrets through the API.
	EtcdClientCertSecret string `json:"etcd_client_cert_secret"`
	InsecureTLS          bool   `json:"insecure_tls"`
	TokenFile            string `json:"token_file"`
	CAFile               string `json:"ca_file"`
}

ControlPlaneConfig is the `controlplane` section of the cluster agent's config. The API server is scraped through the in-cluster service account (the ClusterRole carries `get` on the non-resource URL /metrics). The scheduler and controller manager are scraped only when named in Targets; kubeadm serves them on https :10259 and :10257 of each control-plane node (their bind-address must not be 127.0.0.1). etcd needs client certificates, so it is scraped only when EtcdClientCertSecret is set.

type Decision

type Decision struct {
	Workload, Namespace, Strategy, Action string
	Patch                                 []byte
}

Decision is what one pass did for one workload (tests and the audit record use it).

type ExtMetrics

type ExtMetrics struct {
	Metrics map[string]string
	Query   func(ctx context.Context, promql string) ([]ExtSample, error)
	Now     func() time.Time
}

ExtMetrics answers external.metrics.k8s.io requests; Query runs one instant PromQL query and returns (labels, value) per series.

func (*ExtMetrics) ServeHTTP

func (e *ExtMetrics) ServeHTTP(w http.ResponseWriter, r *http.Request)

type ExtMetricsConfig

type ExtMetricsConfig struct {
	APIURL               string            `json:"api_url"`
	Project              string            `json:"project"`
	APIKey               string            `json:"api_key"` // a secret reference; needs telemetry read
	Listen               string            `json:"listen"`  // default :6443
	CertFile             string            `json:"cert_file"`
	KeyFile              string            `json:"key_file"`
	ClientCAFile         string            `json:"client_ca_file"`
	InsecureNoClientAuth bool              `json:"insecure_no_client_auth"`
	Metrics              map[string]string `json:"metrics"`
}

External metrics (INF-008, Datadog Cluster Agent external metrics provider): the `external_metrics` module serves external.metrics.k8s.io/v1beta1 so an HPA can scale on any Watchtower metric. Each exposed metric is a named PromQL query in the local config; the HPA's metric selector becomes extra label matchers through the `{{selector}}` placeholder, e.g.

metrics: {queue_lag: 'sum(kafka_consumergroup_lag{ {{selector}} })'}

Every agent pod can answer (it is stateless), so the chart's APIService points at a Service over the DaemonSet. The kube-apiserver must present a client certificate from client_ca_file (the cluster's requestheader / front-proxy CA) unless insecure_no_client_auth is set.

type ExtSample

type ExtSample struct {
	Labels map[string]string
	Value  float64
}

ExtSample is one series of an instant query result.

type FSStats

type FSStats struct {
	UsedBytes     *uint64 `json:"usedBytes"`
	CapacityBytes *uint64 `json:"capacityBytes"`
}

The kubelet's /stats/summary document, reduced to the fields the agent reports. Numbers are pointers because the kubelet omits what it cannot measure.

type Kubelet

type Kubelet struct {
	URL       string // https://<node ip>:10250
	TokenFile string
	// contains filtered or unexported fields
}

Kubelet fetches the summary of one node's kubelet with the pod's service account token (RBAC: get on nodes/stats).

func NewKubelet

func NewKubelet(url, tokenFile, caFile string, insecure bool) (*Kubelet, error)

NewKubelet builds the client. The kubelet's serving certificate is usually signed by a CA the cluster CA file does not cover, so verification uses caFile when given and is skipped only when insecure is set in the agent's own config (it is never settable remotely).

func (*Kubelet) Cadvisor

func (k *Kubelet) Cadvisor(ctx context.Context) (map[string]*dto.MetricFamily, error)

Cadvisor fetches and parses /metrics/cadvisor (RBAC: get on nodes/metrics).

func (*Kubelet) Summary

func (k *Kubelet) Summary(ctx context.Context) (*Summary, error)

Summary fetches and parses /stats/summary.

type Lookup

type Lookup func(ctx context.Context, kind, ns, name string) (*metav1.OwnerReference, bool)

Lookup returns the controller owner of the ReplicaSet or Job called name in ns.

func NewAPILookup

func NewAPILookup(cs kubernetes.Interface) Lookup

NewAPILookup resolves ReplicaSet and Job owners with one GET each, cached for ten minutes in at most 5000 entries, evicting expired entries (then the oldest) when full. The node agent uses it so it needs no cluster-wide ReplicaSet watch.

type MemStats

type MemStats struct {
	UsageBytes      *uint64 `json:"usageBytes"`
	WorkingSetBytes *uint64 `json:"workingSetBytes"`
	AvailableBytes  *uint64 `json:"availableBytes"`
}

The kubelet's /stats/summary document, reduced to the fields the agent reports. Numbers are pointers because the kubelet omits what it cannot measure.

type NetIface

type NetIface struct {
	Name     string  `json:"name"`
	RxBytes  *uint64 `json:"rxBytes"`
	RxErrors *uint64 `json:"rxErrors"`
	TxBytes  *uint64 `json:"txBytes"`
	TxErrors *uint64 `json:"txErrors"`
}

The kubelet's /stats/summary document, reduced to the fields the agent reports. Numbers are pointers because the kubelet omits what it cannot measure.

type NetStats

type NetStats struct {
	Interfaces []NetIface `json:"interfaces"`
}

The kubelet's /stats/summary document, reduced to the fields the agent reports. Numbers are pointers because the kubelet omits what it cannot measure.

type NodeConfig

type NodeConfig struct {
	Enabled         *bool  `json:"enabled"`
	Interval        string `json:"interval"`     // default 30s, at least 5s
	ClusterName     string `json:"cluster_name"` // k8s.cluster.name on everything
	NodeName        string `json:"node_name"`    // default $NODE_NAME
	KubeletURL      string `json:"kubelet_url"`  // default https://$NODE_IP:10250
	KubeletCAFile   string `json:"kubelet_ca_file"`
	KubeletInsecure bool   `json:"kubelet_insecure_tls"`
	TokenFile       string `json:"token_file"`
	PodLogDir       string `json:"pod_log_dir"` // default /var/log/pods; "off" disables log tailing
	Cadvisor        *bool  `json:"cadvisor"`    // kubelet /metrics/cadvisor container_* series; default true
	// contains filtered or unexported fields
}

NodeConfig is the node agent's config. Only Enabled and Interval can be set remotely; the kubelet address, credentials and log directory live in the agent's own file.

type NodeStats

type NodeStats struct {
	NodeName string    `json:"nodeName"`
	CPU      *CPUStats `json:"cpu"`
	Memory   *MemStats `json:"memory"`
	Network  *NetStats `json:"network"`
	FS       *FSStats  `json:"fs"`
}

The kubelet's /stats/summary document, reduced to the fields the agent reports. Numbers are pointers because the kubelet omits what it cannot measure.

type PodRef

type PodRef struct {
	Name      string `json:"name"`
	Namespace string `json:"namespace"`
	UID       string `json:"uid"`
}

The kubelet's /stats/summary document, reduced to the fields the agent reports. Numbers are pointers because the kubelet omits what it cannot measure.

type PodStats

type PodStats struct {
	PodRef     PodRef           `json:"podRef"`
	CPU        *CPUStats        `json:"cpu"`
	Memory     *MemStats        `json:"memory"`
	Network    *NetStats        `json:"network"`
	Ephemeral  *FSStats         `json:"ephemeral-storage"`
	Containers []ContainerStats `json:"containers"`
}

The kubelet's /stats/summary document, reduced to the fields the agent reports. Numbers are pointers because the kubelet omits what it cannot measure.

type Recommendation

type Recommendation struct {
	Cluster     string `json:"cluster"`
	Namespace   string `json:"namespace"`
	Workload    string `json:"workload"` // "Kind/name", or a bare name for a Deployment
	Confidence  string `json:"confidence"`
	Current     Res    `json:"current"`
	Recommended Res    `json:"recommended"`
}

Recommendation is the part of the API's K8sCostRecommendation the module uses.

type Res

type Res struct {
	CPUCores float64 `json:"cpu_cores"`
	MemGiB   float64 `json:"mem_gib"`
}

Res is requests per pod.

type RightsizeConfig

type RightsizeConfig struct {
	APIURL    string  `json:"api_url"`
	Project   string  `json:"project"`
	APIKey    string  `json:"api_key"`
	Cluster   string  `json:"cluster"`   // k8s.cluster.name the recommendations carry
	Interval  string  `json:"interval"`  // default 10m
	Cooldown  string  `json:"cooldown"`  // default 24h between patches of one workload
	Tolerance float64 `json:"tolerance"` // default 0.1: smaller relative changes are skipped
	DryRun    bool    `json:"dry_run"`   // audit what would change, patch nothing
}

RightsizeConfig is the module config (local file only; it holds the API key reference).

type Rightsizer

type Rightsizer struct {
	Cfg   RightsizeConfig
	Fetch func(ctx context.Context) ([]Recommendation, error)
	Get   func(ctx context.Context, kind, ns, name string) (*workloadObj, error)
	Patch func(ctx context.Context, kind, ns, name string, patch []byte) error
	Event func(ctx context.Context, w *workloadObj, msg string)
	Out   sink.Sink
	Now   func() time.Time
}

Rightsizer applies recommendations to one cluster.

func (*Rightsizer) Once

func (r *Rightsizer) Once(ctx context.Context) ([]Decision, error)

Once runs one pass and returns a decision for every recommendation of this cluster.

type Summary

type Summary struct {
	Node NodeStats  `json:"node"`
	Pods []PodStats `json:"pods"`
}

Summary is the response of GET /stats/summary.

func ParseSummary

func ParseSummary(r io.Reader) (*Summary, error)

ParseSummary decodes a /stats/summary body (bounded to 64 MiB).

type Target

type Target struct {
	Namespace   string
	Pod         string
	UID         string
	IP          string
	Port        int
	Path        string
	Integration string
}

Target is a pod endpoint that opted in to scraping with annotations:

watchtower.dev/scrape: "true"
watchtower.dev/port: "9102"             (default: the first declared container port)
watchtower.dev/path: "/metrics"         (default /metrics)
watchtower.dev/integration: "redis"     (an integration manifest name, task I4)

func Discover

func Discover(pods []*corev1.Pod) []Target

Discover returns the opted-in targets among pods, sorted by namespace, pod and port. A pod without an IP, one that is not running, or with an unusable port or path is skipped; the annotations are untrusted input from whoever can edit pods.

func Explain

func Explain(p *corev1.Pod) (Target, string)

Explain resolves one pod to its scrape target, or says why it is not scraped (`wtctl k8s doctor` prints the reason). why is "" when the pod is a target.

func Targets

func Targets() []Target

Targets is the node agent's current discovery result (nil before the first poll or when the node agent is not running). The integrations module (I4) turns these into scrapes.

func (Target) URL

func (t Target) URL() string

URL is the scrape URL (plain http inside the cluster).

type Timing

type Timing struct {
	LeaseDuration, RenewDeadline, RetryPeriod time.Duration
}

Timing of the Lease election. A crashed leader is replaced after at most LeaseDuration.

Jump to

Keyboard shortcuts

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