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
- Variables
- func CadvisorAttrs(labels map[string]string, node, cluster string) (res, point map[string]string, ok bool)
- func Chain(ctx context.Context, ns string, refs []metav1.OwnerReference, look Lookup) []metav1.OwnerReference
- func ControlPlaneURLs(pods []*corev1.Pod, component string) []string
- func Duration(s string, def, floor time.Duration) time.Duration
- func Emit(out sink.Sink, s *Summary, nodeRes map[string]string, ...)
- func EmitCadvisor(out sink.Sink, fams map[string]*dto.MetricFamily, node, cluster string, ...)
- func IndexContainers(pods []*corev1.Pod) map[string]ContainerRef
- func Manifest(obj any) string
- func NetpolAttrs(sp *netv1.NetworkPolicySpec) map[string]string
- func NodeProps(n *corev1.Node) map[string]string
- func OwnerAttrs(chain []metav1.OwnerReference) map[string]string
- func ParseCRI(line string) (at time.Time, stream, text string, partial, ok bool)
- func ParsePodLogPath(dir, path string) (ns, pod, uid, container string, ok bool)
- func PodAttrs(ctx context.Context, cluster string, pod *corev1.Pod, look Lookup) map[string]string
- func ResourceProps(kind string, spec *corev1.PodSpec, n int32) map[string]string
- func RunCluster(ctx context.Context, raw json.RawMessage, out sink.Sink) error
- func RunElected(ctx context.Context, cs kubernetes.Interface, ns, name, id string, tm Timing, ...) error
- func RunExtMetrics(ctx context.Context, raw json.RawMessage) error
- func RunNode(ctx context.Context, raw json.RawMessage, stateDir string, out sink.Sink) error
- func RunRightsize(ctx context.Context, raw json.RawMessage, out sink.Sink) error
- func RunScoped(ctx context.Context, raw json.RawMessage, out sink.Sink) error
- func SelectorMatchers(sel string) (string, error)
- func SpecAttrs(kind string, spec *corev1.PodSpec, replicas *int32, labels map[string]string) map[string]string
- func Trim(obj any) (any, error)
- func WorkloadOf(ctx context.Context, p *corev1.Pod, look Lookup) (string, string)
- type CPUStats
- type CheckTarget
- type ClusterConfig
- type ContainerRef
- type ContainerStats
- type ControlPlane
- type ControlPlaneConfig
- type Decision
- type ExtMetrics
- type ExtMetricsConfig
- type ExtSample
- type FSStats
- type Kubelet
- type Lookup
- type MemStats
- type NetIface
- type NetStats
- type NodeConfig
- type NodeStats
- type PodRef
- type PodStats
- type Recommendation
- type Res
- type RightsizeConfig
- type Rightsizer
- type ScopedConfig
- type Summary
- type Target
- type Timing
Constants ¶
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.
const AnnPrefix = "watchtower.dev/"
AnnPrefix is the pod annotation namespace the agent reads (autodiscovery).
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 ¶
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.
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 ¶
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 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 ¶
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 ¶
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 ParsePodLogPath ¶
ParsePodLogPath splits <dir>/<ns>_<pod>_<uid>/<container>/<n>.log.
func PodAttrs ¶
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 ¶
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 ¶
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 RunRightsize ¶
RunRightsize runs the module on the elected replica until ctx ends.
func SelectorMatchers ¶
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.
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"`
// ExcludeNamespaces drops pod state and events of these namespaces (cluster mode, e.g. kube-system).
ExcludeNamespaces []string `json:"exclude_namespaces"`
// 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.
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 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 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 ¶
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).
type Lookup ¶
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 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.
type ScopedConfig ¶ added in v0.4.0
type ScopedConfig struct {
Enabled *bool `json:"enabled"`
Interval string `json:"interval"` // default 30s, at least 10s
ClusterName string `json:"cluster_name"`
Namespaces []string `json:"namespaces"` // or $WT_AGENT_K8S_NAMESPACES
ExcludeNamespaces []string `json:"exclude_namespaces"` // removed from Namespaces
Selector string `json:"selector"` // label selector applied to pods (server side)
MaxLogStreams int `json:"max_log_streams"` // concurrent pods/log follows, default 50
Logs *bool `json:"logs"` // default true
Events *bool `json:"events"` // default true
Metrics *bool `json:"metrics"` // metrics.k8s.io PodMetrics, default true
}
ScopedConfig is the config of the "kubernetes" module (namespaced scope). Only Enabled and Interval can be set remotely. Every API call is made inside one of Namespaces; nothing is ever listed cluster-wide and filtered afterwards, so a Role per namespace is all the RBAC it needs.
func (*ScopedConfig) Scope ¶ added in v0.4.0
func (c *ScopedConfig) Scope() ([]string, error)
Scope resolves the namespaces to watch: the configured list (else the environment) minus the excluded ones, de-duplicated and sorted. An empty result is an error: namespaced mode never falls back to the whole cluster. The selector is validated here.
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 ¶
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 ¶
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.