inventory

package
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Oct 12, 2026 License: Apache-2.0 Imports: 16 Imported by: 0 modules, 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

Index

Constants

View Source
const (
	// MaxStringBytes caps every string in an inventory, map keys
	// included (versions, chart names, image repositories, kubeVersion
	// constraints, file paths and annotation values too), but the two
	// below, which are capped apart: what one finding can repeat of any
	// of them stays small.
	MaxStringBytes = 16 << 10
	// MaxReasonBytes caps a capability's Reason, which joins one error per
	// resource a collector could not read.
	MaxReasonBytes = 64 << 10
	// MaxManagerBytes caps an ObjectRef's Manager, a managedFields
	// manager: the apiserver refuses a longer one.
	MaxManagerBytes = 128
	// MaxCapabilities caps the capabilities an inventory reports (six
	// today): each one not assessed is a gap in every report and in every
	// evaluation summary the fleet-wide reads carry.
	MaxCapabilities = 32
)

Limits on what an inventory carries beyond its identifiers (ValidateIdentifiers). They are what a collector records (the object and image caps, one entry per group/version/kind), or far above any genuine value; the free text a collector copies whole from what it reads, which Kubernetes lets be longer (a capability's reason and skipped entries, the ignore annotations), it cuts to them (CutFreeText), and so does the server, for agents that did not. The server refuses an inventory beyond one (422) before evaluating it, because the engine repeats these values in the findings it builds: a kubeVersion of 20 MB of quotes was a 84 MB report, a release per finding with a short one eight times its push.

View Source
const (
	SkippedPersistentVolumes = "v1 persistentvolumes"
	SkippedStorageClasses    = "storage.k8s.io/v1 storageclasses"
)

SkippedPersistentVolumes and SkippedStorageClasses are the volumes capability's Skipped entries for a PersistentVolume or StorageClass list that was refused or failed (#362): the in-tree plugins of the objects not read were not checked.

View Source
const (
	GitOpsArgoCD = "argocd"
	GitOpsFlux   = "flux"
)

The GitOps tools whose chart sources the helm capability reads, as GitOpsChart.Tool and a helm capability's Skipped name them.

View Source
const CurrentCollectorSchema = 1

CurrentCollectorSchema is the generation of field meanings this package's collectors fill an Inventory with, stamped as Inventory.CollectorSchema. 1 is v0.2.0's: api-usage counts the objects written through a deprecated version and names them in Objects, a chart-found add-on's Version is its app version, and an add-on image that names no version (a digest, ":latest") takes the version label of its pod (#301). Bump it when a field's meaning changes without a schemaVersion bump.

View Source
const LabelVersionCollectorSchema = 1

LabelVersionCollectorSchema is the first CollectorSchema whose collectors take an image's add-on version from its pod's app.kubernetes.io/version label when the image names none (#301). An inventory below it (0: v0.1.x and v0.2.0's release candidates, which predate the stamp) never consulted that label for such an image, so what a finding says is missing from it must not say the label was unreadable. It equals CurrentCollectorSchema because v0.2.0 has not been released: no released agent stamps 1 without it, and the stamp and the label rule ship together. Unreleased builds of main between the stamp and the label rule (agentVersion "dev" or a pseudo-version) are the exception: they stamp 1 without reading the label, so their inventories read as having consulted it. Raise CurrentCollectorSchema past it for a later change; do not move this one.

View Source
const MaxObjectNameBytes = 253

MaxObjectNameBytes caps an object name in an inventory: the most an RFC 1123 subdomain, which almost every kind's name must be, may take.

View Source
const MaxObjectRefs = 100

MaxObjectRefs caps APIUsage.Objects so a render with thousands of objects of one kind cannot bloat the inventory, the report or SARIF output.

View Source
const MaxUnrecognizedImages = 200

MaxUnrecognizedImages caps Inventory.UnrecognizedImages, so a cluster running thousands of distinct images cannot bloat the inventory or the report.

View Source
const MaxVolumePlugins = 64

MaxVolumePlugins caps Inventory.VolumePlugins: one entry per plugin, of the few dozen fields corev1.VolumeSource has.

View Source
const SkippedNewerKB = "knowledge base differs from the agent's"

SkippedNewerKB is the Skipped entry of api-usage, helm and addons that the server (never a collector) adds when a snapshot was collected with a knowledge base other than its own: the agent listed API usage and matched add-ons by its own data, so evidence the server's data would have collected is missing. The engine reads it as a required gap for api-usage and addons, so the verdict is unknown.

View Source
const SkippedPods = "v1 pods"

SkippedPods is the addons capability's Skipped entry for a cluster-wide pod list that failed: pod images and labels find an add-on whatever installed it, so the engine keeps that gap required.

View Source
const SupportedSchemaVersion = 1

SupportedSchemaVersion is the schemaVersion of the inventories this module writes and judges. Another version means fields it would misread.

Variables

This section is empty.

Functions

func AppendReason added in v0.2.0

func AppendReason(reason, addition string) string

AppendReason returns reason with addition appended after "; ", within MaxReasonBytes: the server builds on a reason a snapshot carries (already cut by CutFreeText) and must stay within the bound admission applies. It is the existing text that is cut, so the addition, which says what the server judged, is always whole; an addition itself over the bound is cut.

func ValidateClusterName added in v0.2.0

func ValidateClusterName(name string) error

ValidateClusterName checks a cluster name, as an agent sends it and the server registers it: an RFC 1123 subdomain of at most 253 bytes, as a Kubernetes object's name usually is. It must not be empty.

Types

type APIUsage

type APIUsage struct {
	Group      string         `json:"group"` // "" for core
	Version    string         `json:"version"`
	Kind       string         `json:"kind"`
	Count      int            `json:"count"`
	Namespaces map[string]int `json:"namespaces,omitempty"` // ns → count; cluster-scoped key ""
	// Objects identifies the objects behind Count, in collection order,
	// capped at MaxObjectRefs; ObjectsOmitted counts the refs dropped by
	// the cap. Collectors that cannot identify objects leave both empty.
	Objects        []ObjectRef `json:"objects,omitempty"`
	ObjectsOmitted int         `json:"objectsOmitted,omitempty"`
}

type AddOnInstance

type AddOnInstance struct {
	ID string `json:"id"` // registry id, e.g. "ingress-nginx"
	// Version is the app version (a Helm release's appVersion, else the
	// image tag's or app.kubernetes.io/version label's), normalised; may be "".
	Version string `json:"version"`
	// ChartVersion is the Helm chart version, kept as evidence when the
	// add-on was found through a release; registry data never uses it.
	ChartVersion string `json:"chartVersion,omitempty"`
	// Namespaces is empty for an install known only from a cluster-scoped
	// IngressClass.
	Namespaces []string `json:"namespaces"`
	// Source is the strongest evidence found: "chart" (a Helm release),
	// "image" (an image matcher), "gitops" (a GitOps tool's chart source,
	// which gives no app version), "labels" (pod labels naming the add-on)
	// or "ingressclass" (an IngressClass controller; no version).
	Source string `json:"source"`
}

AddOnInstance is one install of a registry add-on. Collectors emit one per add-on and namespace (two where a Helm release's pods run images on another release line than its appVersion), so an ID can appear several times, each with its own version; inventories from agents that predate that carry one merged entry per ID (the oldest version, every namespace).

type CRD added in v0.2.0

type CRD struct {
	Group    string       `json:"group"`
	Kind     string       `json:"kind"`
	Plural   string       `json:"plural"`
	Versions []CRDVersion `json:"versions"` // spec.versions, in spec order
	// StoredVersions is status.storedVersions: every version objects may
	// have been persisted at since the CRD was created. Empty in files
	// mode, where a manifest's status says nothing about a cluster.
	StoredVersions []string `json:"storedVersions,omitempty"`
	// Usage counts, per version and as Inventory.APIUsage does per GVK
	// (with this CRD's Group and Kind), the custom resources that use a
	// version that is deprecated, not served, or missing from Versions:
	// live objects some manager still writes through it (ObjectRef.Manager
	// names it), manifest objects at it. Sorted by Version.
	Usage []APIUsage `json:"usage,omitempty"`
}

CRD is one CustomResourceDefinition (apiextensions.k8s.io/v1): the versions it serves and stores, and the custom resources that use a version it deprecates, does not serve, or no longer lists.

func (CRD) PreferredVersion added in v0.2.0

func (c CRD) PreferredVersion() string

PreferredVersion is the version to read and write a CRD's custom resources at: the storage version when it is served and not deprecated, else the highest-priority such version; "" when there is none. The collector lists custom resources at it, and the engine names it as the version to move them to.

type CRDVersion added in v0.2.0

type CRDVersion struct {
	Name               string `json:"name"`
	Served             bool   `json:"served"`
	Storage            bool   `json:"storage"`
	Deprecated         bool   `json:"deprecated,omitempty"`
	DeprecationWarning string `json:"deprecationWarning,omitempty"`
}

CRDVersion is one entry of a CRD's spec.versions.

type Capability

type Capability string
const (
	CapAPIUsage        Capability = "api-usage"
	CapDeprecatedCalls Capability = "deprecated-calls"
	CapHelm            Capability = "helm"
	CapAddOns          Capability = "addons"
	CapVersions        Capability = "versions"
	// CapCRDs: CustomResourceDefinitions' versions, and the custom
	// resources that use one the CRD deprecates or does not serve.
	// Inventories from collectors that predate it do not report it.
	CapCRDs Capability = "crds"
	// CapVolumes: the in-tree volume plugins pods, pod templates and
	// PersistentVolume manifests name (Inventory.VolumePlugins, #351). It is
	// optional, and inventories from collectors that predate it do not
	// report it.
	CapVolumes Capability = "volumes"
)

type CapabilityStatus

type CapabilityStatus struct {
	Available bool   `json:"available"`
	Reason    string `json:"reason,omitempty"` // e.g. `nodes list forbidden`
	// Partial marks an available capability that could not read all it
	// covers: one forbidden resource among many, an API group whose
	// discovery failed, a Helm release that could not be read. Its data is
	// incomplete; Reason says what failed. An available capability with a
	// Reason but not Partial (helm's per-driver release counts) is complete.
	Partial bool `json:"partial,omitempty"`
	// Skipped names what a Partial capability did not read, sorted, in the
	// capability's own terms:
	//   - api-usage: the flagged APIs whose objects went unchecked,
	//     "group/version Kind" ("policy/v1beta1 PodSecurityPolicy"; core
	//     renders as "v1 Endpoints");
	//   - deprecated-calls: the resources the scanner lists itself at a
	//     deprecated version, "group/version resource", whose metric rows
	//     cannot be told apart from its own requests;
	//   - helm: storage drivers not read ("configmaps") and releases not
	//     read, not decodable, left out for a name or chart metadata the
	//     server would refuse, or whose manifest was not fully parsed
	//     ("namespace/name", an invalid name quoted and cut: see
	//     Inventory.Conform); GitOps tools that deploy charts without
	//     leaving a Helm release the scan can read, or whose custom
	//     resources it could not read (GitOpsArgoCD, GitOpsFlux);
	//   - versions: the control-plane components with a kube-system pod
	//     whose version could not be read where upstream would have told
	//     it ("kube-proxy", "kube-scheduler"): an upstream-named image
	//     with no version tag, or any unread kube-apiserver,
	//     kube-controller-manager or kube-scheduler pod. A kube-proxy pod
	//     on a vendor image of another name (OKE's oke-public-kube-proxy)
	//     is named in Reason only, so Skipped may be empty. "nodes"
	//     means the Node list was empty, so kubelet skew and node
	//     runtimes were not assessed (#174);
	//   - addons: resources not read for add-on evidence,
	//     "group/version resource" ("networking.k8s.io/v1 ingressclasses",
	//     "v1 pods", SkippedPods);
	//   - api-usage, helm and addons, as the server adds them to a snapshot
	//     collected with another knowledge base than its own:
	//     SkippedNewerKB;
	//   - crds: the custom resources not checked for use of a deprecated
	//     or unserved CRD version, "group/version Kind"
	//     ("cert-manager.io/v1alpha2 Certificate").
	// May be empty when nothing nameable was skipped (a discovery failure
	// in a group without flagged APIs).
	Skipped []string `json:"skipped,omitempty"`
}

type CollectorSchemaError added in v0.2.0

type CollectorSchemaError struct {
	Got int
}

CollectorSchemaError is an inventory from a later collector generation than this module knows, or a negative one: field meanings it would judge as its own.

func (*CollectorSchemaError) Error added in v0.2.0

func (e *CollectorSchemaError) Error() string

type ComponentVersion

type ComponentVersion struct {
	Component string `json:"component"` // e.g. "kube-apiserver"
	Version   string `json:"version"`   // raw image tag, e.g. "v1.34.2"; always ParseVersion-able
	// Node is the node a kube-proxy pod runs on (pod.Spec.NodeName), so the
	// engine can pair it with that node's kubelet. Empty for other
	// components, for a pod not yet scheduled, and in inventories from
	// collectors before the field.
	Node string `json:"node,omitempty"`
}

ComponentVersion is one observed control-plane component version, detected from kube-system pod image tags (kube-apiserver, kube-controller-manager, kube-scheduler, kube-proxy). The list is (Component, Version)-deduped and sorted, except kube-proxy, which is listed once per node it runs on (Node); managed control planes (EKS/GKE) expose no such pods, so the slice is empty there.

type DeprecatedCall

type DeprecatedCall struct {
	Group          string `json:"group"`
	Version        string `json:"version"`
	Resource       string `json:"resource"`
	Subresource    string `json:"subresource,omitempty"`
	RemovedRelease string `json:"removedRelease,omitempty"` // "1.32" (may be empty)
}

type GitOpsChart added in v0.2.0

type GitOpsChart struct {
	Tool string `json:"tool"` // GitOpsArgoCD or GitOpsFlux
	// Name and Namespace are the Application's or HelmRelease's own.
	Name      string `json:"name"`
	Namespace string `json:"namespace,omitempty"`
	// Target is the namespace the chart deploys into: an Application's
	// destination.namespace, a HelmRelease's targetNamespace or else its
	// own namespace; "" when the resource leaves it to the manifests.
	Target string `json:"target,omitempty"`
	Chart  string `json:"chart"`
	// Version is the chart version as the resource spells it, which may be
	// a constraint ("4.*", ">=4.0.0"), a tag, or the digest a Flux
	// OCIRepository pins ("sha256:..."; Flux applies a digest over a semver
	// range over a tag, and so is it recorded); "" when it names none. An
	// Argo CD source's is its targetRevision.
	Version string `json:"version,omitempty"`
	// Repo is an Application's repoURL, a HelmRelease's chart source
	// ("HelmRepository/flux-system/ingress-nginx") or the URL of the
	// OCIRepository it references. A URL is recorded without userinfo,
	// query string or fragment. A token embedded in the path (Cloudsmith's
	// dl.cloudsmith.io/<token>/...) cannot be told from a path and is kept.
	Repo string `json:"repo,omitempty"`
}

GitOpsChart is a Helm chart a GitOps tool deploys into the cluster, read from the tool's own custom resource: an Argo CD Application source with chart set (or a native OCI source: repoURL oci://..., no chart field), or a Flux HelmRelease. Argo CD renders with helm template and leaves no release the Helm collector can read, so this is all that is known of its chart: no appVersion, no stored manifest. (Flux's helm-controller does leave a release Secret, which the Helm collector reads on its own.) Only resources that deploy into the scanned cluster are listed.

type HelmRelease

type HelmRelease struct {
	Name         string `json:"name"`
	Namespace    string `json:"namespace"`
	ChartName    string `json:"chartName"`
	ChartVersion string `json:"chartVersion"`
	AppVersion   string `json:"appVersion,omitempty"`
	// KubeVersion is the chart's Chart.yaml kubeVersion constraint, verbatim
	// (e.g. ">=1.21.0-0 <1.33.0-0"); "" when the chart declares none.
	KubeVersion string `json:"kubeVersion,omitempty"`
	// Status and Revision identify the revision everything else was read
	// from: the installed one, which is the newest revision unless that one
	// failed (then the newest deployed or superseded revision before it).
	// A release with nothing installed (uninstalled with --keep-history, or
	// only failed revisions) is not listed. Revision is 0 in inventories
	// from agents that predate it, whose Status is the newest revision's.
	Status   string `json:"status"` // deployed, superseded, pending-upgrade…
	Revision int    `json:"revision,omitempty"`
	// ManifestAPIs are the objects in that revision's stored manifest at a
	// group/version/kind the collector's KB flags as deprecated or removed,
	// per GVK as in Inventory.APIUsage. Refs carry the object's line in the
	// manifest (no File) and its template (RenderedFrom); Namespace is
	// empty where the chart leaves metadata.namespace unset.
	ManifestAPIs []APIUsage `json:"manifestApis,omitempty"`
}

type IdentifierError added in v0.2.0

type IdentifierError struct {
	Field    string   // JSON path within the inventory, e.g. "apiUsage[3].namespaces"
	Value    string   // the identifier
	Rule     string   // what it must be
	Problems []string // why it is not, as k8s.io/apimachinery says
}

IdentifierError is an identifier in an inventory, or a cluster name, that is not valid for what it names.

func (*IdentifierError) Error added in v0.2.0

func (e *IdentifierError) Error() string

func (*IdentifierError) Unquoted added in v0.2.0

func (e *IdentifierError) Unquoted() string

Unquoted says which field holds an identifier that is not what it must be, and nothing of the identifier: what may be shown where the inventory's contents must not be. Field holds no map key.

type Inventory

type Inventory struct {
	SchemaVersion int    `json:"schemaVersion"` // 1
	ClusterID     string `json:"clusterId"`     // kube-system ns UID, or "files"
	// CollectorSchema is CurrentCollectorSchema in every inventory this
	// package collects. It is absent (0) from those of collectors that
	// predate it — v0.1.x and v0.2.0's release candidates — which the
	// server tells apart by the pushing agent's version.
	CollectorSchema int       `json:"collectorSchema,omitempty"`
	Source          Source    `json:"source,omitempty"`
	CollectedAt     time.Time `json:"collectedAt"`
	ServerVersion   string    `json:"serverVersion,omitempty"` // raw GitVersion, e.g. "v1.34.2", "v1.34.2-gke.100"
	// Provider is eks, gke, aks, or other when the cluster shows none of
	// them; empty when it was not determined: a files inventory, one from
	// a collector that predates the field, or a live cluster whose nodes
	// could not be listed and whose server version names no provider.
	Provider           Provider                        `json:"provider,omitempty"`
	Capabilities       map[Capability]CapabilityStatus `json:"capabilities"`
	APIUsage           []APIUsage                      `json:"apiUsage,omitempty"`
	DeprecatedCalls    []DeprecatedCall                `json:"deprecatedCalls,omitempty"`
	HelmReleases       []HelmRelease                   `json:"helmReleases,omitempty"`
	GitOpsCharts       []GitOpsChart                   `json:"gitopsCharts,omitempty"`
	AddOns             []AddOnInstance                 `json:"addOns,omitempty"`
	Nodes              []NodeInfo                      `json:"nodes,omitempty"`
	ControlPlane       []ComponentVersion              `json:"controlPlane,omitempty"`
	Namespaces         []NamespaceInfo                 `json:"namespaces,omitempty"`
	UnrecognizedImages []string                        `json:"unrecognizedImages,omitempty"` // repos ("host/path") no image matcher claims; deduped, sorted, cap MaxUnrecognizedImages

	// UnrecognizedImagesOmitted counts the UnrecognizedImages the cap
	// dropped. Both are add-on detection gaps, never findings.
	UnrecognizedImagesOmitted int `json:"unrecognizedImagesOmitted,omitempty"`

	CRDs []CRD `json:"crds,omitempty"` // sorted by Group, then Kind

	// APIAuthorshipUnknown holds the objects of a flagged kind that nothing
	// can be attributed to (live clusters only): no managedFields entry
	// outside the status subresource and the control plane's managers, and
	// no usable last-applied annotation, as an object created through a
	// deprecated version with an empty spec has. Shaped like APIUsage, once
	// per kind (under one of its flagged versions). The object may as well
	// have been created through the replacement, so the engine reports it as
	// info and never as use of the deprecated API.
	APIAuthorshipUnknown []APIUsage `json:"apiAuthorshipUnknown,omitempty"`

	// APIServerStartTime is the process_start_time_seconds of the
	// kube-apiserver whose /metrics DeprecatedCalls were read from, in
	// whole seconds: apiserver_requested_deprecated_apis counts requests
	// since then. Zero when the scrape did not report it, and in
	// inventories from collectors that predate it. It describes which
	// apiserver answered, not the cluster, so it is not part of a
	// snapshot's identity: the agent's and the server's canonical hashes
	// leave it out, as they do CollectedAt, and an agent that moves between
	// HA apiservers sends the same snapshot.
	APIServerStartTime time.Time `json:"apiServerStartTime,omitzero"`

	// AddOnEvidenceAgeSeconds is how old the pod evidence the add-ons were
	// detected from was, in whole seconds (at least 1), when a collection
	// reused it: the agent lists the pods outside kube-system only every
	// --pod-pass-every ticks (or --pod-pass-max-age), and in between detects
	// add-ons from the images and labels the last full pass read (#228). An
	// add-on installed or upgraded since is then reported as it was at that
	// pass, for at most this long: a pass of --pod-pass-max-age or more is
	// not reused, so this is below it when the collection began, and the
	// report stays up until the next one. A change in the Helm releases or
	// GitOps charts that name an add-on forces a full pass instead.
	// Absent (0) when every pod was read in this collection, as a scan's
	// always are, and in inventories from collectors that predate the field.
	// The kube-system pods, Helm releases, GitOps resources and IngressClasses
	// are read in every collection whatever this says. It describes how the
	// snapshot was collected, not the cluster, so it is not part of a
	// snapshot's identity: Canonical leaves it out, as it does the times.
	AddOnEvidenceAgeSeconds int64 `json:"addOnEvidenceAgeSeconds,omitempty"`

	// VolumePlugins are the in-tree volume plugins (kb.VolumePluginNames)
	// the volumes capability found, one entry per plugin, sorted by Plugin;
	// see VolumePluginUse.
	VolumePlugins []VolumePluginUse `json:"volumePlugins,omitempty"`
}

func (*Inventory) Admit added in v0.2.0

func (inv *Inventory) Admit() error

Admit checks a decoded inventory before it is judged, as the server does every push: its schemaVersion is SupportedSchemaVersion, its collectorSchema none or at most CurrentCollectorSchema, its serverVersion, when it has one, a Kubernetes 1.x version, its identifiers valid (ValidateIdentifiers), and, once the free text collectors copy whole is cut to the limits (CutFreeText, which changes inv), its other values within them (ValidateLimits). It returns the first problem as a *SchemaVersionError, *CollectorSchemaError, *ServerVersionError, *IdentifierError or *LimitError, whose Error quotes the value at fault (in part, where it can be long); IdentifierError.Unquoted and LimitError.Unquoted say the same without it. An inventory with no serverVersion at all (its versions collector failed) is admitted.

func (Inventory) Canonical added in v0.2.0

func (inv Inventory) Canonical() Inventory

Canonical returns inv without what describes the collection and not the cluster: CollectedAt (it changes every tick), APIServerStartTime (it says which apiserver answered the /metrics scrape, and moves with HA apiservers) and AddOnEvidenceAgeSeconds (it grows with each tick that reuses a pod pass). It also puts in a fixed order the two lists whose order the report does not depend on but which a pusher may order differently: each CRD's Versions (by Name) and each capability's Skipped (#367); they are copied, so inv is not reordered. The agent's and the server's snapshot hashes are over this form, so a push that differs only in those is a duplicate.

func (*Inventory) Conform added in v0.2.0

func (inv *Inventory) Conform() (notes []string, err error)

Conform repairs an inventory a collector built so that Admit does not refuse it, and records every repair in the status of the capability it cost data: the capability is marked Partial, Skipped names what was not recorded, and Reason says how much and why. A capability the collector never reported stays absent (the server reads that as a gap of its own); the repair is in the notes only. A collector reads identifiers and strings from objects the apiserver validated, and so Admit holds the server to them; but a Helm release's name is a label value, the objects in its stored manifest are text inside a payload anyone who can create a Secret can plant, and an image string or a chart's kubeVersion has no limit of its own. One such object must not make the server refuse (422) every push of a cluster for ever, as the agent would offer the same inventory each tick: the entry that is not valid is left out, and said to be, and the rest is sent.

It repairs, in order:

  • the free text CutFreeText cuts;
  • a Helm release whose name or namespace is not an identifier, or any of whose strings is over MaxStringBytes (its chart's name, version, appVersion or kubeVersion, the last of which a cut would turn into a narrower constraint): the release is dropped, and named in helm's Skipped by its namespace and name, cut where long;
  • an object of an API usage entry (apiUsage, apiAuthorshipUnknown, a release's manifestApis, a CRD's usage) whose namespace or name is not an identifier, or whose strings are over the limit: the object is dropped and counted in objectsOmitted, and a namespace key that is not a namespace name is dropped from the entry's namespaces;
  • an API usage entry (apiUsage, apiAuthorshipUnknown, a release's manifestApis, a CRD's usage) with a negative count, objectsOmitted or namespace count, which no collector writes and which the engine would read as nothing found (a Helm release's) or as "-5 objects": the entry is dropped by dropElement, named in api-usage's Skipped (a release's whole, named in helm's, a CRD's whole);
  • an add-on install any of whose strings (id, version, chartVersion, source) is over MaxStringBytes: dropped, in one pass, and addons names SkippedPods, as an install that is gone may be what blocks an upgrade. An image tag is a pod creator's, so a version can be 17 KiB of digits and pods in any number of namespaces make as many such installs; the one-at-a-time net below could not keep up;
  • a volume plugin entry (volumePlugins): its objects and namespace keys as an API usage entry's; an entry whose plugin is not a field name, or whose counts are negative, is dropped (dropElement), and the entries beyond MaxVolumePlugins are dropped, each named in volumes' Skipped by its plugin, quoted and cut where it is not a field name;
  • unrecognizedImages over MaxStringBytes, or beyond MaxUnrecognizedImages: dropped and counted in unrecognizedImagesOmitted;
  • whatever else Admit's identifier and limit checks still refuse, one element of its list at a time (see dropElement): an element it cannot drop is returned as the error, as Admit would.

It returns what it did, one line per kind of repair and capability, for a log; err is the first thing Admit still refuses after the repairs, which it does not repair (the schema versions, the server version, the capabilities), or nil: an inventory it returns no error for passes Admit.

func (*Inventory) CutFreeText added in v0.2.0

func (inv *Inventory) CutFreeText() bool

CutFreeText cuts the free text a collector copies whole from what it reads, and that Kubernetes lets be longer than the limits, to them, and reports whether it cut anything. None of it is needed whole:

  • a capability's Reason (one error per resource it could not read: a CRD collector without RBAC for custom resources adds ~200 bytes per CRD at a deprecated version) to MaxReasonBytes, and each Skipped entry to MaxStringBytes, ending in cutMark;
  • an object's Ignore and IgnoreReason, the upgradescope.basit.engineer/ignore and ignore-reason annotations (up to 256 KiB), to MaxStringBytes: Ignore to the comma-separated tokens that fit whole, IgnoreReason ending in cutMark;
  • an object's RenderedFrom, the text of a Helm manifest's "# Source:" comment, to MaxStringBytes, ending in cutMark;
  • a GitOps chart's Chart, Version and Repo, copied from a custom resource's spec, to MaxStringBytes, ending in cutMark.

Each cut keeps whole UTF-8 characters. Collect calls it, and the server calls it on every push before ValidateLimits, so older agents' pushes are cut rather than refused.

func (Inventory) ValidateIdentifiers added in v0.2.0

func (inv Inventory) ValidateIdentifiers() error

ValidateIdentifiers checks every Kubernetes identifier in inv against the rule the apiserver applies to it, and returns the first that fails as an *IdentifierError: namespace names (API usage namespaces and object refs, Helm releases, add-on installs, the namespace list), object names, node names (a kube-proxy's too) and Helm release names, and team label values, and the provider name, bounded as a label value (an unknown provider is accepted: see ruleProvider). Fields that are not identifiers (versions, image repositories, field managers, annotation values) are not checked.

func (Inventory) ValidateLimits added in v0.2.0

func (inv Inventory) ValidateLimits() error

ValidateLimits checks what ValidateIdentifiers does not, and returns the first problem as a *LimitError:

  • every string, map keys included, is at most MaxStringBytes, a capability's reason at most MaxReasonBytes, and an object's manager at most MaxManagerBytes of printable characters, as the apiserver requires of a managedFields manager;
  • an API usage entry's count, objectsOmitted and every namespace's count are at least zero, in each of those lists;
  • an API usage entry lists at most MaxObjectRefs objects (collectors count the rest in objectsOmitted), and a list of them (apiUsage, apiAuthorshipUnknown, a Helm release's manifestApis, a CRD's usage) names each group/version/kind once, as every collector counts them;
  • unrecognizedImages lists at most MaxUnrecognizedImages, and capabilities at most MaxCapabilities.

type LimitError added in v0.2.0

type LimitError struct {
	Field   string // JSON path within the inventory, e.g. "apiUsage[3].objects"
	Problem string // what is wrong, quoting (a prefix of) the value at fault

	// At is Field with each map key in it shown as […], and Limit is
	// Problem without the value: what Unquoted says.
	At, Limit string
}

LimitError is a value in an inventory beyond what any collector records.

func (*LimitError) Error added in v0.2.0

func (e *LimitError) Error() string

func (*LimitError) Unquoted added in v0.2.0

func (e *LimitError) Unquoted() string

Unquoted says where the inventory breaks which limit, and nothing of what it holds there, map keys included: what may be shown where the inventory's contents must not be.

type NamespaceInfo

type NamespaceInfo struct {
	Name string `json:"name"`
	Team string `json:"team,omitempty"` // from --team-label (default "team")
}

type NodeInfo

type NodeInfo struct {
	Name           string `json:"name"`
	KubeletVersion string `json:"kubeletVersion"` // raw, e.g. "v1.33.1", "v1.33.1-eks-aeac579"
	// ContainerRuntime is status.nodeInfo.containerRuntimeVersion, raw:
	// "<runtime>://<version>", e.g. "containerd://1.7.27".
	ContainerRuntime string `json:"containerRuntime,omitempty"`
}

type ObjectRef added in v0.2.0

type ObjectRef struct {
	Namespace    string `json:"namespace,omitempty"`
	Name         string `json:"name,omitempty"`
	File         string `json:"file,omitempty"`
	Line         int    `json:"line,omitempty"`
	RenderedFrom string `json:"renderedFrom,omitempty"`
	Manager      string `json:"manager,omitempty"`
	Ignore       string `json:"ignore,omitempty"`
	IgnoreReason string `json:"ignoreReason,omitempty"`

	IgnoreLegacyKey       bool `json:"-"`
	IgnoreReasonLegacyKey bool `json:"-"`
}

ObjectRef identifies one object using an API. Namespace/Name are the object's identity (empty Namespace: metadata.namespace unset, or a cluster-scoped object). File and Line are set only for objects read from manifest text: File is slash-separated and relative to the scanned root (empty for a single posted stream); Line is the 1-based line of the object's apiVersion key. RenderedFrom is the Helm template the object was rendered from, taken from helm template's "# Source: <chart>/templates/x.yaml" comment. Manager is set only for live objects flagged because they were written through the deprecated group/version: the metadata.managedFields manager that wrote it, or "kubectl last-applied" when only the kubectl.kubernetes.io/last-applied-configuration annotation names it. Ignore and IgnoreReason are the object's ignore and ignore-reason annotation values (apigroup.IgnoreAnnotation, IgnoreReasonAnnotation), verbatim (see internal/suppress). IgnoreLegacyKey and IgnoreReasonLegacyKey mark the ignore and the ignore-reason value as read from a pre-v0.2.0 key (apigroup.ReadIgnore), each apart, for suppress's deprecation warning; they never leave the process (json "-"), so the wire format and the report keep no field that v0.3.0 drops.

func (ObjectRef) LegacyIgnore added in v0.2.0

func (r ObjectRef) LegacyIgnore() bool

LegacyIgnore reports that either ignore annotation came from a pre-v0.2.0 key.

type Provider added in v0.2.0

type Provider string

Provider is the managed Kubernetes service a cluster's control plane is bought from, inferred by the collector from signals only that service produces (see collect.providerEvidence). It is never guessed: a cluster that does not show one of the three is ProviderOther, and one whose evidence could not be read is left empty (undetermined), not ProviderOther.

const (
	ProviderEKS   Provider = "eks"
	ProviderGKE   Provider = "gke"
	ProviderAKS   Provider = "aks"
	ProviderOther Provider = "other"
)

type SchemaVersionError added in v0.2.0

type SchemaVersionError struct {
	Got int
}

SchemaVersionError is an inventory of a schemaVersion this module does not judge ({} and a missing one included).

func (*SchemaVersionError) Error added in v0.2.0

func (e *SchemaVersionError) Error() string

type ServerVersionError added in v0.2.0

type ServerVersionError struct {
	Err error
}

ServerVersionError is an inventory whose serverVersion is not a Kubernetes 1.x version. Err, from parseMajorOne, quotes the value.

func (*ServerVersionError) Error added in v0.2.0

func (e *ServerVersionError) Error() string

func (*ServerVersionError) Unwrap added in v0.2.0

func (e *ServerVersionError) Unwrap() error

type Source added in v0.2.0

type Source string

Source records how an inventory was collected. It decides which capabilities the engine requires before it can call a cluster ready.

const (
	// SourceCluster: collected from a live cluster (scan, agent). The empty
	// Source means the same — v0.1 agents push inventories without it.
	SourceCluster Source = "cluster"
	// SourceFiles: built from rendered manifests (scan --files, the server's
	// manifest gate). There is no cluster, so no versions to collect.
	SourceFiles Source = "files"
)

type Version

type Version struct{ Major, Minor int }

Version is a Kubernetes minor version (e.g. 1.34). Patch is ignored for evaluation.

func OldestCovered added in v0.2.0

func OldestCovered() Version

OldestCovered returns the oldest Kubernetes minor the knowledge base covers (see oldestCoveredMinor), the floor of every user-supplied target.

func ParseClusterVersion added in v0.2.0

func ParseClusterVersion(s string) (Version, error)

ParseClusterVersion parses the version a cluster runs (a --from flag): ParseVersion plus major == 1, with no floor, because a cluster's own version is judged, not refused, however old it is (Admit does the same for an inventory's serverVersion).

func ParseTarget added in v0.2.0

func ParseTarget(s string) (Version, error)

ParseTarget parses a user-supplied upgrade target (a --target flag, a ClusterReadiness spec target, a gate's target query parameter): ParseVersion plus major == 1, since Kubernetes has only ever shipped major 1 and "2.0" is a typo, not a target, plus a minor of at least OldestCovered. A minor below it is what YAML makes of a version written as a number: target: 1.30 is the number 1.3, and 1.3 would judge nothing (no API is removed before 1.16) and read ready, so it is refused, with the pitfall named.

func ParseVersion

func ParseVersion(s string) (Version, error)

ParseVersion parses a Kubernetes version string. Accepted forms: "1.34", "v1.34", "v1.34.2", "1.34.2", and — for versions observed on real clusters — MAJOR.MINOR.PATCH followed by a semver pre-release and/or build suffix, as vendors report in GitVersion: "v1.30.2-eks-1234abc" (EKS), "v1.29.4-gke.1043002" (GKE), "v1.28.5+k3s1" (k3s), "v1.27.3+rke2r1" (RKE2), "v1.29.5+29a0aa9" (OpenShift). The patch and suffix are validated but discarded — evaluation only cares about minors.

The major version is not range-checked here: callers validating user input (a --target flag, a CRD spec target) additionally require major 1.

func (Version) Compare

func (v Version) Compare(o Version) int

Compare returns -1 if v < o, 0 if equal, 1 if v > o.

func (Version) MarshalJSON

func (v Version) MarshalJSON() ([]byte, error)

MarshalJSON emits the canonical wire form, a string like "1.38" — matching String() and the camelCase report contract.

func (Version) Next

func (v Version) Next() Version

Next returns the following minor version: 1.34 → 1.35.

func (Version) String

func (v Version) String() string

String renders the minor version, e.g. "1.34". Never includes a "v" prefix.

func (*Version) UnmarshalJSON

func (v *Version) UnmarshalJSON(data []byte) error

UnmarshalJSON accepts the canonical string form ("1.38", anything ParseVersion takes) and, for back-compat with datasets written before the string form existed, the legacy object form {"Major":1,"Minor":38} (strict: unknown keys rejected).

type VolumePluginUse added in v0.2.0

type VolumePluginUse struct {
	Plugin         string         `json:"plugin"`
	Count          int            `json:"count"`
	Namespaces     map[string]int `json:"namespaces,omitempty"`
	Objects        []ObjectRef    `json:"objects,omitempty"`
	ObjectsOmitted int            `json:"objectsOmitted,omitempty"`
}

VolumePluginUse is one in-tree volume plugin in use (#351): the pods, PersistentVolumes and StorageClasses (live, #362) or the pod templates, pods, PersistentVolumes and StorageClasses (manifests) that name it, by its field name in corev1.VolumeSource or corev1.PersistentVolumeSource ("glusterfs", "awsElasticBlockStore"); a StorageClass names it by its in-tree provisioner ("kubernetes.io/rbd").

Count is how many name it, each once whatever the number of its volumes that do. Namespaces counts them per namespace (live, a bound PersistentVolume under its claim's; "" for an unbound one and a StorageClass, which are cluster-scoped, and for a manifest object without metadata.namespace). Objects names them, at most MaxObjectRefs, ObjectsOmitted counting the rest: in manifests located (File, Line, and the object's Namespace and Name); live, the PersistentVolumes and StorageClasses by Name only. A live collection names no pod, so its size does not grow with the pods. Between full pod passes, the agent reports the pods outside kube-system as the last full pass read them, for at most Inventory.AddOnEvidenceAgeSeconds.

Jump to

Keyboard shortcuts

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