state

package
v0.11.0 Latest Latest
Warning

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

Go to latest
Published: Oct 2, 2026 License: Apache-2.0 Imports: 37 Imported by: 0

Documentation

Overview

Package state normalizes Kubernetes objects into protocol state, edges, scopes, and kube_* series.

Index

Constants

View Source
const (
	KindNamespace   = "Namespace"
	KindNode        = "Node"
	KindPod         = "Pod"
	KindDeployment  = "apps/Deployment"
	KindReplicaSet  = "apps/ReplicaSet"
	KindStatefulSet = "apps/StatefulSet"
	KindDaemonSet   = "apps/DaemonSet"
	KindJob         = "batch/Job"
	KindCronJob     = "batch/CronJob"
	KindService     = "Service"
	KindIngress     = "networking.k8s.io/Ingress"
	KindNetPol      = "networking.k8s.io/NetworkPolicy"
	KindPVC         = "PersistentVolumeClaim"
	KindPV          = "PersistentVolume"
	KindStorageCls  = "storage.k8s.io/StorageClass"
	KindConfigMap   = "ConfigMap"
	KindHPA         = "autoscaling/HorizontalPodAutoscaler"
	KindPDB         = "policy/PodDisruptionBudget"
	KindEvent       = "Event"
)

Protocol kind strings (SPEC 4.2).

View Source
const (
	EdgeOwns    = "owns"
	EdgeRunsOn  = "runs-on"
	EdgeSelects = "selects"
	EdgeMounts  = "mounts"
	EdgeBinds   = "binds"
	EdgeRoutes  = "routes"
	EdgeTargets = "targets"
	EdgeScales  = "scales"
	EdgeGuards  = "guards"
)

Edge types of the change graph.

View Source
const (
	ReasonForbidden        = "forbidden"
	ReasonUnauthorized     = "unauthorized"
	ReasonNotServed        = "not served"
	ReasonCollectionFailed = "collection failed"
	ReasonRelisting        = "relisting"
)

Scope failure reasons recorded on scope status.

View Source
const (
	LimitationPinned       = "volume is node-local (nodeAffinity): the coordinator is pinned to its node"
	LimitationZonal        = "volume is zonal (nodeAffinity): the coordinator can only be rescheduled within its zone"
	LimitationRWO          = "ReadWriteOnce without ReadWriteOncePod: single writer relies on the spool file lock"
	LimitationRWX          = "ReadWriteMany is not supported for the coordinator spool"
	LimitationNoAccessMode = "no access mode reported"
)

Placement limitations reported on the connector.

View Source
const CatalogSchema = 1

CatalogSchema is the field catalog version; it changes whenever an exported path changes meaning.

View Source
const ReasonScopeRemoved = "scope removed"

Scope removal reason recorded on the scope status.

Variables

View Source
var DefaultAnnotationAllowlist = []string{}

DefaultAnnotationAllowlist is used when no annotation allowlist is configured: no annotations.

View Source
var DefaultLabelAllowlist = []string{
	"app.kubernetes.io/name", "app.kubernetes.io/instance", "app.kubernetes.io/component",
	"app.kubernetes.io/part-of", "app.kubernetes.io/version", "app", "k8s-app",
	"topology.kubernetes.io/zone", "topology.kubernetes.io/region", "node-role.kubernetes.io/*",
}

DefaultLabelAllowlist is used when no label allowlist is configured.

View Source
var ErrAggregatedKind = errors.New("state: kind is aggregated, not exported")

ErrAggregatedKind reports an object that is aggregated onto other resources instead of exported.

View Source
var ErrUnsupportedKind = errors.New("state: unsupported kind")

ErrUnsupportedKind reports an object whose kind is not in the catalog; it is reported, never exported.

Functions

func KindOf

func KindOf(obj *unstructured.Unstructured) string

KindOf returns the protocol kind of obj.

func NodeAffinitySummary

func NodeAffinitySummary(na *corev1.VolumeNodeAffinity) string

NodeAffinitySummary renders required node affinity terms canonically; terms are ORed.

func Normalize

Normalize normalizes obj with the default options.

func PathPattern

func PathPattern(path string) *regexp.Regexp

PathPattern compiles a catalog path into a regular expression matching concrete field keys.

func ProtocolKind

func ProtocolKind(group, kind string) string

ProtocolKind returns the protocol kind string for an API group and kind.

func PublishedSubset

func PublishedSubset() map[string]bool

PublishedSubset returns the set of published kube_* series names for rule validation.

func RenderFieldCatalog

func RenderFieldCatalog() string

RenderFieldCatalog renders docs/field-catalog.md from the catalog.

func RenderKubeSeriesDoc

func RenderKubeSeriesDoc() string

RenderKubeSeriesDoc renders docs/kube-series.md.

func ResolveKinds

func ResolveKinds(names []string) (kinds []string, unsupported []string)

ResolveKinds maps configured resource names to catalog kinds and returns the unsupported names.

