Documentation
¶
Overview ¶
Package collect builds an inventory.Inventory from a live cluster (or, in files mode, from rendered manifests). Sub-collectors degrade independently: an error marks the capability unavailable with a reason instead of failing the whole collection (spec §9).
Index ¶
- Constants
- func AssessCRDs(inv *inventory.Inventory, crds []inventory.CRD)
- func Collect(ctx context.Context, c Clients, k kb.KB, opts Options) inventory.Inventory
- func CollectManifests(r io.Reader, addons []registry.AddOn) (inventory.Inventory, error)
- type Clients
- type DiscoveryCache
- type FileWarning
- type FilesSummary
- type GitOpsCache
- type HelmCache
- type Options
- type PodPassCache
- type UnrenderedChart
Constants ¶
const ( IgnoreAnnotation = apigroup.IgnoreAnnotation IgnoreReasonAnnotation = apigroup.IgnoreReasonAnnotation )
The annotations that accept findings for one object, recorded on its ObjectRef by both the live and the files collector: a comma-separated list of finding categories or keys, and why (see internal/suppress). Their pre-v0.2.0 keys are still read (apigroup.ReadIgnore).
const ( // DefaultPodPassEvery is the default of --pod-pass-every: at the default // interval of 10 minutes, a full pod pass about every 30 minutes. DefaultPodPassEvery = 3 // DefaultPodPassMaxAge is the default of --pod-pass-max-age. DefaultPodPassMaxAge = time.Hour )
Defaults of the agent's --pod-pass-every and --pod-pass-max-age (#228).
const DiscoveryMaxAge = time.Hour
DiscoveryMaxAge is the oldest API discovery a DiscoveryCache serves.
const ForbiddenListRecheck = time.Hour
ForbiddenListRecheck is how long a GitOpsCache remembers a refused list: once that much time has passed it is asked for again, so a list granted later is used within the hour.
Variables ¶
This section is empty.
Functions ¶
func AssessCRDs ¶ added in v0.2.0
AssessCRDs judges the custom resources in inv.APIUsage against crds as files mode judges a render against the CRDs in it (assessCRDs): a later definition of a group and kind replaces an earlier one, inv.CRDs gets the result, each with the custom resources at a version it deprecates, does not serve or does not list as its Usage, and the crds capability is partial, naming them, when custom resources have no CRD among crds. inv.Capabilities must not be nil. The server gate judges posted manifests with it against a cluster's CRDs merged with the manifests' own (#150).
func Collect ¶
Collect builds an Inventory from a live cluster. It never returns an error: each sub-collector failure becomes Capabilities[cap] = {Available: false, Reason: err.Error()} and collection continues. Each sub-collector runs under its own share of ctx's deadline (see runSteps), so one stalled step cannot starve the others.
func CollectManifests ¶
CollectManifests builds an Inventory from a single concatenated YAML/JSON manifest stream (the server's CI gate endpoint body). Same parsing as CollectFiles, but a document that fails to decode is an error rather than a warning: the stream is one deliberate request body, and an API response has nowhere to put a warning, so silently dropping it would be a false pass. Warnings about documents decoded anyway (duplicate keys, objects located by kubectl's decoder) are dropped. Object refs carry stream lines and no file. Add-ons and CRDs are assessed as CollectFiles assesses them, so the server gate without ?cluster= judges a render as scan --files does. With ?cluster=, the gate merges this inventory's API usage, add-ons and CRDs into the cluster's and judges its custom resources again against the merged CRDs (AssessCRDs).
Types ¶
type Clients ¶
type Clients struct {
Kube kubernetes.Interface
Metadata metadata.Interface
Discovery discovery.DiscoveryInterface
RESTClient rest.Interface
// APIExtensions reads CustomResourceDefinitions (the crds capability).
APIExtensions apiextensionsclient.Interface
// Dynamic reads the Argo CD and Flux custom resources that name the
// charts they deploy (the helm capability). Nil: they are not read.
Dynamic dynamic.Interface
}
Clients bundles the API clients the live-cluster sub-collectors need. Any nil client degrades the capabilities that depend on it.
func NewClients ¶
NewClients builds the concrete client set from a rest.Config. The sole construction point — everything else consumes the interfaces.
API warning headers are discarded: client-go's default handler prints each one to stderr as a klog line, above the report and in agent logs, and the deprecations they announce are already findings. Without a caller-set rate limit, clientQPS/clientBurst apply. The caller's cfg is not modified.
type DiscoveryCache ¶ added in v0.2.0
type DiscoveryCache struct {
// contains filtered or unexported fields
}
DiscoveryCache keeps what API discovery returned between the agent's ticks (#228), so a steady tick does not ask the apiserver again which groups, versions and resources it serves: 4 requests of every tick, plus one for each GitOps group-version the cluster serves (6 with the Argo CD and Flux CRDs), asked by the GitOps detection and by api-usage, whose answer changes only when the cluster's APIs do.
What it keeps is one complete answer of ServerGroupsAndResources, the call api-usage makes; GitOps detection's ServerGroups and ServerResourcesForGroupVersion are answered from it once it holds one. An answer with an error, even a partial one (a group whose discovery failed), is never kept, so a failure is asked again on the next call. The server version is never cached: the versions step asks for it on every tick, and an answer from another version empties the cache before any other step reads it, so an upgrade of the apiserver is seen on the tick it happens. Otherwise the answer is dropped, and asked again on the next tick, when
- it is DiscoveryMaxAge (an hour) old;
- the tick's CustomResourceDefinitions (their groups, kinds and served versions, read by the crds step) differ from those of the tick it was filled in, or the crds step could not list them: a CRD added, removed or changed is seen one tick later. Custom resources that could not be listed (the crds capability partial) are not a reason: the CRDs were still read;
so discovery is at most one tick behind a CRD change, and an hour behind any other change of the APIs served at the same version (an APIService registered, an API enabled by a restart with other flags). One exception: the CRDs of the tick that fills the cache are read by the crds step, after api-usage asked for discovery, so a CRD changed between those two steps is recorded as the CRDs discovery saw, and is seen only when the answer is dropped for another reason, at the latest when it is an hour old.
The zero value is not usable; a nil *DiscoveryCache caches nothing, which is what a one-shot scan has. One collection at a time.
func NewDiscoveryCache ¶ added in v0.2.0
func NewDiscoveryCache() *DiscoveryCache
NewDiscoveryCache returns an empty cache.
type FileWarning ¶ added in v0.2.0
type FileWarning struct {
File string // relative to the scanned root, slash-separated
Line int // 1-based line where the problem starts
Err error
// Unassessed: the document (or the rest of the file, after an error
// that ends it) was skipped, so no object in it was counted.
Unassessed bool
}
FileWarning is a problem with part of a file: a document that could not be decoded and was skipped (Unassessed), or one decoded the way kubectl decodes it despite a duplicate key.
func (FileWarning) String ¶ added in v0.2.0
func (w FileWarning) String() string
String is "file:line: error", or "dir: error" for a directory not walked (Line 0).
type FilesSummary ¶ added in v0.2.0
type FilesSummary struct {
Files int // regular files walked
Skipped int // files that held no Kubernetes object
Objects int // Kubernetes objects found (List items, not wrappers)
Warnings []FileWarning // in walk order
// Charts lists the directories holding a Chart.yaml (the outermost one
// of a nested chart) under which files could not be decoded and
// contain "{{": unrendered Helm templates. Their per-file warnings are
// not in Warnings, and api-usage is not assessed (see CollectFiles).
Charts []UnrenderedChart
// Templated counts the files outside any chart directory that could
// not be decoded and contain "{{". They are not in Warnings either, and
// do not change what is assessed.
Templated int
}
FilesSummary describes what a CollectFiles walk saw.
func CollectFiles ¶
CollectFiles builds an Inventory from rendered manifests on disk (--files mode, CI gating). root is a directory, walked recursively in lexical order for *.yaml/*.yml/*.json, or a single file, parsed whatever its extension. API usage, add-ons and CRDs are assessed offline: add-ons from the pod templates of workload manifests (images and labels, see podTemplateOf) and IngressClass controllers, with the matchers a live scan uses (matchAddOns); CRDs from CustomResourceDefinition manifests, which judge the custom resources in the files (assessCRDs). Every other capability degrades with reason "files mode": a manifest carries no cluster version and no Helm release.
A repository holds YAML that is not Kubernetes manifests (values files, workflows, unrendered chart templates), so non-manifest documents are skipped and documents that fail to decode become warnings in the summary, never an error; the caller decides what to do when no object was found. But a document that could not be decoded and whose text (or what kubectl's decoder finds in it) names an API the knowledge base lists as removed may hide a blocker: then api-usage is not available, its reason naming those documents, so the engine's verdict is at least unknown. Images in a document not decoded are not read either.
Object refs carry paths relative to root (the base name for a single file). A symlink named as root is resolved. VCS metadata and dependency trees below root are not walked (see skipDir), nor are symlinked directories, which kubectl apply -R does not walk either (following them could also leave the repository, or loop); each skipped directory but VCS metadata is a warning. Symlinked files are read, as kubectl reads them. Only I/O errors fail the walk.
type GitOpsCache ¶ added in v0.2.0
type GitOpsCache struct {
// contains filtered or unexported fields
}
GitOpsCache remembers, between a long-running caller's (the agent's) collections, which OCIRepository lists the apiserver refused (#248). A role granted get but not list on them (a namespaced Role, or one written for the agent before #248) refuses the cluster-wide list and then each namespace's before readOCIRepositories falls back to a GET by name: one refused request per namespace plus one, each an entry in the audit log, on every tick. With a cache, a refused list is not asked for again until ForbiddenListRecheck has passed since it was refused, so a steady tick goes straight to what worked; then it is asked again, and forgotten once it succeeds.
Only a refusal (403) is remembered: a list that failed otherwise is asked for again on the next call. A list is keyed by the API version it was asked at and its namespace, so a Flux upgrade that serves another version starts afresh, and a refusal is dropped once it is ForbiddenListRecheck old, so the cache holds at most one entry per namespace refused within that time, plus the cluster-wide list.
The zero value is not usable; a nil *GitOpsCache remembers nothing, which is what a one-shot scan has: it asks for each list once, in its one pass.
func NewGitOpsCache ¶ added in v0.2.0
func NewGitOpsCache() *GitOpsCache
NewGitOpsCache returns an empty cache.
type HelmCache ¶ added in v0.2.0
type HelmCache struct {
// contains filtered or unexported fields
}
HelmCache keeps what a long-running caller (the agent) decoded from each Helm release's installed revision, so a tick fetches only the storage objects it has not decoded yet instead of one per release (#71).
An entry is keyed by the object's namespace, name, UID and resourceVersion as the metadata-only list reports them, so an object that was replaced or written again is read again and nothing else is. What is kept is the few fields a release contributes to the inventory, never the payload, and an entry is dropped as soon as its object is no longer a release's installed revision, so the cache is as big as the cluster's release list and not its history. Entries also depend on which API versions the knowledge base flags (they record the manifest objects at those), so the cache empties itself when that set differs.
A fetch that failed leaves nothing behind. A payload that cannot be decoded, or a manifest that cannot be fully parsed, is remembered as such and reported on every tick in the same words without being downloaded again: it cannot get better until the object changes.
The zero value is not usable, and a nil *HelmCache is: it remembers nothing, which is what a one-shot scan wants. Not safe for concurrent use; one collection at a time.
func NewHelmCache ¶ added in v0.2.0
func NewHelmCache() *HelmCache
NewHelmCache returns an empty cache.
type Options ¶
type Options struct {
TeamLabel string // namespace label used for team attribution; default "team"
// HelmCache, when set, remembers the Helm releases an earlier Collect
// decoded, so this one fetches only the storage objects that are new or
// changed instead of one per release. A long-running caller (the agent)
// keeps one across calls; a one-shot scan leaves it nil.
HelmCache *HelmCache
// HelmNamespaces, when set, are the only namespaces Helm's release
// storage is listed and read in, never across the cluster (#344): the
// agent's --helm-namespaces, for a role that grants Secrets and
// ConfigMaps there alone (the chart's rbac.helmSecretsNamespaces). The
// helm capability is then partial, saying releases elsewhere were not
// assessed. Empty reads the whole cluster; a one-shot scan leaves it so.
HelmNamespaces []string
// DiscoveryCache, when set, keeps API discovery across calls under the
// staleness rules DiscoveryCache states, so a steady tick does not ask
// for it again. The agent keeps one; a one-shot scan leaves it nil.
DiscoveryCache *DiscoveryCache
// GitOpsCache, when set, remembers the OCIRepository lists the
// apiserver refused, so a role without list on them is not asked again
// on every call, only once ForbiddenListRecheck has passed. The agent
// keeps one; a one-shot scan leaves it nil.
GitOpsCache *GitOpsCache
// OnConform, when set, is called once per Collect with what the
// collector left out so that the server would accept the inventory
// (inventory.Conform's notes: counts and kinds, never an identifier),
// when it left out anything. The capability reasons carry the same
// for the report; this is for a log. The agent logs it every tick.
OnConform func(notes []string)
// PodPass, when set, reads the pods outside kube-system only every few
// collections and detects add-ons in between from the last full pass's
// images and labels (#228), under the rules PodPassCache states. The
// agent keeps one; a one-shot scan leaves it nil and reads every pod.
PodPass *PodPassCache
}
Options tunes collection behavior.
type PodPassCache ¶ added in v0.2.0
type PodPassCache struct {
// contains filtered or unexported fields
}
PodPassCache lets a long-running caller (the agent) read the pods outside kube-system only every few collections, and detect add-ons in between from the evidence the last full pass read (#228).
The pods are most of what a steady collection costs on a large cluster: at 2,001 nodes and about 14,000 pods, 16 of 31 requests and 79% of the bytes, decoded whole to read their images and labels. The cluster-wide list is the cost, and a watch or informer is excluded by design (AG-01), so the list is made less often. A collection reuses the last full pass while fewer than Every collections have run since it (the pass itself is the first of them) and it is less than MaxAge old, and otherwise lists every pod again. So an add-on installed or upgraded right after a pass is reported as it was for at most Every-1 collections, and never for longer than MaxAge: the age of what was reused is left in inventory.AddOnEvidenceAgeSeconds.
What is reused is the images and labels of the pods outside kube-system, the evidence matchAddOns reads, and how many of them name each in-tree volume plugin (the volumes capability, #351), never a verdict: the registry is applied to it every time, so a knowledge-base update takes effect at once. Not reused, read in every collection: the kube-system pods (the versions capability lists them for the control-plane components and kube-proxy skew, and the add-ons take their evidence from that list, #227), Helm releases, GitOps resources and IngressClasses.
A full pass is forced, whatever the counts say, when
- the cache holds no complete pass (it is new, or the last pass failed or read only some of its pages: a failed or partial pass is never reused, and the evidence of an earlier one is dropped with it);
- the versions capability did not list the kube-system pods in this collection, because the add-ons would then need them from the pass, and the pass does not hold them;
- the Helm releases and GitOps chart references that name a registry add-on are not those the pass was taken with (installSignature): they are read in every collection and joined with the pods, so a release upgraded across a release line would otherwise be reported beside a phantom install from the old pods, and a chart without an appVersion, or a GitOps add-on, would take its version from them. This costs no request: the releases are read anyway.
The cache holds the distinct (namespace, image) pairs and the distinct labelled pods among the pods outside kube-system, never the pods, so it is as big as the cluster's variety of images, at most what one pass retains while it matches. A collection that lists every pod drops the held pass before its first list (forget), so the old pass is never held beside the new one: the memory during a full pass is the evidence that pass reads plus the deduplicated copy record makes of it at the end, and a pass that fails at any page leaves nothing held.
Every <= 1 reuses nothing, as a nil *PodPassCache does, which is what a one-shot scan wants. Not safe for concurrent use; one collection at a time.
func NewPodPassCache ¶ added in v0.2.0
func NewPodPassCache(every int, maxAge time.Duration) *PodPassCache
NewPodPassCache returns an empty cache that reuses a full pass for the collections after it, up to every-1 of them, none that is maxAge or more after it began. every of 1 or less reuses nothing; a maxAge of 0 or less is no limit but the count.
func (*PodPassCache) Held ¶ added in v0.2.0
func (c *PodPassCache) Held() bool
Held reports whether a complete pass is held, for tests and diagnostics.
type UnrenderedChart ¶ added in v0.2.0
type UnrenderedChart struct {
Dir string // relative to the scanned root, slash-separated; "." for the root itself
Templates int
}
UnrenderedChart is a chart directory scanned unrendered: Templates files under it could not be decoded and contain "{{".