func ScopeKey

func ScopeKey(kind, namespace string) string

ScopeKey returns the scope key "<kind>|<namespace>"; the namespace is empty for cluster-wide collection.

func Transform

func Transform(n *Normalizer, kind string) cache.TransformFunc

Transform returns the informer transform that strips unexported and sensitive fields before caching.

Types

type Collector

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

Collector runs read-only list and watch loops for every permitted scope and feeds the Tracker.

func NewCollector

func NewCollector(o CollectorOptions) (*Collector, error)

NewCollector validates o and prepares the scopes.

func (*Collector) Coverage

func (c *Collector) Coverage() Coverage

Coverage reports the status of every scope.

func (*Collector) Run

func (c *Collector) Run(ctx context.Context) error

Run collects until ctx is done.

func (*Collector) Synced

func (c *Collector) Synced() <-chan struct{}

Synced is closed once every scope finished its first attempt and OnSynced ran.

type CollectorOptions

type CollectorOptions struct {
	Dynamic   dynamic.Interface
	Metadata  metadata.Interface
	Discovery discovery.DiscoveryInterface
	Tracker   *Tracker
	Sink      Sink
	// OnSynced receives the state once every scope finished its first attempt; ops before it are not sent to Sink.
	OnSynced func(st *protocol.State)
	// Namespaces selects the namespace profile; empty collects cluster-wide.
	Namespaces        []string
	ExcludeNamespaces []string
	// Resources lists configured resource names; empty selects every catalog kind.
	Resources []string
	Logger    *slog.Logger
	Clock     func() time.Time
	// RetryBase and RetryMax bound the exponential backoff after access failures, default 30s and 30m.
	RetryBase, RetryMax time.Duration
	// FlushInterval is the event count flush period, default 30s.
	FlushInterval time.Duration
	// Wait sleeps for d or until ctx is done, reporting whether to continue; default uses a timer.
	Wait             func(ctx context.Context, d time.Duration) bool
	ReflectorBackoff *wait.Backoff
}

CollectorOptions configures a Collector.

type Coverage

type Coverage struct {
	Scopes      []ScopeReport
	Unsupported []string
}

Coverage summarizes collection: every scope and the configured resources that are not supported.

type Field

type Field struct {
	Path      string
	Source    string
	Type      FieldType
	Redaction Redaction
	Default   bool
}

Field is one exported field path; placeholders are described in docs/field-catalog.md.

type FieldType

type FieldType string

FieldType is the value type of an exported field.

const (
	TypeString     FieldType = "string"
	TypeInt        FieldType = "int"
	TypeBool       FieldType = "bool"
	TypeQuantity   FieldType = "quantity"
	TypeTimestamp  FieldType = "timestamp"
	TypeStringList FieldType = "list<string>"
)

type KindSpec

type KindSpec struct {
	Kind         string
	GVR          schema.GroupVersionResource
	APIKind      string
	Namespaced   bool
	MetadataOnly bool
	Aggregated   bool
	Fields       []Field
	// contains filtered or unexported fields
}

KindSpec describes one collected kind.

func Catalog

func Catalog() []KindSpec

Catalog returns a copy of the field catalog ordered by kind.

func LookupKind

func LookupKind(kind string) (KindSpec, bool)

LookupKind returns the catalog entry for a protocol kind.

type Normalizer

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

Normalizer turns Kubernetes objects into normalized resources using the field catalog.

func NewNormalizer

func NewNormalizer(o Options) (*Normalizer, error)

NewNormalizer validates o and builds a Normalizer.

func (*Normalizer) Normalize

Normalize returns the normalized resource and its owner edges (owner uid -> child uid).

func (*Normalizer) Selected

func (n *Normalizer) Selected(kind, path string) bool

Selected reports whether a catalog field is exported: default-on or deliberately selected.

type Options

type Options struct {
	// LabelAllowlist and AnnotationAllowlist hold exact keys or prefixes ending in "*"; nil selects the defaults.
	LabelAllowlist      []string
	AnnotationAllowlist []string
	// Fields selects non-default catalog fields as "<kind>:<path>", for example "Pod:containers.<container>.args".
	Fields   []string
	Redactor *redact.Redactor
}

Options configures a Normalizer.

func OptionsFromConfig

func OptionsFromConfig(k config.Kubernetes, r *redact.Redactor) Options

OptionsFromConfig derives normalizer options from the Kubernetes configuration section.

type Placement

type Placement struct {
	Claim        string
	Volume       string
	StorageClass string
	AccessModes  []string
	Driver       string
	NodeAffinity string
	// PinnedNodes lists hostnames the volume is restricted to when affinity uses kubernetes.io/hostname.
	PinnedNodes []string
	Pinned      bool
	// Zonal reports affinity to a topology zone without pinning to one node.
	Zonal       bool
	Limitations []string
}

Placement describes where the coordinator spool volume lives (PRD A8).

func PlacementFromVolume

func PlacementFromVolume(pv *corev1.PersistentVolume) Placement

PlacementFromVolume derives placement from a PersistentVolume.

func ReadPlacement

func ReadPlacement(ctx context.Context, cs kubernetes.Interface, namespace, claim string) (Placement, error)

ReadPlacement reads the coordinator's own claim and its bound PersistentVolume with get requests only.

type Redaction

type Redaction string

Redaction is the redaction class of an exported field.

const (
	// RedactStructural fields hold API enumerations, numbers, and addresses, exported as is.
	RedactStructural Redaction = "structural"
	// RedactReference fields hold object and key names, never the referenced values.
	RedactReference Redaction = "reference"
	// RedactText fields hold free text and pass through internal/redact.
	RedactText Redaction = "text"
	// RedactAllowlist fields are exported only for allowlisted keys, with values passed through internal/redact.
	RedactAllowlist Redaction = "allowlist"
)

type ScopeReport

type ScopeReport struct {
	Key       string
	Kind      string
	Namespace string
	State     protocol.ScopeState
	Reason    string
	Attempts  int
}

ScopeReport is the collection status of one scope.

type Series

type Series struct {
	Labels labels.Labels
	Value  float64
	T      int64
}

Series is one synthesized kube_* sample at time T (milliseconds).

func KubeSeries

func KubeSeries(st *protocol.State, nowMs int64) []Series

KubeSeries synthesizes the published kube_* subset from state with kube-state-metrics v2 semantics.

func NodeScoped

func NodeScoped(series []Series, nodeName string) []Series

NodeScoped returns the series pushed to one node: pod series for pods on it plus its kube_node_* series.

func PodSeriesFromPods

func PodSeriesFromPods(n *Normalizer, pods []*unstructured.Unstructured, nowMs int64) ([]Series, error)

PodSeriesFromPods derives pod-scoped series from a node agent's own pod watch.

type SeriesSpec

type SeriesSpec struct {
	Name   string
	Kind   string
	Labels []string
	Source string
}

SeriesSpec documents one published kube_* series.

func KubeSeriesCatalog

func KubeSeriesCatalog() []SeriesSpec

KubeSeriesCatalog returns the published series specifications.

type Sink

type Sink func(ops []protocol.Op, synthetic bool, uncertain *protocol.Interval)

Sink receives ops in state order; synthetic relist ops carry the interval where transients may be missed.

type Tracker

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

Tracker holds the normalized state of a cluster and turns observations into canonical ops.

func NewTracker

func NewTracker(o TrackerOptions) *Tracker

NewTracker returns an empty Tracker.

func (*Tracker) FlushEvents

func (t *Tracker) FlushEvents() []protocol.Op

FlushEvents publishes event counts that are due: changed or decayed counts whose last update is older than the interval.

func (*Tracker) Normalizer

func (t *Tracker) Normalizer() *Normalizer

Normalizer returns the tracker's normalizer.

func (*Tracker) Reconcile

func (t *Tracker) Reconcile(kind, namespace string, objects []*unstructured.Unstructured) ([]protocol.Op, map[string]bool, error)

Reconcile diffs one scope against a fresh list and returns the ops and every UID they touch.

func (*Tracker) Remove

func (t *Tracker) Remove(obj *unstructured.Unstructured) ([]protocol.Op, error)

Remove observes the deletion of obj.

func (*Tracker) RemoveScope

func (t *Tracker) RemoveScope(kind, namespace string) []protocol.Op

RemoveScope deletes every resource of the scope with reason scope removed and marks the scope unavailable.

func (*Tracker) ScopeLost

func (t *Tracker) ScopeLost(kind, namespace, reason string) []protocol.Op

ScopeLost marks a scope unavailable (permission loss or collection failure); resources are kept, never deleted.

func (*Tracker) ScopePartial

func (t *Tracker) ScopePartial(kind, namespace, reason string) []protocol.Op

ScopePartial marks a scope partial, for example while it is relisted.

func (*Tracker) ScopeRestored

func (t *Tracker) ScopeRestored(kind, namespace string) []protocol.Op

ScopeRestored marks a scope complete.

func (*Tracker) Snapshot

func (t *Tracker) Snapshot() *protocol.State

Snapshot returns a deep copy of the state for checkpoints.

func (*Tracker) Upsert

func (t *Tracker) Upsert(obj *unstructured.Unstructured) ([]protocol.Op, error)

Upsert observes obj and returns ops for the resource and every changed edge, none when unchanged.

type TrackerOptions

type TrackerOptions struct {
	Normalizer *Normalizer
	Clock      func() time.Time
	// EventWindow is the sliding window for Warning event counts, default 1h.
	EventWindow time.Duration
	// EventInterval bounds how often event counts of one object are updated, default 5m.
	EventInterval time.Duration
}

TrackerOptions configures a Tracker.

Jump to

Keyboard shortcuts

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