19 Commits
Author SHA1 Message Date
Виталий Чефанов e6dafc746c fix: distinguish recovered restarts and intentionally idle services 2026-10-27 08:39:47 +03:00
Виталий ЧефановandClaude Opus 5.5 8d9bac1840 v0.11.4: failed probes of a ready pod are information
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-28 16:53:59 +03:00
Виталий ЧефановandClaude Opus 5.5 58c4ffe804 v0.11.3: one FailedMount of a ready pod is information
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-28 16:46:05 +03:00
Виталий ЧефановandClaude Opus 5.5 4a63f57674 v0.11.2: events of finished or since-scheduled pods are history
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-26 14:22:43 +03:00
Виталий ЧефановandClaude Opus 5.5 8ed76cd01a v0.11.1: repeated restarts and OOM kills stay on the map for a day
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-25 22:50:08 +03:00
Виталий ЧефановandClaude Opus 5.5 4c5eb288cb v0.11.0: HTTP details on links where Cilium parses L7
Requests, response classes, p50/p95 latency and the busiest paths per link,
from Hubble L7 flows (method, path, status, latency only; headers are never
requested). The two inner legs of a proxied connection (Envoy -> pod, and the
pod's answers to the node on an ephemeral port) are no longer counted as
links.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-25 02:13:10 +03:00
Виталий ЧефановandClaude Opus 5.5 c50020e420 v0.10.0: each viewer sees what their own RBAC allows
Until now anyone admitted through Dex saw every namespace and every log,
read with the module's service account. auth.visibility: ViewerRBAC (the
default) asks the API server as the viewer, with the token the
DexAuthenticator forwards: list pods in all namespaces means the whole
cluster; otherwise the namespaces where they can list pods. Logs also
need get pods/log, node cards list nodes, cluster-wide alerts are for
cluster-wide viewers. Traffic to a hidden namespace keeps its counts with
the peer shown as hidden. One minute cache per token hash, SSARs in
parallel (8), a cluster-wide viewer costs two.

Verified against the live cluster with two real tokens: a service
account with view in one namespace got that namespace only (0 nodes, 403
on another namespace's YAML and logs, 403 on node usage); the module's
own account, cluster-wide, got all 56 namespaces and 6 nodes; no token,
401. auth.visibility: Everything keeps the old behaviour. The
DexAuthenticator now forwards the token when either actions or ViewerRBAC
need it (templates/_helpers.tpl).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-25 01:03:50 +03:00
Виталий ЧефановandClaude Opus 5.5 ce6dad9a58 v0.9.0: vulnerabilities on the map; event counts scaled to the window
Vulnerabilities: VulnerabilityReports from operator-trivy are cached
(trimmed to the fields shown) and mapped to cards through the scanned
object in their labels. A card shows a red shield with its CRITICAL CVE
count; the details list CRITICAL and HIGH CVEs with packages, installed
and fixed versions and the advisory link, one row per CVE and image.
Counted per CVE, not per package: openssh's six subpackages had made one
CVE count six times. Kept apart from problems on purpose: on the live
cluster 22 cards have some, which would bury the "is it working" badges.

Fixes, both found on the live cluster, where they made all five current
"problems":
- a Warning event's count is cumulative since its first occurrence; four
  dex-authenticators on xeon had 38-51 probe failures over two days (one
  an hour, pods never left Ready) and were badged as a burst. The count
  is now scaled to the part of the event's lifetime the window covers.
- upmeter's smoke-mini services and pods are its synthetic test, moved
  between nodes on purpose (NoEndpoints, FailedMount while moving).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-25 00:50:37 +03:00
Виталий ЧефановandClaude Opus 5.5 c563cd3a2f v0.8.3: a manual CronJob run is not a problem
Kubernetes emits UnexpectedJob for every Job of a CronJob it did not
schedule itself; the backup job the site's maintenance starts by hand
kept a warning on wordpress-backup.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-24 18:31:23 +03:00
Виталий ЧефановandClaude Opus 5.5 b01f884530 v0.8.2: no false problems for redirecting Ingresses and deleted pods
Found on the live cluster: d8-monitoring/grafana-v10 routes
prometheus.<domain> to a Service that does not exist, but a snippet
redirects every such request, so the backend is never used. And a
verification pod created and deleted by a backup check kept a warning
badge on its namespace for 30 minutes after it was gone.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-24 18:25:11 +03:00
Виталий ЧефановandClaude Opus 5.5 1025c40561 v0.8.1: request a kubernetes-audience token for actions
user-authn adds audience:server:client_id:kubernetes to the dex
authenticator's scope only for DexAuthenticators annotated
dexauthenticator.deckhouse.io/allow-access-to-kubernetes, which is what
the console module does. v0.8.0 set sendAuthorizationHeader alone, so the
token in the header was one the API server does not accept.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-24 17:41:44 +03:00
Виталий ЧефановandClaude Opus 5.5 f24eaa3f23 Makefile: start the stopped build registry instead of waiting for it forever
After a reboot the registry container exists but is stopped; docker
inspect succeeded, nothing started it, and the readiness loop never ended.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-24 17:36:40 +03:00
Виталий ЧефановandClaude Opus 5.5 3cdc2583ee v0.8.0: problem badges, actions as the viewer, load, events, lock
Problems: cards, namespace and node boxes and the tree carry a yellow or
red badge, computed on the server from object state (crash loops, image
pulls, pending and unschedulable pods, readiness older than 2 minutes, a
stuck rollout, a failed CronJob run, Services without endpoints,
Ingresses to missing Services, node conditions), recent Warning events
(notable reasons at once, others after five repeats) and Deckhouse
ClusterAlerts mapped by their labels. A Problems panel lists them all.
Checked against the live cluster: upmeter's synthetic probe pods and
ingress-nginx's fakeservice Ingresses are excluded, they fail on purpose.

Actions: restart, scale, run a CronJob now, suspend/resume, delete a
pod, cordon/uncordon. They run with the viewer's bearer token from the
DexAuthenticator (sendAuthorizationHeader), buttons follow a
SelfSubjectAccessReview, the service account stays read-only. Cross-site
writes are refused by Sec-Fetch-Site/Origin/content type. Scale retries
on conflict: right after a restart a single Get+Update got 409.

Load (metrics.k8s.io against requests/limits/allocatable, per-pod table)
and an Events tab. Cards are locked until the padlock is opened; the map
exports to PNG; the page refreshes badges every minute in place.

Performance, measured on the live cluster:
- layout of big views 3-4x faster: equal-size cards with no edges are
  laid out on the grid ELK would produce (same sizes, checked against
  ELK on a frozen node view), skipping ~8 ms per ELK call;
- hubble-relay gets ~20% fewer flows: the to-overlay copy of pod-to-pod
  traffic is dropped at the agents; 331/331 directions unchanged;
- static files carry ETags, a reload revalidates instead of pulling
  ~2 MB of vendored scripts.

KUBECONFIG is honoured for running the binary on a workstation.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-24 17:25:36 +03:00
Виталий ЧефановandClaude Opus 5.5 8b8fe341d5 v0.7.2: empty traffic window no longer blanks the map
The flows API sent "edges": null for a window without connections (a nil
Go slice); the frontend iterated it and renderMap threw after the new
breadcrumbs were drawn, so the previous namespace stayed on screen under
the new name. The API now sends empty lists, fetchFlows guards against
null, and a failed draw reports itself in the status bar.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-23 22:18:28 +03:00
Vitaliy ChefanovandClaude Opus 5.5 1df5d3559a v0.7.1: render alert rules on DKP without operator-prometheus-crd
helm_lib_prometheus_rules only renders when "operator-prometheus-crd" is
an enabled module; on DKP 1.76 that module doesn't exist (the CRDs come
with operator-prometheus), so the two alerts were silently dropped on a
live install. Gate on the PrometheusRule API instead.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-23 21:47:20 +03:00
Vitaliy ChefanovandClaude Opus 5.5 1bd2006125 bundle: ship changelog.yaml; keep version.json out of the Helm release
Both were warnings from `dmt lint remote` on the published bundle.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-23 21:30:44 +03:00
Vitaliy ChefanovandClaude Opus 5.5 d6558c3d44 Makefile: build into a local registry, publish only final artifacts
werf keeps every stage in --repo, base images included; pushing
Deckhouse's builder/golang-alpine (762 MB layer) to Gitea over a home
uplink timed out. Stages now live in a local registry:2 and publish
crane-copies the app image, bundle and release, keeping digests.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-23 21:27:31 +03:00
Vitaliy ChefanovandClaude Opus 5.5 18869e8bfc Makefile: keep only the base images this module uses
.werf/stages/base-images.yaml defines a werf image for every key of
base_images.yml, and Deckhouse's published file has ~1200 keys; a full
build started pulling and storing all of them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-23 21:23:40 +03:00
Vitaliy ChefanovandClaude Opus 5.5 4518393ce1 Package cluster-map as a Deckhouse module
Layout, build and templates follow deckhouse/modules-template; dmt lint
passes with no findings (Go files are excluded from the Flant-only
license-header rule, see .dmtlint.yaml).

- module.yaml, openapi schemas with Russian docs, lib-helm templates:
  https modes, ingress class, publicDomainTemplate, node placement,
  priority class, PSS-restricted security context, VPA, PDB, Ingress
  plus Gateway API ListenerSet/HTTPRoute, DexAuthenticator.
- module-sdk hooks: hubble CA from d8-cni-cilium (public certificate
  only), external_auth, copy_custom_certificate.
- The app moves to images/cluster-map/src and is split into packages;
  traffic mode Continuous/OnDemand/Disabled and retention are module
  settings; graceful shutdown; Prometheus metrics and two alerts;
  frontend embedded, English and Russian, strict CSP.
- Built with werf on Deckhouse's published base images; Makefile
  publishes the registry layout modules-actions uses.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-23 21:17:52 +03:00
99 changed files with 10854 additions and 1454 deletions
+12
View File
@@ -0,0 +1,12 @@
# The license rule only accepts "Copyright <year> Flant JSC" headers. This
# module is developed outside Flant, so its Go files carry an Apache-2.0
# header with a neutral copyright line and are excluded from that one rule.
# On transfer to the Deckhouse team, rewrite the headers and drop this file;
# every other rule runs at its default severity.
linters-settings:
module:
exclude-rules:
license:
directories:
- images/cluster-map/src
- hooks/batch
+5 -2
View File
@@ -1,2 +1,5 @@
/cluster-map base_images.yml
*.log images_tags_werf.json
/.werf-*
*.tgz
!charts/*.tgz
+20
View File
@@ -0,0 +1,20 @@
.git/
.gitignore
.werf/
.dmtlint.yaml
base_images.yml
base_images.yml.example
crds
docs
hooks
images
openapi
Makefile
*.md
werf*.yaml
oss.yaml
module.yaml
changelog.yaml
LICENSE
version.json
images_digests.json
+1
View File
@@ -0,0 +1 @@
d8-cluster-map
+553
View File
@@ -0,0 +1,553 @@
{{/*
Internal helpers.
*/}}
{{- define "oss_yaml_render_condition" -}}
{{- $cond := index . 0 -}}
{{- $indent := (index . 1) | default "" -}}
{{- if not $cond -}}
{{- /* nothing */ -}}
{{- else -}}
{{- /* fromYaml returns map[interface{}]interface{}; normalize to map[string]interface{} for deterministic key sorting */ -}}
{{- $condStr := dict -}}
{{- range $k, $v := $cond -}}
{{- $_ := set $condStr (printf "%v" $k) $v -}}
{{- end -}}
{{- $keys := keys $condStr | sortAlpha -}}
{{- range $keys -}}
{{- $k := . -}}
{{- $val := index $condStr $k -}}
{{- if kindIs "slice" $val -}}
{{- printf "%s%s:\n" $indent ($k | quote) -}}
{{- range $val -}}
{{- printf "%s - %s\n" $indent ((printf "%v" .) | quote) -}}
{{- end -}}
{{- else -}}
{{- printf "%s%s: %s\n" $indent ($k | quote) ((printf "%v" $val) | quote) -}}
{{- end -}}
{{- end -}}
{{- end -}}
{{- end -}}
{{- define "oss_yaml_render_version_struct" -}}
{{- $v := index . 0 -}}
{{- $indent := (index . 1) | default "" -}}
{{- $ver := (index $v "version") | default "" -}}
{{- if eq $ver "" -}}
{{- fail "\n[ERROR] Version struct has empty .version" -}}
{{- end -}}
{{- printf "%sversion: %s\n" $indent ($ver | quote) -}}
{{- $name := (index $v "name") | default "" -}}
{{- if ne $name "" -}}
{{- printf "%sname: %s\n" $indent ($name | quote) -}}
{{- end -}}
{{- $cond := index $v "condition" -}}
{{- if $cond -}}
{{- printf "%scondition:\n" $indent -}}
{{- include "oss_yaml_render_condition" (list $cond (printf "%s " $indent)) -}}
{{- end -}}
{{- end -}}
{{/*
Public helpers.
*/}}
{{- define "get_oss_version_by_id" -}}
{{- $id := index . 0 -}}
{{- $ctx := index . 1 -}}
{{- $version := "" -}}
{{- $ossYamlPath := "oss.yaml" -}}
{{- if not ($ctx.Files.Exists $ossYamlPath) -}}
{{- fail (printf "\n[ERROR] OSS file not found at path: %s" $ossYamlPath) -}}
{{- end -}}
{{- $raw := printf "data:\n%s" ($ctx.Files.Get $ossYamlPath) | fromYaml -}}
{{- $item := dict -}}
{{- range $raw.data -}}
{{- if eq .id $id -}}
{{- $item = . -}}
{{- break -}}
{{- end -}}
{{- end -}}
{{- if eq (len $item) 0 -}}
{{- fail (printf "\n[ERROR] ID '%s' not found in file: %s" $id $ossYamlPath) -}}
{{- end -}}
{{- $versions := index $item "versions" -}}
{{- if not $versions -}}
{{- $versions = list -}}
{{- end -}}
{{- if gt (len $versions) 0 -}}
{{- if eq (len $versions) 1 -}}
{{- $version = (index (index $versions 0) "version") | default "" -}}
{{- else -}}
{{- fail (printf "\n[ERROR] Multiple versions are defined for ID '%s' in file: %s. Use helper 'get_oss_version_by_id_and_condition'." $id $ossYamlPath) -}}
{{- end -}}
{{- else -}}
{{- $version = (index $item "version") | default "" -}}
{{- end -}}
{{- if eq $version "" -}}
{{- fail (printf "\n[ERROR] Version for ID '%s' is empty or not found in file: %s" $id $ossYamlPath) -}}
{{- end -}}
{{- $version -}}
{{- end -}}
{{/*
Returns YAML of a single version structure for a given id.
*/}}
{{- define "get_oss_version_struct_by_id" -}}
{{- $id := index . 0 -}}
{{- $ctx := index . 1 -}}
{{- $ossYamlPath := "oss.yaml" -}}
{{- if not ($ctx.Files.Exists $ossYamlPath) -}}
{{- fail (printf "\n[ERROR] OSS file not found at path: %s" $ossYamlPath) -}}
{{- end -}}
{{- $raw := printf "data:\n%s" ($ctx.Files.Get $ossYamlPath) | fromYaml -}}
{{- $item := dict -}}
{{- range $raw.data -}}
{{- if eq .id $id -}}
{{- $item = . -}}
{{- break -}}
{{- end -}}
{{- end -}}
{{- if eq (len $item) 0 -}}
{{- fail (printf "\n[ERROR] ID '%s' not found in file: %s" $id $ossYamlPath) -}}
{{- end -}}
{{- $versions := index $item "versions" -}}
{{- if not $versions -}}
{{- $versions = list -}}
{{- end -}}
{{- if gt (len $versions) 0 -}}
{{- if eq (len $versions) 1 -}}
{{- include "oss_yaml_render_version_struct" (list (index $versions 0) "") | trim -}}
{{- else -}}
{{- fail (printf "\n[ERROR] Multiple versions are defined for ID '%s' in file: %s. Use helper 'get_oss_version_by_id_and_condition' or 'get_oss_versions_by_id'." $id $ossYamlPath) -}}
{{- end -}}
{{- else -}}
{{- $version := (index $item "version") | default "" -}}
{{- if eq $version "" -}}
{{- fail (printf "\n[ERROR] Version for ID '%s' is empty or not found in file: %s" $id $ossYamlPath) -}}
{{- end -}}
{{- include "oss_yaml_render_version_struct" (list (dict "version" $version) "") | trim -}}
{{- end -}}
{{- end -}}
{{/*
Returns concrete version string for a given id and condition.
*/}}
{{- define "get_oss_version_by_id_and_condition" -}}
{{- $id := index . 0 -}}
{{- $condition := index . 1 -}}
{{- $ctx := index . 2 -}}
{{- $version := "" -}}
{{- $ossYamlPath := "oss.yaml" -}}
{{- if not ($ctx.Files.Exists $ossYamlPath) -}}
{{- fail (printf "\n[ERROR] OSS file not found at path: %s" $ossYamlPath) -}}
{{- end -}}
{{- $raw := printf "data:\n%s" ($ctx.Files.Get $ossYamlPath) | fromYaml -}}
{{- $item := dict -}}
{{- range $raw.data -}}
{{- if eq .id $id -}}
{{- $item = . -}}
{{- break -}}
{{- end -}}
{{- end -}}
{{- if eq (len $item) 0 -}}
{{- fail (printf "\n[ERROR] ID '%s' not found in file: %s" $id $ossYamlPath) -}}
{{- end -}}
{{- $versions := index $item "versions" -}}
{{- if not $versions -}}
{{- $versions = list -}}
{{- end -}}
{{- if gt (len $versions) 0 -}}
{{- range $versions -}}
{{- $vCond := index . "condition" -}}
{{- if not $vCond -}}
{{- $vCond = dict -}}
{{- end -}}
{{- $match := true -}}
{{- range $k, $qVal := $condition -}}
{{- $cVal := index $vCond $k -}}
{{- if eq $cVal nil -}}
{{- $match = false -}}
{{- break -}}
{{- end -}}
{{- $cand := list -}}
{{- if kindIs "slice" $cVal -}}
{{- range $cVal -}}
{{- $cand = append $cand (printf "%v" .) -}}
{{- end -}}
{{- else -}}
{{- $cand = append $cand (printf "%v" $cVal) -}}
{{- end -}}
{{- $query := list -}}
{{- if kindIs "slice" $qVal -}}
{{- range $qVal -}}
{{- $query = append $query (printf "%v" .) -}}
{{- end -}}
{{- else -}}
{{- $query = append $query (printf "%v" $qVal) -}}
{{- end -}}
{{- range $query -}}
{{- $q := . -}}
{{- $found := false -}}
{{- range $cand -}}
{{- if eq . $q -}}
{{- $found = true -}}
{{- break -}}
{{- end -}}
{{- end -}}
{{- if not $found -}}
{{- $match = false -}}
{{- break -}}
{{- end -}}
{{- end -}}
{{- if not $match -}}
{{- break -}}
{{- end -}}
{{- end -}}
{{- if $match -}}
{{- $version = (index . "version") | default "" -}}
{{- break -}}
{{- end -}}
{{- end -}}
{{- if eq $version "" -}}
{{- $available := list -}}
{{- range $versions -}}
{{- $c := index . "condition" -}}
{{- if not $c -}}
{{- $c = dict -}}
{{- end -}}
{{- $available = append $available ((toJson $c) | default "{}") -}}
{{- end -}}
{{- fail (printf "\n[ERROR] Version for ID '%s' not found for condition %s in file: %s. Available conditions: %s" $id (toJson $condition) $ossYamlPath (join "; " $available)) -}}
{{- end -}}
{{- else -}}
{{- $version = (index $item "version") | default "" -}}
{{- end -}}
{{- if eq $version "" -}}
{{- fail (printf "\n[ERROR] Version for ID '%s' is empty or not found in file: %s" $id $ossYamlPath) -}}
{{- end -}}
{{- $version -}}
{{- end -}}
{{/*
Returns YAML array of version structures for a given id.
*/}}
{{- define "get_oss_versions_by_id" -}}
{{- $id := index . 0 -}}
{{- $ctx := index . 1 -}}
{{- $ossYamlPath := "oss.yaml" -}}
{{- if not ($ctx.Files.Exists $ossYamlPath) -}}
{{- fail (printf "\n[ERROR] OSS file not found at path: %s" $ossYamlPath) -}}
{{- end -}}
{{- $raw := printf "data:\n%s" ($ctx.Files.Get $ossYamlPath) | fromYaml -}}
{{- $item := dict -}}
{{- range $raw.data -}}
{{- if eq .id $id -}}
{{- $item = . -}}
{{- break -}}
{{- end -}}
{{- end -}}
{{- if eq (len $item) 0 -}}
{{- fail (printf "\n[ERROR] ID '%s' not found in file: %s" $id $ossYamlPath) -}}
{{- end -}}
{{- $versions := index $item "versions" -}}
{{- if not $versions -}}
{{- $versions = list -}}
{{- end -}}
{{- if gt (len $versions) 0 -}}
{{- range $versions -}}
{{- $v := . -}}
{{- $ver := (index $v "version") | default "" -}}
{{- if eq $ver "" -}}
{{- fail (printf "\n[ERROR] Empty version in versions[] for ID '%s' in file: %s" $id $ossYamlPath) -}}
{{- end -}}
{{- printf "- version: %s\n" ($ver | quote) -}}
{{- $name := (index $v "name") | default "" -}}
{{- if ne $name "" -}}
{{- printf " name: %s\n" ($name | quote) -}}
{{- end -}}
{{- $cond := index $v "condition" -}}
{{- if $cond -}}
{{- printf " condition:\n" -}}
{{- include "oss_yaml_render_condition" (list $cond " ") -}}
{{- end -}}
{{- end -}}
{{- else -}}
{{- $version := (index $item "version") | default "" -}}
{{- if eq $version "" -}}
{{- fail (printf "\n[ERROR] Version for ID '%s' is empty or not found in file: %s" $id $ossYamlPath) -}}
{{- end -}}
{{- printf "- version: %s\n" ($version | quote) -}}
{{- end -}}
{{- end -}}
{{/*
Returns mapping <condition[key] value> -> <version> for a given id.
*/}}
{{- define "get_oss_version_map_by_id_and_condition_key" -}}
{{- $id := index . 0 -}}
{{- $key := index . 1 -}}
{{- $ctx := index . 2 -}}
{{- $ossYamlPath := "oss.yaml" -}}
{{- if not ($ctx.Files.Exists $ossYamlPath) -}}
{{- fail (printf "\n[ERROR] OSS file not found at path: %s" $ossYamlPath) -}}
{{- end -}}
{{- $raw := printf "data:\n%s" ($ctx.Files.Get $ossYamlPath) | fromYaml -}}
{{- $item := dict -}}
{{- range $raw.data -}}
{{- if eq .id $id -}}
{{- $item = . -}}
{{- break -}}
{{- end -}}
{{- end -}}
{{- if eq (len $item) 0 -}}
{{- fail (printf "\n[ERROR] ID '%s' not found in file: %s" $id $ossYamlPath) -}}
{{- end -}}
{{- $versions := index $item "versions" -}}
{{- if not $versions -}}
{{- $versions = list -}}
{{- end -}}
{{- if eq (len $versions) 0 -}}
{{- fail (printf "\n[ERROR] No 'versions' array is defined for ID '%s' in file: %s" $id $ossYamlPath) -}}
{{- end -}}
{{- $out := dict -}}
{{- range $versions -}}
{{- $cond := index . "condition" -}}
{{- if not $cond -}}
{{- $cond = dict -}}
{{- end -}}
{{- $val := index $cond $key -}}
{{- if eq $val nil -}}
{{- fail (printf "\n[ERROR] Condition key '%s' is not defined for ID '%s' in file: %s. Condition: %s" $key $id $ossYamlPath (toJson $cond)) -}}
{{- end -}}
{{- $ver := (index . "version") | default "" -}}
{{- if eq $ver "" -}}
{{- fail (printf "\n[ERROR] Empty version in versions[] for ID '%s' in file: %s" $id $ossYamlPath) -}}
{{- end -}}
{{- $vals := list -}}
{{- if kindIs "slice" $val -}}
{{- range $val -}}
{{- $vals = append $vals (printf "%v" .) -}}
{{- end -}}
{{- else -}}
{{- $vals = append $vals (printf "%v" $val) -}}
{{- end -}}
{{- range $vals -}}
{{- $k := . -}}
{{- if ne (index $out $k) nil -}}
{{- fail (printf "\n[ERROR] Overlapping conditions for ID '%s' and key '%s': value '%s' is defined more than once in file: %s" $id $key $k $ossYamlPath) -}}
{{- end -}}
{{- $_ := set $out $k $ver -}}
{{- end -}}
{{- end -}}
{{- $keys := keys $out | sortAlpha -}}
{{- range $i, $k := $keys -}}
{{- printf "%s: %s\n" ($k | quote) ((index $out $k) | quote) -}}
{{- end -}}
{{- end -}}
{{/*
Returns mapping <k8s_version_in_range> -> <version> by evaluating semver constraints in `condition.<key>`.
*/}}
{{- define "get_oss_version_map_by_id_and_condition_key_semver" -}}
{{- $id := index . 0 -}}
{{- $key := index . 1 -}}
{{- $rangeSpec := index . 2 -}}
{{- $ctx := index . 3 -}}
{{- $ossYamlPath := "oss.yaml" -}}
{{- if not ($ctx.Files.Exists $ossYamlPath) -}}
{{- fail (printf "\n[ERROR] OSS file not found at path: %s" $ossYamlPath) -}}
{{- end -}}
{{- if not (kindIs "slice" $rangeSpec) -}}
{{- fail (printf "\n[ERROR] rangeSpec must be a list, got: %s" (kindOf $rangeSpec)) -}}
{{- end -}}
{{- if ne (mod (len $rangeSpec) 2) 0 -}}
{{- fail (printf "\n[ERROR] rangeSpec must contain even number of elements (key/value pairs), got len=%d" (len $rangeSpec)) -}}
{{- end -}}
{{- $range := dict -}}
{{- range $i, $_ := $rangeSpec -}}
{{- if eq (mod $i 2) 0 -}}
{{- $k := printf "%v" (index $rangeSpec $i) -}}
{{- $v := printf "%v" (index $rangeSpec (add $i 1)) -}}
{{- $_ := set $range $k $v -}}
{{- end -}}
{{- end -}}
{{- $start := (index $range "start") | default "" -}}
{{- $end := (index $range "end") | default "" -}}
{{- if or (eq $start "") (eq $end "") -}}
{{- fail (printf "\n[ERROR] rangeSpec must include 'start' and 'end'. Got: %s" (toJson $range)) -}}
{{- end -}}
{{- $sParts := splitList "." $start -}}
{{- $eParts := splitList "." $end -}}
{{- if or (ne (len $sParts) 2) (ne (len $eParts) 2) -}}
{{- fail (printf "\n[ERROR] start/end must look like '<major>.<minor>' (e.g. 1.32). Got start=%s end=%s" $start $end) -}}
{{- end -}}
{{- $major := (atoi (index $sParts 0)) | int -}}
{{- $sMinor := (atoi (index $sParts 1)) | int -}}
{{- $eMajor := (atoi (index $eParts 0)) | int -}}
{{- $eMinor := (atoi (index $eParts 1)) | int -}}
{{- if ne $major $eMajor -}}
{{- fail (printf "\n[ERROR] start/end major version mismatch: start=%s end=%s" $start $end) -}}
{{- end -}}
{{- if gt $sMinor $eMinor -}}
{{- fail (printf "\n[ERROR] start minor is greater than end minor: start=%s end=%s" $start $end) -}}
{{- end -}}
{{- $raw := printf "data:\n%s" ($ctx.Files.Get $ossYamlPath) | fromYaml -}}
{{- $item := dict -}}
{{- range $raw.data -}}
{{- if eq .id $id -}}
{{- $item = . -}}
{{- break -}}
{{- end -}}
{{- end -}}
{{- if eq (len $item) 0 -}}
{{- fail (printf "\n[ERROR] ID '%s' not found in file: %s" $id $ossYamlPath) -}}
{{- end -}}
{{- $versions := index $item "versions" -}}
{{- if not $versions -}}
{{- $versions = list -}}
{{- end -}}
{{- if eq (len $versions) 0 -}}
{{- fail (printf "\n[ERROR] No 'versions' array is defined for ID '%s' in file: %s" $id $ossYamlPath) -}}
{{- end -}}
{{- range $minor := untilStep $sMinor (add $eMinor 1 | int) 1 -}}
{{- $target := printf "%d.%d" $major $minor -}}
{{- $matchedVersion := "" -}}
{{- $matchedCount := 0 -}}
{{- range $versions -}}
{{- $cond := index . "condition" -}}
{{- if not $cond -}}
{{- $cond = dict -}}
{{- end -}}
{{- $val := index $cond $key -}}
{{- if eq $val nil -}}
{{- fail (printf "\n[ERROR] Condition key '%s' is not defined for ID '%s' in file: %s. Condition: %s" $key $id $ossYamlPath (toJson $cond)) -}}
{{- end -}}
{{- $ver := (index . "version") | default "" -}}
{{- if eq $ver "" -}}
{{- fail (printf "\n[ERROR] Empty version in versions[] for ID '%s' in file: %s" $id $ossYamlPath) -}}
{{- end -}}
{{- $constraints := list -}}
{{- if kindIs "slice" $val -}}
{{- range $val -}}
{{- $constraints = append $constraints (printf "%v" .) -}}
{{- end -}}
{{- else -}}
{{- $constraints = append $constraints (printf "%v" $val) -}}
{{- end -}}
{{- $entryMatches := false -}}
{{- range $constraints -}}
{{- $c := . -}}
{{- $cNorm := $c -}}
{{- /* exact version '1.35' -> '= 1.35' */ -}}
{{- if regexMatch "^[0-9]+\\.[0-9]+(\\.[0-9]+)?$" $cNorm -}}
{{- $cNorm = printf "= %s" $cNorm -}}
{{- else -}}
{{- /* normalize operator without whitespace: '<=1.34' -> '<= 1.34' */ -}}
{{- $cNorm = regexReplaceAll "^(<=|>=|<|>|=|!=)\\s*" $cNorm "${1} " -}}
{{- end -}}
{{- if semverCompare $cNorm $target -}}
{{- $entryMatches = true -}}
{{- break -}}
{{- end -}}
{{- end -}}
{{- if $entryMatches -}}
{{- $matchedCount = add $matchedCount 1 -}}
{{- if eq $matchedCount 1 -}}
{{- $matchedVersion = $ver -}}
{{- end -}}
{{- end -}}
{{- end -}}
{{- if eq $matchedCount 0 -}}
{{- fail (printf "\n[ERROR] No version matched for ID '%s' key '%s' at %s in file: %s" $id $key $target $ossYamlPath) -}}
{{- end -}}
{{- if gt $matchedCount 1 -}}
{{- fail (printf "\n[ERROR] Overlapping semver conditions for ID '%s' key '%s' at %s in file: %s" $id $key $target $ossYamlPath) -}}
{{- end -}}
{{- printf "%s: %s\n" ($target | quote) ($matchedVersion | quote) -}}
{{- end -}}
{{- end -}}
+18
View File
@@ -0,0 +1,18 @@
# Base Images
{{- $baseImages := .Files.Get "base_images.yml" | fromYaml }}
{{- range $k, $v := $baseImages }}
{{ $baseImagePath := (printf "%s@%s" $baseImages.REGISTRY_PATH (trimSuffix "/" $v)) }}
{{- if ne $k "REGISTRY_PATH" }}
{{- $_ := set $baseImages $k $baseImagePath }}
{{- end }}
{{- end }}
{{- $_ := unset $baseImages "REGISTRY_PATH" }}
{{- $_ := set . "Images" $baseImages }}
# base images artifacts
{{- range $k, $v := .Images }}
---
image: {{ $k }}
from: {{ $v }}
final: false
{{- end }}
+27
View File
@@ -0,0 +1,27 @@
# Golang deps image, required to download dependencies and put it to the final module image (bundle)
# Image for building batch hooks with https://github.com/deckhouse/module-sdk support
---
image: batch-hooks
fromImage: builder/golang-alpine
final: false
git:
- add: /
to: /usr/src/app
includePaths:
- hooks/batch
stageDependencies:
install:
- '**/go.mod'
- '**/go.sum'
beforeSetup:
- '**/*.go'
shell:
install:
# Build patch must contains the `hooks/` folder
- cd /usr/src/app/hooks/batch
- go mod download
beforeSetup:
- |
cd /usr/src/app/hooks/batch;
# don't use `-trimpath` flag for building go hooks. Embedded binary path is necessary to properly identify a hook name
CGO_ENABLED=0 go build -gcflags=all="-l -B" -ldflags="-w -s" -o /usr/local/bin/batchhooks *.go;
+48
View File
@@ -0,0 +1,48 @@
# Bundle image, stored in your.registry.io/modules/<module-name>:<semver>
---
image: bundle
fromImage: builder/scratch
import:
# Enrich image digest and version
# Rendering .werf/stages/images-digests.yaml is required!
- image: images-digests-and-version
add: /
to: /
includePaths:
- images_digests.json
- version.json
after: setup
# batch hooks built with batch-go.yaml werf job
- image: batch-hooks
add: /usr/local/bin/batchhooks
to: /hooks/batchhooks
after: setup
# Uncomment if you use python hooks
# - image: python-dependencies
# add: /usr/bin
# to: /hooks/venv/
# before: setup
# - image: python-dependencies
# add: /lib/python/dist
# to: /lib/python/dist
# before: setup
git:
- add: /
to: /
excludePaths:
- hooks/batch # exclude sources
- docs/internal
includePaths:
- .helmignore
- changelog.yaml
- docs
- charts
- crds
- enabled
- hooks
- monitoring
- openapi
- templates
- Chart.yaml
- module.yaml
- values.yaml
+47
View File
@@ -0,0 +1,47 @@
{{- /* Find all images digests and save use them to compose a structure for the module values. */ -}}
{{- $ImagesIDList := list }}
{{- $Images := tpl (.Files.Get ".werf/stages/images.yaml") . }}
{{- range $ImageManifest := regexSplit "\n?---[ \t]*\n" $Images -1 }}
{{- $ImageManifest := $ImageManifest | fromYaml }}
{{- if $ImageManifest.image }}
{{- if ne $ImageManifest.final false }}
{{- $ImagesIDList = append $ImagesIDList $ImageManifest.image }}
{{- end }}
{{- end }}
{{- end }}
# Images Digest: a files with all image digests to be able to use them in helm templates of a module
# Version: module version
---
image: images-digests-and-version
final: false
fromImage: builder/alpine
import:
- image: jq
add: /usr/bin/jq
before: install
dependencies:
{{- range $ImageID := $ImagesIDList }}
{{- $ImageNameCamel := $ImageID | splitList "/" | last | camelcase | untitle }}
- image: {{ $ImageID }}
before: setup
imports:
- type: ImageDigest
targetEnv: MODULE_IMAGE_DIGEST_{{ $ImageNameCamel }}
{{- end }}
shell:
setup:
- |
env | grep MODULE_IMAGE_DIGEST | jq -Rn '
reduce inputs as $i (
{};
. * (
$i | ltrimstr("MODULE_IMAGE_DIGEST_") | sub("=";"_") |
split("_") as [$imageName, $digest] |
{($imageName): $digest}
)
)
' > /images_digests.json
- |
jq -n --arg version "{{ env "MODULES_MODULE_TAG" }}" '{"version": $version}' > /version.json
+16
View File
@@ -0,0 +1,16 @@
{{- $Root := . }}
{{- $ImagesBuildFiles := .Files.Glob "images/*/{Dockerfile,werf.inc.yaml}" }}
{{- range $path, $content := $ImagesBuildFiles }}
{{- $ctx := dict }}
{{- $_ := set $ctx "ImageName" ($path | split "/")._1 }}
{{- $_ := set $ctx "ModuleName" "cluster-map" }}
{{- $_ := set $ctx "ImagePath" (printf "/images/%s" $ctx.ImageName) }}
{{- $_ := set $ctx "ModuleDir" "/" }}
{{- $_ := set $ctx "ProjectName" (list $ctx.ModuleName $ctx.ImageName | join "/") }}
{{- $_ := set $ctx "Commit" $Root.Commit }}
---
{{- $_ := set $ctx "Files" $Root.Files }}
{{ tpl $content $ctx }}
{{- end }}
+22
View File
@@ -0,0 +1,22 @@
# Release image, stored in your.registry.io/modules/<module-name>/release:<semver>
---
image: release-channel-version
fromImage: builder/scratch
import:
- image: images-digests-and-version
add: /
to: /
includePaths:
- version.json
after: install
git:
- add: /
to: /
includePaths:
- changelog.yaml
- crds
- docs
- module.yaml
- openapi
excludePaths:
- docs/internal
+6
View File
@@ -0,0 +1,6 @@
name: cluster-map
version: 0.10.0
dependencies:
- name: deckhouse_lib_helm
version: 1.72.24
repository: https://deckhouse.github.io/lib-helm
-14
View File
@@ -1,14 +0,0 @@
FROM golang:1.25-alpine AS build
WORKDIR /src
COPY go.mod go.sum ./
RUN go mod download
COPY *.go ./
RUN CGO_ENABLED=0 go build -trimpath -ldflags="-s -w" -o /cluster-map .
FROM alpine:3.20
RUN adduser -D -u 10001 app
COPY --from=build /cluster-map /cluster-map
COPY static /static
USER app
WORKDIR /
ENTRYPOINT ["/cluster-map"]
+201
View File
@@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright The Events Exporter authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
+84
View File
@@ -0,0 +1,84 @@
# cluster-map Deckhouse module.
#
# make test unit tests of the app and the hooks
# make lint golangci-lint + dmt
# make render helm template with test values (catches template errors fast)
# make publish VERSION=v0.7.0 [CHANNEL=alpha] build, push and register the module
# make release VERSION=v0.7.0 CHANNEL=stable move a release channel
#
# The registry layout follows deckhouse/modules-actions: <SOURCE>:<module>
# registers the module, <SOURCE>/<module>:<version> is the bundle,
# <SOURCE>/<module>/release:<version|channel> is the release image.
empty :=
space := $(empty) $(empty)
MODULE ?= cluster-map
SOURCE ?= git.project-chimera.ru/fanchji/cluster-map
CHANNEL ?= alpha
BASE_IMAGES_VERSION ?= v2.1.7
CRANE ?= crane
WERF ?= werf
# Stages are built into a local registry and only the final artifacts are
# copied to SOURCE. werf keeps every stage in --repo, base images included
# (Deckhouse's builder/golang-alpine has a 762 MB layer), which a remote or
# small registry doesn't need to hold. crane copy keeps digests, so the
# images_digests.json baked into the bundle stays valid.
BUILD_REGISTRY ?= localhost:5555
BUILD_REPO ?= $(BUILD_REGISTRY)/$(MODULE)
DMT ?= dmt
API_VERSIONS ?= --api-versions autoscaling.k8s.io/v1/VerticalPodAutoscaler --api-versions monitoring.coreos.com/v1/PodMonitor --api-versions monitoring.coreos.com/v1/PrometheusRule
.PHONY: test lint render base-images build-registry build publish release
test:
cd images/cluster-map/src && go test -race -count=1 ./...
cd hooks/batch && go test -count=1 ./...
lint:
cd images/cluster-map/src && golangci-lint run ./...
cd hooks/batch && go vet ./...
$(DMT) lint .
render:
helm template $(MODULE) . --namespace d8-cluster-map $(API_VERSIONS) -f tests/values/default.yaml > /dev/null
helm template $(MODULE) . --namespace d8-cluster-map $(API_VERSIONS) -f tests/values/default.yaml -f tests/values/no-hubble.yaml > /dev/null
@echo render OK
# Deckhouse publishes its base image digests; the same file official modules
# build from. .werf/stages/base-images.yaml turns every key into a werf image,
# and the full file has ~1200 of them, so only the keys this module uses are kept.
BASE_IMAGE_KEYS := REGISTRY_PATH builder/golang-alpine builder/alpine builder/scratch base/distroless jq
base_images.yml:
curl -sfL "https://fox.flant.com/api/v4/projects/deckhouse%2Fcontainer-base%2Fbase-images/packages/generic/base_images/$(BASE_IMAGES_VERSION)/base_images.yml" \
| grep -E '^($(subst $(space),|,$(BASE_IMAGE_KEYS))):' > $@
@test "$$(wc -l < $@)" -eq $(words $(BASE_IMAGE_KEYS)) || (echo "base_images.yml: expected $(words $(BASE_IMAGE_KEYS)) keys"; cat $@; rm -f $@; exit 1)
base-images: base_images.yml
# The container survives a reboot stopped, so it is started, not only created.
build-registry:
@docker inspect cluster-map-build-registry >/dev/null 2>&1 || \
docker run -d --name cluster-map-build-registry -p 127.0.0.1:5555:5000 -v cluster-map-build-registry:/var/lib/registry registry:2 >/dev/null
@docker start cluster-map-build-registry >/dev/null
@for i in $$(seq 30); do curl -sf http://$(BUILD_REGISTRY)/v2/ >/dev/null && exit 0; sleep 1; done; \
echo "build registry on $(BUILD_REGISTRY) did not come up" >&2; exit 1
build: base_images.yml build-registry
@test -n "$(VERSION)" || (echo "VERSION is required, e.g. VERSION=v0.7.0" && exit 1)
MODULES_MODULE_TAG=$(VERSION) $(WERF) build --repo=$(BUILD_REPO) --insecure-registry --save-build-report --build-report-path images_tags_werf.json
# Application images first (the bundle refers to them by digest), then the
# bundle and the release, then the module registration.
publish: build
jq -r '.Images | to_entries[] | select((.key | startswith("$(MODULE)/")) and (.key | endswith("-build") | not)) | .value.DockerImageName' images_tags_werf.json \
| while read -r img; do $(CRANE) copy --insecure "$$img" "$(SOURCE)/$(MODULE):$${img##*:}"; done
$(CRANE) copy --insecure "$$(jq -r '.Images.bundle.DockerImageName' images_tags_werf.json)" "$(SOURCE)/$(MODULE):$(VERSION)"
$(CRANE) copy --insecure "$$(jq -r '.Images."release-channel-version".DockerImageName' images_tags_werf.json)" "$(SOURCE)/$(MODULE)/release:$(VERSION)"
$(CRANE) append --oci-empty-base --new_layer "" --new_tag "$(SOURCE):$(MODULE)"
$(MAKE) release VERSION=$(VERSION) CHANNEL=$(CHANNEL)
release:
@test -n "$(VERSION)" || (echo "VERSION is required" && exit 1)
$(CRANE) copy "$(SOURCE)/$(MODULE)/release:$(VERSION)" "$(SOURCE)/$(MODULE)/release:$(CHANNEL)"
+99 -62
View File
@@ -1,74 +1,111 @@
# cluster-map # cluster-map
Topology map of the Project Chimera Deckhouse cluster. A Deckhouse Kubernetes Platform module: an interactive topology map of the cluster with live traffic from Cilium Hubble. User documentation is in [docs/README.md](docs/README.md) ([на русском](docs/README_RU.md)).
- **Left**: inventory tree in two views. *Namespaces* groups objects by The module follows [deckhouse/modules-template](https://github.com/deckhouse/modules-template): werf build, lib-helm templates, module-sdk hooks, and it passes `dmt lint` with no findings.
namespace and kind; *Ноды* shows what is scheduled on each node. Search
matches names, images and ingress hosts.
- **Centre**: the selected namespace(s) or node as compact cards inside
namespace boxes. Solid arrows come from configuration (Ingress → Service
→ workload by label selector); dashed animated arrows are real traffic
from Hubble Relay over the chosen window (5 min / 15 min / 1 h), red when
Cilium dropped some of it. Peers from other namespaces are drawn as
dashed "ghost" cards. Kubelet probes, DNS, cilium health and node-to-node
traffic are not collected (see Backend). Traffic refreshes in place every 30 s without
relayout; peers that would need new cards wait for "Обновить".
- **Right**: details for the selected object — overview, links (config and
traffic, clickable), live YAML, pod logs.
Workloads under non-native controllers (kruise Advanced DaemonSet behind ## Layout
ingress-nginx, database operators, bare Jobs) are included and named the
way Hubble names them, so traffic attaches to the same cards.
## Backend | Path | What |
Go, `client-go` in-cluster config. The graph is built from informer caches
(watch-backed, managedFields stripped), so `/api/graph` costs milliseconds
instead of ~0.9 s of List calls.
Traffic: each Cilium agent keeps only 4095 flows in its ring buffer — at a
few hundred flows/s that is ~10 s of history, so reading the buffer on
request can't answer "last 15 minutes". A background follow stream from
`hubble-relay.d8-cni-cilium.svc:443` (TLS verified with the public part of
Deckhouse's hubble CA at `/etc/hubble-ca/ca.crt`; relay does not ask for a
client certificate) feeds per-minute buckets for the last hour. Counts are
**distinct connections** (5-tuples), not Hubble events — one connection
produces several events. `new` = opened by TCP SYN inside the window,
`dropped` = tuples with a DROPPED verdict. After a restart the collector
only knows what it has seen since; `coveredSec` says how much of the
window that is.
Infra traffic is filtered at the agents (`infraFilters` in `flows.go`):
host-originated flows (kubelet probes, hostNetwork pods), remote-node,
cilium health and DNS :53. On a 12k-event sample they were ~74% of
non-reply events, none of them attach to a workload card, and streaming
them cost hubble-relay ~400m CPU.
| Endpoint | What |
|---|---| |---|---|
| `/api/graph` | nodes + config edges + pod placement | | `module.yaml`, `Chart.yaml`, `.helmignore`, `oss.yaml`, `changelog.yaml` | module metadata |
| `/api/flows?namespaces=a,b&window=300` | aggregated traffic touching those namespaces | | `openapi/` | `config-values.yaml` (ModuleConfig settings), `doc-ru-config-values.yaml`, `values.yaml` (internal values) |
| `/api/resource?kind=&namespace=&name=` | live YAML (managedFields stripped) | | `templates/` | Helm templates on [lib-helm](https://github.com/deckhouse/lib-helm) (`charts/deckhouse_lib_helm-*.tgz`) |
| `/api/pods?id=wl/<ns>/<kind>/<name>&namespace=` | pods of a workload | | `hooks/batch/` | Go hooks on [module-sdk](https://github.com/deckhouse/module-sdk): hubble CA, external auth, custom certificate |
| `/api/logs?namespace=&pod=&container=` | last 500 log lines | | `images/cluster-map/` | the application image: `werf.inc.yaml` and the Go source in `src/` |
| `/healthz` | liveness/readiness | | `monitoring/prometheus-rules/` | alert rules |
| `docs/` | user documentation, English and Russian |
| `.werf/`, `werf.yaml`, `werf-giterminism.yaml` | build, from modules-template |
| `tests/values/` | values for `make render` |
## Frontend ### The application (`images/cluster-map/src`)
Plain JS, no build step: `static/index.html`, `app.css`, `app.js`. | Package | What |
Cytoscape.js draws, elkjs lays out in two passes (each box on its own with |---|---|
its unconnected groups packed in rows, then the boxes against each other). | `cmd/cluster-map` | wiring, signals, graceful shutdown |
Both libraries are vendored in `static/vendor/` so the page works without a | `internal/config` | settings from the environment (the Deployment template is the only writer) |
CDN. Theme follows `prefers-color-scheme`. | `internal/kube` | informer caches, managedFields stripped |
| `internal/topology` | the graph: workloads, Services, Ingresses, nodes, the pod-owner rules shared with traffic, and the problems attached to cards |
| `internal/traffic` | Hubble follow stream, per-minute buckets of distinct connections |
| `internal/actions` | restart, scale, run, suspend, delete pod, cordon — as the viewer |
| `internal/access` | what each viewer may see: SelfSubjectAccessReviews as the viewer, cached per token |
| `internal/server` | HTTP API, CSP headers, request metrics |
| `internal/metrics` | Prometheus metrics |
| `web/` | the frontend, embedded into the binary: plain JS, Cytoscape.js, elkjs, English and Russian |
## Build and deploy API: `/api/graph` (with problems), `/api/flows?namespaces=a,b&window=<seconds>`, `/api/resource?kind=&namespace=&name=`, `/api/pods?id=&namespace=`, `/api/logs?namespace=&pod=&container=`, `/api/events?id=`, `/api/usage?id=`, `/api/me`, `/api/permissions?kind=&namespace=&name=`, `POST /api/action`, `/healthz`, `/readyz`; metrics on `:9090/metrics`.
``` `/api/me`, `/api/permissions` and `/api/action` use the viewer's bearer token from the `Authorization` header (the DexAuthenticator adds it when `actions.enabled` or `auth.visibility: ViewerRBAC`), never the module's service account. With `ViewerRBAC` every read endpoint also filters by the viewer's scope and answers 401 without a token.
R=git.project-chimera.ru/fanchji/cluster-map/cluster-map-app
docker build -t $R:vX . && docker push $R:vX To run the binary on a workstation, point `KUBECONFIG` at a kubeconfig; without it the in-cluster service account is used.
docker inspect --format '{{index .RepoDigests 0}}' $R:vX
## Development
```shell
make test # go test -race for the app, hook tests on the module-sdk framework
make lint # golangci-lint and dmt
make render # helm template with tests/values/*.yaml
``` ```
The Deployment pins the image by digest. Anonymous pull works (public Gitea `dmt` is built from [deckhouse/dmt](https://github.com/deckhouse/dmt); `crane` from go-containerregistry.
user), no imagePullSecret. Manifests: `03-kubernetes/apps/cluster-map/` in
`project-chimera`, mirrored to `k8s-manifests` for Argo. ## Build and publish
Base images come from the `base_images.yml` Deckhouse publishes for its own modules (`make base-images`; the file is not committed, as in the template).
```shell
docker login git.project-chimera.ru
make publish VERSION=v0.10.0 # build, push bundle and release, register, channel alpha
make release VERSION=v0.10.0 CHANNEL=stable
```
The registry layout matches [deckhouse/modules-actions](https://github.com/deckhouse/modules-actions):
```text
<SOURCE>:cluster-map module registration (empty image)
<SOURCE>/cluster-map:v0.7.0 bundle
<SOURCE>/cluster-map:<content-tag> application image
<SOURCE>/cluster-map/release:v0.7.0 release
<SOURCE>/cluster-map/release:<channel> alpha | beta | early-access | stable | rock-solid
```
## Install
```yaml
apiVersion: deckhouse.io/v1alpha1
kind: ModuleSource
metadata:
name: cluster-map
spec:
registry:
repo: git.project-chimera.ru/fanchji/cluster-map
scheme: HTTPS
---
apiVersion: deckhouse.io/v1alpha2
kind: ModuleUpdatePolicy
metadata:
name: cluster-map
spec:
releaseChannel: Alpha
update:
mode: Auto
---
apiVersion: deckhouse.io/v1alpha1
kind: ModuleConfig
metadata:
name: cluster-map
spec:
enabled: true
version: 1
updatePolicy: cluster-map
source: cluster-map
settings:
auth:
allowedUserGroups: [admins]
```
The module is `Experimental`: enable `allowExperimentalModules` in the `deckhouse` ModuleConfig first.
## License
Apache 2.0, see [LICENSE](LICENSE). Go files carry an Apache-2.0 header with a neutral copyright line; DMT's license rule expects `Copyright <year> Flant JSC`, so `.dmtlint.yaml` excludes the two Go directories from that rule until the headers are changed on transfer.
+7
View File
@@ -0,0 +1,7 @@
# REGISTRY_PATH is a special key which is concatenated with other base images
REGISTRY_PATH: registry.organization.ru/base_images
tools/yq: "sha256:example"
tools/jq: "sha256:example"
builder/golang-alpine: "sha256:example"
builder/alpine: "sha256:example"
builder/scratch: "sha256:example"
+68
View File
@@ -0,0 +1,68 @@
v0.11.4:
fixes:
- "Failed probes (Unhealthy events) of a pod that is ready now are listed for information: the pod's state already reports NotReady and restarts. Deckhouse answers /readyz with 500 while it works through its queue after a module change and tolerates ten minutes of it; that badged its card after every module release."
v0.11.3:
fixes:
- "A single FailedMount of a pod that is running and ready (kubelet failing to refresh a volume, such as a ConfigMap prometheus-operator deletes and recreates) is listed for information; it badges the card after five repeats in the window, like other events."
v0.11.2:
fixes:
- "Warning events of a pod that has since finished, and FailedScheduling of a pod that has since been scheduled, are listed for information and no longer badge the card: a backup CronJob that waited all night for its node and then ran stayed yellow for half an hour."
v0.11.1:
fixes:
- "A container restarted three times or more stays marked for 24 hours after its last restart or OOM kill, not 30 minutes: a pod OOM-killed five times in a day was no longer shown 40 minutes after the last kill. A single restart still clears after 30 minutes."
v0.11.0:
features:
- "HTTP details where Cilium parses L7 (a CiliumNetworkPolicy with an http rule on the port): requests, responses by class, p50 and p95 latency and the ten busiest paths on the link, IDs in paths grouped as :id. Links with 5xx responses are drawn in the warning colour. Headers are never requested from Hubble. The docs have an example policy that turns this on for one service without restricting it."
fixes:
- "Traffic through the L7 proxy is counted once: Envoy's own connection to the pod no longer shows as a link from world, and the pod's answers to Envoy no longer add one link to the node per request. A pod that reached itself through its own Service is not shown as a link from world either."
v0.10.0:
features:
- "Per-user visibility (auth.visibility: ViewerRBAC, the default): each viewer sees the namespaces where their own RBAC lets them list pods, or the whole cluster if they can list pods everywhere. Logs also need get pods/log, node cards list nodes; traffic peers in hidden namespaces are shown as hidden. Checked with SelfSubjectAccessReviews as the viewer, cached for a minute. auth.visibility: Everything keeps the previous behaviour."
v0.9.0:
features:
- "Vulnerabilities from operator-trivy: a red shield with the number of CRITICAL CVEs on each card, and in the details every CRITICAL and HIGH CVE with its packages, installed and fixed versions and a link. A CVE counts once per card."
fixes:
- "Event counts are scaled to the 30-minute window: a cumulative count spread over days (40 probe failures in two days) no longer badges a card as a burst."
- upmeter's smoke-mini services and pods, which it moves between nodes on purpose, are not reported as problems.
v0.8.3:
fixes:
- UnexpectedJob warnings (the CronJob controller's note on every manual run) are listed for information and no longer badge the CronJob.
v0.8.2:
fixes:
- An Ingress that answers with a redirect (redirect annotations, or rewrite ... permanent / return 30x in a snippet) is not reported for a backend Service that does not exist; Deckhouse's prometheus Ingress does exactly that.
- Warning events about a pod that no longer exists are listed for information and no longer badge the card.
v0.8.1:
fixes:
- "Actions: the DexAuthenticator is annotated allow-access-to-kubernetes, so the user's token carries the kubernetes audience and the API server accepts it. In v0.8.0 the token lacked that audience, the API server rejected it and actions were unavailable."
v0.8.0:
features:
- "Problem badges: a yellow or red \"!\" on cards, namespace and node boxes and in the tree, from object state (crash loops, pending pods, readiness, failed CronJob runs, Services without endpoints, node pressure), Warning events and Deckhouse ClusterAlerts."
- A Problems panel with every current problem, most severe first, filterable to applications or system namespaces.
- "Actions from the details panel: restart, scale, run a CronJob now, suspend and resume, delete a pod, cordon and uncordon a node. They run with the viewer's own token and RBAC; the module's service account stays read-only."
- "Load section: CPU and memory of a workload or node against requests, limits and allocatable, with a per-pod table."
- An Events tab with the events of the object, its pods and ReplicaSets.
- Cards are locked in place until the padlock is opened; the map can be saved as a PNG picture.
- The open page refreshes cards, badges and the tree every minute without moving the layout.
fixes:
- "Layout of a large namespace or node view is 3-4 times faster: levels without edges are packed without a call into ELK."
- "About 20% fewer flows through hubble-relay: the to-overlay copy of pod-to-pod traffic is filtered at the agents; traffic counts are unchanged."
- Static files are revalidated with ETags instead of downloaded again on every visit (about 2 MB).
v0.7.2:
fixes:
- A namespace without traffic in the selected window is drawn again; the empty window was sent as null and the map kept the previous namespace on screen.
- A map that fails to draw shows an error instead of the previous view.
v0.7.1:
fixes:
- Alert rules are rendered on DKP versions without the operator-prometheus-crd module.
v0.7.0:
features:
- First release as a Deckhouse module (ModuleSource, release channels, lib-helm templates).
- "Traffic collection modes: Continuous, OnDemand, Disabled; retention configurable up to 24h."
- Hubble CA is read by a module hook from d8-cni-cilium; no manual copy of the certificate.
- Authentication through user-authn (DexAuthenticator) or any external auth, as in cilium-hubble.
- English and Russian UI.
- Prometheus metrics and alerts for the Hubble stream.
fixes:
- Traffic windows now cover the requested time instead of the agent ring buffer (about 10 seconds).
- Counts are distinct connections, not Hubble events.
- Pod exits cleanly on SIGTERM.
Binary file not shown.
+5
View File
@@ -0,0 +1,5 @@
---
title: "The cluster-map module: configuration"
---
<!-- SCHEMA -->
+5
View File
@@ -0,0 +1,5 @@
---
title: "Модуль cluster-map: настройки"
---
<!-- SCHEMA -->
+82
View File
@@ -0,0 +1,82 @@
---
title: "The cluster-map module: examples"
---
## Enable the module for administrators
```yaml
apiVersion: deckhouse.io/v1alpha1
kind: ModuleConfig
metadata:
name: cluster-map
spec:
enabled: true
version: 1
settings:
auth:
allowedUserGroups:
- admins
```
The web interface opens at `cluster-map.<publicDomainTemplate>`.
## Collect traffic only while the map is in use
```yaml
spec:
settings:
traffic:
mode: OnDemand
onDemandIdleMinutes: 15
```
## Keep a day of traffic
```yaml
spec:
settings:
traffic:
retentionMinutes: 1440
```
Memory grows with retention; watch `cluster_map_traffic_tracked_tuples` and the `ClusterMapTrackedTuplesHigh` alert.
## A read-only map
```yaml
spec:
settings:
actions:
enabled: false
```
No action buttons. With `auth.visibility: Everything` as well, the user's token is no longer passed to the module.
## HTTP details for one service
This policy selects the pods of the `web` Deployment and sends port 8080 through Envoy without restricting anything: `enableDefaultDeny: false` keeps all other traffic allowed, and the empty `http` rule matches every request.
```yaml
apiVersion: cilium.io/v2
kind: CiliumNetworkPolicy
metadata:
name: http-visibility
namespace: shop
spec:
endpointSelector:
matchLabels:
app: web
enableDefaultDeny:
ingress: false
egress: false
ingress:
- toPorts:
- ports:
- port: "8080"
protocol: TCP
rules:
http:
- {}
```
Delete the policy to go back to L3/L4. Before applying it to a service, read the notes in [HTTP details](README.md#http-details).
+82
View File
@@ -0,0 +1,82 @@
---
title: "Модуль cluster-map: примеры"
---
## Включить модуль для администраторов
```yaml
apiVersion: deckhouse.io/v1alpha1
kind: ModuleConfig
metadata:
name: cluster-map
spec:
enabled: true
version: 1
settings:
auth:
allowedUserGroups:
- admins
```
Веб-интерфейс открывается по адресу `cluster-map.<publicDomainTemplate>`.
## Собирать трафик только во время работы с картой
```yaml
spec:
settings:
traffic:
mode: OnDemand
onDemandIdleMinutes: 15
```
## Хранить трафик за сутки
```yaml
spec:
settings:
traffic:
retentionMinutes: 1440
```
Память растёт вместе с глубиной хранения — следите за `cluster_map_traffic_tracked_tuples` и алертом `ClusterMapTrackedTuplesHigh`.
## Карта только для просмотра
```yaml
spec:
settings:
actions:
enabled: false
```
Кнопок действий нет. Если к тому же задано `auth.visibility: Everything`, токен пользователя модулю больше не передаётся.
## Подробности HTTP для одного сервиса
Политика выбирает поды Deployment `web` и пускает порт 8080 через Envoy, ничего не ограничивая: `enableDefaultDeny: false` оставляет весь остальной трафик разрешённым, а пустое правило `http` подходит под любой запрос.
```yaml
apiVersion: cilium.io/v2
kind: CiliumNetworkPolicy
metadata:
name: http-visibility
namespace: shop
spec:
endpointSelector:
matchLabels:
app: web
enableDefaultDeny:
ingress: false
egress: false
ingress:
- toPorts:
- ports:
- port: "8080"
protocol: TCP
rules:
http:
- {}
```
Чтобы вернуться к L3/L4, удалите политику. Прежде чем включать её для сервиса, прочитайте замечания в разделе [Подробности HTTP](README_RU.md#подробности-http).
+120
View File
@@ -0,0 +1,120 @@
---
title: "The cluster-map module"
description: "Interactive topology map of the cluster with live traffic from Cilium Hubble."
webIfaces:
- name: cluster-map
---
The `cluster-map` module answers "where does this service live and what does it talk to" without a trip through `kubectl`. It shows the cluster as an inventory tree and a topology map: namespaces, workloads with their Services and Ingresses, the nodes they run on, real traffic between them, and the YAML and logs of each object.
## What is on the screen
- **Inventory tree** (left). Two views: *Namespaces* — namespace → object kind → objects; *Nodes* — node → namespace → workloads. Search matches names, images and Ingress hosts. The tree is keyboard-navigable.
- **Map** (centre). Only what is selected in the tree: one or several namespaces (Ctrl+click) or one node. Objects are compact cards inside namespace boxes, laid out left to right: Ingress → Service → workload.
- Solid arrows are configuration links: Ingress backends and Service selectors.
- Dashed animated arrows are real connections from Hubble over the chosen window (5 minutes, 15 minutes, 1 hour); red when Cilium dropped some of them. Peers from other namespaces appear as dashed cards in their own boxes.
- With more than 30 traffic directions on screen, lines stay faint until a card is hovered or selected.
- **Details** (right). Overview (a one-line verdict, the object's problems, its facts, CPU and memory against requests and limits, its pods), Links (configuration and traffic, clickable), live YAML, Events, container logs, and the actions the viewer is allowed to run.
- **Problems** (the button in the top bar). Everything that is wrong right now, most severe first, filterable to applications or system namespaces; a click opens the object.
Cards cannot be dragged until the padlock under the zoom buttons is opened, so a stray click does not rearrange the map. The last button saves the current map as a PNG picture.
Workloads managed by non-native controllers are included: Advanced DaemonSets of OpenKruise, database operator clusters, static pods, standalone Jobs. They are named the way Hubble names workloads, so their traffic attaches to the same cards.
## Problems and alerts
A card with a problem carries a badge: yellow `!` for a warning, red `!` for an error. Namespace boxes and cards, node boxes and the tree take the colour of the worst problem inside. Sources:
- **Object state**: containers in `CrashLoopBackOff`, `ImagePullBackOff` and similar, restarts and OOM kills of the last 30 minutes (of the last 24 hours for a container restarted three times or more), pods pending or unschedulable, workloads with no or not all replicas ready for more than 2 minutes, a stuck rollout, a CronJob whose last run failed, a Service with no ready pod, an Ingress routing to a Service that does not exist, a node that is not ready or is under memory, disk or PID pressure.
- **Warning events** of the last 30 minutes, folded per object and reason. Scheduling, volume and back-off failures badge the card at once; any other reason needs five repeats inside the window and is listed without a badge before that, so a single failed probe during a restart does not colour the map. An event's count is cumulative since its first occurrence, so a long-lived event is scaled to the window: 40 probe failures over two days is one an hour, not a burst.
- **Prometheus alerts** that Deckhouse mirrors into `ClusterAlert` objects. An alert is attached by its labels (`deployment`, `statefulset`, `daemonset`, `pod`, `service`, `ingress`, `node`, `namespace`); one without an object or namespace goes to the cluster list. `severity_level` 1–3 is an error, 4–6 a warning, 7–9 information.
Information-level entries (a cordoned node, a single ordinary warning) are listed and never badge a card. Problems are recomputed on every map request and the open page refreshes them every minute.
## Vulnerabilities
With operator-trivy installed, a card whose images have CRITICAL CVEs shows a red shield with their number in the bottom-right corner. The details panel lists every CRITICAL and HIGH CVE of the workload's images: the packages it hits, the installed version and the version that fixes it, with a link to the advisory. A CVE counts once per card, however many packages and containers it is found in. Vulnerabilities are shown apart from problems: nearly every image has some, and a badge on each card would hide what is actually broken.
The data comes from the `VulnerabilityReport` objects operator-trivy writes, so only namespaces it scans appear (labelled `security-scanning.deckhouse.io/enabled`), and only the severities its `severities` setting keeps.
## Actions
With `actions.enabled` (the default), the details panel offers:
| Object | Actions |
|---|---|
| Deployment, StatefulSet | restart (as `kubectl rollout restart`), scale to 0–100 replicas |
| DaemonSet | restart |
| CronJob | run now (as `kubectl create job --from=cronjob/…`), suspend, resume |
| Pod (in the Load table) | delete, so its controller starts a new one |
| Node (click the node box) | cordon, uncordon |
Every action asks for confirmation and runs **as the viewer**: the DexAuthenticator passes the user's own token to the module, the module sends the request to the API server with that token, and the API server checks the user's RBAC. A button is shown only when a `SelfSubjectAccessReview` says the user may do it. The module's service account never gets write permissions, and the API server's audit log records the user; the module also logs each action with the user's name.
Write requests from another site are refused: the module checks `Sec-Fetch-Site`, `Origin` and the JSON content type.
## How traffic is collected
Every Cilium agent keeps only a ring buffer of flows (4095 by default); at a few hundred flows per second this is about ten seconds of history. A one-off query "for the last 15 minutes" would silently return the last few seconds. The module therefore keeps a follow stream from Hubble Relay and aggregates it into per-minute buckets for the configured retention.
Counts are **distinct connections** (source and destination address and port), not Hubble events: one connection produces several events. For each direction the module also reports how many connections were opened (TCP SYN) inside the window and how many had a `DROPPED` verdict.
Kubelet probes and other traffic originating from node hosts, node-to-node traffic, Cilium health checks and DNS are filtered at the agents and never reach the module. On a typical cluster this is about three quarters of all flows and none of it maps to a workload. Set `traffic.collectInfraTraffic` to collect it anyway.
Pod-to-pod traffic between nodes is traced twice, as it leaves the sender's node (`to-overlay`) and as it reaches the receiving pod (`to-endpoint`). The first copy is also filtered at the agents when the receiver is a pod; this removes about a fifth of the remaining flows without changing any count.
The collector runs in one of three modes, see `traffic.mode`:
| Mode | Cost | Traffic windows |
|---|---|---|
| `Continuous` | stream always open; about 100–150m CPU on hubble-relay on a busy cluster | full as soon as the map is opened |
| `OnDemand` | stream only while someone uses the map | fill from the moment the map is opened |
| `Disabled` | none | configuration links only |
History is kept in memory: after a pod restart the windows fill again. The status line says how much of the window has actually been seen.
## HTTP details
Where Cilium parses HTTP on a port, the map adds to that link the number of requests, responses by class (2xx, 3xx, 4xx, 5xx), p50 and p95 latency and the ten busiest paths. A link with 5xx responses is drawn in the warning colour. Paths are grouped: the query string is dropped and segments that look like IDs (numbers, UUIDs, long hex strings) become `:id`, so `/api/users/42?x=1` and `/api/users/43` are one row `/api/users/:id`.
Cilium parses HTTP only on ports named in an L7 rule of a `CiliumNetworkPolicy`; the module does not create such policies. To enable it for one service without restricting its traffic, see [the example](EXAMPLES.md#http-details-for-one-service). Keep in mind:
- the connections to that port go through the Envoy proxy on the node: a fraction of a millisecond per request and CPU of the Cilium agent in proportion to the request rate;
- the port must speak plain HTTP/1.x or HTTP/2 (h2c): Envoy cannot see inside TLS, so put the rule on the backend port behind the Ingress, not on 443. gRPC is parsed, but its status is in the trailers and every call shows as 200; a gRPC stream or a WebSocket is one request, not a series of messages;
- request and response headers reach Hubble, including `Authorization` and cookies. The module asks Hubble for the method, path, status and latency only; the headers are not read, stored or shown. Other Hubble clients (the Hubble UI, `hubble observe`) do see them.
## Requirements
- Deckhouse Kubernetes Platform 1.72 or newer.
- For traffic: the `cni-cilium` and `cilium-hubble` modules. Without `cilium-hubble` the module works and shows configuration links only.
- For access control: the `user-authn` module, or any external authentication (`auth.externalAuthentication`).
## Security
The web interface reads the cluster through the module's own service account (`d8:cluster-map` ClusterRole): `get`, `list`, `watch` on namespaces, pods, services, nodes, events, deployments, statefulsets, daemonsets, cronjobs, ingresses, Deckhouse `clusteralerts` and operator-trivy `vulnerabilityreports`, `get` and `list` on `metrics.k8s.io` pods and nodes, and `get` on `pods/log`. It never reads Secrets or ConfigMaps and has no write verbs. Changes go through [actions](#actions), which use the viewer's own identity.
**What a viewer sees follows the viewer's own RBAC** (`auth.visibility: ViewerRBAC`, the default). With every request the DexAuthenticator passes the user's token; the module asks the API server with that token (`SelfSubjectAccessReview`) and caches the answer for a minute:
- `list pods` in all namespaces — the whole cluster;
- otherwise only the namespaces where the user can `list pods`; cards, YAML, events, load and vulnerabilities of other namespaces are not returned, and a traffic peer there is shown as a hidden peer, with its connections but without its name;
- container logs additionally need `get pods/log` in that namespace, node cards and the node view `list nodes`; cluster-wide alerts are shown to cluster-wide viewers only.
With `auth.visibility: Everything`, anyone admitted to the web interface sees every namespace and can read container logs, whatever their own RBAC is. In both modes restrict who is admitted with `auth.allowedUserGroups` (and optionally `auth.allowedUserEmails` and `auth.whitelistSourceRanges`); what a user can change always follows their own RBAC.
The frontend is served with a strict Content Security Policy: only its own scripts, styles and API, no inline code, no framing.
To verify the Hubble Relay certificate the module needs the public certificate of the hubble CA. A module hook reads it from the `hubble-ca-secret` Secret in `d8-cni-cilium`; the jq filter keeps only `ca.crt`, the CA key never reaches the module values.
## Metrics and alerts
The pod exposes Prometheus metrics on port `9090` (`cluster_map_*`: Hubble stream state, flows processed, tracked connections, API latency) and ships two alerts:
- `ClusterMapHubbleDisconnected` — no flows from Hubble Relay for 15 minutes while the collector is supposed to be running.
- `ClusterMapTrackedTuplesHigh` — the collector holds more than 2 million connections; lower the retention or switch to `OnDemand`.
## Limitations
- One replica: traffic history lives in the process. A second replica would keep its own history and double the load on hubble-relay.
- Visibility is by namespace: a user who can list pods in a namespace sees all its cards, including the manifests of its Deployments and Services, even if their role would not let them read those objects one by one.
- Alerts need the `prometheus` module, which creates `ClusterAlert` objects. Without it the map shows problems from object state and events only.
- HTTP details only where a CiliumNetworkPolicy turns on L7 parsing, see [HTTP details](#http-details). Other protocols are shown at L3/L4.
+126
View File
@@ -0,0 +1,126 @@
---
title: "Модуль cluster-map"
description: "Интерактивная карта кластера с живым трафиком из Cilium Hubble."
webIfaces:
- name: cluster-map
---
Модуль `cluster-map` отвечает на вопрос «где живёт этот сервис и с кем он общается» без похода в `kubectl`. Он показывает кластер деревом инвентаря и картой: namespace, workload'ы с их Service и Ingress, ноды, на которых они работают, реальный трафик между ними, YAML и логи каждого объекта.
## Что на экране
- **Дерево инвентаря** (слева). Два вида: *Namespaces* — namespace → тип объекта → объекты; *Ноды* — нода → namespace → workload'ы. Поиск ищет по имени, образу и хосту Ingress. Дерево управляется с клавиатуры.
- **Карта** (в центре). Только то, что выбрано в дереве: один или несколько namespace (Ctrl+клик) или одна нода. Объекты — компактные карточки в рамках namespace, слева направо: Ingress → Service → workload.
- Сплошные стрелки — связи по конфигурации: backend Ingress и селектор Service.
- Пунктир с анимацией — реальные соединения из Hubble за выбранное окно (5 минут, 15 минут, час); красный, если Cilium часть из них отбросил. Пиры из других namespace — пунктирные карточки в своих рамках.
- Если на экране больше 30 направлений трафика, линии бледные, пока не наведёшь курсор на карточку или не выберешь её.
- **Детали** (справа). Обзор (одна строка — работает или нет, проблемы объекта, его параметры, CPU и память относительно запросов и лимитов, его поды), Связи (по конфигурации и по трафику, с переходом), живой YAML, События, логи контейнеров и действия, которые разрешены пользователю.
- **Проблемы** (кнопка в верхней панели). Всё, что сломано прямо сейчас, сначала самое серьёзное, с фильтром по приложениям и системным namespace; клик открывает объект.
Карточки нельзя перетащить, пока не открыт замок под кнопками масштаба, — случайный клик не перестроит карту. Последняя кнопка сохраняет текущую карту картинкой PNG.
Workload'ы под нестандартными контроллерами тоже на карте: Advanced DaemonSet из OpenKruise, кластеры операторов баз данных, статические поды, одиночные Job. Они названы так же, как их называет Hubble, поэтому трафик привязывается к тем же карточкам.
## Проблемы и алерты
Карточка с проблемой несёт значок: жёлтый `!` — предупреждение, красный `!` — ошибка. Рамки и карточки namespace, рамки нод и дерево окрашиваются по самой серьёзной проблеме внутри. Источники:
- **Состояние объектов**: контейнеры в `CrashLoopBackOff`, `ImagePullBackOff` и подобном, перезапуски и убийства за нехватку памяти за последние 30 минут (за сутки, если контейнер перезапускался три раза и больше), поды в ожидании или без места для запуска, workload'ы, у которых больше 2 минут не готовы все или часть реплик, застрявшая выкатка, CronJob с неудачным последним запуском, Service без готовых подов, Ingress на несуществующий Service, нода не готова или ей не хватает памяти, диска или PID.
- **Warning-события** за последние 30 минут, сгруппированные по объекту и причине. Сбои планирования, томов и back-off дают значок сразу; любой другой причине нужно пять повторов в пределах окна, до этого она в списке без значка — одна проваленная проба во время рестарта не красит карту. Счётчик события накапливается с первого появления, поэтому давнее событие пересчитывается на окно: 40 проваленных проб за двое суток — это раз в час, а не всплеск.
- **Алерты Prometheus**, которые Deckhouse зеркалирует в объекты `ClusterAlert`. Алерт привязывается по меткам (`deployment`, `statefulset`, `daemonset`, `pod`, `service`, `ingress`, `node`, `namespace`); алерт без объекта и namespace попадает в список кластера. `severity_level` 1–3 — ошибка, 4–6 — предупреждение, 7–9 — информация.
Записи уровня «для сведения» (нода закрыта для новых подов, одиночное обычное предупреждение) есть в списке, но значка не дают. Проблемы пересчитываются при каждом запросе карты, открытая страница обновляет их раз в минуту.
## Уязвимости
Если установлен operator-trivy, у карточки, в образах которой есть CVE уровня CRITICAL, в правом нижнем углу красный щит с их числом. В панели деталей — все CVE уровней CRITICAL и HIGH образов workload'а: какие пакеты затронуты, стоящая версия и версия с исправлением, ссылка на описание. Одна CVE считается на карточке один раз, в скольких бы пакетах и контейнерах она ни нашлась. Уязвимости показываются отдельно от проблем: они есть почти в каждом образе, и значок на каждой карточке скрыл бы то, что действительно сломано.
Данные берутся из объектов `VulnerabilityReport`, которые пишет operator-trivy, поэтому видны только namespace, которые он сканирует (с меткой `security-scanning.deckhouse.io/enabled`), и только уровни, оставленные его настройкой `severities`.
## Действия
При `actions.enabled` (по умолчанию включено) в панели деталей есть:
| Объект | Действия |
|---|---|
| Deployment, StatefulSet | перезапуск (как `kubectl rollout restart`), масштабирование на 0–100 реплик |
| DaemonSet | перезапуск |
| CronJob | запустить сейчас (как `kubectl create job --from=cronjob/…`), приостановить, возобновить |
| Под (в таблице «Нагрузка») | удалить, чтобы контроллер запустил новый |
| Нода (клик по рамке ноды) | закрыть для новых подов (cordon) и открыть обратно |
Каждое действие требует подтверждения и выполняется **от имени пользователя**: DexAuthenticator передаёт модулю собственный токен пользователя, модуль отправляет запрос в API-сервер с этим токеном, и API-сервер проверяет RBAC пользователя. Кнопка показывается, только если `SelfSubjectAccessReview` подтверждает право. Сервисный аккаунт модуля не получает прав на запись, в аудит-логе API-сервера записан пользователь; модуль тоже пишет каждое действие в лог с именем пользователя.
Запросы на запись с других сайтов отклоняются: модуль проверяет `Sec-Fetch-Site`, `Origin` и тип содержимого JSON.
## Как собирается трафик
Каждый агент Cilium хранит только кольцевой буфер потоков (по умолчанию 4095); при нескольких сотнях потоков в секунду это около десяти секунд истории. Разовый запрос «за последние 15 минут» молча вернул бы последние секунды. Поэтому модуль держит постоянный поток из Hubble Relay и раскладывает его по минутным корзинам на заданную глубину.
Считаются **различные соединения** (адрес и порт источника и получателя), а не события Hubble: одно соединение даёт несколько событий. Для каждого направления модуль отдельно показывает, сколько соединений открыто внутри окна (TCP SYN) и сколько получили вердикт `DROPPED`.
Пробы kubelet и прочий трафик с хостов нод, трафик между нодами, проверки Cilium health и DNS отсекаются на агентах и до модуля не доходят. На обычном кластере это около трёх четвертей всех потоков, и ни один из них не привязан к workload'у. Чтобы всё же собирать их, включите `traffic.collectInfraTraffic`.
Трафик между подами на разных нодах трассируется дважды: при выходе с ноды отправителя (`to-overlay`) и при доставке в под получателя (`to-endpoint`). Первая копия тоже отсекается на агентах, если получатель — под; это убирает около пятой части оставшихся потоков, ни одно число при этом не меняется.
Режимы сбора — параметр `traffic.mode`:
| Режим | Цена | Окна трафика |
|---|---|---|
| `Continuous` | поток открыт всегда; около 100–150m CPU на hubble-relay на нагруженном кластере | заполнены сразу при открытии карты |
| `OnDemand` | поток открыт, только пока с картой работают | заполняются с момента открытия карты |
| `Disabled` | нет | только связи по конфигурации |
История хранится в памяти: после рестарта пода окна заполняются заново. Строка статуса пишет, сколько из окна реально видно.
## Подробности HTTP
Там, где Cilium разбирает HTTP на порту, карта добавляет к связи число запросов, ответы по классам (2xx, 3xx, 4xx, 5xx), задержку p50 и p95 и десять самых нагруженных путей. Связь, на которой были ответы 5xx, рисуется цветом предупреждения. Пути группируются: строка запроса отбрасывается, а сегменты, похожие на идентификаторы (числа, UUID, длинные hex-строки), заменяются на `:id` — `/api/users/42?x=1` и `/api/users/43` попадают в одну строку `/api/users/:id`.
Cilium разбирает HTTP только на портах, упомянутых в L7-правиле `CiliumNetworkPolicy`; сам модуль таких политик не создаёт. Как включить это для одного сервиса, не ограничивая его трафик, — в [примере](EXAMPLES_RU.md#подробности-http-для-одного-сервиса). Учтите:
- соединения на этот порт идут через прокси Envoy на ноде: доли миллисекунды на запрос и CPU агента Cilium пропорционально числу запросов;
- порт должен говорить на обычном HTTP/1.x или HTTP/2 (h2c): внутрь TLS Envoy не заглядывает, поэтому правило ставится на порт бэкенда за Ingress, а не на 443. gRPC разбирается, но его статус лежит в трейлерах, и каждый вызов виден как 200; поток gRPC или WebSocket — это один запрос, а не последовательность сообщений;
- заголовки запроса и ответа попадают в Hubble, включая `Authorization` и cookie. Модуль запрашивает у Hubble только метод, путь, код и задержку; заголовки он не читает, не хранит и не показывает. Другие клиенты Hubble (Hubble UI, `hubble observe`) их видят.
## Требования
- Deckhouse Kubernetes Platform 1.72 или новее.
- Для трафика — модули `cni-cilium` и `cilium-hubble`. Без `cilium-hubble` модуль работает и показывает только связи по конфигурации.
- Для разграничения доступа — модуль `user-authn` или любая внешняя аутентификация (`auth.externalAuthentication`).
## Безопасность
Веб-интерфейс читает кластер через собственную учётку модуля (ClusterRole `d8:cluster-map`): `get`, `list`, `watch` на namespaces, pods, services, nodes, events, deployments, statefulsets, daemonsets, cronjobs, ingresses, `clusteralerts` Deckhouse и `vulnerabilityreports` operator-trivy, `get` и `list` на pods и nodes из `metrics.k8s.io` и `get` на `pods/log`. Secret и ConfigMap он не читает, прав на запись нет. Изменения идут через [действия](#действия), которые выполняются от имени пользователя.
**Что видит пользователь, определяет его собственный RBAC** (`auth.visibility: ViewerRBAC`, по умолчанию). С каждым запросом DexAuthenticator передаёт токен пользователя; модуль спрашивает API-сервер от его имени (`SelfSubjectAccessReview`) и кеширует ответ на минуту:
- `list pods` во всех namespace — виден весь кластер;
- иначе — только namespace, где пользователь может `list pods`; карточки, YAML, события, нагрузка и уязвимости остальных namespace не отдаются, а сосед по трафику оттуда показывается скрытым — с соединениями, но без имени;
- для логов контейнеров нужно ещё `get pods/log` в этом namespace, для карточек нод и вида по нодам — `list nodes`; общекластерные алерты видны только пользователям с доступом ко всему кластеру.
При `auth.visibility: Everything` любой, кого пустили в веб-интерфейс, видит все namespace и может читать логи контейнеров независимо от своего RBAC. В обоих режимах ограничивайте круг допущенных через `auth.allowedUserGroups` (а также `auth.allowedUserEmails` и `auth.whitelistSourceRanges`); изменить пользователь всегда может только то, что разрешает его RBAC.
Фронтенд отдаётся со строгой Content Security Policy: только собственные скрипты, стили и API, без inline-кода, без встраивания во фреймы.
Чтобы проверять сертификат Hubble Relay, модулю нужен публичный сертификат hubble CA. Хук модуля читает его из Secret `hubble-ca-secret` в `d8-cni-cilium`; jq-фильтр оставляет только `ca.crt`, ключ CA в значения модуля не попадает.
## Метрики и алерты
Под отдаёт метрики Prometheus на порту `9090` (`cluster_map_*`: состояние потока из Hubble, обработанные потоки, число отслеживаемых соединений, задержки API) и приносит два алерта:
- `ClusterMapHubbleDisconnected` — 15 минут нет потоков из Hubble Relay, хотя сбор должен идти.
- `ClusterMapTrackedTuplesHigh` — коллектор держит больше 2 миллионов соединений; уменьшите глубину хранения или переключите режим на `OnDemand`.
## Ограничения
- Одна реплика: история трафика живёт в процессе. Вторая реплика держала бы свою историю и удвоила бы нагрузку на hubble-relay.
- Видимость — по namespace: пользователь, который может смотреть поды в namespace, видит все его карточки, включая манифесты Deployment и Service, даже если его роль не дала бы прочитать эти объекты по отдельности.
- Для алертов нужен модуль `prometheus`, он создаёт объекты `ClusterAlert`. Без него карта показывает проблемы только по состоянию объектов и событиям.
- Подробности HTTP — только там, где CiliumNetworkPolicy включает разбор L7, см. [Подробности HTTP](#подробности-http). Остальные протоколы показываются на уровне L3/L4.
## Уточнение диагностики после перезапуска
Обычный перезапуск контейнера отмечается в течение 30 минут. Накопленный счётчик перезапусков за всю жизнь pod’а не доказывает повторные сбои за сутки; расширенное окно остаётся для последних завершений OOMKilled. Текущий CrashLoopBackOff и неготовность проверяются независимо.
Сервис без endpoints остаётся предупреждением, кроме подтверждённого случая, когда все подходящие Deployment/StatefulSet/DaemonSet уже обработали конфигурацию и ожидают ноль pod’ов. Тогда запись информационная. Неизвестное состояние, устаревший статус контроллера, подходящий CronJob или незавершённый pod сохраняют предупреждение.
-437
View File
@@ -1,437 +0,0 @@
package main
import (
"context"
"crypto/tls"
"crypto/x509"
"encoding/json"
"errors"
"fmt"
"hash/fnv"
"log"
"net/http"
"os"
"sort"
"strconv"
"strings"
"sync"
"time"
flowpb "github.com/cilium/cilium/api/v1/flow"
observerpb "github.com/cilium/cilium/api/v1/observer"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/credentials"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/types/known/fieldmaskpb"
"google.golang.org/protobuf/types/known/timestamppb"
)
// Relay serves a *.hubble-relay.cilium.io certificate signed by Deckhouse's
// hubble CA and does not ask for a client certificate, so plain TLS with
// that CA is enough. The CA is mounted from a ConfigMap (public part only).
const hubbleServerName = "cluster-map.hubble-relay.cilium.io"
// Each agent keeps only 4095 flows in its ring buffer, which at a few
// hundred flows/s is ~10 s of history. So traffic is collected continuously
// from a follow stream into per-minute buckets covering the last hour.
const (
bucketCount = 60
maxTuplesPerKey = 20000 // per edge per minute; beyond it counts stop growing
)
type FlowEndpoint struct {
ID string `json:"id"`
Label string `json:"label"`
Kind string `json:"kind"` // lowercased controller kind, "pod", or "external"
Namespace string `json:"namespace,omitempty"`
}
type FlowEdge struct {
Source string `json:"source"`
Target string `json:"target"`
Port string `json:"port"` // "443/TCP"
Connections int `json:"connections"` // distinct 5-tuples seen in the window
New int `json:"new"` // of those, opened (TCP SYN) in the window
Dropped int `json:"dropped"` // distinct 5-tuples with a DROPPED verdict
Last string `json:"last"`
}
type FlowsResult struct {
WindowSec int `json:"windowSec"`
CoveredSec int `json:"coveredSec"` // how much of the window the collector has actually seen
Connected bool `json:"connected"`
Error string `json:"error,omitempty"`
Endpoints []FlowEndpoint `json:"endpoints"`
Edges []FlowEdge `json:"edges"`
}
type edgeKey struct{ src, dst, port string }
const (
tupleSYN uint8 = 1
tupleDrop uint8 = 2
)
type bucketEdge struct {
tuples map[uint64]uint8
last int64
}
type bucket struct {
minute int64
edges map[edgeKey]*bucketEdge
}
type collector struct {
mu sync.Mutex
buckets [bucketCount]*bucket
endpoints map[string]FlowEndpoint
startedAt time.Time
connected bool
lastErr string
flows uint64
}
var flowsCollector = &collector{endpoints: map[string]FlowEndpoint{}}
func startHubble() {
caPEM, err := os.ReadFile(envOr("HUBBLE_CA_FILE", "/etc/hubble-ca/ca.crt"))
if err != nil {
flowsCollector.setErr(fmt.Errorf("hubble CA: %w", err))
return
}
pool := x509.NewCertPool()
if !pool.AppendCertsFromPEM(caPEM) {
flowsCollector.setErr(errors.New("hubble CA: no certificate in file"))
return
}
creds := credentials.NewTLS(&tls.Config{RootCAs: pool, ServerName: hubbleServerName, MinVersion: tls.VersionTLS12})
conn, err := grpc.NewClient(envOr("HUBBLE_RELAY_ADDR", "hubble-relay.d8-cni-cilium.svc:443"), grpc.WithTransportCredentials(creds))
if err != nil {
flowsCollector.setErr(err)
return
}
go flowsCollector.run(observerpb.NewObserverClient(conn))
}
func envOr(k, def string) string {
if v := os.Getenv(k); v != "" {
return v
}
return def
}
func (c *collector) setErr(err error) {
c.mu.Lock()
defer c.mu.Unlock()
c.connected = false
c.lastErr = err.Error()
log.Printf("hubble: %v", err)
}
// Filtered at the agents, so the relay never serialises them. Measured on a
// 12k-event sample: host-originated traffic (kubelet probes, hostNetwork
// pods) 43% of non-reply events, DNS :53 19%, remote-node 11%, cilium
// health 1%. None of it attaches to a workload card, and the relay spent
// ~400m CPU streaming it all.
var infraFilters = []*flowpb.FlowFilter{
{SourceLabel: []string{"reserved:host"}},
{SourceLabel: []string{"reserved:remote-node"}},
{SourceLabel: []string{"reserved:health"}},
{DestinationLabel: []string{"reserved:health"}},
{DestinationPort: []string{"53"}},
}
var flowFields = []string{"time", "verdict", "IP", "l4", "source", "destination", "source_names", "destination_names", "node_name"}
func (c *collector) run(obs observerpb.ObserverClient) {
c.mu.Lock()
c.startedAt = time.Now()
c.mu.Unlock()
useMask := true
backoff := time.Second
for {
req := &observerpb.GetFlowsRequest{
Follow: true,
// backfill whatever the ring buffers still hold; duplicate
// tuples after a reconnect collapse in the per-minute sets
Since: timestamppb.New(time.Now().Add(-time.Minute)),
Whitelist: []*flowpb.FlowFilter{{Reply: []bool{false}}},
Blacklist: infraFilters,
}
if useMask {
req.FieldMask = &fieldmaskpb.FieldMask{Paths: flowFields}
}
before := c.flowsSeen()
err := c.stream(obs, req)
if status.Code(err) == codes.InvalidArgument && useMask {
useMask = false
log.Printf("hubble: relay rejected field mask, retrying without it: %v", err)
continue
}
c.setErr(err)
if c.flowsSeen() > before {
backoff = time.Second // the stream worked for a while; reconnect quickly
}
time.Sleep(backoff)
backoff = min(backoff*2, 30*time.Second)
}
}
func (c *collector) flowsSeen() uint64 {
c.mu.Lock()
defer c.mu.Unlock()
return c.flows
}
func (c *collector) stream(obs observerpb.ObserverClient, req *observerpb.GetFlowsRequest) error {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
s, err := obs.GetFlows(ctx, req)
if err != nil {
return err
}
for {
resp, err := s.Recv()
if err != nil {
return err
}
if f := resp.GetFlow(); f != nil {
c.add(f)
}
}
}
func (c *collector) add(f *flowpb.Flow) {
src := flowEndpoint(f.GetSource(), f.GetSourceNames(), f.GetNodeName())
dst := flowEndpoint(f.GetDestination(), f.GetDestinationNames(), f.GetNodeName())
if src.ID == dst.ID {
return
}
port, tuple, syn := l4Info(f)
ts := time.Now()
if t := f.GetTime(); t != nil {
ts = t.AsTime()
}
minute := ts.Unix() / 60
c.mu.Lock()
defer c.mu.Unlock()
if !c.connected {
c.connected, c.lastErr = true, ""
}
c.flows++
b := c.buckets[minute%bucketCount]
if b == nil || b.minute != minute {
if b != nil && b.minute > minute {
return // older than the retained hour
}
b = &bucket{minute: minute, edges: map[edgeKey]*bucketEdge{}}
c.buckets[minute%bucketCount] = b
c.pruneEndpoints()
}
c.endpoints[src.ID] = src
c.endpoints[dst.ID] = dst
k := edgeKey{src.ID, dst.ID, port}
e := b.edges[k]
if e == nil {
e = &bucketEdge{tuples: map[uint64]uint8{}}
b.edges[k] = e
}
h := hashTuple(f.GetIP().GetSource(), f.GetIP().GetDestination(), tuple)
flags, seen := e.tuples[h]
if !seen && len(e.tuples) >= maxTuplesPerKey {
return
}
if syn {
flags |= tupleSYN
}
if f.GetVerdict() == flowpb.Verdict_DROPPED {
flags |= tupleDrop
}
e.tuples[h] = flags
e.last = max(e.last, ts.Unix())
}
// pruneEndpoints drops metadata for endpoints no retained bucket mentions.
func (c *collector) pruneEndpoints() {
used := map[string]bool{}
for _, b := range c.buckets {
if b == nil {
continue
}
for k := range b.edges {
used[k.src], used[k.dst] = true, true
}
}
for id := range c.endpoints {
if !used[id] {
delete(c.endpoints, id)
}
}
}
func hashTuple(srcIP, dstIP, rest string) uint64 {
h := fnv.New64a()
h.Write([]byte(srcIP))
h.Write([]byte{0})
h.Write([]byte(dstIP))
h.Write([]byte{0})
h.Write([]byte(rest))
return h.Sum64()
}
// l4Info returns the display port ("443/TCP"), the port part of the
// connection tuple, and whether this event opens a TCP connection.
func l4Info(f *flowpb.Flow) (port, tuple string, syn bool) {
l4 := f.GetL4()
switch {
case l4.GetTCP() != nil:
t := l4.GetTCP()
fl := t.GetFlags()
return strconv.Itoa(int(t.GetDestinationPort())) + "/TCP",
"tcp:" + strconv.Itoa(int(t.GetSourcePort())) + ":" + strconv.Itoa(int(t.GetDestinationPort())),
fl.GetSYN() && !fl.GetACK()
case l4.GetUDP() != nil:
u := l4.GetUDP()
return strconv.Itoa(int(u.GetDestinationPort())) + "/UDP",
"udp:" + strconv.Itoa(int(u.GetSourcePort())) + ":" + strconv.Itoa(int(u.GetDestinationPort())), false
case l4.GetSCTP() != nil:
s := l4.GetSCTP()
return strconv.Itoa(int(s.GetDestinationPort())) + "/SCTP",
"sctp:" + strconv.Itoa(int(s.GetSourcePort())) + ":" + strconv.Itoa(int(s.GetDestinationPort())), false
case l4.GetICMPv4() != nil || l4.GetICMPv6() != nil:
return "ICMP", "icmp", false
}
return "?", "?", false
}
func (c *collector) query(namespaces map[string]bool, window int) FlowsResult {
now := time.Now()
fromMinute := now.Add(-time.Duration(window)*time.Second).Unix() / 60
c.mu.Lock()
defer c.mu.Unlock()
res := FlowsResult{WindowSec: window, Connected: c.connected, Error: c.lastErr}
if !c.startedAt.IsZero() {
res.CoveredSec = min(window, int(now.Sub(c.startedAt).Seconds()))
}
touches := func(id string) bool { return namespaces[c.endpoints[id].Namespace] }
type acc struct {
tuples map[uint64]uint8
last int64
}
merged := map[edgeKey]*acc{}
for _, b := range c.buckets {
if b == nil || b.minute < fromMinute {
continue
}
for k, e := range b.edges {
if !touches(k.src) && !touches(k.dst) {
continue
}
a := merged[k]
if a == nil {
a = &acc{tuples: make(map[uint64]uint8, len(e.tuples))}
merged[k] = a
}
for h, fl := range e.tuples {
a.tuples[h] |= fl
}
a.last = max(a.last, e.last)
}
}
eps := map[string]bool{}
for k, a := range merged {
fe := FlowEdge{Source: k.src, Target: k.dst, Port: k.port, Connections: len(a.tuples), Last: time.Unix(a.last, 0).UTC().Format(time.RFC3339)}
for _, fl := range a.tuples {
if fl&tupleSYN != 0 {
fe.New++
}
if fl&tupleDrop != 0 {
fe.Dropped++
}
}
res.Edges = append(res.Edges, fe)
eps[k.src], eps[k.dst] = true, true
}
for id := range eps {
res.Endpoints = append(res.Endpoints, c.endpoints[id])
}
sort.Slice(res.Endpoints, func(i, j int) bool { return res.Endpoints[i].ID < res.Endpoints[j].ID })
sort.Slice(res.Edges, func(i, j int) bool { return res.Edges[i].Connections > res.Edges[j].Connections })
return res
}
func handleFlows(w http.ResponseWriter, r *http.Request) {
namespaces := map[string]bool{}
for _, ns := range strings.Split(r.URL.Query().Get("namespaces"), ",") {
if ns = strings.TrimSpace(ns); ns != "" {
namespaces[ns] = true
}
}
if len(namespaces) == 0 || len(namespaces) > 100 {
http.Error(w, "namespaces: от 1 до 100 через запятую", http.StatusBadRequest)
return
}
window, _ := strconv.Atoi(r.URL.Query().Get("window"))
if window <= 0 {
window = 300
}
window = min(window, bucketCount*60)
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(flowsCollector.query(namespaces, window))
}
// flowEndpoint maps a Hubble endpoint to an ID that matches a graph node
// when the peer is one of our workloads. Hubble leaves Endpoint.Workloads
// empty on some flows (typically the half observed on the peer's node), so
// pods are resolved through the informer cache with the graph's own rules,
// and Hubble's workload name is only a fallback for pods already gone.
func flowEndpoint(e *flowpb.Endpoint, names []string, nodeName string) FlowEndpoint {
if e.GetPodName() != "" {
ns := e.GetNamespace()
if p, err := podLister.Pods(ns).Get(e.GetPodName()); err == nil {
if kind, name, _ := podOwner(*p); kind != "" {
return FlowEndpoint{ID: workloadID(ns, kind, name), Label: name, Kind: kind, Namespace: ns}
}
}
for _, wl := range e.GetWorkloads() {
kind, name := strings.ToLower(wl.GetKind()), wl.GetName()
if kind == "job" {
if i := strings.LastIndex(name, "-"); i > 0 && allDigits(name[i+1:]) {
kind, name = "cronjob", name[:i]
}
}
if kind != "" && name != "" {
return FlowEndpoint{ID: workloadID(ns, kind, name), Label: name, Kind: kind, Namespace: ns}
}
}
return FlowEndpoint{ID: "pod/" + ns + "/" + e.GetPodName(), Label: e.GetPodName(), Kind: "pod", Namespace: ns}
}
labels := e.GetLabels()
has := func(l string) bool {
for _, x := range labels {
if x == l {
return true
}
}
return false
}
switch {
case has("reserved:host"):
return FlowEndpoint{ID: "ext/host/" + nodeName, Label: "host " + nodeName, Kind: "external"}
case has("reserved:remote-node"):
return FlowEndpoint{ID: "ext/remote-node", Label: "другие ноды", Kind: "external"}
case has("reserved:kube-apiserver"):
return FlowEndpoint{ID: "ext/kube-apiserver", Label: "kube-apiserver", Kind: "external"}
case has("reserved:health"):
return FlowEndpoint{ID: "ext/health", Label: "cilium health", Kind: "external"}
}
if len(names) > 0 {
return FlowEndpoint{ID: "ext/dns/" + names[0], Label: names[0], Kind: "external"}
}
return FlowEndpoint{ID: "ext/world", Label: "интернет", Kind: "external"}
}
+33
View File
@@ -0,0 +1,33 @@
/*
Copyright 2026 The cluster-map Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package main
import (
extauth "github.com/deckhouse/module-sdk/common-hooks/external_auth"
)
// With user-authn enabled and no externalAuthentication in the ModuleConfig,
// the module deploys its own DexAuthenticator and points the Ingress at it.
// Anything the user sets explicitly wins.
var _ = extauth.RegisterHook(extauth.Settings{
ExternalAuthPath: "clusterMap.auth.externalAuthentication",
DexAuthenticatorEnabledPath: "clusterMap.internal.deployDexAuthenticator",
DexExternalAuth: extauth.ExternalAuth{
AuthURL: "https://cluster-map-dex-authenticator.d8-cluster-map.svc.%CLUSTER_DOMAIN%/dex-authenticator/auth",
AuthSignInURL: "https://$host/dex-authenticator/sign_in",
},
})
+109
View File
@@ -0,0 +1,109 @@
module hook
go 1.25.8
require (
github.com/deckhouse/module-sdk v0.12.5
github.com/stretchr/testify v1.12.1
)
require (
github.com/DataDog/gostackparse v0.7.0 // indirect
github.com/beorn7/perks v1.0.1 // indirect
github.com/caarlos0/env/v11 v11.4.1 // indirect
github.com/cespare/xxhash/v2 v2.3.0 // indirect
github.com/cloudflare/cfssl v1.6.5 // indirect
github.com/containerd/stargz-snapshotter/estargz v0.18.2 // indirect
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect
github.com/deckhouse/deckhouse/pkg/log v0.2.0 // indirect
github.com/docker/cli v29.4.0+incompatible // indirect
github.com/docker/distribution v2.8.3+incompatible // indirect
github.com/docker/docker-credential-helpers v0.9.3 // indirect
github.com/emicklei/go-restful/v3 v3.13.0 // indirect
github.com/ettle/strcase v0.2.0 // indirect
github.com/evanphx/json-patch/v5 v5.9.11 // indirect
github.com/fsnotify/fsnotify v1.9.0 // indirect
github.com/fxamacker/cbor/v2 v2.9.2 // indirect
github.com/go-logr/logr v1.4.3 // indirect
github.com/go-openapi/jsonpointer v0.23.1 // indirect
github.com/go-openapi/jsonreference v0.21.6 // indirect
github.com/go-openapi/swag v0.25.5 // indirect
github.com/go-openapi/swag/cmdutils v0.25.5 // indirect
github.com/go-openapi/swag/conv v0.25.5 // indirect
github.com/go-openapi/swag/fileutils v0.25.5 // indirect
github.com/go-openapi/swag/jsonname v0.26.0 // indirect
github.com/go-openapi/swag/jsonutils v0.25.5 // indirect
github.com/go-openapi/swag/loading v0.25.5 // indirect
github.com/go-openapi/swag/mangling v0.25.5 // indirect
github.com/go-openapi/swag/netutils v0.25.5 // indirect
github.com/go-openapi/swag/stringutils v0.25.5 // indirect
github.com/go-openapi/swag/typeutils v0.25.5 // indirect
github.com/go-openapi/swag/yamlutils v0.25.5 // indirect
github.com/gogo/protobuf v1.3.2 // indirect
github.com/gojuno/minimock/v3 v3.4.7 // indirect
github.com/google/btree v1.1.3 // indirect
github.com/google/certificate-transparency-go v1.3.2 // indirect
github.com/google/gnostic-models v0.7.1 // indirect
github.com/google/go-cmp v0.7.0 // indirect
github.com/google/go-containerregistry v0.21.3 // indirect
github.com/google/uuid v1.6.0 // indirect
github.com/inconshreveable/mousetrap v1.1.0 // indirect
github.com/itchyny/gojq v0.12.17 // indirect
github.com/itchyny/timefmt-go v0.1.6 // indirect
github.com/jmoiron/sqlx v1.3.5 // indirect
github.com/jonboulle/clockwork v0.5.0 // indirect
github.com/json-iterator/go v1.1.12 // indirect
github.com/klauspost/compress v1.18.5 // indirect
github.com/mitchellh/go-homedir v1.1.0 // indirect
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
github.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee // indirect
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect
github.com/opencontainers/go-digest v1.0.0 // indirect
github.com/opencontainers/image-spec v1.1.1 // indirect
github.com/pelletier/go-toml v1.9.3 // indirect
github.com/pkg/errors v0.9.1 // indirect
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect
github.com/prometheus/client_golang v1.22.0 // indirect
github.com/prometheus/client_model v0.6.2 // indirect
github.com/prometheus/common v0.62.0 // indirect
github.com/prometheus/procfs v0.15.1 // indirect
github.com/sirupsen/logrus v1.9.4 // indirect
github.com/spf13/cobra v1.10.2 // indirect
github.com/spf13/pflag v1.0.10 // indirect
github.com/sylabs/oci-tools v0.19.0 // indirect
github.com/tidwall/gjson v1.19.0 // indirect
github.com/tidwall/match v1.1.1 // indirect
github.com/tidwall/pretty v1.2.0 // indirect
github.com/vbatts/tar-split v0.12.2 // indirect
github.com/weppos/publicsuffix-go v0.30.0 // indirect
github.com/x448/float16 v0.8.4 // indirect
github.com/zmap/zcrypto v0.0.0-20230310154051-c8b263fd8300 // indirect
github.com/zmap/zlint/v3 v3.5.0 // indirect
go.yaml.in/yaml/v2 v2.4.4 // indirect
go.yaml.in/yaml/v3 v3.0.5 // indirect
golang.org/x/crypto v0.55.0 // indirect
golang.org/x/net v0.58.0 // indirect
golang.org/x/oauth2 v0.36.0 // indirect
golang.org/x/sync v0.22.0 // indirect
golang.org/x/sys v0.47.0 // indirect
golang.org/x/term v0.45.0 // indirect
golang.org/x/text v0.41.0 // indirect
golang.org/x/time v0.11.0 // indirect
gomodules.xyz/jsonpatch/v2 v2.4.0 // indirect
google.golang.org/protobuf v1.36.11 // indirect
gopkg.in/evanphx/json-patch.v4 v4.12.0 // indirect
gopkg.in/inf.v0 v0.9.1 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
k8s.io/api v0.34.8 // indirect
k8s.io/apiextensions-apiserver v0.34.8 // indirect
k8s.io/apimachinery v0.34.8 // indirect
k8s.io/client-go v0.34.8 // indirect
k8s.io/klog/v2 v2.140.0 // indirect
k8s.io/kube-openapi v0.0.0-20260603220949-865597e52e25 // indirect
k8s.io/utils v0.0.0-20260507154919-ff6756f316d2 // indirect
sigs.k8s.io/controller-runtime v0.22.5 // indirect
sigs.k8s.io/json v0.0.0-20250730193827-2d320260d730 // indirect
sigs.k8s.io/randfill v1.0.0 // indirect
sigs.k8s.io/structured-merge-diff/v6 v6.3.2 // indirect
sigs.k8s.io/yaml v1.6.0 // indirect
)
+363
View File
@@ -0,0 +1,363 @@
github.com/DataDog/gostackparse v0.7.0 h1:i7dLkXHvYzHV308hnkvVGDL3BR4FWl7IsXNPz/IGQh4=
github.com/DataDog/gostackparse v0.7.0/go.mod h1:lTfqcJKqS9KnXQGnyQMCugq3u1FP6UZMfWR0aitKFMM=
github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM=
github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw=
github.com/caarlos0/env/v11 v11.4.1 h1:fYwH0sWEsBSMPG7t4e/PEfTFzrWrpjyygXyUnWiSwEw=
github.com/caarlos0/env/v11 v11.4.1/go.mod h1:qupehSf/Y0TUTsxKywqRt/vJjN5nz6vauiYEUUr8P4U=
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
github.com/cloudflare/cfssl v1.6.5 h1:46zpNkm6dlNkMZH/wMW22ejih6gIaJbzL2du6vD7ZeI=
github.com/cloudflare/cfssl v1.6.5/go.mod h1:Bk1si7sq8h2+yVEDrFJiz3d7Aw+pfjjJSZVaD+Taky4=
github.com/containerd/stargz-snapshotter/estargz v0.18.2 h1:yXkZFYIzz3eoLwlTUZKz2iQ4MrckBxJjkmD16ynUTrw=
github.com/containerd/stargz-snapshotter/estargz v0.18.2/go.mod h1:XyVU5tcJ3PRpkA9XS2T5us6Eg35yM0214Y+wvrZTBrY=
github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM=
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/deckhouse/deckhouse/pkg/log v0.2.0 h1:6tmZQLwNb1o/hP1gzJQBjcwfA/bubbgObovXzxq+Exo=
github.com/deckhouse/deckhouse/pkg/log v0.2.0/go.mod h1:pbAxTSDcPmwyl3wwKDcEB3qdxHnRxqTV+J0K+sha8bw=
github.com/deckhouse/module-sdk v0.12.5 h1:701OR/GXVDMkJ/85mGdcDS5o3RY2D1l22bJGUCKbEL0=
github.com/deckhouse/module-sdk v0.12.5/go.mod h1:X+o+eFGsfApWJ3n6SqaAw/9Oifrhy2djeG4Inq8umaw=
github.com/docker/cli v29.4.0+incompatible h1:+IjXULMetlvWJiuSI0Nbor36lcJ5BTcVpUmB21KBoVM=
github.com/docker/cli v29.4.0+incompatible/go.mod h1:JLrzqnKDaYBop7H2jaqPtU4hHvMKP+vjCwu2uszcLI8=
github.com/docker/distribution v2.8.3+incompatible h1:AtKxIZ36LoNK51+Z6RpzLpddBirtxJnzDrHLEKxTAYk=
github.com/docker/distribution v2.8.3+incompatible/go.mod h1:J2gT2udsDAN96Uj4KfcMRqY0/ypR+oyYUYmja8H+y+w=
github.com/docker/docker-credential-helpers v0.9.3 h1:gAm/VtF9wgqJMoxzT3Gj5p4AqIjCBS4wrsOh9yRqcz8=
github.com/docker/docker-credential-helpers v0.9.3/go.mod h1:x+4Gbw9aGmChi3qTLZj8Dfn0TD20M/fuWy0E5+WDeCo=
github.com/emicklei/go-restful/v3 v3.13.0 h1:C4Bl2xDndpU6nJ4bc1jXd+uTmYPVUwkD6bFY/oTyCes=
github.com/emicklei/go-restful/v3 v3.13.0/go.mod h1:6n3XBCmQQb25CM2LCACGz8ukIrRry+4bhvbpWn3mrbc=
github.com/ettle/strcase v0.2.0 h1:fGNiVF21fHXpX1niBgk0aROov1LagYsOwV/xqKDKR/Q=
github.com/ettle/strcase v0.2.0/go.mod h1:DajmHElDSaX76ITe3/VHVyMin4LWSJN5Z909Wp+ED1A=
github.com/evanphx/json-patch v5.9.0+incompatible h1:fBXyNpNMuTTDdquAq/uisOr2lShz4oaXpDTX2bLe7ls=
github.com/evanphx/json-patch v5.9.0+incompatible/go.mod h1:50XU6AFN0ol/bzJsmQLiYLvXMP4fmwYFNcr97nuDLSk=
github.com/evanphx/json-patch/v5 v5.9.11 h1:/8HVnzMq13/3x9TPvjG08wUGqBTmZBsCWzjTM0wiaDU=
github.com/evanphx/json-patch/v5 v5.9.11/go.mod h1:3j+LviiESTElxA4p3EMKAB9HXj3/XEtnUf6OZxqIQTM=
github.com/fsnotify/fsnotify v1.9.0 h1:2Ml+OJNzbYCTzsxtv8vKSFD9PbJjmhYF14k/jKC7S9k=
github.com/fsnotify/fsnotify v1.9.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0=
github.com/fxamacker/cbor/v2 v2.9.2 h1:X4Ksno9+x3cz0TZv69ec1hxP/+tymuR8PXQJyDwfh78=
github.com/fxamacker/cbor/v2 v2.9.2/go.mod h1:vM4b+DJCtHn+zz7h3FFp/hDAI9WNWCsZj23V5ytsSxQ=
github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=
github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
github.com/go-logr/zapr v1.3.0 h1:XGdV8XW8zdwFiwOA2Dryh1gj2KRQyOOoNmBy4EplIcQ=
github.com/go-logr/zapr v1.3.0/go.mod h1:YKepepNBd1u/oyhd/yQmtjVXmm9uML4IXUgMOwR8/Gg=
github.com/go-openapi/jsonpointer v0.23.1 h1:1HBACs7XIwR2RcmItfdSFlALhGbe6S92p0ry4d1GWg4=
github.com/go-openapi/jsonpointer v0.23.1/go.mod h1:iWRmZTrGn7XwYhtPt/fvdSFj1OfNBngqRT2UG3BxSqY=
github.com/go-openapi/jsonreference v0.21.6 h1:NZ5nGfnaM1n4I43Xjm1e5/M2GjOwQwndQz22uhxwD+Y=
github.com/go-openapi/jsonreference v0.21.6/go.mod h1:xzbgtQ3ZbWxvET3AxdzCJlJt6vkovbf+IfSPJjD0tUY=
github.com/go-openapi/swag v0.25.5 h1:pNkwbUEeGwMtcgxDr+2GBPAk4kT+kJ+AaB+TMKAg+TU=
github.com/go-openapi/swag v0.25.5/go.mod h1:B3RT6l8q7X803JRxa2e59tHOiZlX1t8viplOcs9CwTA=
github.com/go-openapi/swag/cmdutils v0.25.5 h1:yh5hHrpgsw4NwM9KAEtaDTXILYzdXh/I8Whhx9hKj7c=
github.com/go-openapi/swag/cmdutils v0.25.5/go.mod h1:pdae/AFo6WxLl5L0rq87eRzVPm/XRHM3MoYgRMvG4A0=
github.com/go-openapi/swag/conv v0.25.5 h1:wAXBYEXJjoKwE5+vc9YHhpQOFj2JYBMF2DUi+tGu97g=
github.com/go-openapi/swag/conv v0.25.5/go.mod h1:CuJ1eWvh1c4ORKx7unQnFGyvBbNlRKbnRyAvDvzWA4k=
github.com/go-openapi/swag/fileutils v0.25.5 h1:B6JTdOcs2c0dBIs9HnkyTW+5gC+8NIhVBUwERkFhMWk=
github.com/go-openapi/swag/fileutils v0.25.5/go.mod h1:V3cT9UdMQIaH4WiTrUc9EPtVA4txS0TOmRURmhGF4kc=
github.com/go-openapi/swag/jsonname v0.26.0 h1:gV1NFX9M8avo0YSpmWogqfQISigCmpaiNci8cGECU5w=
github.com/go-openapi/swag/jsonname v0.26.0/go.mod h1:urBBR8bZNoDYGr653ynhIx+gTeIz0ARZxHkAPktJK2M=
github.com/go-openapi/swag/jsonutils v0.25.5 h1:XUZF8awQr75MXeC+/iaw5usY/iM7nXPDwdG3Jbl9vYo=
github.com/go-openapi/swag/jsonutils v0.25.5/go.mod h1:48FXUaz8YsDAA9s5AnaUvAmry1UcLcNVWUjY42XkrN4=
github.com/go-openapi/swag/jsonutils/fixtures_test v0.25.5 h1:SX6sE4FrGb4sEnnxbFL/25yZBb5Hcg1inLeErd86Y1U=
github.com/go-openapi/swag/jsonutils/fixtures_test v0.25.5/go.mod h1:/2KvOTrKWjVA5Xli3DZWdMCZDzz3uV/T7bXwrKWPquo=
github.com/go-openapi/swag/loading v0.25.5 h1:odQ/umlIZ1ZVRteI6ckSrvP6e2w9UTF5qgNdemJHjuU=
github.com/go-openapi/swag/loading v0.25.5/go.mod h1:I8A8RaaQ4DApxhPSWLNYWh9NvmX2YKMoB9nwvv6oW6g=
github.com/go-openapi/swag/mangling v0.25.5 h1:hyrnvbQRS7vKePQPHHDso+k6CGn5ZBs5232UqWZmJZw=
github.com/go-openapi/swag/mangling v0.25.5/go.mod h1:6hadXM/o312N/h98RwByLg088U61TPGiltQn71Iw0NY=
github.com/go-openapi/swag/netutils v0.25.5 h1:LZq2Xc2QI8+7838elRAaPCeqJnHODfSyOa7ZGfxDKlU=
github.com/go-openapi/swag/netutils v0.25.5/go.mod h1:lHbtmj4m57APG/8H7ZcMMSWzNqIQcu0RFiXrPUara14=
github.com/go-openapi/swag/stringutils v0.25.5 h1:NVkoDOA8YBgtAR/zvCx5rhJKtZF3IzXcDdwOsYzrB6M=
github.com/go-openapi/swag/stringutils v0.25.5/go.mod h1:PKK8EZdu4QJq8iezt17HM8RXnLAzY7gW0O1KKarrZII=
github.com/go-openapi/swag/typeutils v0.25.5 h1:EFJ+PCga2HfHGdo8s8VJXEVbeXRCYwzzr9u4rJk7L7E=
github.com/go-openapi/swag/typeutils v0.25.5/go.mod h1:itmFmScAYE1bSD8C4rS0W+0InZUBrB2xSPbWt6DLGuc=
github.com/go-openapi/swag/yamlutils v0.25.5 h1:kASCIS+oIeoc55j28T4o8KwlV2S4ZLPT6G0iq2SSbVQ=
github.com/go-openapi/swag/yamlutils v0.25.5/go.mod h1:Gek1/SjjfbYvM+Iq4QGwa/2lEXde9n2j4a3wI3pNuOQ=
github.com/go-openapi/testify/enable/yaml/v2 v2.4.0 h1:7SgOMTvJkM8yWrQlU8Jm18VeDPuAvB/xWrdxFJkoFag=
github.com/go-openapi/testify/enable/yaml/v2 v2.4.0/go.mod h1:14iV8jyyQlinc9StD7w1xVPW3CO3q1Gj04Jy//Kw4VM=
github.com/go-openapi/testify/v2 v2.5.1 h1:TMdhCaw8fUNraVSf3Omoob1dO/AzBfhtFAPW0an6sBo=
github.com/go-openapi/testify/v2 v2.5.1/go.mod h1:SgsVHtfooshd0tublTtJ50FPKhujf47YRqauXXOUxfw=
github.com/go-sql-driver/mysql v1.6.0/go.mod h1:DCzpHaOWr8IXmIStZouvnhqoel9Qv2LBy8hT2VhHyBg=
github.com/go-task/slim-sprig/v3 v3.0.0 h1:sUs3vkvUymDpBKi3qH1YSqBQk9+9D/8M2mN1vB6EwHI=
github.com/go-task/slim-sprig/v3 v3.0.0/go.mod h1:W848ghGpv3Qj3dhTPRyJypKRiqCdHZiAzKg9hl15HA8=
github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q=
github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q=
github.com/gojuno/minimock/v3 v3.4.7 h1:vhE5zpniyPDRT0DXd5s3DbtZJVlcbmC5k80izYtj9lY=
github.com/gojuno/minimock/v3 v3.4.7/go.mod h1:QxJk4mdPrVyYUmEZGc2yD2NONpqM/j4dWhsy9twjFHg=
github.com/google/btree v1.1.3 h1:CVpQJjYgC4VbzxeGVHfvZrv1ctoYCAI8vbl07Fcxlyg=
github.com/google/btree v1.1.3/go.mod h1:qOPhT0dTNdNzV6Z/lhRX0YXUafgPLFUh+gZMl761Gm4=
github.com/google/certificate-transparency-go v1.3.2 h1:9ahSNZF2o7SYMaKaXhAumVEzXB2QaayzII9C8rv7v+A=
github.com/google/certificate-transparency-go v1.3.2/go.mod h1:H5FpMUaGa5Ab2+KCYsxg6sELw3Flkl7pGZzWdBoYLXs=
github.com/google/gnostic-models v0.7.1 h1:SisTfuFKJSKM5CPZkffwi6coztzzeYUhc3v4yxLWH8c=
github.com/google/gnostic-models v0.7.1/go.mod h1:whL5G0m6dmc5cPxKc5bdKdEN3UjI7OUGxBlw57miDrQ=
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
github.com/google/go-containerregistry v0.21.3 h1:Xr+yt3VvwOOn/5nJzd7UoOhwPGiPkYW0zWDLLUXqAi4=
github.com/google/go-containerregistry v0.21.3/go.mod h1:D5ZrJF1e6dMzvInpBPuMCX0FxURz7GLq2rV3Us9aPkc=
github.com/google/go-github v17.0.0+incompatible/go.mod h1:zLgOLi98H3fifZn+44m+umXrS52loVEgC2AApnigrVQ=
github.com/google/go-querystring v1.0.0/go.mod h1:odCYkC5MyYFN7vkCjXpyrEuKhc/BUO6wN/zVPAxq5ck=
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
github.com/google/gofuzz v1.2.0 h1:xRy4A+RhZaiKjJ1bPfwQ8sedCA+YS2YcCHW6ec7JMi0=
github.com/google/gofuzz v1.2.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
github.com/google/pprof v0.0.0-20241029153458-d1b30febd7db h1:097atOisP2aRj7vFgYQBbFN4U4JNXUNYpxael3UzMyo=
github.com/google/pprof v0.0.0-20241029153458-d1b30febd7db/go.mod h1:vavhavw2zAxS5dIdcRluK6cSGGPlZynqzFM8NdvU144=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
github.com/itchyny/gojq v0.12.17 h1:8av8eGduDb5+rvEdaOO+zQUjA04MS0m3Ps8HiD+fceg=
github.com/itchyny/gojq v0.12.17/go.mod h1:WBrEMkgAfAGO1LUcGOckBl5O726KPp+OlkKug0I/FEY=
github.com/itchyny/timefmt-go v0.1.6 h1:ia3s54iciXDdzWzwaVKXZPbiXzxxnv1SPGFfM/myJ5Q=
github.com/itchyny/timefmt-go v0.1.6/go.mod h1:RRDZYC5s9ErkjQvTvvU7keJjxUYzIISJGxm9/mAERQg=
github.com/jmoiron/sqlx v1.3.5 h1:vFFPA71p1o5gAeqtEAwLU4dnX2napprKtHr7PYIcN3g=
github.com/jmoiron/sqlx v1.3.5/go.mod h1:nRVWtLre0KfCLJvgxzCsLVMogSvQ1zNJtpYr2Ccp0mQ=
github.com/jonboulle/clockwork v0.5.0 h1:Hyh9A8u51kptdkR+cqRpT1EebBwTn1oK9YfGYbdFz6I=
github.com/jonboulle/clockwork v0.5.0/go.mod h1:3mZlmanh0g2NDKO5TWZVJAfofYk64M7XN3SzBPjZF60=
github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8=
github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck=
github.com/klauspost/compress v1.18.5 h1:/h1gH5Ce+VWNLSWqPzOVn6XBO+vJbCNGvjoaGBFW2IE=
github.com/klauspost/compress v1.18.5/go.mod h1:cwPg85FWrGar70rWktvGQj8/hthj3wpl0PGDogxkrSQ=
github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
github.com/konsorten/go-windows-terminal-sequences v1.0.3/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc=
github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw=
github.com/lib/pq v1.2.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo=
github.com/mattn/go-sqlite3 v1.14.6/go.mod h1:NyWgC/yNuGj7Q9rpYnZvas74GogHl5/Z4A/KQRfk6bU=
github.com/mitchellh/go-homedir v1.1.0 h1:lukF9ziXFxDFPkA1vsr5zpc1XuPDn/wFntq5mG+4E0Y=
github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0=
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
github.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee h1:W5t00kpgFdJifH4BDsTlE89Zl93FEloxaWZfGcifgq8=
github.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
github.com/mreiferson/go-httpclient v0.0.0-20160630210159-31f0106b4474/go.mod h1:OQA4XLvDbMgS8P0CevmM4m9Q3Jq4phKUzcocxuGJ5m8=
github.com/mreiferson/go-httpclient v0.0.0-20201222173833-5e475fde3a4d/go.mod h1:OQA4XLvDbMgS8P0CevmM4m9Q3Jq4phKUzcocxuGJ5m8=
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA=
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ=
github.com/onsi/ginkgo/v2 v2.22.0 h1:Yed107/8DjTr0lKCNt7Dn8yQ6ybuDRQoMGrNFKzMfHg=
github.com/onsi/ginkgo/v2 v2.22.0/go.mod h1:7Du3c42kxCUegi0IImZ1wUQzMBVecgIHjR1C+NkhLQo=
github.com/onsi/gomega v1.36.1 h1:bJDPBO7ibjxcbHMgSCoo4Yj18UWbKDlLwX1x9sybDcw=
github.com/onsi/gomega v1.36.1/go.mod h1:PvZbdDc8J6XJEpDK4HCuRBm8a6Fzp9/DmhC9C7yFlog=
github.com/op/go-logging v0.0.0-20160315200505-970db520ece7/go.mod h1:HzydrMdWErDVzsI23lYNej1Htcns9BCg93Dk0bBINWk=
github.com/opencontainers/go-digest v1.0.0 h1:apOUWs51W5PlhuyGyz9FCeeBIOUDA/6nW8Oi/yOhh5U=
github.com/opencontainers/go-digest v1.0.0/go.mod h1:0JzlMkj0TRzQZfJkVvzbP0HBR3IKzErnv2BNG4W4MAM=
github.com/opencontainers/image-spec v1.1.1 h1:y0fUlFfIZhPF1W537XOLg0/fcx6zcHCJwooC2xJA040=
github.com/opencontainers/image-spec v1.1.1/go.mod h1:qpqAh3Dmcf36wStyyWU+kCeDgrGnAve2nCC8+7h8Q0M=
github.com/pelletier/go-toml v1.9.3 h1:zeC5b1GviRUyKYd6OJPvBU/mcVDVoL1OhT17FCt5dSQ=
github.com/pelletier/go-toml v1.9.3/go.mod h1:u1nR/EPcESfeI/szUZKdtJ0xRNbUoANCkoOuaOx1Y+c=
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U=
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/prometheus/client_golang v1.22.0 h1:rb93p9lokFEsctTys46VnV1kLCDpVZ0a/Y92Vm0Zc6Q=
github.com/prometheus/client_golang v1.22.0/go.mod h1:R7ljNsLXhuQXYZYtw6GAE9AZg8Y7vEW5scdCXrWRXC0=
github.com/prometheus/client_model v0.6.2 h1:oBsgwpGs7iVziMvrGhE53c/GrLUsZdHnqNwqPLxwZyk=
github.com/prometheus/client_model v0.6.2/go.mod h1:y3m2F6Gdpfy6Ut/GBsUqTWZqCUvMVzSfMLjcu6wAwpE=
github.com/prometheus/common v0.62.0 h1:xasJaQlnWAeyHdUBeGjXmutelfJHWMRr+Fg4QszZ2Io=
github.com/prometheus/common v0.62.0/go.mod h1:vyBcEuLSvWos9B1+CyL7JZ2up+uFzXhkqml0W5zIY1I=
github.com/prometheus/procfs v0.15.1 h1:YagwOFzUgYfKKHX6Dr+sHT7km/hxC76UB0learggepc=
github.com/prometheus/procfs v0.15.1/go.mod h1:fB45yRUv8NstnjriLhBQLuOUt+WW4BsoGhij/e3PBqk=
github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=
github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
github.com/sebdah/goldie/v2 v2.8.0 h1:dZb9wR8q5++oplmEiJT+U/5KyotVD+HNGCAc5gNr8rc=
github.com/sebdah/goldie/v2 v2.8.0/go.mod h1:oZ9fp0+se1eapSRjfYbsV/0Hqhbuu3bJVvKI/NNtssI=
github.com/sergi/go-diff v1.3.1 h1:xkr+Oxo4BOQKmkn/B9eMK0g5Kg/983T9DqqPHwYqD+8=
github.com/sergi/go-diff v1.3.1/go.mod h1:aMJSSKb2lpPvRNec0+w3fl7LP9IOFzdc9Pa4NFbPK1I=
github.com/sirupsen/logrus v1.3.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo=
github.com/sirupsen/logrus v1.7.0/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic61uBYv0=
github.com/sirupsen/logrus v1.9.0/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ=
github.com/sirupsen/logrus v1.9.4 h1:TsZE7l11zFCLZnZ+teH4Umoq5BhEIfIzfRDZ1Uzql2w=
github.com/sirupsen/logrus v1.9.4/go.mod h1:ftWc9WdOfJ0a92nsE2jF5u5ZwH8Bv2zdeOC42RjbV2g=
github.com/spf13/cobra v1.10.2 h1:DMTTonx5m65Ic0GOoRY2c16WCbHxOOw6xxezuLaBpcU=
github.com/spf13/cobra v1.10.2/go.mod h1:7C1pvHqHw5A4vrJfjNwvOdzYu0Gml16OCs2GRiTUUS4=
github.com/spf13/pflag v1.0.9/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
github.com/spf13/pflag v1.0.10 h1:4EBh2KAYBwaONj6b2Ye1GiHfwjqyROoF4RwYO+vPwFk=
github.com/spf13/pflag v1.0.10/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.5.3 h1:jmXUvGomnU1o3W/V5h2VEradbpJDwGrzugQQvL0POH4=
github.com/stretchr/objx v0.5.3/go.mod h1:rDQraq+vQZU7Fde9LOZLr8Tax6zZvy4kuNKF+QYS+U0=
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE=
github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg=
github.com/sylabs/oci-tools v0.19.0 h1:7Dr+CjL2Xl/VzILxdPBhLQif84+W4QJ7XHltyyOf24E=
github.com/sylabs/oci-tools v0.19.0/go.mod h1:ZiYPGZHUshGkzXtE3pEuWSUqBLJNH4Q2eDxE/1OhMyc=
github.com/sylabs/sif/v2 v2.23.0 h1:VWJC7iryINdIgyIK8EdxMCJkx8EDPVlvFaskgY+ruFk=
github.com/sylabs/sif/v2 v2.23.0/go.mod h1:0UJk7MMSQS2n/95yYd+CvAfK7K2mE0aWHRYYybd+ouw=
github.com/tidwall/gjson v1.19.0 h1:xwxm7n691Uf3u5OFjzngavjGTh55KX5q/9w9xHW88JU=
github.com/tidwall/gjson v1.19.0/go.mod h1:V37/opeE/JbLUOfH0QTXiNez2l0RUjYUhpT4szFQAfc=
github.com/tidwall/match v1.1.1 h1:+Ho715JplO36QYgwN9PGYNhgZvoUSc9X2c80KVTi+GA=
github.com/tidwall/match v1.1.1/go.mod h1:eRSPERbgtNPcGhD8UCthc6PmLEQXEWd3PRB5JTxsfmM=
github.com/tidwall/pretty v1.2.0 h1:RWIZEg2iJ8/g6fDDYzMpobmaoGh5OLl4AXtGUGPcqCs=
github.com/tidwall/pretty v1.2.0/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU=
github.com/vbatts/tar-split v0.12.2 h1:w/Y6tjxpeiFMR47yzZPlPj/FcPLpXbTUi/9H7d3CPa4=
github.com/vbatts/tar-split v0.12.2/go.mod h1:eF6B6i6ftWQcDqEn3/iGFRFRo8cBIMSJVOpnNdfTMFA=
github.com/weppos/publicsuffix-go v0.12.0/go.mod h1:z3LCPQ38eedDQSwmsSRW4Y7t2L8Ln16JPQ02lHAdn5k=
github.com/weppos/publicsuffix-go v0.13.0/go.mod h1:z3LCPQ38eedDQSwmsSRW4Y7t2L8Ln16JPQ02lHAdn5k=
github.com/weppos/publicsuffix-go v0.30.0 h1:QHPZ2GRu/YE7cvejH9iyavPOkVCB4dNxp2ZvtT+vQLY=
github.com/weppos/publicsuffix-go v0.30.0/go.mod h1:kBi8zwYnR0zrbm8RcuN1o9Fzgpnnn+btVN8uWPMyXAY=
github.com/weppos/publicsuffix-go/publicsuffix/generator v0.0.0-20220927085643-dc0d00c92642/go.mod h1:GHfoeIdZLdZmLjMlzBftbTDntahTttUMWjxZwQJhULE=
github.com/x448/float16 v0.8.4 h1:qLwI1I70+NjRFUR3zs1JPUCgaCXSh3SW62uAKT1mSBM=
github.com/x448/float16 v0.8.4/go.mod h1:14CWIYCyZA/cWjXOioeEpHeN/83MdbZDRQHoFcYsOfg=
github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
github.com/zmap/rc2 v0.0.0-20131011165748-24b9757f5521/go.mod h1:3YZ9o3WnatTIZhuOtot4IcUfzoKVjUHqu6WALIyI0nE=
github.com/zmap/rc2 v0.0.0-20190804163417-abaa70531248/go.mod h1:3YZ9o3WnatTIZhuOtot4IcUfzoKVjUHqu6WALIyI0nE=
github.com/zmap/zcertificate v0.0.0-20180516150559-0e3d58b1bac4/go.mod h1:5iU54tB79AMBcySS0R2XIyZBAVmeHranShAFELYx7is=
github.com/zmap/zcertificate v0.0.1/go.mod h1:q0dlN54Jm4NVSSuzisusQY0hqDWvu92C+TWveAxiVWk=
github.com/zmap/zcrypto v0.0.0-20201128221613-3719af1573cf/go.mod h1:aPM7r+JOkfL+9qSB4KbYjtoEzJqUK50EXkkJabeNJDQ=
github.com/zmap/zcrypto v0.0.0-20201211161100-e54a5822fb7e/go.mod h1:aPM7r+JOkfL+9qSB4KbYjtoEzJqUK50EXkkJabeNJDQ=
github.com/zmap/zcrypto v0.0.0-20230310154051-c8b263fd8300 h1:DZH5n7L3L8RxKdSyJHZt7WePgwdhHnPhQFdQSJaHF+o=
github.com/zmap/zcrypto v0.0.0-20230310154051-c8b263fd8300/go.mod h1:mOd4yUMgn2fe2nV9KXsa9AyQBFZGzygVPovsZR+Rl5w=
github.com/zmap/zlint/v3 v3.0.0/go.mod h1:paGwFySdHIBEMJ61YjoqT4h7Ge+fdYG4sUQhnTb1lJ8=
github.com/zmap/zlint/v3 v3.5.0 h1:Eh2B5t6VKgVH0DFmTwOqE50POvyDhUaU9T2mJOe1vfQ=
github.com/zmap/zlint/v3 v3.5.0/go.mod h1:JkNSrsDJ8F4VRtBZcYUQSvnWFL7utcjDIn+FE64mlBI=
go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=
go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=
go.uber.org/zap v1.27.0 h1:aJMhYGrd5QSmlpLMr2MftRKl7t8J8PTZPA732ud/XR8=
go.uber.org/zap v1.27.0/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E=
go.yaml.in/yaml/v2 v2.4.4 h1:tuyd0P+2Ont/d6e2rl3be67goVK4R6deVxCUX5vyPaQ=
go.yaml.in/yaml/v2 v2.4.4/go.mod h1:gMZqIpDtDqOfM0uNfy0SkpRhvUryYH0Z6wdMYcacYXQ=
go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw=
go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg=
golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/crypto v0.0.0-20201124201722-c8d3bf9c5392/go.mod h1:jdWPYTVW3xRLrWPugEBEK3UY2ZEsg3UU495nc5E+M+I=
golang.org/x/crypto v0.0.0-20201208171446-5f87f3452ae9/go.mod h1:jdWPYTVW3xRLrWPugEBEK3UY2ZEsg3UU495nc5E+M+I=
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
golang.org/x/crypto v0.7.0/go.mod h1:pYwdfH91IfpZVANVyUOhSIPZaFoJGxTFbZhFTx+dXZU=
golang.org/x/crypto v0.55.0 h1:+KWHjbgOaAQ66dh/YlkZKHlz9ZUlq61AFirAR9ntP8M=
golang.org/x/crypto v0.55.0/go.mod h1:uq0V9dE/fzQuJtbnL+2EhWOE63vo164FY8xqEnV9xis=
golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20200202094626-16171245cfb2/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU=
golang.org/x/net v0.0.0-20201110031124-69a78807bb2b/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU=
golang.org/x/net v0.0.0-20201209123823-ac852fbbde11/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=
golang.org/x/net v0.7.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=
golang.org/x/net v0.8.0/go.mod h1:QVkue5JL9kW//ek3r6jTKnTFis1tRmNAW2P1shuFdJc=
golang.org/x/net v0.58.0 h1:ynWG7rqYi4ccpTEuPZ2QGWHktVEM9DMCj9yzDE0Q7To=
golang.org/x/net v0.58.0/go.mod h1:YwCddHnFlT7eLQqVprV19OnhLGtc5xOKgE0RyqgfWAU=
golang.org/x/oauth2 v0.36.0 h1:peZ/1z27fi9hUOFCAZaHyrpWG5lwe0RJEEEeH0ThlIs=
golang.org/x/oauth2 v0.36.0/go.mod h1:YDBUJMTkDnJS+A4BP4eZBjCqtokkg1hODuPjwiGPO7Q=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek=
golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20201126233918-771906719818/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs=
golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
golang.org/x/term v0.0.0-20201117132131-f5c789dd3221/go.mod h1:Nr5EML6q2oocZ2LXRh80K7BxOlk5/8JxuGnuhpl+muw=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k=
golang.org/x/term v0.6.0/go.mod h1:m6U89DPEgQRMq3DNkDClhWw02AUbt2daBVO4cn4Hv9U=
golang.org/x/term v0.45.0 h1:NwWyBmoJCbfTHpxrWoZ9C6/VxOf7ic219I8xZZFdrf0=
golang.org/x/term v0.45.0/go.mod h1:9aqxs0blBcrm/n0L9QW0aRVD+ktan8ssZromtqJC43w=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.4/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
golang.org/x/text v0.8.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8=
golang.org/x/text v0.41.0 h1:vz/seA0lnX87Othu2f/0L24RcgrXD9/YFTSuGjj3rH8=
golang.org/x/text v0.41.0/go.mod h1:jvf1O8ajNzZqhSrQBPbutR/EB83Cc0CFrezNQIwbb5M=
golang.org/x/time v0.11.0 h1:/bpjEDfN9tkoN/ryeYHnv5hcMlc8ncjMcM4XBk5NWV0=
golang.org/x/time v0.11.0/go.mod h1:CDIdPxbZBQxdj6cxyCIdrNogrJKMJ7pr37NYpMcMDSg=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.0.0-20200619180055-7c47624df98f/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE=
golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA=
golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU=
golang.org/x/tools v0.48.0 h1:3+hClM1aLL5mjMKm5ovokw9epgRXPuu2tILgismM6RE=
golang.org/x/tools v0.48.0/go.mod h1:08xX0orndb/F7jJxGDicx061tyd5pcMto75YMAXr6lk=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
gomodules.xyz/jsonpatch/v2 v2.4.0 h1:Ci3iUJyx9UeRx7CeFN8ARgGbkESwJK+KB9lLcWxY/Zw=
gomodules.xyz/jsonpatch/v2 v2.4.0/go.mod h1:AH3dM2RI6uoBZxn3LVrfvJ3E0/9dG4cSrbuBJT4moAY=
google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=
google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
gopkg.in/evanphx/json-patch.v4 v4.12.0 h1:n6jtcsulIzXPJaxegRbvFNNrZDjbij7ny3gmSPG+6V4=
gopkg.in/evanphx/json-patch.v4 v4.12.0/go.mod h1:p8EYWUEYMpynmqDbY58zCKCFZw8pRWMG4EsWvDvM72M=
gopkg.in/inf.v0 v0.9.1 h1:73M5CoZyi3ZLMOyDlQh031Cx6N9NDJ2Vvfl76EDAgDc=
gopkg.in/inf.v0 v0.9.1/go.mod h1:cWUDdTG/fYaXco+Dcufb5Vnc6Gp2YChqWtbxRZE0mXw=
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gotest.tools/v3 v3.4.0 h1:ZazjZUfuVeZGLAmlKKuyv3IKP5orXcwtOwDQH6YVr6o=
gotest.tools/v3 v3.4.0/go.mod h1:CtbdzLSsqVhDgMtKsx03ird5YTGB3ar27v0u/yKBW5g=
k8s.io/api v0.34.8 h1:PATray7Ixf5fzuvW6WTrLGqWpaeSUlV3NqygBu10YC0=
k8s.io/api v0.34.8/go.mod h1:kkv5KLONEBxemk51GDsqR0TaBig60bVriYyDj9v3gg8=
k8s.io/apiextensions-apiserver v0.34.8 h1:iovXsJk6GKQdgEQFpeTJcFHGVGx576gyAA3StSkwNk0=
k8s.io/apiextensions-apiserver v0.34.8/go.mod h1:hmkveoSZ3WH4HBMc/FcraqfPbASAZ/TbAfaHFfiEvlY=
k8s.io/apimachinery v0.34.8 h1:Vjyd/TdakksL0g7ikxyaAk3s3qgqRRYz9vj0AudwNzc=
k8s.io/apimachinery v0.34.8/go.mod h1:z7dd12Xd400CXIycE8nmn32xZhApV9zskHs0A5xeU/Q=
k8s.io/client-go v0.34.8 h1:/4Ar6TX6V/vwhFQDeTMySO0+OBbslk7inkEdOQdR66A=
k8s.io/client-go v0.34.8/go.mod h1:VVLUD4GP16X+ePPZ3YpCyxn1rhaf1lczr/HCI0e40h8=
k8s.io/klog/v2 v2.140.0 h1:Tf+J3AH7xnUzZyVVXhTgGhEKnFqye14aadWv7bzXdzc=
k8s.io/klog/v2 v2.140.0/go.mod h1:o+/RWfJ6PwpnFn7OyAG3QnO47BFsymfEfrz6XyYSSp0=
k8s.io/kube-openapi v0.0.0-20260603220949-865597e52e25 h1:mPMaPMpBij2V1Wv/fR+HW124vVGXXvOSS9ver/9yjWs=
k8s.io/kube-openapi v0.0.0-20260603220949-865597e52e25/go.mod h1:V/QaCUYDa+0QpcHhVVc5l99Uz56wEMEXBSj9oCDkNDY=
k8s.io/utils v0.0.0-20260507154919-ff6756f316d2 h1:wU4tMEhLGgIbLvXQb1cfN+EcM0wf7zC6CPF+C79jroc=
k8s.io/utils v0.0.0-20260507154919-ff6756f316d2/go.mod h1:xDxuJ0whA3d0I4mf/C4ppKHxXynQ+fxnkmQH0vTHnuk=
sigs.k8s.io/controller-runtime v0.22.5 h1:v3nfSUMowX/2WMp27J9slwGFyAt7IV0YwBxAkrUr0GE=
sigs.k8s.io/controller-runtime v0.22.5/go.mod h1:pc5SoYWnWI6I+cBHYYdZ7B6YHZVY5xNfll88JB+vniI=
sigs.k8s.io/json v0.0.0-20250730193827-2d320260d730 h1:IpInykpT6ceI+QxKBbEflcR5EXP7sU1kvOlxwZh5txg=
sigs.k8s.io/json v0.0.0-20250730193827-2d320260d730/go.mod h1:mdzfpAEoE6DHQEN0uh9ZbOCuHbLK5wOm7dK4ctXE9Tg=
sigs.k8s.io/randfill v1.0.0 h1:JfjMILfT8A6RbawdsK2JXGBR5AQVfd+9TbzrlneTyrU=
sigs.k8s.io/randfill v1.0.0/go.mod h1:XeLlZ/jmk4i1HRopwe7/aU3H5n1zNUcX6TM94b3QxOY=
sigs.k8s.io/structured-merge-diff/v6 v6.3.2 h1:kwVWMx5yS1CrnFWA/2QHyRVJ8jM6dBA80uLmm0wJkk8=
sigs.k8s.io/structured-merge-diff/v6 v6.3.2/go.mod h1:M3W8sfWvn2HhQDIbGWj3S099YozAsymCo/wrT5ohRUE=
sigs.k8s.io/yaml v1.6.0 h1:G8fkbMSAFqgEFgh4b1wmtzDnioxFCUgTZhlbj5P9QYs=
sigs.k8s.io/yaml v1.6.0/go.mod h1:796bPqUfzR/0jLAl6XjHl3Ck7MiyVv8dbTdyT3/pMf4=
@@ -0,0 +1,25 @@
/*
Copyright 2026 The cluster-map Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Package https registers the common hook that copies a CustomCertificate
// secret from d8-system into the module values.
package https
import (
copycustomcertificate "github.com/deckhouse/module-sdk/common-hooks/copy-custom-certificate"
)
var _ = copycustomcertificate.RegisterHook("clusterMap")
+72
View File
@@ -0,0 +1,72 @@
/*
Copyright 2026 The cluster-map Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package main
import (
"context"
"encoding/base64"
"fmt"
"github.com/deckhouse/module-sdk/pkg"
objectpatch "github.com/deckhouse/module-sdk/pkg/object-patch"
"github.com/deckhouse/module-sdk/pkg/registry"
)
const (
hubbleCASnapshot = "hubble_ca"
hubbleCAValuePath = "clusterMap.internal.hubbleCA"
)
// hubbleCAConfig watches the hubble CA secret of the cilium-hubble module.
// The jq filter keeps only the public certificate: the CA key never
// reaches the module's values.
var hubbleCAConfig = &pkg.HookConfig{
OnBeforeHelm: &pkg.OrderedConfig{Order: 10},
Kubernetes: []pkg.KubernetesConfig{{
Name: hubbleCASnapshot,
APIVersion: "v1",
Kind: "Secret",
NameSelector: &pkg.NameSelector{
MatchNames: []string{"hubble-ca-secret"},
},
NamespaceSelector: &pkg.NamespaceSelector{
NameSelector: &pkg.NameSelector{MatchNames: []string{"d8-cni-cilium"}},
},
JqFilter: `.data."ca.crt" // ""`,
}},
}
var _ = registry.RegisterFunc(hubbleCAConfig, handleHubbleCA)
// handleHubbleCA publishes the CA for the Deployment, or an empty string
// when cilium-hubble is not installed, which turns traffic off.
func handleHubbleCA(_ context.Context, input *pkg.HookInput) error {
certs, err := objectpatch.UnmarshalToStruct[string](input.Snapshots, hubbleCASnapshot)
if err != nil {
return fmt.Errorf("read %s snapshot: %w", hubbleCASnapshot, err)
}
if len(certs) == 0 || certs[0] == "" {
input.Values.Set(hubbleCAValuePath, "")
return nil
}
pem, err := base64.StdEncoding.DecodeString(certs[0])
if err != nil {
return fmt.Errorf("decode hubble CA: %w", err)
}
input.Values.Set(hubbleCAValuePath, string(pem))
return nil
}
+55
View File
@@ -0,0 +1,55 @@
/*
Copyright 2026 The cluster-map Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package main
import (
"testing"
"github.com/stretchr/testify/require"
"github.com/deckhouse/module-sdk/testing/framework"
)
const initValues = `{"clusterMap": {"internal": {}}}`
func TestHubbleCAIsCopiedWithoutKey(t *testing.T) {
hec := framework.HookExecutionConfigInit(t, hubbleCAConfig, handleHubbleCA, initValues, `{}`)
hec.KubeStateSet(`
---
apiVersion: v1
kind: Secret
metadata:
name: hubble-ca-secret
namespace: d8-cni-cilium
data:
ca.crt: LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0tCg==
ca.key: bm90LWZvci11cw==
`)
hec.RunHook()
require.NoError(t, hec.HookError())
require.Equal(t, "-----BEGIN CERTIFICATE-----\n", hec.ValuesGet("clusterMap.internal.hubbleCA").String())
require.NotContains(t, hec.ValuesGet("clusterMap").Raw, "not-for-us")
}
func TestNoHubbleMeansEmptyCA(t *testing.T) {
hec := framework.HookExecutionConfigInit(t, hubbleCAConfig, handleHubbleCA, initValues, `{}`)
hec.KubeStateSet(``)
hec.RunHook()
require.NoError(t, hec.HookError())
require.True(t, hec.ValuesGet("clusterMap.internal.hubbleCA").Exists())
require.Equal(t, "", hec.ValuesGet("clusterMap.internal.hubbleCA").String())
}
+28
View File
@@ -0,0 +1,28 @@
/*
Copyright 2026 The cluster-map Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Command batchhooks is the cluster-map module's hook binary (module-sdk).
package main
import (
_ "hook/https"
"github.com/deckhouse/module-sdk/pkg/app"
)
func main() {
app.Run()
}
+23
View File
@@ -0,0 +1,23 @@
version: "2"
linters:
default: standard
enable:
- bodyclose
- errorlint
- gocritic
- gosec
- misspell
- nilerr
- revive
- unconvert
settings:
gosec:
excludes:
- G104 # unchecked errors on http.ResponseWriter writes: nothing useful to do with them
exclusions:
presets:
- std-error-handling
formatters:
enable:
- gofmt
- goimports
@@ -0,0 +1,172 @@
/*
Copyright 2026 The cluster-map Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Command cluster-map serves a topology map of a Kubernetes cluster with
// live traffic from Cilium Hubble.
package main
import (
"context"
"crypto/tls"
"crypto/x509"
"errors"
"fmt"
"log/slog"
"net/http"
"os"
"os/signal"
"syscall"
"time"
observerpb "github.com/cilium/cilium/api/v1/observer"
"github.com/prometheus/client_golang/prometheus/promhttp"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
"k8s.io/client-go/dynamic"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/clientcmd"
"git.project-chimera.ru/fanchji/cluster-map/internal/actions"
"git.project-chimera.ru/fanchji/cluster-map/internal/config"
"git.project-chimera.ru/fanchji/cluster-map/internal/kube"
"git.project-chimera.ru/fanchji/cluster-map/internal/metrics"
"git.project-chimera.ru/fanchji/cluster-map/internal/server"
"git.project-chimera.ru/fanchji/cluster-map/internal/topology"
"git.project-chimera.ru/fanchji/cluster-map/internal/traffic"
"git.project-chimera.ru/fanchji/cluster-map/web"
)
func main() {
slog.SetDefault(slog.New(slog.NewJSONHandler(os.Stdout, nil)))
if err := run(); err != nil {
slog.Error("exiting", "err", err)
os.Exit(1)
}
}
func run() error {
cfg, err := config.Load()
if err != nil {
return err
}
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGTERM, syscall.SIGINT)
defer stop()
restCfg, err := restConfig()
if err != nil {
return err
}
var asViewer actions.ClientFactory
if cfg.ActionsEnabled || cfg.ViewerVisibility {
asViewer = actions.NewClientFactory(restCfg)
}
srv := server.New(cfg, web.Static(), asViewer)
api := &http.Server{Addr: cfg.ListenAddr, Handler: srv.Handler(), ReadHeaderTimeout: 10 * time.Second}
metricsSrv := &http.Server{Addr: cfg.MetricsAddr, Handler: promhttp.HandlerFor(metrics.Registry, promhttp.HandlerOpts{}), ReadHeaderTimeout: 10 * time.Second}
errc := make(chan error, 2)
for _, s := range []*http.Server{api, metricsSrv} {
go func() {
if err := s.ListenAndServe(); !errors.Is(err, http.ErrServerClosed) {
errc <- err
}
}()
}
slog.Info("listening", "api", cfg.ListenAddr, "metrics", cfg.MetricsAddr, "traffic", cfg.TrafficMode, "actions", cfg.ActionsEnabled, "viewerVisibility", cfg.ViewerVisibility)
client, err := kubernetes.NewForConfig(restCfg)
if err != nil {
return err
}
dyn, err := dynamic.NewForConfig(restCfg)
if err != nil {
return err
}
cache, err := kube.Start(ctx, client, dyn, 2*time.Minute)
if err != nil {
return err
}
metrics.CacheSynced.Set(1)
obs, err := hubbleClient(cfg)
if err != nil && cfg.TrafficMode != config.TrafficDisabled {
slog.Error("traffic disabled: cannot set up the Hubble client", "err", err)
}
collector := traffic.NewCollector(cfg, obs, podResolver(cache))
go collector.Run(ctx)
srv.SetReady(cache, collector)
slog.Info("ready")
select {
case <-ctx.Done():
case err := <-errc:
return err
}
slog.Info("shutting down")
shutdownCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
return errors.Join(api.Shutdown(shutdownCtx), metricsSrv.Shutdown(shutdownCtx))
}
// restConfig is the pod's service account; KUBECONFIG, when set, is for
// running the binary on a workstation during development.
func restConfig() (*rest.Config, error) {
if path := os.Getenv("KUBECONFIG"); path != "" {
return clientcmd.BuildConfigFromFlags("", path)
}
cfg, err := rest.InClusterConfig()
if err != nil {
return nil, fmt.Errorf("in-cluster config: %w", err)
}
return cfg, nil
}
// hubbleClient connects to Hubble Relay over TLS. Relay presents a
// *.hubble-relay.cilium.io certificate signed by the cluster's hubble CA
// and does not ask for a client certificate, so only the CA is needed.
func hubbleClient(cfg config.Config) (observerpb.ObserverClient, error) {
if cfg.TrafficMode == config.TrafficDisabled {
return nil, nil
}
caPEM, err := os.ReadFile(cfg.HubbleCAFile)
if err != nil {
return nil, fmt.Errorf("hubble CA: %w", err)
}
pool := x509.NewCertPool()
if !pool.AppendCertsFromPEM(caPEM) {
return nil, errors.New("hubble CA: no certificate in " + cfg.HubbleCAFile)
}
creds := credentials.NewTLS(&tls.Config{RootCAs: pool, ServerName: cfg.HubbleServerName, MinVersion: tls.VersionTLS12})
conn, err := grpc.NewClient(cfg.HubbleRelayAddr, grpc.WithTransportCredentials(creds))
if err != nil {
return nil, err
}
return observerpb.NewObserverClient(conn), nil
}
func podResolver(c *kube.Cache) traffic.PodResolver {
return func(ns, name string) (traffic.Endpoint, bool) {
p, err := c.Pods.Pods(ns).Get(name)
if err != nil {
return traffic.Endpoint{}, false
}
kind, owner, _ := topology.PodOwner(*p)
if kind == "" {
return traffic.Endpoint{}, false
}
return traffic.Endpoint{ID: topology.WorkloadID(ns, kind, owner), Label: owner, Kind: kind, Namespace: ns}, true
}
}
+7
View File
@@ -4,6 +4,7 @@ go 1.25.0
require ( require (
github.com/cilium/cilium v1.17.4 github.com/cilium/cilium v1.17.4
github.com/prometheus/client_golang v1.24.1
google.golang.org/grpc v1.84.0 google.golang.org/grpc v1.84.0
google.golang.org/protobuf v1.36.11 google.golang.org/protobuf v1.36.11
k8s.io/api v0.32.0 k8s.io/api v0.32.0
@@ -13,6 +14,8 @@ require (
) )
require ( require (
github.com/beorn7/perks v1.0.1 // indirect
github.com/cespare/xxhash/v2 v2.3.0 // indirect
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect
github.com/emicklei/go-restful/v3 v3.12.0 // indirect github.com/emicklei/go-restful/v3 v3.12.0 // indirect
github.com/fxamacker/cbor/v2 v2.7.0 // indirect github.com/fxamacker/cbor/v2 v2.7.0 // indirect
@@ -33,6 +36,10 @@ require (
github.com/modern-go/reflect2 v1.0.2 // indirect github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect
github.com/pkg/errors v0.9.1 // indirect github.com/pkg/errors v0.9.1 // indirect
github.com/prometheus/client_model v0.6.2 // indirect
github.com/prometheus/common v0.70.1 // indirect
github.com/prometheus/procfs v0.21.1 // indirect
github.com/spf13/pflag v1.0.6-0.20210604193023-d5e0c0615ace // indirect
github.com/x448/float16 v0.8.4 // indirect github.com/x448/float16 v0.8.4 // indirect
golang.org/x/net v0.57.0 // indirect golang.org/x/net v0.57.0 // indirect
golang.org/x/oauth2 v0.36.0 // indirect golang.org/x/oauth2 v0.36.0 // indirect
+22 -2
View File
@@ -1,3 +1,7 @@
github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM=
github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw=
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
github.com/cilium/cilium v1.17.4 h1:fO1VBbBLU69wbhN2csULVLPs7gR3qr0IrnYmI2SwU40= github.com/cilium/cilium v1.17.4 h1:fO1VBbBLU69wbhN2csULVLPs7gR3qr0IrnYmI2SwU40=
github.com/cilium/cilium v1.17.4/go.mod h1:wVAXueJW11HUvZo0c+szVo7zeCLZ5yOCgNHP0lwiS8g= github.com/cilium/cilium v1.17.4/go.mod h1:wVAXueJW11HUvZo0c+szVo7zeCLZ5yOCgNHP0lwiS8g=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
@@ -40,10 +44,14 @@ github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnr
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8= github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8=
github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck=
github.com/klauspost/compress v1.19.1 h1:VsB4HPswih7mmZ8WleSFQ75c/Ui1M4trX5oAsJnhSlk=
github.com/klauspost/compress v1.19.1/go.mod h1:cwPg85FWrGar70rWktvGQj8/hthj3wpl0PGDogxkrSQ=
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc=
github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw=
github.com/mailru/easyjson v0.7.7 h1:UGYAvKxe3sBsEDzO8ZeWOSlIQfWFlxbzLZe7hwFURr0= github.com/mailru/easyjson v0.7.7 h1:UGYAvKxe3sBsEDzO8ZeWOSlIQfWFlxbzLZe7hwFURr0=
github.com/mailru/easyjson v0.7.7/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc= github.com/mailru/easyjson v0.7.7/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc=
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
@@ -63,18 +71,30 @@ github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINE
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U= github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U=
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/prometheus/client_golang v1.24.1 h1:JnJkREXzWxUdCuPFpIWZiPispT9xVV59uiuyR2bPlnU=
github.com/prometheus/client_golang v1.24.1/go.mod h1:F+oSRECHg4sse5ucfYpYDeIv/hu68Zo0uoHKetWnzcE=
github.com/prometheus/client_model v0.6.2 h1:oBsgwpGs7iVziMvrGhE53c/GrLUsZdHnqNwqPLxwZyk=
github.com/prometheus/client_model v0.6.2/go.mod h1:y3m2F6Gdpfy6Ut/GBsUqTWZqCUvMVzSfMLjcu6wAwpE=
github.com/prometheus/common v0.70.1 h1:1HvjP4D5oL3t8RsPlwxA9onvvStjtIHYE5XuuwOi/PY=
github.com/prometheus/common v0.70.1/go.mod h1:VdFUQDMZK3VLkurFUVhia6uys/0suUp86TJz5qbJRhc=
github.com/prometheus/procfs v0.21.1 h1:GljZCt+zSTS+NZq88cyQ1LjZ+RCHp3uVuabBWA5+OJI=
github.com/prometheus/procfs v0.21.1/go.mod h1:aB55Cww9pdSJVHk0hUf0inxWyyjPogFIjmHKYgMKmtY=
github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8= github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8=
github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4= github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4=
github.com/spf13/pflag v1.0.6-0.20210604193023-d5e0c0615ace h1:9PNP1jnUjRhfmGMlkXHjYPishpcw4jpSt/V/xYY3FMA= github.com/spf13/pflag v1.0.6-0.20210604193023-d5e0c0615ace h1:9PNP1jnUjRhfmGMlkXHjYPishpcw4jpSt/V/xYY3FMA=
github.com/spf13/pflag v1.0.6-0.20210604193023-d5e0c0615ace/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= github.com/spf13/pflag v1.0.6-0.20210604193023-d5e0c0615ace/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA= github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
github.com/x448/float16 v0.8.4 h1:qLwI1I70+NjRFUR3zs1JPUCgaCXSh3SW62uAKT1mSBM= github.com/x448/float16 v0.8.4 h1:qLwI1I70+NjRFUR3zs1JPUCgaCXSh3SW62uAKT1mSBM=
github.com/x448/float16 v0.8.4/go.mod h1:14CWIYCyZA/cWjXOioeEpHeN/83MdbZDRQHoFcYsOfg= github.com/x448/float16 v0.8.4/go.mod h1:14CWIYCyZA/cWjXOioeEpHeN/83MdbZDRQHoFcYsOfg=
github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
go.yaml.in/yaml/v2 v2.4.4 h1:tuyd0P+2Ont/d6e2rl3be67goVK4R6deVxCUX5vyPaQ=
go.yaml.in/yaml/v2 v2.4.4/go.mod h1:gMZqIpDtDqOfM0uNfy0SkpRhvUryYH0Z6wdMYcacYXQ=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
@@ -0,0 +1,184 @@
/*
Copyright 2026 The cluster-map Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Package access decides what a viewer may see on the map, from the
// viewer's own RBAC.
//
// The map reads the cluster with the module's service account, which can
// read everything it shows. Without this package anyone admitted to the web
// interface would see every namespace and every log. With it, each request
// carries the viewer's token (the DexAuthenticator's Authorization header),
// and the API server answers SelfSubjectAccessReviews for that viewer:
// "list pods in all namespaces" means the whole cluster, otherwise the
// namespaces where the viewer can list pods. The answer is cached per token
// for a minute, so a page load costs one round of reviews, not one per call.
package access
import (
"context"
"crypto/sha256"
"errors"
"sync"
"time"
authzv1 "k8s.io/api/authorization/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
)
// Scope is what one viewer may see.
type Scope struct {
// All: the viewer can list pods in every namespace; nothing is hidden.
All bool
// Namespaces the viewer can list pods in, when not All.
Namespaces map[string]bool
// Nodes: the viewer can list nodes (node cards, node view, node usage).
Nodes bool
}
// Everything is the scope when filtering is off.
var Everything = &Scope{All: true, Nodes: true}
// Namespace reports whether objects in ns are visible.
func (s *Scope) Namespace(ns string) bool {
return s.All || s.Namespaces[ns]
}
// ClientFactory returns a clientset authenticated as the viewer.
type ClientFactory func(token string) (kubernetes.Interface, error)
// ErrNoToken is returned when the request has no viewer token.
var ErrNoToken = errors.New("no user token in the request: per-user visibility needs the DexAuthenticator to send the Authorization header")
// Checker computes and caches scopes.
type Checker struct {
asViewer ClientFactory
namespaces func() []string // namespaces to check when the viewer is not cluster-wide
ttl time.Duration
now func() time.Time
mu sync.Mutex
cache map[[32]byte]entry
}
type entry struct {
scope *Scope
at time.Time
}
const maxEntries = 512
// NewChecker returns a checker; namespaces lists the cluster's namespaces (from the cache).
func NewChecker(asViewer ClientFactory, namespaces func() []string) *Checker {
return &Checker{asViewer: asViewer, namespaces: namespaces, ttl: time.Minute, now: time.Now, cache: map[[32]byte]entry{}}
}
// For returns the viewer's scope.
func (c *Checker) For(ctx context.Context, token string) (*Scope, error) {
if token == "" {
return nil, ErrNoToken
}
key := sha256.Sum256([]byte(token))
c.mu.Lock()
if e, ok := c.cache[key]; ok && c.now().Sub(e.at) < c.ttl {
c.mu.Unlock()
return e.scope, nil
}
c.mu.Unlock()
client, err := c.asViewer(token)
if err != nil {
return nil, err
}
scope, err := c.compute(ctx, client)
if err != nil {
return nil, err
}
c.mu.Lock()
if len(c.cache) >= maxEntries {
for k, e := range c.cache {
if c.now().Sub(e.at) >= c.ttl {
delete(c.cache, k)
}
}
if len(c.cache) >= maxEntries {
c.cache = map[[32]byte]entry{}
}
}
c.cache[key] = entry{scope, c.now()}
c.mu.Unlock()
return scope, nil
}
func (c *Checker) compute(ctx context.Context, client kubernetes.Interface) (*Scope, error) {
all, err := Can(ctx, client, "", "pods", "", "list", "")
if err != nil {
return nil, err
}
nodes, err := Can(ctx, client, "", "nodes", "", "list", "")
if err != nil {
return nil, err
}
s := &Scope{All: all, Nodes: nodes}
if all {
return s, nil
}
s.Namespaces = map[string]bool{}
type result struct {
ns string
ok bool
err error
}
names := c.namespaces()
results := make(chan result, len(names))
sem := make(chan struct{}, 8)
var wg sync.WaitGroup
for _, ns := range names {
wg.Add(1)
go func() {
defer wg.Done()
sem <- struct{}{}
defer func() { <-sem }()
ok, err := Can(ctx, client, "", "pods", "", "list", ns)
results <- result{ns, ok, err}
}()
}
wg.Wait()
close(results)
for r := range results {
if r.err != nil {
return nil, r.err
}
if r.ok {
s.Namespaces[r.ns] = true
}
}
return s, nil
}
// Can asks the API server whether the viewer behind client may perform the
// verb; namespace "" means cluster-wide (or all namespaces).
func Can(ctx context.Context, client kubernetes.Interface, group, resource, subresource, verb, namespace string) (bool, error) {
r, err := client.AuthorizationV1().SelfSubjectAccessReviews().Create(ctx, &authzv1.SelfSubjectAccessReview{
Spec: authzv1.SelfSubjectAccessReviewSpec{ResourceAttributes: &authzv1.ResourceAttributes{
Group: group, Resource: resource, Subresource: subresource, Verb: verb, Namespace: namespace,
}},
}, metav1.CreateOptions{})
if err != nil {
return false, err
}
return r.Status.Allowed, nil
}
@@ -0,0 +1,76 @@
/*
Copyright 2026 The cluster-map Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package access
import (
"context"
"errors"
"sync/atomic"
"testing"
authzv1 "k8s.io/api/authorization/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/kubernetes/fake"
k8stesting "k8s.io/client-go/testing"
)
// viewer may list pods in "shop" only, and not nodes.
func factory(calls *atomic.Int32, allowAll bool) ClientFactory {
return func(string) (kubernetes.Interface, error) {
c := fake.NewSimpleClientset()
c.PrependReactor("create", "selfsubjectaccessreviews", func(a k8stesting.Action) (bool, runtime.Object, error) {
calls.Add(1)
r := a.(k8stesting.CreateAction).GetObject().(*authzv1.SelfSubjectAccessReview)
at := r.Spec.ResourceAttributes
r.Status.Allowed = allowAll || (at.Resource == "pods" && at.Namespace == "shop")
return true, r, nil
})
return c, nil
}
}
func TestScopeAndCache(t *testing.T) {
var calls atomic.Int32
c := NewChecker(factory(&calls, false), func() []string { return []string{"shop", "bank", "d8-system"} })
s, err := c.For(context.Background(), "tok")
if err != nil {
t.Fatal(err)
}
if s.All || s.Nodes || !s.Namespace("shop") || s.Namespace("bank") {
t.Errorf("scope: %+v", s)
}
first := calls.Load()
if _, err := c.For(context.Background(), "tok"); err != nil || calls.Load() != first {
t.Errorf("second request within the TTL asked the API server again (%d -> %d)", first, calls.Load())
}
if _, err := c.For(context.Background(), ""); !errors.Is(err, ErrNoToken) {
t.Errorf("no token: %v", err)
}
}
func TestClusterWideViewerSkipsNamespaceChecks(t *testing.T) {
var calls atomic.Int32
c := NewChecker(factory(&calls, true), func() []string { return []string{"a", "b", "c"} })
s, err := c.For(context.Background(), "admin")
if err != nil || !s.All || !s.Nodes {
t.Fatalf("scope %+v, %v", s, err)
}
if calls.Load() != 2 { // pods cluster-wide and nodes
t.Errorf("cluster-wide viewer needed %d reviews, want 2", calls.Load())
}
}
@@ -0,0 +1,263 @@
/*
Copyright 2026 The cluster-map Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Package actions runs the few changes the map offers (restart, scale,
// delete a pod, run a CronJob, cordon a node) as the viewer.
//
// Every call goes to the API server with the viewer's own bearer token,
// the one the DexAuthenticator puts into the Authorization header. The
// module's service account stays read-only, so the map can never do more
// than its viewer could do with kubectl, and the API server's audit log
// names the person, not cluster-map.
package actions
import (
"context"
"errors"
"fmt"
"strconv"
"time"
authnv1 "k8s.io/api/authentication/v1"
authzv1 "k8s.io/api/authorization/v1"
batchv1 "k8s.io/api/batch/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/types"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
"k8s.io/client-go/util/retry"
)
// Action names, as the UI sends them.
const (
Restart = "restart"
Scale = "scale"
DeletePod = "delete-pod"
Run = "run"
Suspend = "suspend"
Resume = "resume"
Cordon = "cordon"
Uncordon = "uncordon"
)
// MaxReplicas bounds Scale; a typo in the dialog should not start 5000 pods.
const MaxReplicas = 100
// Request is the body of POST /api/action.
type Request struct {
Action string `json:"action"`
Kind string `json:"kind"` // deployment | statefulset | daemonset | cronjob | pod | node
Namespace string `json:"namespace"`
Name string `json:"name"`
Replicas *int32 `json:"replicas,omitempty"`
}
func (r Request) String() string {
if r.Namespace == "" {
return r.Kind + "/" + r.Name
}
return r.Kind + " " + r.Namespace + "/" + r.Name
}
// check is the RBAC question an action asks the API server first.
type check struct{ group, resource, subresource, verb string }
var byKind = map[string]map[string]check{
"deployment": {
Restart: {"apps", "deployments", "", "patch"},
Scale: {"apps", "deployments", "scale", "update"},
},
"statefulset": {
Restart: {"apps", "statefulsets", "", "patch"},
Scale: {"apps", "statefulsets", "scale", "update"},
},
"daemonset": {
Restart: {"apps", "daemonsets", "", "patch"},
},
"cronjob": {
Run: {"batch", "jobs", "", "create"},
Suspend: {"batch", "cronjobs", "", "patch"},
Resume: {"batch", "cronjobs", "", "patch"},
},
"pod": {
DeletePod: {"", "pods", "", "delete"},
},
"node": {
Cordon: {"", "nodes", "", "patch"},
Uncordon: {"", "nodes", "", "patch"},
},
}
// ErrUnsupported is returned for an action the kind does not offer.
var ErrUnsupported = errors.New("this action is not offered for this kind of object")
// ClientFactory returns a clientset that authenticates as the viewer.
type ClientFactory func(token string) (kubernetes.Interface, error)
// NewClientFactory keeps base's API server address and CA and drops its
// credentials, so a request carries the viewer's token and nothing else.
func NewClientFactory(base *rest.Config) ClientFactory {
return func(token string) (kubernetes.Interface, error) {
cfg := rest.AnonymousClientConfig(base)
cfg.BearerToken = token
cfg.UserAgent = "cluster-map (on behalf of the viewer)"
cfg.Timeout = 15 * time.Second
return kubernetes.NewForConfig(cfg)
}
}
// WhoAmI returns the viewer's username as the API server sees it.
func WhoAmI(ctx context.Context, c kubernetes.Interface) (string, error) {
r, err := c.AuthenticationV1().SelfSubjectReviews().Create(ctx, &authnv1.SelfSubjectReview{}, metav1.CreateOptions{})
if err != nil {
return "", err
}
return r.Status.UserInfo.Username, nil
}
// Allowed asks the API server which of the kind's actions the viewer may
// run on the object.
func Allowed(ctx context.Context, c kubernetes.Interface, kind, namespace, name string) (map[string]bool, error) {
out := map[string]bool{}
for action, ch := range byKind[kind] {
ok, err := can(ctx, c, ch, namespace, name)
if err != nil {
return nil, err
}
out[action] = ok
}
return out, nil
}
func can(ctx context.Context, c kubernetes.Interface, ch check, namespace, name string) (bool, error) {
attrs := &authzv1.ResourceAttributes{Group: ch.group, Resource: ch.resource, Subresource: ch.subresource, Verb: ch.verb, Namespace: namespace, Name: name}
if ch.verb == "create" {
attrs.Name = "" // a Job that does not exist yet
}
r, err := c.AuthorizationV1().SelfSubjectAccessReviews().Create(ctx, &authzv1.SelfSubjectAccessReview{
Spec: authzv1.SelfSubjectAccessReviewSpec{ResourceAttributes: attrs},
}, metav1.CreateOptions{})
if err != nil {
return false, err
}
return r.Status.Allowed, nil
}
// Do runs the action and returns a short description of what changed.
// Authorization is the API server's: a viewer without the right gets its
// Forbidden error back unchanged.
func Do(ctx context.Context, c kubernetes.Interface, r Request, now time.Time) (string, error) {
if _, ok := byKind[r.Kind][r.Action]; !ok {
return "", ErrUnsupported
}
if r.Name == "" || (r.Kind != "node" && r.Namespace == "") {
return "", errors.New("namespace and name are required")
}
switch r.Action {
case Restart:
// what kubectl rollout restart does
patch := fmt.Sprintf(`{"spec":{"template":{"metadata":{"annotations":{"kubectl.kubernetes.io/restartedAt":%q}}}}}`, now.UTC().Format(time.RFC3339))
var err error
switch r.Kind {
case "deployment":
_, err = c.AppsV1().Deployments(r.Namespace).Patch(ctx, r.Name, types.StrategicMergePatchType, []byte(patch), metav1.PatchOptions{})
case "statefulset":
_, err = c.AppsV1().StatefulSets(r.Namespace).Patch(ctx, r.Name, types.StrategicMergePatchType, []byte(patch), metav1.PatchOptions{})
case "daemonset":
_, err = c.AppsV1().DaemonSets(r.Namespace).Patch(ctx, r.Name, types.StrategicMergePatchType, []byte(patch), metav1.PatchOptions{})
}
return "rollout restarted", err
case Scale:
return scale(ctx, c, r)
case DeletePod:
return "pod deleted", c.CoreV1().Pods(r.Namespace).Delete(ctx, r.Name, metav1.DeleteOptions{})
case Run:
return runCronJob(ctx, c, r, now)
case Suspend, Resume:
patch := fmt.Sprintf(`{"spec":{"suspend":%t}}`, r.Action == Suspend)
_, err := c.BatchV1().CronJobs(r.Namespace).Patch(ctx, r.Name, types.MergePatchType, []byte(patch), metav1.PatchOptions{})
if r.Action == Suspend {
return "suspended", err
}
return "resumed", err
case Cordon, Uncordon:
patch := fmt.Sprintf(`{"spec":{"unschedulable":%t}}`, r.Action == Cordon)
_, err := c.CoreV1().Nodes().Patch(ctx, r.Name, types.MergePatchType, []byte(patch), metav1.PatchOptions{})
return r.Action + "ed", err
}
return "", ErrUnsupported
}
// scale reads and writes the scale subresource, retrying on a conflict:
// right after a restart the controller keeps updating the object, and a
// single Get+Update then failed with 409.
func scale(ctx context.Context, c kubernetes.Interface, r Request) (string, error) {
if r.Replicas == nil || *r.Replicas < 0 || *r.Replicas > MaxReplicas {
return "", fmt.Errorf("replicas must be between 0 and %d", MaxReplicas)
}
err := retry.RetryOnConflict(retry.DefaultRetry, func() error {
if r.Kind == "deployment" {
s, err := c.AppsV1().Deployments(r.Namespace).GetScale(ctx, r.Name, metav1.GetOptions{})
if err != nil {
return err
}
s.Spec.Replicas = *r.Replicas
_, err = c.AppsV1().Deployments(r.Namespace).UpdateScale(ctx, r.Name, s, metav1.UpdateOptions{})
return err
}
s, err := c.AppsV1().StatefulSets(r.Namespace).GetScale(ctx, r.Name, metav1.GetOptions{})
if err != nil {
return err
}
s.Spec.Replicas = *r.Replicas
_, err = c.AppsV1().StatefulSets(r.Namespace).UpdateScale(ctx, r.Name, s, metav1.UpdateOptions{})
return err
})
return "scaled to " + strconv.Itoa(int(*r.Replicas)), err
}
// runCronJob creates a Job from the CronJob's template, as kubectl create
// job --from=cronjob/<name> does. The name ends in digits, so the map and
// Hubble both attribute its pods to the CronJob.
func runCronJob(ctx context.Context, c kubernetes.Interface, r Request, now time.Time) (string, error) {
cj, err := c.BatchV1().CronJobs(r.Namespace).Get(ctx, r.Name, metav1.GetOptions{})
if err != nil {
return "", err
}
base := cj.Name
if len(base) > 52 { // Job names end up in a 63-character label
base = base[:52]
}
annotations := map[string]string{"cronjob.kubernetes.io/instantiate": "manual"}
for k, v := range cj.Spec.JobTemplate.Annotations {
annotations[k] = v
}
job := &batchv1.Job{
ObjectMeta: metav1.ObjectMeta{
Name: base + "-" + strconv.FormatInt(now.Unix(), 10),
Namespace: cj.Namespace,
Labels: cj.Spec.JobTemplate.Labels,
Annotations: annotations,
OwnerReferences: []metav1.OwnerReference{*metav1.NewControllerRef(cj, batchv1.SchemeGroupVersion.WithKind("CronJob"))},
},
Spec: cj.Spec.JobTemplate.Spec,
}
created, err := c.BatchV1().Jobs(r.Namespace).Create(ctx, job, metav1.CreateOptions{})
if err != nil {
return "", err
}
return "job " + created.Name + " created", nil
}
@@ -0,0 +1,133 @@
/*
Copyright 2026 The cluster-map Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package actions
import (
"context"
"strings"
"testing"
"time"
appsv1 "k8s.io/api/apps/v1"
autoscalingv1 "k8s.io/api/autoscaling/v1"
batchv1 "k8s.io/api/batch/v1"
corev1 "k8s.io/api/core/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/client-go/kubernetes/fake"
k8stesting "k8s.io/client-go/testing"
)
var t0 = time.Date(2026, 9, 24, 12, 0, 0, 0, time.UTC)
func TestRestartSuspendCordon(t *testing.T) {
c := fake.NewSimpleClientset(
&appsv1.Deployment{ObjectMeta: metav1.ObjectMeta{Name: "web", Namespace: "shop"}},
&batchv1.CronJob{ObjectMeta: metav1.ObjectMeta{Name: "backup", Namespace: "shop"}},
&corev1.Node{ObjectMeta: metav1.ObjectMeta{Name: "node-a"}},
)
ctx := context.Background()
if _, err := Do(ctx, c, Request{Action: Restart, Kind: "deployment", Namespace: "shop", Name: "web"}, t0); err != nil {
t.Fatal(err)
}
d, _ := c.AppsV1().Deployments("shop").Get(ctx, "web", metav1.GetOptions{})
if d.Spec.Template.Annotations["kubectl.kubernetes.io/restartedAt"] != "2026-09-24T12:00:00Z" {
t.Errorf("restart annotation: %v", d.Spec.Template.Annotations)
}
if msg, err := Do(ctx, c, Request{Action: Suspend, Kind: "cronjob", Namespace: "shop", Name: "backup"}, t0); err != nil || msg != "suspended" {
t.Fatal(msg, err)
}
cj, _ := c.BatchV1().CronJobs("shop").Get(ctx, "backup", metav1.GetOptions{})
if cj.Spec.Suspend == nil || !*cj.Spec.Suspend {
t.Error("cronjob not suspended")
}
if _, err := Do(ctx, c, Request{Action: Cordon, Kind: "node", Name: "node-a"}, t0); err != nil {
t.Fatal(err)
}
n, _ := c.CoreV1().Nodes().Get(ctx, "node-a", metav1.GetOptions{})
if !n.Spec.Unschedulable {
t.Error("node not cordoned")
}
}
func TestRunCronJob(t *testing.T) {
c := fake.NewSimpleClientset(&batchv1.CronJob{
ObjectMeta: metav1.ObjectMeta{Name: "backup", Namespace: "shop", UID: "u1"},
Spec: batchv1.CronJobSpec{JobTemplate: batchv1.JobTemplateSpec{
ObjectMeta: metav1.ObjectMeta{Labels: map[string]string{"app": "backup"}},
Spec: batchv1.JobSpec{Template: corev1.PodTemplateSpec{Spec: corev1.PodSpec{Containers: []corev1.Container{{Name: "dump"}}}}},
}},
})
ctx := context.Background()
msg, err := Do(ctx, c, Request{Action: Run, Kind: "cronjob", Namespace: "shop", Name: "backup"}, t0)
if err != nil {
t.Fatal(err)
}
jobs, _ := c.BatchV1().Jobs("shop").List(ctx, metav1.ListOptions{})
if len(jobs.Items) != 1 || !strings.Contains(msg, jobs.Items[0].Name) {
t.Fatalf("jobs: %+v, msg %q", jobs.Items, msg)
}
j := jobs.Items[0]
if j.Name != "backup-1790251200" || j.OwnerReferences[0].Kind != "CronJob" || j.OwnerReferences[0].UID != "u1" ||
j.Annotations["cronjob.kubernetes.io/instantiate"] != "manual" || j.Labels["app"] != "backup" {
t.Errorf("job: %+v", j.ObjectMeta)
}
}
func TestScaleRetriesConflict(t *testing.T) {
c := fake.NewSimpleClientset()
var updated int32 = -1
attempts := 0
c.PrependReactor("get", "deployments", func(k8stesting.Action) (bool, runtime.Object, error) {
return true, &autoscalingv1.Scale{ObjectMeta: metav1.ObjectMeta{Name: "web", Namespace: "shop"}, Spec: autoscalingv1.ScaleSpec{Replicas: 1}}, nil
})
c.PrependReactor("update", "deployments", func(a k8stesting.Action) (bool, runtime.Object, error) {
attempts++
if attempts == 1 { // the controller got there first
return true, nil, apierrors.NewConflict(schema.GroupResource{Group: "apps", Resource: "deployments"}, "web", nil)
}
s := a.(k8stesting.UpdateAction).GetObject().(*autoscalingv1.Scale)
updated = s.Spec.Replicas
return true, s, nil
})
three := int32(3)
if _, err := Do(context.Background(), c, Request{Action: Scale, Kind: "deployment", Namespace: "shop", Name: "web", Replicas: &three}, t0); err != nil {
t.Fatal(err)
}
if updated != 3 || attempts != 2 {
t.Errorf("scale sent %d after %d attempts", updated, attempts)
}
tooMany := int32(MaxReplicas + 1)
if _, err := Do(context.Background(), c, Request{Action: Scale, Kind: "deployment", Namespace: "shop", Name: "web", Replicas: &tooMany}, t0); err == nil {
t.Error("replicas above the limit accepted")
}
}
func TestUnsupported(t *testing.T) {
c := fake.NewSimpleClientset()
for _, r := range []Request{
{Action: Scale, Kind: "daemonset", Namespace: "a", Name: "b"},
{Action: "exec", Kind: "pod", Namespace: "a", Name: "b"},
{Action: DeletePod, Kind: "pod", Name: "b"},
} {
if _, err := Do(context.Background(), c, r, t0); err == nil {
t.Errorf("%+v accepted", r)
}
}
}
@@ -0,0 +1,152 @@
/*
Copyright 2026 The cluster-map Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Package config reads cluster-map settings from the environment. The
// module's Helm templates are the only intended writer of these variables.
package config
import (
"fmt"
"os"
"strconv"
"strings"
"time"
)
// TrafficMode selects when cluster-map reads flows from Hubble.
type TrafficMode string
const (
// TrafficContinuous keeps a Hubble follow stream open all the time, so
// every traffic window is full as soon as someone opens the map.
TrafficContinuous TrafficMode = "Continuous"
// TrafficOnDemand opens the stream on the first traffic request and
// closes it after OnDemandIdle without requests: near-zero cost when
// nobody looks, but windows only fill while the map is in use.
TrafficOnDemand TrafficMode = "OnDemand"
// TrafficDisabled never talks to Hubble; the map shows configuration only.
TrafficDisabled TrafficMode = "Disabled"
)
// Config is the full runtime configuration.
type Config struct {
ListenAddr string
MetricsAddr string
TrafficMode TrafficMode
Retention time.Duration // how far back traffic windows can reach
OnDemandIdle time.Duration
CollectInfra bool // keep kubelet probes, DNS, health, node-to-node
HubbleRelayAddr string
HubbleCAFile string
HubbleServerName string
// Namespaces matching these prefixes/names are grouped as "system".
SystemNamespacePrefixes []string
LogTailLines int64
// ActionsEnabled turns on restart/scale/delete and the rest. They run
// with the viewer's own token (the Authorization header the
// DexAuthenticator adds), never with the module's service account.
ActionsEnabled bool
// ViewerVisibility limits what each viewer sees to what the viewer's
// own RBAC can read (namespaces where they can list pods). Off, anyone
// admitted to the web interface sees the whole cluster.
ViewerVisibility bool
}
// Load reads and validates the configuration from the environment.
func Load() (Config, error) {
c := Config{
ListenAddr: env("LISTEN_ADDR", ":8080"),
MetricsAddr: env("METRICS_ADDR", ":9090"),
TrafficMode: TrafficMode(env("TRAFFIC_MODE", string(TrafficContinuous))),
HubbleRelayAddr: env("HUBBLE_RELAY_ADDR", "hubble-relay.d8-cni-cilium.svc:443"),
HubbleCAFile: env("HUBBLE_CA_FILE", "/etc/hubble-ca/ca.crt"),
HubbleServerName: env("HUBBLE_SERVER_NAME", "cluster-map.hubble-relay.cilium.io"),
SystemNamespacePrefixes: split(env("SYSTEM_NAMESPACE_PREFIXES", "d8-,kube-")),
}
var err error
if c.Retention, err = duration("TRAFFIC_RETENTION", "60m"); err != nil {
return c, err
}
if c.OnDemandIdle, err = duration("TRAFFIC_ON_DEMAND_IDLE", "10m"); err != nil {
return c, err
}
if c.CollectInfra, err = strconv.ParseBool(env("TRAFFIC_COLLECT_INFRA", "false")); err != nil {
return c, fmt.Errorf("TRAFFIC_COLLECT_INFRA: %w", err)
}
if c.LogTailLines, err = strconv.ParseInt(env("LOG_TAIL_LINES", "500"), 10, 64); err != nil {
return c, fmt.Errorf("LOG_TAIL_LINES: %w", err)
}
if c.ActionsEnabled, err = strconv.ParseBool(env("ACTIONS_ENABLED", "false")); err != nil {
return c, fmt.Errorf("ACTIONS_ENABLED: %w", err)
}
switch v := env("VISIBILITY", "ViewerRBAC"); v {
case "ViewerRBAC":
c.ViewerVisibility = true
case "Everything":
default:
return c, fmt.Errorf("VISIBILITY: %q is not one of ViewerRBAC, Everything", v)
}
switch c.TrafficMode {
case TrafficContinuous, TrafficOnDemand, TrafficDisabled:
default:
return c, fmt.Errorf("TRAFFIC_MODE: %q is not one of Continuous, OnDemand, Disabled", c.TrafficMode)
}
if c.Retention < time.Minute || c.Retention > 24*time.Hour {
return c, fmt.Errorf("TRAFFIC_RETENTION: %s is outside 1m..24h", c.Retention)
}
return c, nil
}
// IsSystemNamespace reports whether ns is platform-owned rather than an
// application namespace. A prefix ending in "-" matches by prefix, anything
// else matches the whole name.
func (c Config) IsSystemNamespace(ns string) bool {
for _, p := range c.SystemNamespacePrefixes {
if (strings.HasSuffix(p, "-") && strings.HasPrefix(ns, p)) || ns == p {
return true
}
}
return false
}
func env(k, def string) string {
if v, ok := os.LookupEnv(k); ok && v != "" {
return v
}
return def
}
func duration(k, def string) (time.Duration, error) {
d, err := time.ParseDuration(env(k, def))
if err != nil {
return 0, fmt.Errorf("%s: %w", k, err)
}
return d, nil
}
func split(s string) []string {
var out []string
for _, p := range strings.Split(s, ",") {
if p = strings.TrimSpace(p); p != "" {
out = append(out, p)
}
}
return out
}
@@ -0,0 +1,59 @@
/*
Copyright 2026 The cluster-map Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package config
import (
"testing"
"time"
)
func TestDefaults(t *testing.T) {
c, err := Load()
if err != nil {
t.Fatal(err)
}
if c.TrafficMode != TrafficContinuous || c.Retention != time.Hour || c.CollectInfra {
t.Errorf("defaults: %+v", c)
}
}
func TestValidation(t *testing.T) {
for k, v := range map[string]string{
"TRAFFIC_MODE": "Sometimes",
"TRAFFIC_RETENTION": "30s",
"TRAFFIC_COLLECT_INFRA": "maybe",
} {
t.Run(k, func(t *testing.T) {
t.Setenv(k, v)
if _, err := Load(); err == nil {
t.Errorf("%s=%s should be rejected", k, v)
}
})
}
}
func TestIsSystemNamespace(t *testing.T) {
c := Config{SystemNamespacePrefixes: []string{"d8-", "kube-", "monitoring"}}
for ns, want := range map[string]bool{
"d8-system": true, "kube-system": true, "monitoring": true,
"monitoring-extra": false, "shop": false, "d8": false,
} {
if got := c.IsSystemNamespace(ns); got != want {
t.Errorf("%s: got %v want %v", ns, got, want)
}
}
}
@@ -0,0 +1,249 @@
/*
Copyright 2026 The cluster-map Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Package kube holds the informer-backed read-only view of the cluster
// that the graph and the traffic resolver read from.
package kube
import (
"context"
"fmt"
"log/slog"
"time"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/meta"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/fields"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/client-go/dynamic"
"k8s.io/client-go/dynamic/dynamicinformer"
"k8s.io/client-go/informers"
"k8s.io/client-go/kubernetes"
appslisters "k8s.io/client-go/listers/apps/v1"
batchlisters "k8s.io/client-go/listers/batch/v1"
corelisters "k8s.io/client-go/listers/core/v1"
netlisters "k8s.io/client-go/listers/networking/v1"
"k8s.io/client-go/tools/cache"
)
// ClusterAlerts is the resource Deckhouse's prometheus module mirrors
// firing Alertmanager alerts into.
var ClusterAlerts = schema.GroupVersionResource{Group: "deckhouse.io", Version: "v1alpha1", Resource: "clusteralerts"}
// VulnerabilityReports are what operator-trivy writes per scanned
// container (namespaced, owned by the workload's ReplicaSet/StatefulSet/…).
var VulnerabilityReports = schema.GroupVersionResource{Group: "aquasecurity.github.io", Version: "v1alpha1", Resource: "vulnerabilityreports"}
// Cache holds synced listers plus a client for reads that must be live
// (YAML view, logs).
type Cache struct {
Client kubernetes.Interface
// Events holds Warning events only; Normal ones are most of the event
// volume and none of them is a problem.
Events corelisters.EventLister
// Alerts is nil when the ClusterAlert resource is not served (the
// prometheus module is off).
Alerts cache.GenericLister
// VulnReports is nil when operator-trivy is not installed.
VulnReports cache.GenericLister
Namespaces corelisters.NamespaceLister
Pods corelisters.PodLister
Services corelisters.ServiceLister
Nodes corelisters.NodeLister
Deployments appslisters.DeploymentLister
StatefulSets appslisters.StatefulSetLister
DaemonSets appslisters.DaemonSetLister
CronJobs batchlisters.CronJobLister
Ingresses netlisters.IngressLister
}
// stripManagedFields: managedFields is most of a cached object's size and
// nothing here reads it.
func stripManagedFields(obj any) (any, error) {
if a, err := meta.Accessor(obj); err == nil {
a.SetManagedFields(nil)
}
return obj, nil
}
// Start runs the informers and blocks until every cache has synced or ctx
// is done.
func Start(ctx context.Context, client kubernetes.Interface, dyn dynamic.Interface, syncTimeout time.Duration) (*Cache, error) {
f := informers.NewSharedInformerFactoryWithOptions(client, 0, informers.WithTransform(stripManagedFields))
// A separate factory: a list option tweak applies to every informer of
// the factory it is set on.
ef := informers.NewSharedInformerFactoryWithOptions(client, 0, informers.WithTransform(stripManagedFields),
informers.WithTweakListOptions(func(o *metav1.ListOptions) {
o.FieldSelector = fields.OneTermEqualSelector("type", corev1.EventTypeWarning).String()
}))
c := &Cache{
Client: client,
Namespaces: f.Core().V1().Namespaces().Lister(),
Pods: f.Core().V1().Pods().Lister(),
Services: f.Core().V1().Services().Lister(),
Nodes: f.Core().V1().Nodes().Lister(),
Deployments: f.Apps().V1().Deployments().Lister(),
StatefulSets: f.Apps().V1().StatefulSets().Lister(),
DaemonSets: f.Apps().V1().DaemonSets().Lister(),
CronJobs: f.Batch().V1().CronJobs().Lister(),
Ingresses: f.Networking().V1().Ingresses().Lister(),
Events: ef.Core().V1().Events().Lister(),
}
var df dynamicinformer.DynamicSharedInformerFactory
if dyn != nil {
df = dynamicinformer.NewDynamicSharedInformerFactory(dyn, 0)
}
if df != nil && served(client, ClusterAlerts) {
c.Alerts = df.ForResource(ClusterAlerts).Lister()
} else {
slog.Info("ClusterAlert resource is not served; alerts are not shown")
}
if df != nil && served(client, VulnerabilityReports) {
inf := df.ForResource(VulnerabilityReports)
if err := inf.Informer().SetTransform(trimVulnReport); err != nil {
return nil, err
}
c.VulnReports = inf.Lister()
} else {
slog.Info("VulnerabilityReport resource is not served; vulnerabilities are not shown")
}
f.Start(ctx.Done())
ef.Start(ctx.Done())
if df != nil {
df.Start(ctx.Done())
}
syncCtx, cancel := context.WithTimeout(ctx, syncTimeout)
defer cancel()
for t, ok := range f.WaitForCacheSync(syncCtx.Done()) {
if !ok {
return nil, fmt.Errorf("cache for %v did not sync within %s", t, syncTimeout)
}
}
for t, ok := range ef.WaitForCacheSync(syncCtx.Done()) {
if !ok {
return nil, fmt.Errorf("cache for %v did not sync within %s", t, syncTimeout)
}
}
if df != nil {
for r, ok := range df.WaitForCacheSync(syncCtx.Done()) {
if !ok {
return nil, fmt.Errorf("cache for %v did not sync within %s", r, syncTimeout)
}
}
}
return c, nil
}
// served reports whether the API server serves the resource, so an
// informer is not started for a CRD that is not installed.
func served(client kubernetes.Interface, gvr schema.GroupVersionResource) bool {
list, err := client.Discovery().ServerResourcesForGroupVersion(gvr.GroupVersion().String())
if err != nil {
return false
}
for _, r := range list.APIResources {
if r.Name == gvr.Resource {
return true
}
}
return false
}
// vulnFields are the parts of a vulnerability entry the map shows; the
// rest (links, PURLs, dates) is dropped before caching.
var vulnFields = []string{"vulnerabilityID", "severity", "resource", "installedVersion", "fixedVersion", "title", "primaryLink", "score"}
func trimVulnReport(obj any) (any, error) {
u, ok := obj.(*unstructured.Unstructured)
if !ok {
return obj, nil
}
u.SetManagedFields(nil)
vulns, found, _ := unstructured.NestedSlice(u.Object, "report", "vulnerabilities")
if !found {
return u, nil
}
for i, v := range vulns {
m, ok := v.(map[string]any)
if !ok {
continue
}
kept := make(map[string]any, len(vulnFields))
for _, f := range vulnFields {
if x, ok := m[f]; ok {
kept[f] = x
}
}
vulns[i] = kept
}
return u, unstructured.SetNestedSlice(u.Object, vulns, "report", "vulnerabilities")
}
// VulnReportList returns the cached VulnerabilityReports, nil when off.
func (c *Cache) VulnReportList() []*unstructured.Unstructured {
if c.VulnReports == nil {
return nil
}
objs, err := c.VulnReports.List(labels.Everything())
if err != nil {
return nil
}
out := make([]*unstructured.Unstructured, 0, len(objs))
for _, o := range objs {
if u, ok := o.(*unstructured.Unstructured); ok {
out = append(out, u)
}
}
return out
}
// AlertList returns the cached ClusterAlerts, or nil when they are off.
func (c *Cache) AlertList() []*unstructured.Unstructured {
if c.Alerts == nil {
return nil
}
objs, err := c.Alerts.List(labels.Everything())
if err != nil {
return nil
}
out := make([]*unstructured.Unstructured, 0, len(objs))
for _, o := range objs {
if u, ok := o.(*unstructured.Unstructured); ok {
out = append(out, u)
}
}
return out
}
// List reads a lister as values. Callers must not mutate cached objects,
// and copying the top-level struct is cheap.
func List[T any](l interface {
List(labels.Selector) ([]*T, error)
}) ([]T, error) {
ptrs, err := l.List(labels.Everything())
if err != nil {
return nil, err
}
out := make([]T, len(ptrs))
for i, p := range ptrs {
out[i] = *p
}
return out, nil
}
@@ -0,0 +1,64 @@
/*
Copyright 2026 The cluster-map Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Package metrics exposes cluster-map's own Prometheus metrics.
package metrics
import (
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/collectors"
)
// Registry holds only cluster-map's metrics plus the Go and process ones.
var Registry = prometheus.NewRegistry()
// Metrics exported on /metrics.
var (
HubbleStreamActive = gauge("cluster_map_hubble_stream_active", "1 while a Hubble follow stream is supposed to be open (always in Continuous mode, while viewed in OnDemand).")
HubbleConnected = gauge("cluster_map_hubble_connected", "1 while flows are arriving from Hubble Relay.")
HubbleReconnects = counter("cluster_map_hubble_reconnects_total", "Hubble streams that ended and were reopened.")
FlowsProcessed = counter("cluster_map_flows_processed_total", "Hubble flows received and aggregated.")
TrackedTuples = gauge("cluster_map_traffic_tracked_tuples", "Distinct connection tuples held across all retained minute buckets.")
CacheSynced = gauge("cluster_map_cache_synced", "1 once the Kubernetes informer caches have synced.")
HTTPRequests = prometheus.NewCounterVec(prometheus.CounterOpts{
Name: "cluster_map_http_requests_total", Help: "HTTP API requests by handler and status code.",
}, []string{"handler", "code"})
Actions = prometheus.NewCounterVec(prometheus.CounterOpts{
Name: "cluster_map_actions_total", Help: "Actions run from the UI, by action and result (ok, denied, error).",
}, []string{"action", "result"})
HTTPDuration = prometheus.NewHistogramVec(prometheus.HistogramOpts{
Name: "cluster_map_http_request_duration_seconds", Help: "HTTP API latency by handler.",
Buckets: []float64{.001, .005, .01, .05, .1, .5, 1, 5},
}, []string{"handler"})
)
func init() {
Registry.MustRegister(
collectors.NewGoCollector(),
collectors.NewProcessCollector(collectors.ProcessCollectorOpts{}),
HubbleStreamActive, HubbleConnected, HubbleReconnects, FlowsProcessed, TrackedTuples, CacheSynced,
HTTPRequests, HTTPDuration, Actions,
)
}
func gauge(name, help string) prometheus.Gauge {
return prometheus.NewGauge(prometheus.GaugeOpts{Name: name, Help: help})
}
func counter(name, help string) prometheus.Counter {
return prometheus.NewCounter(prometheus.CounterOpts{Name: name, Help: help})
}
@@ -0,0 +1,187 @@
/*
Copyright 2026 The cluster-map Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package server
import (
"encoding/json"
"errors"
"log/slog"
"mime"
"net/http"
"net/url"
"strings"
"time"
apierrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/client-go/kubernetes"
"git.project-chimera.ru/fanchji/cluster-map/internal/actions"
"git.project-chimera.ru/fanchji/cluster-map/internal/metrics"
)
// viewerToken is the bearer token the DexAuthenticator forwarded, or "".
func viewerToken(r *http.Request) string {
h := r.Header.Get("Authorization")
if len(h) > 7 && strings.EqualFold(h[:7], "Bearer ") {
return strings.TrimSpace(h[7:])
}
return ""
}
// viewerClient returns a client acting as the viewer, or writes the reason
// there is none.
func (s *Server) viewerClient(w http.ResponseWriter, r *http.Request) (kubernetes.Interface, bool) {
if !s.cfg.ActionsEnabled || s.asViewer == nil {
http.Error(w, "actions are disabled in the module settings", http.StatusNotFound)
return nil, false
}
token := viewerToken(r)
if token == "" {
http.Error(w, "no user token in the request: actions need the DexAuthenticator to send the Authorization header", http.StatusUnauthorized)
return nil, false
}
c, err := s.asViewer(token)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return nil, false
}
return c, true
}
// Me is the /api/me response.
type Me struct {
ActionsEnabled bool `json:"actionsEnabled"`
User string `json:"user,omitempty"`
Reason string `json:"reason,omitempty"` // why actions are unavailable: disabled | noToken | rejected
// Visibility: "all" (the whole cluster), "namespaces" (Namespaces of
// them, by the viewer's RBAC) or "" when it could not be determined.
Visibility string `json:"visibility,omitempty"`
Namespaces int `json:"namespaces,omitempty"`
}
func (s *Server) handleMe(w http.ResponseWriter, r *http.Request) {
me := Me{ActionsEnabled: s.cfg.ActionsEnabled && s.asViewer != nil}
token := viewerToken(r)
switch {
case s.access == nil:
me.Visibility = "all"
case token != "":
if sc, err := s.access.For(r.Context(), token); err == nil {
me.Visibility, me.Namespaces = "namespaces", len(sc.Namespaces)
if sc.All {
me.Visibility, me.Namespaces = "all", 0
}
}
}
switch {
case !me.ActionsEnabled:
me.Reason = "disabled"
case token == "":
me.Reason = "noToken"
default:
c, err := s.asViewer(token)
if err == nil {
me.User, err = actions.WhoAmI(r.Context(), c)
}
if err != nil {
slog.Info("viewer token rejected", "err", err)
me.Reason = "rejected"
}
}
writeJSON(w, me)
}
func (s *Server) handlePermissions(w http.ResponseWriter, r *http.Request) {
c, ok := s.viewerClient(w, r)
if !ok {
return
}
q := r.URL.Query()
allowed, err := actions.Allowed(r.Context(), c, q.Get("kind"), q.Get("namespace"), q.Get("name"))
if err != nil {
http.Error(w, err.Error(), apiStatus(err))
return
}
writeJSON(w, map[string]any{"allowed": allowed})
}
// sameOrigin rejects cross-site writes: the Fetch metadata header that
// every current browser sends, then Origin for older ones. A JSON content
// type also keeps a plain HTML form from reaching the handler.
func sameOrigin(r *http.Request) error {
if ct, _, _ := mime.ParseMediaType(r.Header.Get("Content-Type")); ct != "application/json" {
return errors.New("content type must be application/json")
}
switch r.Header.Get("Sec-Fetch-Site") {
case "", "same-origin":
default:
return errors.New("cross-site request")
}
if o := r.Header.Get("Origin"); o != "" {
u, err := url.Parse(o)
if err != nil || u.Host != r.Host {
return errors.New("origin does not match the host")
}
}
return nil
}
func (s *Server) handleAction(w http.ResponseWriter, r *http.Request) {
if err := sameOrigin(r); err != nil {
http.Error(w, err.Error(), http.StatusForbidden)
return
}
c, ok := s.viewerClient(w, r)
if !ok {
return
}
var req actions.Request
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 4096)).Decode(&req); err != nil {
http.Error(w, "bad request body: "+err.Error(), http.StatusBadRequest)
return
}
user, err := actions.WhoAmI(r.Context(), c)
if err != nil {
http.Error(w, "the API server did not accept the user token: "+err.Error(), http.StatusUnauthorized)
return
}
msg, err := actions.Do(r.Context(), c, req, time.Now())
// The API server's audit log has the same record under the user's name;
// this one ties it to the map.
log := slog.With("user", user, "action", req.Action, "target", req.String())
switch {
case err == nil:
log.Info("action done", "result", msg)
metrics.Actions.WithLabelValues(req.Action, "ok").Inc()
writeJSON(w, map[string]string{"result": msg})
case errors.Is(err, actions.ErrUnsupported):
http.Error(w, err.Error(), http.StatusBadRequest)
case apierrors.IsForbidden(err):
log.Info("action denied", "err", err)
metrics.Actions.WithLabelValues(req.Action, "denied").Inc()
http.Error(w, err.Error(), http.StatusForbidden)
default:
log.Warn("action failed", "err", err)
metrics.Actions.WithLabelValues(req.Action, "error").Inc()
code := http.StatusBadRequest // Do's own validation errors
var st apierrors.APIStatus
if errors.As(err, &st) && st.Status().Code != 0 {
code = int(st.Status().Code)
}
http.Error(w, err.Error(), code)
}
}
@@ -0,0 +1,152 @@
/*
Copyright 2026 The cluster-map Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package server
import (
"net/http"
"net/http/httptest"
"strings"
"testing"
"testing/fstest"
"time"
appsv1 "k8s.io/api/apps/v1"
authnv1 "k8s.io/api/authentication/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/kubernetes/fake"
k8stesting "k8s.io/client-go/testing"
"git.project-chimera.ru/fanchji/cluster-map/internal/config"
)
// actionServer: tokens are checked by the fake "API server": "good" is
// alice, anything else is rejected; alice may patch deployments only.
func actionServer(t *testing.T, enabled bool) (http.Handler, *fake.Clientset) {
t.Helper()
c := fake.NewSimpleClientset(&appsv1.Deployment{ObjectMeta: metav1.ObjectMeta{Name: "web", Namespace: "shop"}})
c.PrependReactor("create", "selfsubjectreviews", func(k8stesting.Action) (bool, runtime.Object, error) {
return true, &authnv1.SelfSubjectReview{Status: authnv1.SelfSubjectReviewStatus{UserInfo: authnv1.UserInfo{Username: "alice@example.com"}}}, nil
})
c.PrependReactor("patch", "nodes", func(k8stesting.Action) (bool, runtime.Object, error) {
return true, nil, apierrors.NewForbidden(schema.GroupResource{Resource: "nodes"}, "node-a", nil)
})
factory := func(token string) (kubernetes.Interface, error) {
if token != "good" {
return fake.NewSimpleClientset(), nil
}
return c, nil
}
cfg := config.Config{TrafficMode: config.TrafficDisabled, Retention: time.Hour, ActionsEnabled: enabled}
s := New(cfg, fstest.MapFS{"index.html": {Data: []byte("x")}}, factory)
s.ready.Store(true)
return s.Handler(), c
}
func post(h http.Handler, body string, headers map[string]string) *httptest.ResponseRecorder {
req := httptest.NewRequest(http.MethodPost, "http://cluster-map.example.com/api/action", strings.NewReader(body))
req.Header.Set("Content-Type", "application/json")
for k, v := range headers {
req.Header.Set(k, v)
}
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
return rec
}
const restartWeb = `{"action":"restart","kind":"deployment","namespace":"shop","name":"web"}`
func TestActionRunsAsViewer(t *testing.T) {
h, c := actionServer(t, true)
rec := post(h, restartWeb, map[string]string{"Authorization": "Bearer good", "Sec-Fetch-Site": "same-origin", "Origin": "http://cluster-map.example.com"})
if rec.Code != http.StatusOK {
t.Fatalf("%d %s", rec.Code, rec.Body)
}
var patched bool
for _, a := range c.Actions() {
if a.GetVerb() == "patch" && a.GetResource().Resource == "deployments" {
patched = true
}
}
if !patched {
t.Error("the viewer's client did not patch the deployment")
}
}
func TestActionGuards(t *testing.T) {
h, _ := actionServer(t, true)
cases := []struct {
name string
body string
headers map[string]string
want int
}{
{"no token", restartWeb, map[string]string{"Sec-Fetch-Site": "same-origin"}, http.StatusUnauthorized},
{"cross-site", restartWeb, map[string]string{"Authorization": "Bearer good", "Sec-Fetch-Site": "cross-site"}, http.StatusForbidden},
{"foreign origin", restartWeb, map[string]string{"Authorization": "Bearer good", "Origin": "https://evil.example.org"}, http.StatusForbidden},
{"form post", restartWeb, map[string]string{"Authorization": "Bearer good", "Content-Type": "application/x-www-form-urlencoded"}, http.StatusForbidden},
{"api forbids", `{"action":"cordon","kind":"node","name":"node-a"}`, map[string]string{"Authorization": "Bearer good"}, http.StatusForbidden},
{"unsupported", `{"action":"scale","kind":"daemonset","namespace":"shop","name":"x","replicas":1}`, map[string]string{"Authorization": "Bearer good"}, http.StatusBadRequest},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
if rec := post(h, c.body, c.headers); rec.Code != c.want {
t.Errorf("got %d (%s), want %d", rec.Code, strings.TrimSpace(rec.Body.String()), c.want)
}
})
}
off, _ := actionServer(t, false)
if rec := post(off, restartWeb, map[string]string{"Authorization": "Bearer good"}); rec.Code != http.StatusNotFound {
t.Errorf("actions disabled: %d", rec.Code)
}
}
func TestMe(t *testing.T) {
h, _ := actionServer(t, true)
req := httptest.NewRequest(http.MethodGet, "/api/me", nil)
req.Header.Set("Authorization", "Bearer good")
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if !strings.Contains(rec.Body.String(), `"user":"alice@example.com"`) {
t.Errorf("me: %s", rec.Body)
}
if body := get(h, "/api/me").Body.String(); !strings.Contains(body, `"reason":"noToken"`) {
t.Errorf("me without a token: %s", body)
}
}
func TestStaticRevalidation(t *testing.T) {
_, h := newServer(t, config.TrafficDisabled)
first := get(h, "/")
tag := first.Header().Get("ETag")
if tag == "" || first.Header().Get("Cache-Control") != "no-cache" {
t.Fatalf("static headers: %v", first.Header())
}
req := httptest.NewRequest(http.MethodGet, "/", nil)
req.Header.Set("If-None-Match", tag)
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusNotModified {
t.Errorf("revalidation: %d", rec.Code)
}
if get(h, "/api/graph").Header().Get("Cache-Control") != "no-store" {
t.Error("API responses must stay no-store")
}
}
@@ -0,0 +1,357 @@
/*
Copyright 2026 The cluster-map Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package server
import (
"context"
"encoding/json"
"net/http"
"sort"
"strings"
"time"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/fields"
"git.project-chimera.ru/fanchji/cluster-map/internal/kube"
"git.project-chimera.ru/fanchji/cluster-map/internal/topology"
)
// EventInfo is one row of the Events tab.
type EventInfo struct {
Type string `json:"type"`
Reason string `json:"reason"`
Message string `json:"message"`
Object string `json:"object"` // Kind/name of what the event is about
Count int32 `json:"count"`
Last string `json:"last"`
}
const maxEvents = 100
// handleEvents lists recent events of a card: for a workload also those of
// its pods and ReplicaSets, which is where Kubernetes reports most of what
// goes wrong with it. Read live, all types, not from the Warning cache.
func (s *Server) handleEvents(w http.ResponseWriter, r *http.Request) {
id := r.URL.Query().Get("id")
parts := strings.Split(id, "/")
ctx := r.Context()
if !s.cardVisible(w, r, parts) {
return
}
var list *corev1.EventList
var err error
match := func(corev1.ObjectReference) bool { return true }
switch {
case len(parts) == 2 && parts[0] == "node":
list, err = s.cache.Client.CoreV1().Events("").List(ctx, metav1.ListOptions{FieldSelector: fields.Set{
"involvedObject.kind": "Node", "involvedObject.name": parts[1]}.String()})
case len(parts) == 2 && parts[0] == "ns":
list, err = s.cache.Client.CoreV1().Events(parts[1]).List(ctx, metav1.ListOptions{Limit: 500})
case len(parts) == 3 && (parts[0] == "service" || parts[0] == "ingress"):
kind := map[string]string{"service": "Service", "ingress": "Ingress"}[parts[0]]
list, err = s.cache.Client.CoreV1().Events(parts[1]).List(ctx, metav1.ListOptions{FieldSelector: fields.Set{
"involvedObject.kind": kind, "involvedObject.name": parts[2]}.String()})
case len(parts) == 4 && parts[0] == "wl":
ns, name := parts[1], parts[3]
owners := s.podOwners(ns)
match = func(ref corev1.ObjectReference) bool {
if topology.EventTargetID(ref, owners) == id {
return true
}
// a pod already gone is no longer in the cache; its name still tells
return ref.Kind == "Pod" && owners[ns+"/"+ref.Name] == "" && strings.HasPrefix(ref.Name, name+"-")
}
list, err = s.cache.Client.CoreV1().Events(ns).List(ctx, metav1.ListOptions{Limit: 500})
default:
http.Error(w, "id must be a card id (wl/…, service/…, ingress/…, node/…, ns/…)", http.StatusBadRequest)
return
}
if err != nil {
http.Error(w, err.Error(), apiStatus(err))
return
}
out := []EventInfo{}
for _, e := range list.Items {
if !match(e.InvolvedObject) {
continue
}
count := e.Count
if e.Series != nil {
count = e.Series.Count
}
out = append(out, EventInfo{
Type: e.Type, Reason: e.Reason, Message: e.Message, Count: max(count, 1),
Object: e.InvolvedObject.Kind + "/" + e.InvolvedObject.Name, Last: lastSeen(e).UTC().Format(time.RFC3339),
})
}
sort.Slice(out, func(i, j int) bool { return out[i].Last > out[j].Last })
if len(out) > maxEvents {
out = out[:maxEvents]
}
writeJSON(w, out)
}
func lastSeen(e corev1.Event) time.Time {
switch {
case e.Series != nil && !e.Series.LastObservedTime.IsZero():
return e.Series.LastObservedTime.Time
case !e.LastTimestamp.IsZero():
return e.LastTimestamp.Time
case !e.EventTime.IsZero():
return e.EventTime.Time
}
return e.CreationTimestamp.Time
}
func (s *Server) podOwners(ns string) map[string]string {
pods, _ := kube.List[corev1.Pod](s.cache.Pods.Pods(ns))
out := make(map[string]string, len(pods))
for _, p := range pods {
out[ns+"/"+p.Name] = topology.OwnerWorkloadID(p)
}
return out
}
// Amount is a CPU (millicores) or memory (bytes) figure; nil when unknown.
type Amount struct {
Usage *int64 `json:"usage"`
Request int64 `json:"request"`
Limit int64 `json:"limit"` // 0 when any container has no limit
Capacity int64 `json:"capacity"` // allocatable, nodes only
}
// PodUsage is one pod in the usage table.
type PodUsage struct {
Name string `json:"name"`
Node string `json:"node"`
Ready bool `json:"ready"`
Restarts int32 `json:"restarts"`
CPU *int64 `json:"cpu"`
Memory *int64 `json:"memory"`
}
// Usage is the /api/usage response.
type Usage struct {
Metrics bool `json:"metrics"` // false when metrics.k8s.io did not answer
CPU Amount `json:"cpu"`
Memory Amount `json:"memory"`
Pods []PodUsage `json:"pods"`
}
// metricsList is the part of a metrics.k8s.io PodMetricsList read here.
type metricsList struct {
Items []struct {
Metadata metav1.ObjectMeta `json:"metadata"`
Containers []struct {
Usage corev1.ResourceList `json:"usage"`
} `json:"containers"`
} `json:"items"`
}
type nodeMetrics struct {
Usage corev1.ResourceList `json:"usage"`
}
// metricsGet reads the resource metrics API through the discovery REST
// client, which spares a dependency on k8s.io/metrics for two GETs.
func (s *Server) metricsGet(ctx context.Context, into any, path ...string) bool {
ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
raw, err := s.cache.Client.Discovery().RESTClient().Get().AbsPath(append([]string{"/apis/metrics.k8s.io/v1beta1"}, path...)...).DoRaw(ctx)
if err != nil {
return false
}
return json.Unmarshal(raw, into) == nil
}
func ptr(v int64) *int64 { return &v }
// handleUsage: CPU and memory of a workload (sum over its pods) or a node,
// against requests, limits and, for a node, allocatable.
func (s *Server) handleUsage(w http.ResponseWriter, r *http.Request) {
id := r.URL.Query().Get("id")
parts := strings.Split(id, "/")
if !s.cardVisible(w, r, parts) {
return
}
var pods []corev1.Pod
u := Usage{Pods: []PodUsage{}}
switch {
case len(parts) == 4 && parts[0] == "wl":
all, err := kube.List[corev1.Pod](s.cache.Pods.Pods(parts[1]))
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
for _, p := range all {
if topology.OwnerWorkloadID(p) == id {
pods = append(pods, p)
}
}
case len(parts) == 2 && parts[0] == "node":
n, err := s.cache.Nodes.Get(parts[1])
if err != nil {
http.Error(w, err.Error(), http.StatusNotFound)
return
}
u.CPU.Capacity = n.Status.Allocatable.Cpu().MilliValue()
u.Memory.Capacity = n.Status.Allocatable.Memory().Value()
all, _ := kube.List[corev1.Pod](s.cache.Pods)
for _, p := range all {
if p.Spec.NodeName == parts[1] {
pods = append(pods, p)
}
}
var nm nodeMetrics
if s.metricsGet(r.Context(), &nm, "nodes", parts[1]) {
u.Metrics = true
u.CPU.Usage, u.Memory.Usage = ptr(nm.Usage.Cpu().MilliValue()), ptr(nm.Usage.Memory().Value())
}
default:
http.Error(w, "id must be a workload (wl/…) or a node (node/…)", http.StatusBadRequest)
return
}
live := pods[:0]
for _, p := range pods {
if p.Status.Phase != corev1.PodSucceeded && p.Status.Phase != corev1.PodFailed {
live = append(live, p)
}
}
cpuReq, cpuLim, memReq, memLim, noCPULimit, noMemLimit := requests(live)
u.CPU.Request, u.Memory.Request = cpuReq, memReq
if !noCPULimit {
u.CPU.Limit = cpuLim
}
if !noMemLimit {
u.Memory.Limit = memLim
}
workload := parts[0] == "wl"
var ml metricsList
byPod := map[string][2]int64{}
if workload && s.metricsGet(r.Context(), &ml, "namespaces", parts[1], "pods") {
u.Metrics = true
for _, it := range ml.Items {
var cpu, mem int64
for _, c := range it.Containers {
cpu += c.Usage.Cpu().MilliValue()
mem += c.Usage.Memory().Value()
}
byPod[it.Metadata.Name] = [2]int64{cpu, mem}
}
var cpu, mem int64
for _, p := range live {
cpu += byPod[p.Name][0]
mem += byPod[p.Name][1]
}
u.CPU.Usage, u.Memory.Usage = ptr(cpu), ptr(mem)
}
if workload {
for _, p := range live {
row := PodUsage{Name: p.Name, Node: p.Spec.NodeName, Ready: isReady(p)}
for _, cs := range p.Status.ContainerStatuses {
row.Restarts += cs.RestartCount
}
if v, ok := byPod[p.Name]; ok {
row.CPU, row.Memory = ptr(v[0]), ptr(v[1])
}
u.Pods = append(u.Pods, row)
}
sort.Slice(u.Pods, func(i, j int) bool { return u.Pods[i].Name < u.Pods[j].Name })
}
writeJSON(w, u)
}
// requests sums the regular containers' requests and limits. A limit sum
// only means something when every container has one.
func requests(pods []corev1.Pod) (cpuReq, cpuLim, memReq, memLim int64, noCPULimit, noMemLimit bool) {
for _, p := range pods {
for _, c := range p.Spec.Containers {
cpuReq += qty(c.Resources.Requests, corev1.ResourceCPU, true)
memReq += qty(c.Resources.Requests, corev1.ResourceMemory, false)
if _, ok := c.Resources.Limits[corev1.ResourceCPU]; !ok {
noCPULimit = true
}
if _, ok := c.Resources.Limits[corev1.ResourceMemory]; !ok {
noMemLimit = true
}
cpuLim += qty(c.Resources.Limits, corev1.ResourceCPU, true)
memLim += qty(c.Resources.Limits, corev1.ResourceMemory, false)
}
}
return
}
func qty(l corev1.ResourceList, name corev1.ResourceName, milli bool) int64 {
q, ok := l[name]
if !ok {
return 0
}
if milli {
return q.MilliValue()
}
return q.Value()
}
func isReady(p corev1.Pod) bool {
for _, c := range p.Status.Conditions {
if c.Type == corev1.PodReady {
return c.Status == corev1.ConditionTrue
}
}
return false
}
// maxVulns bounds the details list; an old base image can carry hundreds.
const maxVulns = 300
// handleVulns lists the CRITICAL/HIGH findings of a card's images from the
// cached VulnerabilityReports.
func (s *Server) handleVulns(w http.ResponseWriter, r *http.Request) {
id := r.URL.Query().Get("id")
if !strings.HasPrefix(id, "wl/") {
http.Error(w, "id must be a workload (wl/...)", http.StatusBadRequest)
return
}
parts := strings.Split(id, "/")
if !s.cardVisible(w, r, parts) {
return
}
ns := parts[1]
pods, _ := kube.List[corev1.Pod](s.cache.Pods.Pods(ns))
writeJSON(w, map[string]any{
"available": s.cache.VulnReports != nil,
"vulns": topology.VulnsFor(s.cache.VulnReportList(), pods, id, maxVulns),
})
}
// cardVisible checks a card ID (split on "/") against the viewer's scope:
// node/<name> needs node access, anything else its namespace.
func (s *Server) cardVisible(w http.ResponseWriter, r *http.Request, parts []string) bool {
sc, ok := s.scope(w, r)
if !ok {
return false
}
visible := len(parts) >= 2 && ((parts[0] == "node" && sc.Nodes) || (parts[0] != "node" && sc.Namespace(parts[1])))
if !visible {
hidden(w)
}
return visible
}
@@ -0,0 +1,421 @@
/*
Copyright 2026 The cluster-map Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Package server is the HTTP API and static frontend.
package server
import (
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"io"
"io/fs"
"log/slog"
"net/http"
"sort"
"strconv"
"strings"
"sync/atomic"
"time"
corev1 "k8s.io/api/core/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"sigs.k8s.io/yaml"
"git.project-chimera.ru/fanchji/cluster-map/internal/access"
"git.project-chimera.ru/fanchji/cluster-map/internal/actions"
"git.project-chimera.ru/fanchji/cluster-map/internal/config"
"git.project-chimera.ru/fanchji/cluster-map/internal/kube"
"git.project-chimera.ru/fanchji/cluster-map/internal/metrics"
"git.project-chimera.ru/fanchji/cluster-map/internal/topology"
"git.project-chimera.ru/fanchji/cluster-map/internal/traffic"
)
// Server serves the JSON API and the embedded frontend.
type Server struct {
cfg config.Config
cache *kube.Cache
traffic *traffic.Collector
static fs.FS
etags map[string]string
asViewer actions.ClientFactory // nil when neither actions nor viewer visibility is on
access *access.Checker // nil when everyone sees everything
ready atomic.Bool
}
// New returns a server that answers 503 on the API until SetReady.
// asViewer builds clients from the viewer's token; nil disables actions
// and per-viewer visibility.
func New(cfg config.Config, static fs.FS, asViewer actions.ClientFactory) *Server {
s := &Server{cfg: cfg, static: static, etags: etags(static), asViewer: asViewer}
if cfg.ViewerVisibility && asViewer != nil {
s.access = access.NewChecker(access.ClientFactory(asViewer), s.namespaceNames)
}
return s
}
func (s *Server) namespaceNames() []string {
nss, _ := kube.List[corev1.Namespace](s.cache.Namespaces)
out := make([]string, len(nss))
for i, n := range nss {
out[i] = n.Name
}
return out
}
// scope is what the viewer of this request may see, or it writes why
// nothing can be shown.
func (s *Server) scope(w http.ResponseWriter, r *http.Request) (*access.Scope, bool) {
if s.access == nil {
return access.Everything, true
}
sc, err := s.access.For(r.Context(), viewerToken(r))
switch {
case err == nil:
return sc, true
case errors.Is(err, access.ErrNoToken), apierrors.IsUnauthorized(err):
http.Error(w, err.Error(), http.StatusUnauthorized)
default:
http.Error(w, "checking the viewer's permissions: "+err.Error(), http.StatusBadGateway)
}
return nil, false
}
// hidden answers 403 for an object outside the viewer's scope.
func hidden(w http.ResponseWriter) {
http.Error(w, "not visible with your permissions", http.StatusForbidden)
}
// etags hashes the embedded files once: they cannot change while the
// process runs, so a browser revalidates with If-None-Match and gets a 304
// instead of the 2 MB of vendored scripts on every visit.
func etags(static fs.FS) map[string]string {
out := map[string]string{}
_ = fs.WalkDir(static, ".", func(path string, d fs.DirEntry, err error) error {
if err != nil || d.IsDir() {
return err
}
b, err := fs.ReadFile(static, path)
if err != nil {
return err
}
sum := sha256.Sum256(b)
out["/"+path] = `"` + hex.EncodeToString(sum[:12]) + `"`
return nil
})
if v, ok := out["/index.html"]; ok {
out["/"] = v
}
return out
}
// staticHandler serves the embedded frontend with validators. Everything
// is revalidated on each load (no-cache), so a new release shows up on the
// next reload without versioned file names.
func (s *Server) staticHandler() http.Handler {
files := http.FileServerFS(s.static)
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if tag, ok := s.etags[r.URL.Path]; ok {
w.Header().Set("ETag", tag)
w.Header().Set("Cache-Control", "no-cache")
}
files.ServeHTTP(w, r)
})
}
// SetReady is called once the caches have synced; until then API calls
// and the readiness probe answer 503.
func (s *Server) SetReady(cache *kube.Cache, collector *traffic.Collector) {
s.cache, s.traffic = cache, collector
s.ready.Store(true)
}
// Handler returns the routes wrapped in security headers.
func (s *Server) Handler() http.Handler {
mux := http.NewServeMux()
mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, _ *http.Request) { _, _ = io.WriteString(w, "ok") })
mux.HandleFunc("GET /readyz", func(w http.ResponseWriter, _ *http.Request) {
if !s.ready.Load() {
http.Error(w, "caches not synced", http.StatusServiceUnavailable)
return
}
_, _ = io.WriteString(w, "ok")
})
mux.Handle("GET /api/graph", s.api("graph", s.handleGraph))
mux.Handle("GET /api/flows", s.api("flows", s.handleFlows))
mux.Handle("GET /api/resource", s.api("resource", s.handleResource))
mux.Handle("GET /api/pods", s.api("pods", s.handlePods))
mux.Handle("GET /api/logs", s.api("logs", s.handleLogs))
mux.Handle("GET /api/events", s.api("events", s.handleEvents))
mux.Handle("GET /api/usage", s.api("usage", s.handleUsage))
mux.Handle("GET /api/vulns", s.api("vulns", s.handleVulns))
mux.Handle("GET /api/me", s.api("me", s.handleMe))
mux.Handle("GET /api/permissions", s.api("permissions", s.handlePermissions))
mux.Handle("POST /api/action", s.api("action", s.handleAction))
mux.Handle("GET /", s.staticHandler())
return securityHeaders(mux)
}
type statusWriter struct {
http.ResponseWriter
code int
}
func (w *statusWriter) WriteHeader(code int) { w.code = code; w.ResponseWriter.WriteHeader(code) }
// api wraps an API handler with readiness gating and request metrics.
func (s *Server) api(name string, h http.HandlerFunc) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
sw := &statusWriter{ResponseWriter: w, code: http.StatusOK}
if !s.ready.Load() {
http.Error(sw, "caches not synced yet", http.StatusServiceUnavailable)
} else {
h(sw, r)
}
metrics.HTTPRequests.WithLabelValues(name, strconv.Itoa(sw.code)).Inc()
metrics.HTTPDuration.WithLabelValues(name).Observe(time.Since(start).Seconds())
})
}
// securityHeaders: the page loads only its own scripts, styles and images
// (card images are data: SVGs), talks only to its own API, and can't be
// framed.
func securityHeaders(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
h := w.Header()
h.Set("Content-Security-Policy", "default-src 'self'; img-src 'self' data:; style-src 'self'; script-src 'self'; connect-src 'self'; frame-ancestors 'none'; base-uri 'none'; form-action 'none'")
h.Set("X-Content-Type-Options", "nosniff")
h.Set("Referrer-Policy", "no-referrer")
h.Set("Cache-Control", "no-store")
next.ServeHTTP(w, r)
})
}
func writeJSON(w http.ResponseWriter, v any) {
w.Header().Set("Content-Type", "application/json")
if err := json.NewEncoder(w).Encode(v); err != nil {
slog.Debug("writing response", "err", err) // client went away
}
}
func (s *Server) handleGraph(w http.ResponseWriter, r *http.Request) {
sc, ok := s.scope(w, r)
if !ok {
return
}
g, err := topology.Build(s.cache, s.cfg.IsSystemNamespace)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
writeJSON(w, topology.Filter(g, sc.All, sc.Nodes, sc.Namespace))
}
func (s *Server) handleFlows(w http.ResponseWriter, r *http.Request) {
sc, ok := s.scope(w, r)
if !ok {
return
}
if s.cfg.TrafficMode == config.TrafficDisabled {
writeJSON(w, traffic.Result{Mode: config.TrafficDisabled})
return
}
namespaces := map[string]bool{}
for _, ns := range strings.Split(r.URL.Query().Get("namespaces"), ",") {
if ns = strings.TrimSpace(ns); ns != "" {
namespaces[ns] = true
}
}
if len(namespaces) == 0 || len(namespaces) > 200 {
http.Error(w, "namespaces: 1 to 200, comma-separated", http.StatusBadRequest)
return
}
window, err := time.ParseDuration(r.URL.Query().Get("window") + "s")
if err != nil || window <= 0 {
window = 5 * time.Minute
}
for ns := range namespaces {
if !sc.Namespace(ns) {
delete(namespaces, ns)
}
}
res := s.traffic.Query(namespaces, window)
if !sc.All {
res = traffic.Restrict(res, sc.Namespace)
}
writeJSON(w, res)
}
// handleResource returns the live object as YAML. It reads through the API
// rather than the cache so the view is exactly what the API server holds.
func (s *Server) handleResource(w http.ResponseWriter, r *http.Request) {
q := r.URL.Query()
kind, ns, name := q.Get("kind"), q.Get("namespace"), q.Get("name")
sc, ok := s.scope(w, r)
if !ok {
return
}
if (kind == "node" && !sc.Nodes) || (kind == "namespace" && !sc.Namespace(name)) || (kind != "node" && kind != "namespace" && !sc.Namespace(ns)) {
hidden(w)
return
}
ctx := r.Context()
c := s.cache.Client
var obj metav1.Object
var err error
switch kind {
case "namespace":
obj, err = c.CoreV1().Namespaces().Get(ctx, name, metav1.GetOptions{})
case "deployment":
obj, err = c.AppsV1().Deployments(ns).Get(ctx, name, metav1.GetOptions{})
case "statefulset":
obj, err = c.AppsV1().StatefulSets(ns).Get(ctx, name, metav1.GetOptions{})
case "daemonset":
obj, err = c.AppsV1().DaemonSets(ns).Get(ctx, name, metav1.GetOptions{})
case "cronjob":
obj, err = c.BatchV1().CronJobs(ns).Get(ctx, name, metav1.GetOptions{})
case "service":
obj, err = c.CoreV1().Services(ns).Get(ctx, name, metav1.GetOptions{})
case "ingress":
obj, err = c.NetworkingV1().Ingresses(ns).Get(ctx, name, metav1.GetOptions{})
case "node":
obj, err = c.CoreV1().Nodes().Get(ctx, name, metav1.GetOptions{})
case "pod":
obj, err = c.CoreV1().Pods(ns).Get(ctx, name, metav1.GetOptions{})
default:
http.Error(w, "unknown kind", http.StatusBadRequest)
return
}
if err != nil {
http.Error(w, err.Error(), apiStatus(err))
return
}
obj.SetManagedFields(nil)
out, err := yaml.Marshal(obj)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
_, _ = w.Write(out)
}
func apiStatus(err error) int {
var st apierrors.APIStatus
if errors.As(err, &st) && st.Status().Code != 0 {
return int(st.Status().Code)
}
return http.StatusInternalServerError
}
// PodInfo is one pod behind a workload, for the log picker.
type PodInfo struct {
Name string `json:"name"`
NodeName string `json:"nodeName"`
Phase string `json:"phase"`
Containers []string `json:"containers"`
}
// handlePods lists the live pods behind a workload ID, resolved with the
// same owner rules the graph uses.
func (s *Server) handlePods(w http.ResponseWriter, r *http.Request) {
id, ns := r.URL.Query().Get("id"), r.URL.Query().Get("namespace")
if ns == "" || !strings.HasPrefix(id, "wl/"+ns+"/") {
http.Error(w, "namespace and a workload id (wl/<ns>/<kind>/<name>) are required", http.StatusBadRequest)
return
}
if sc, ok := s.scope(w, r); !ok {
return
} else if !sc.Namespace(ns) {
hidden(w)
return
}
pods, err := kube.List[corev1.Pod](s.cache.Pods.Pods(ns))
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
out := []PodInfo{}
for _, p := range pods {
if topology.OwnerWorkloadID(p) != id {
continue
}
info := PodInfo{Name: p.Name, NodeName: p.Spec.NodeName, Phase: string(p.Status.Phase)}
for _, c := range p.Spec.Containers {
info.Containers = append(info.Containers, c.Name)
}
out = append(out, info)
}
sort.Slice(out, func(i, j int) bool { return out[i].Name < out[j].Name })
writeJSON(w, out)
}
// handleLogs returns a container's recent log tail. No follow: this is a
// click-to-inspect view, not a live tail.
func (s *Server) handleLogs(w http.ResponseWriter, r *http.Request) {
q := r.URL.Query()
ns, pod, container := q.Get("namespace"), q.Get("pod"), q.Get("container")
if ns == "" || pod == "" {
http.Error(w, "namespace and pod are required", http.StatusBadRequest)
return
}
if !s.canReadLogs(w, r, ns) {
return
}
tail := s.cfg.LogTailLines
opts := &corev1.PodLogOptions{TailLines: &tail, Container: container}
stream, err := s.cache.Client.CoreV1().Pods(ns).GetLogs(pod, opts).Stream(r.Context())
if err != nil {
http.Error(w, err.Error(), apiStatus(err))
return
}
defer stream.Close()
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
if _, err := io.Copy(w, stream); err != nil {
slog.Debug("streaming logs", "err", err)
}
}
// canReadLogs: logs are the most sensitive thing the map shows, so beyond
// the namespace scope the viewer must be allowed pods/log there.
func (s *Server) canReadLogs(w http.ResponseWriter, r *http.Request, ns string) bool {
sc, ok := s.scope(w, r)
if !ok {
return false
}
if !sc.Namespace(ns) {
hidden(w)
return false
}
if s.access == nil || sc.All {
return true
}
c, err := s.asViewer(viewerToken(r))
if err == nil {
ok, err = access.Can(r.Context(), c, "", "pods", "log", "get", ns)
}
if err != nil {
http.Error(w, "checking the viewer's permissions: "+err.Error(), http.StatusBadGateway)
return false
}
if !ok {
hidden(w)
}
return ok
}
@@ -0,0 +1,108 @@
/*
Copyright 2026 The cluster-map Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package server
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"
"testing/fstest"
"time"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes/fake"
"git.project-chimera.ru/fanchji/cluster-map/internal/config"
"git.project-chimera.ru/fanchji/cluster-map/internal/kube"
"git.project-chimera.ru/fanchji/cluster-map/internal/traffic"
)
func newServer(t *testing.T, mode config.TrafficMode) (*Server, http.Handler) {
t.Helper()
cfg := config.Config{TrafficMode: mode, Retention: time.Hour, LogTailLines: 10, SystemNamespacePrefixes: []string{"d8-"}}
s := New(cfg, fstest.MapFS{"index.html": {Data: []byte("<!doctype html>")}}, nil)
return s, s.Handler()
}
func get(h http.Handler, path string) *httptest.ResponseRecorder {
rec := httptest.NewRecorder()
h.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, path, nil))
return rec
}
func TestNotReadyUntilCachesSync(t *testing.T) {
_, h := newServer(t, config.TrafficDisabled)
if code := get(h, "/readyz").Code; code != http.StatusServiceUnavailable {
t.Errorf("readyz before sync: %d", code)
}
if code := get(h, "/api/graph").Code; code != http.StatusServiceUnavailable {
t.Errorf("api before sync: %d", code)
}
if code := get(h, "/healthz").Code; code != http.StatusOK {
t.Errorf("healthz must not depend on caches: %d", code)
}
}
func TestSecurityHeaders(t *testing.T) {
_, h := newServer(t, config.TrafficDisabled)
rec := get(h, "/")
if csp := rec.Header().Get("Content-Security-Policy"); !strings.Contains(csp, "frame-ancestors 'none'") || !strings.Contains(csp, "default-src 'self'") {
t.Errorf("CSP: %q", csp)
}
if rec.Header().Get("X-Content-Type-Options") != "nosniff" {
t.Error("nosniff missing")
}
}
func TestPodsAndFlows(t *testing.T) {
yes := true
client := fake.NewSimpleClientset(
&corev1.Pod{
ObjectMeta: metav1.ObjectMeta{Name: "web-5f-abc", Namespace: "shop", OwnerReferences: []metav1.OwnerReference{{Kind: "ReplicaSet", Name: "web-5f", Controller: &yes}}},
Spec: corev1.PodSpec{NodeName: "node-a", Containers: []corev1.Container{{Name: "app"}, {Name: "sidecar"}}},
Status: corev1.PodStatus{Phase: corev1.PodRunning},
},
&corev1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "other", Namespace: "shop"}},
)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
cache, err := kube.Start(ctx, client, nil, 10*time.Second)
if err != nil {
t.Fatal(err)
}
s, h := newServer(t, config.TrafficDisabled)
s.SetReady(cache, traffic.NewCollector(s.cfg, nil, nil))
rec := get(h, "/api/pods?namespace=shop&id=wl/shop/deployment/web")
var pods []PodInfo
if err := json.Unmarshal(rec.Body.Bytes(), &pods); err != nil || len(pods) != 1 || len(pods[0].Containers) != 2 {
t.Fatalf("pods: %d %s", rec.Code, rec.Body)
}
if code := get(h, "/api/pods?namespace=shop&id=wl/other/deployment/web").Code; code != http.StatusBadRequest {
t.Errorf("id from another namespace must be rejected: %d", code)
}
var res traffic.Result
rec = get(h, "/api/flows?namespaces=shop&window=300")
if err := json.Unmarshal(rec.Body.Bytes(), &res); err != nil || res.Mode != config.TrafficDisabled {
t.Fatalf("flows in disabled mode: %d %s", rec.Code, rec.Body)
}
}
@@ -0,0 +1,104 @@
/*
Copyright 2026 The cluster-map Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package server
import (
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
"testing/fstest"
"time"
authzv1 "k8s.io/api/authorization/v1"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/kubernetes/fake"
k8stesting "k8s.io/client-go/testing"
"git.project-chimera.ru/fanchji/cluster-map/internal/config"
"git.project-chimera.ru/fanchji/cluster-map/internal/kube"
"git.project-chimera.ru/fanchji/cluster-map/internal/topology"
"git.project-chimera.ru/fanchji/cluster-map/internal/traffic"
)
// The viewer "shop-dev" may list pods in shop and nothing else.
func visibilityServer(t *testing.T) http.Handler {
t.Helper()
cluster := fake.NewSimpleClientset(
&corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: "shop"}},
&corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: "bank"}},
&corev1.Service{ObjectMeta: metav1.ObjectMeta{Name: "web", Namespace: "shop"}},
&corev1.Service{ObjectMeta: metav1.ObjectMeta{Name: "core", Namespace: "bank"}},
)
ctx := t.Context()
cache, err := kube.Start(ctx, cluster, nil, 10*time.Second)
if err != nil {
t.Fatal(err)
}
factory := func(token string) (kubernetes.Interface, error) {
c := fake.NewSimpleClientset()
c.PrependReactor("create", "selfsubjectaccessreviews", func(a k8stesting.Action) (bool, runtime.Object, error) {
r := a.(k8stesting.CreateAction).GetObject().(*authzv1.SelfSubjectAccessReview)
r.Status.Allowed = token == "shop-dev" && r.Spec.ResourceAttributes.Namespace == "shop"
return true, r, nil
})
return c, nil
}
cfg := config.Config{TrafficMode: config.TrafficDisabled, Retention: time.Hour, ViewerVisibility: true}
s := New(cfg, fstest.MapFS{"index.html": {Data: []byte("x")}}, factory)
s.SetReady(cache, traffic.NewCollector(cfg, nil, nil))
return s.Handler()
}
func getAs(h http.Handler, path, token string) *httptest.ResponseRecorder {
req := httptest.NewRequest(http.MethodGet, path, nil)
if token != "" {
req.Header.Set("Authorization", "Bearer "+token)
}
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
return rec
}
func TestGraphFollowsViewerRBAC(t *testing.T) {
h := visibilityServer(t)
if code := getAs(h, "/api/graph", "").Code; code != http.StatusUnauthorized {
t.Errorf("no token: %d", code)
}
rec := getAs(h, "/api/graph", "shop-dev")
var g topology.Graph
if err := json.Unmarshal(rec.Body.Bytes(), &g); err != nil {
t.Fatalf("%d %s", rec.Code, rec.Body)
}
for _, n := range g.Nodes {
if n.Namespace == "bank" || n.ID == "ns/bank" {
t.Errorf("bank visible to shop-dev: %s", n.ID)
}
}
if code := getAs(h, "/api/resource?kind=service&namespace=bank&name=core", "shop-dev").Code; code != http.StatusForbidden {
t.Errorf("YAML from a hidden namespace: %d", code)
}
if code := getAs(h, "/api/logs?namespace=bank&pod=core-0", "shop-dev").Code; code != http.StatusForbidden {
t.Errorf("logs from a hidden namespace: %d", code)
}
if code := getAs(h, "/api/events?id=node/a", "shop-dev").Code; code != http.StatusForbidden {
t.Errorf("node events without node access: %d", code)
}
}
@@ -0,0 +1,50 @@
/*
Copyright 2026 The cluster-map Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package topology
// Filter returns the part of the graph a viewer may see: namespaced cards
// in visible namespaces, node cards only with node access, edges whose both
// ends stay. Cluster-wide problems (alerts about the cluster itself) are
// for cluster-wide viewers only. all short-circuits to the graph as is.
func Filter(g *Graph, all, nodes bool, namespace func(string) bool) *Graph {
if all {
return g
}
out := &Graph{Nodes: []Node{}, Edges: []Edge{}, ClusterProblems: []Problem{}, AlertsAvailable: g.AlertsAvailable, VulnsAvailable: g.VulnsAvailable}
kept := make(map[string]bool, len(g.Nodes))
for _, n := range g.Nodes {
var ok bool
switch n.Kind {
case "node":
ok = nodes
case "namespace":
ok = namespace(n.Label)
default:
ok = namespace(n.Namespace)
}
if ok {
out.Nodes = append(out.Nodes, n)
kept[n.ID] = true
}
}
for _, e := range g.Edges {
if kept[e.Source] && kept[e.Target] {
out.Edges = append(out.Edges, e)
}
}
return out
}
@@ -0,0 +1,54 @@
/*
Copyright 2026 The cluster-map Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package topology
import "testing"
func TestFilter(t *testing.T) {
g := &Graph{
Nodes: []Node{
{ID: "ns/shop", Kind: "namespace", Label: "shop"}, {ID: "ns/bank", Kind: "namespace", Label: "bank"},
{ID: "wl/shop/deployment/web", Kind: "deployment", Namespace: "shop"}, {ID: "wl/bank/deployment/core", Kind: "deployment", Namespace: "bank"},
{ID: "node/a", Kind: "node", Label: "a"},
},
Edges: []Edge{
{ID: "e1", Source: "wl/shop/deployment/web", Target: "node/a"},
{ID: "e2", Source: "wl/bank/deployment/core", Target: "node/a"},
},
ClusterProblems: []Problem{{Reason: "ClusterWide"}},
}
out := Filter(g, false, true, func(ns string) bool { return ns == "shop" })
ids := map[string]bool{}
for _, n := range out.Nodes {
ids[n.ID] = true
}
if len(ids) != 3 || !ids["ns/shop"] || !ids["wl/shop/deployment/web"] || !ids["node/a"] {
t.Errorf("nodes: %v", ids)
}
if len(out.Edges) != 1 || out.Edges[0].ID != "e1" {
t.Errorf("edges: %+v", out.Edges)
}
if len(out.ClusterProblems) != 0 {
t.Error("cluster-wide problems shown to a namespaced viewer")
}
if noNodes := Filter(g, false, false, func(ns string) bool { return ns == "shop" }); len(noNodes.Edges) != 0 {
t.Error("placement edge to a hidden node kept")
}
if Filter(g, true, true, nil) != g {
t.Error("cluster-wide viewer must get the graph as is")
}
}
@@ -0,0 +1,492 @@
/*
Copyright 2026 The cluster-map Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Package topology turns the cached cluster state into the graph the map
// draws: namespaces, workloads, Services, Ingresses and nodes, joined by
// configuration edges (Ingress backend, Service selector) and placement.
package topology
import (
"sort"
"strconv"
"strings"
appsv1 "k8s.io/api/apps/v1"
batchv1 "k8s.io/api/batch/v1"
corev1 "k8s.io/api/core/v1"
networkingv1 "k8s.io/api/networking/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"git.project-chimera.ru/fanchji/cluster-map/internal/kube"
)
// Node is one card or box on the map.
type Node struct {
ID string `json:"id"`
Label string `json:"label"`
Kind string `json:"kind"` // namespace | deployment | statefulset | daemonset | cronjob | pod | service | ingress | node
Namespace string `json:"namespace"` // empty for namespace and node
Parent string `json:"parent,omitempty"`
Facts map[string]string `json:"facts,omitempty"` // short summary shown without a follow-up fetch
Problems []Problem `json:"problems,omitempty"`
Vulns *VulnSummary `json:"vulns,omitempty"`
}
// Edge is a configuration or placement link between two nodes.
type Edge struct {
ID string `json:"id"`
Source string `json:"source"`
Target string `json:"target"`
Kind string `json:"kind"` // selects (workload -> service) | routes (ingress -> service) | schedules-on (workload -> node)
}
// Graph is the whole /api/graph response.
type Graph struct {
Nodes []Node `json:"nodes"`
Edges []Edge `json:"edges"`
// ClusterProblems are problems no card owns: cluster-wide alerts and
// alerts about namespaces that no longer exist.
ClusterProblems []Problem `json:"clusterProblems"`
// AlertsAvailable is false when ClusterAlerts are not served, so the UI
// can say that alerts are not part of the picture.
AlertsAvailable bool `json:"alertsAvailable"`
// VulnsAvailable is false when operator-trivy is not installed.
VulnsAvailable bool `json:"vulnsAvailable"`
}
// WorkloadID is the graph ID of a workload. Traffic endpoints use the same
// scheme, which is what lets Hubble flows attach to graph cards.
func WorkloadID(ns, kind, name string) string { return "wl/" + ns + "/" + kind + "/" + name }
var nativeKinds = map[string]bool{"deployment": true, "statefulset": true, "daemonset": true, "cronjob": true}
type workloadRef struct {
id string
labels map[string]string
}
// Build assembles the graph from the cache. isSystem classifies namespaces.
func Build(c *kube.Cache, isSystem func(string) bool) (*Graph, error) {
g := &Graph{Nodes: []Node{}, Edges: []Edge{}}
namespaces, err := kube.List[corev1.Namespace](c.Namespaces)
if err != nil {
return nil, err
}
for _, ns := range namespaces {
g.Nodes = append(g.Nodes, Node{
ID: "ns/" + ns.Name, Label: ns.Name, Kind: "namespace",
Facts: map[string]string{"system": strconv.FormatBool(isSystem(ns.Name))},
})
}
var workloads []workloadRef
deployments, err := kube.List[appsv1.Deployment](c.Deployments)
if err != nil {
return nil, err
}
for _, d := range deployments {
id := WorkloadID(d.Namespace, "deployment", d.Name)
g.Nodes = append(g.Nodes, workloadNode(id, "deployment", d.Namespace, d.Name, deploymentFacts(d)))
workloads = append(workloads, workloadRef{id, d.Spec.Template.Labels})
}
statefulsets, err := kube.List[appsv1.StatefulSet](c.StatefulSets)
if err != nil {
return nil, err
}
for _, s := range statefulsets {
id := WorkloadID(s.Namespace, "statefulset", s.Name)
g.Nodes = append(g.Nodes, workloadNode(id, "statefulset", s.Namespace, s.Name, statefulsetFacts(s)))
workloads = append(workloads, workloadRef{id, s.Spec.Template.Labels})
}
daemonsets, err := kube.List[appsv1.DaemonSet](c.DaemonSets)
if err != nil {
return nil, err
}
for _, ds := range daemonsets {
id := WorkloadID(ds.Namespace, "daemonset", ds.Name)
g.Nodes = append(g.Nodes, workloadNode(id, "daemonset", ds.Namespace, ds.Name, daemonsetFacts(ds)))
workloads = append(workloads, workloadRef{id, ds.Spec.Template.Labels})
}
cronjobs, err := kube.List[batchv1.CronJob](c.CronJobs)
if err != nil {
return nil, err
}
for _, cj := range cronjobs {
id := WorkloadID(cj.Namespace, "cronjob", cj.Name)
g.Nodes = append(g.Nodes, workloadNode(id, "cronjob", cj.Namespace, cj.Name, cronjobFacts(cj)))
}
pods, err := kube.List[corev1.Pod](c.Pods)
if err != nil {
return nil, err
}
nodes, foreignRefs := foreignWorkloads(pods, g.Nodes)
g.Nodes = append(g.Nodes, nodes...)
workloads = append(workloads, foreignRefs...)
services, err := kube.List[corev1.Service](c.Services)
if err != nil {
return nil, err
}
for _, svc := range services {
id := "service/" + svc.Namespace + "/" + svc.Name
g.Nodes = append(g.Nodes, Node{ID: id, Label: svc.Name, Kind: "service", Namespace: svc.Namespace, Parent: "ns/" + svc.Namespace, Facts: serviceFacts(svc)})
for _, wl := range workloads {
if strings.HasPrefix(wl.id, "wl/"+svc.Namespace+"/") && SelectorMatches(svc.Spec.Selector, wl.labels) {
g.Edges = append(g.Edges, Edge{ID: wl.id + "->" + id, Source: wl.id, Target: id, Kind: "selects"})
}
}
}
ingresses, err := kube.List[networkingv1.Ingress](c.Ingresses)
if err != nil {
return nil, err
}
for _, ing := range ingresses {
id := "ingress/" + ing.Namespace + "/" + ing.Name
g.Nodes = append(g.Nodes, Node{ID: id, Label: ing.Name, Kind: "ingress", Namespace: ing.Namespace, Parent: "ns/" + ing.Namespace, Facts: ingressFacts(ing)})
for _, svcName := range IngressBackendServices(ing) {
target := "service/" + ing.Namespace + "/" + svcName
g.Edges = append(g.Edges, Edge{ID: id + "->" + target, Source: id, Target: target, Kind: "routes"})
}
}
hostNodes, err := kube.List[corev1.Node](c.Nodes)
if err != nil {
return nil, err
}
for _, n := range hostNodes {
g.Nodes = append(g.Nodes, Node{ID: "node/" + n.Name, Label: n.Name, Kind: "node", Facts: nodeFacts(n)})
}
g.Edges = append(g.Edges, placementEdges(pods)...)
events, err := kube.List[corev1.Event](c.Events)
if err != nil {
return nil, err
}
attachProblems(g, problemInputs{
pods: pods, deployments: deployments, daemonsets: daemonsets, statefulsets: statefulsets, cronjobs: cronjobs,
services: services, ingresses: ingresses, nodes: hostNodes, events: events, alerts: c.AlertList(),
})
g.AlertsAvailable = c.Alerts != nil
attachVulns(g, c.VulnReportList(), pods)
g.VulnsAvailable = c.VulnReports != nil
sort.Slice(g.Nodes, func(i, j int) bool { return g.Nodes[i].ID < g.Nodes[j].ID })
sort.Slice(g.Edges, func(i, j int) bool { return g.Edges[i].ID < g.Edges[j].ID })
return g, nil
}
// foreignWorkloads turns pods whose controller is not a native workload
// (kruise Advanced DaemonSet, database operators, bare Jobs, static pods)
// into workload nodes of their own, named the way Hubble names workloads.
func foreignWorkloads(pods []corev1.Pod, existing []Node) ([]Node, []workloadRef) {
known := make(map[string]bool, len(existing))
for _, n := range existing {
known[n.ID] = true
}
type acc struct {
ns, kind, name, controller string
pods, ready int
labels map[string]string
}
byID := map[string]*acc{}
for _, p := range pods {
kind, name, ctrl := PodOwner(p)
if kind == "" {
continue
}
id := WorkloadID(p.Namespace, kind, name)
if known[id] {
continue
}
a := byID[id]
if a == nil {
a = &acc{ns: p.Namespace, kind: kind, name: name, controller: ctrl, labels: p.Labels}
byID[id] = a
}
if p.Status.Phase == corev1.PodSucceeded {
continue
}
a.pods++
if podReady(p) {
a.ready++
}
}
var nodes []Node
var refs []workloadRef
for id, a := range byID {
kind := a.kind
if !nativeKinds[kind] {
kind = "pod"
}
nodes = append(nodes, workloadNode(id, kind, a.ns, a.name, map[string]string{
"controller": a.controller,
"pods": strconv.Itoa(a.pods),
"ready": strconv.Itoa(a.ready),
"health": Health(a.pods, a.ready),
"foreign": "true",
}))
refs = append(refs, workloadRef{id, a.labels})
}
return nodes, refs
}
func placementEdges(pods []corev1.Pod) []Edge {
seen := map[string]bool{}
var out []Edge
for _, p := range pods {
if p.Spec.NodeName == "" {
continue
}
wl := OwnerWorkloadID(p)
if wl == "" {
continue
}
key := wl + "@" + p.Spec.NodeName
if seen[key] {
continue
}
seen[key] = true
out = append(out, Edge{ID: key, Source: wl, Target: "node/" + p.Spec.NodeName, Kind: "schedules-on"})
}
return out
}
// SelectorMatches reports whether every key/value of a Service selector is
// present in a pod template's labels. An empty selector matches nothing
// here: in Kubernetes it selects no pods for endpoints either.
func SelectorMatches(sel, labels map[string]string) bool {
if len(sel) == 0 {
return false
}
for k, v := range sel {
if labels[k] != v {
return false
}
}
return true
}
// PodOwner names the workload a pod belongs to the way Hubble does
// (cilium's GetWorkloadMetaFromPod): ReplicaSet -> its Deployment, a Job
// whose name ends in the scheduler's numeric suffix -> its CronJob, a
// kubelet mirror pod -> its component, any other controller kind as-is.
// controller is "<apiVersion> <Kind>" of the owner reference.
func PodOwner(p corev1.Pod) (kind, name, controller string) {
var o *metav1.OwnerReference
for i := range p.OwnerReferences {
if c := p.OwnerReferences[i].Controller; c != nil && *c {
o = &p.OwnerReferences[i]
break
}
}
if o == nil && len(p.OwnerReferences) > 0 {
o = &p.OwnerReferences[0]
}
if o == nil {
return "", "", ""
}
controller = o.APIVersion + " " + o.Kind
switch o.Kind {
case "ReplicaSet":
if i := strings.LastIndex(o.Name, "-"); i > 0 {
return "deployment", o.Name[:i], controller
}
case "Job":
if name, ok := CronJobFromJob(o.Name); ok {
return "cronjob", name, controller
}
case "Node":
// static pod "<component>-<node>", grouped per component across nodes
return "staticpod", strings.TrimSuffix(p.Name, "-"+p.Spec.NodeName), "static pod (kubelet)"
}
return strings.ToLower(o.Kind), o.Name, controller
}
// CronJobFromJob returns the CronJob behind a Job name produced by the
// CronJob controller ("<cronjob>-<scheduled minute>").
func CronJobFromJob(job string) (string, bool) {
i := strings.LastIndex(job, "-")
if i <= 0 || !allDigits(job[i+1:]) {
return "", false
}
return job[:i], true
}
// OwnerWorkloadID is PodOwner as a graph ID, empty for bare pods.
func OwnerWorkloadID(p corev1.Pod) string {
kind, name, _ := PodOwner(p)
if kind == "" {
return ""
}
return WorkloadID(p.Namespace, kind, name)
}
func allDigits(s string) bool {
if s == "" {
return false
}
for _, c := range s {
if c < '0' || c > '9' {
return false
}
}
return true
}
func podReady(p corev1.Pod) bool {
for _, c := range p.Status.Conditions {
if c.Type == corev1.PodReady {
return c.Status == corev1.ConditionTrue
}
}
return false
}
func workloadNode(id, kind, ns, name string, facts map[string]string) Node {
return Node{ID: id, Label: name, Kind: kind, Namespace: ns, Parent: "ns/" + ns, Facts: facts}
}
// IngressBackendServices lists the distinct Services an Ingress routes to.
func IngressBackendServices(ing networkingv1.Ingress) []string {
seen := map[string]bool{}
var out []string
add := func(name string) {
if name != "" && !seen[name] {
seen[name] = true
out = append(out, name)
}
}
if b := ing.Spec.DefaultBackend; b != nil && b.Service != nil {
add(b.Service.Name)
}
for _, rule := range ing.Spec.Rules {
if rule.HTTP == nil {
continue
}
for _, path := range rule.HTTP.Paths {
if path.Backend.Service != nil {
add(path.Backend.Service.Name)
}
}
}
return out
}
// Health is what the status dot on a card shows: ok, warn (partly ready),
// error (nothing ready) or idle (scaled to zero or suspended).
func Health(want, ready int) string {
switch {
case want == 0:
return "idle"
case ready >= want:
return "ok"
case ready == 0:
return "error"
}
return "warn"
}
func replicasOf(p *int32) int {
if p == nil {
return 1
}
return int(*p)
}
func firstImage(cs []corev1.Container) string {
if len(cs) == 0 {
return ""
}
return cs[0].Image
}
func deploymentFacts(d appsv1.Deployment) map[string]string {
want := replicasOf(d.Spec.Replicas)
return map[string]string{
"replicas": strconv.Itoa(want), "readyReplicas": strconv.Itoa(int(d.Status.ReadyReplicas)),
"image": firstImage(d.Spec.Template.Spec.Containers), "health": Health(want, int(d.Status.ReadyReplicas)),
}
}
func statefulsetFacts(s appsv1.StatefulSet) map[string]string {
want := replicasOf(s.Spec.Replicas)
return map[string]string{
"replicas": strconv.Itoa(want), "readyReplicas": strconv.Itoa(int(s.Status.ReadyReplicas)),
"image": firstImage(s.Spec.Template.Spec.Containers), "health": Health(want, int(s.Status.ReadyReplicas)),
}
}
func daemonsetFacts(ds appsv1.DaemonSet) map[string]string {
want, ready := int(ds.Status.DesiredNumberScheduled), int(ds.Status.NumberReady)
return map[string]string{
"desired": strconv.Itoa(want), "ready": strconv.Itoa(ready),
"image": firstImage(ds.Spec.Template.Spec.Containers), "health": Health(want, ready),
}
}
func cronjobFacts(cj batchv1.CronJob) map[string]string {
f := map[string]string{"schedule": cj.Spec.Schedule, "health": "ok", "active": strconv.Itoa(len(cj.Status.Active))}
if cj.Spec.Suspend != nil && *cj.Spec.Suspend {
f["suspended"] = "true"
f["health"] = "idle"
}
if t := cj.Status.LastSuccessfulTime; t != nil {
f["lastSuccess"] = t.UTC().Format("2006-01-02 15:04")
}
return f
}
func serviceFacts(svc corev1.Service) map[string]string {
var ports []string
for _, p := range svc.Spec.Ports {
ports = append(ports, strconv.Itoa(int(p.Port))+"/"+string(p.Protocol))
}
return map[string]string{"type": string(svc.Spec.Type), "ports": strings.Join(ports, ", ")}
}
func ingressFacts(ing networkingv1.Ingress) map[string]string {
var hosts []string
for _, r := range ing.Spec.Rules {
if r.Host != "" {
hosts = append(hosts, r.Host)
}
}
class := ""
if ing.Spec.IngressClassName != nil {
class = *ing.Spec.IngressClassName
}
return map[string]string{"hosts": strings.Join(hosts, ", "), "class": class}
}
func nodeFacts(n corev1.Node) map[string]string {
ready := "False"
for _, c := range n.Status.Conditions {
if c.Type == corev1.NodeReady {
ready = string(c.Status)
}
}
h := "ok"
if ready != "True" {
h = "error"
}
f := map[string]string{"ready": ready, "os": n.Status.NodeInfo.OSImage, "kubelet": n.Status.NodeInfo.KubeletVersion, "health": h}
if n.Spec.Unschedulable {
f["unschedulable"] = "true"
}
return f
}
@@ -0,0 +1,175 @@
/*
Copyright 2026 The cluster-map Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package topology
import (
"context"
"testing"
"time"
appsv1 "k8s.io/api/apps/v1"
corev1 "k8s.io/api/core/v1"
networkingv1 "k8s.io/api/networking/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes/fake"
"git.project-chimera.ru/fanchji/cluster-map/internal/kube"
)
func owned(kind, name string) []metav1.OwnerReference {
t := true
return []metav1.OwnerReference{{APIVersion: "apps/v1", Kind: kind, Name: name, Controller: &t}}
}
func TestPodOwner(t *testing.T) {
cases := []struct {
name string
pod corev1.Pod
kind, want string
}{
{"replicaset -> deployment", corev1.Pod{ObjectMeta: metav1.ObjectMeta{OwnerReferences: owned("ReplicaSet", "web-7d9f8c")}}, "deployment", "web"},
{"statefulset", corev1.Pod{ObjectMeta: metav1.ObjectMeta{OwnerReferences: owned("StatefulSet", "db")}}, "statefulset", "db"},
{"cronjob job", corev1.Pod{ObjectMeta: metav1.ObjectMeta{OwnerReferences: owned("Job", "backup-29316120")}}, "cronjob", "backup"},
{"standalone job", corev1.Pod{ObjectMeta: metav1.ObjectMeta{OwnerReferences: owned("Job", "llama-model-download")}}, "job", "llama-model-download"},
{"custom controller", corev1.Pod{ObjectMeta: metav1.ObjectMeta{OwnerReferences: owned("Cluster", "d8ms-pg")}}, "cluster", "d8ms-pg"},
{"static pod", corev1.Pod{
ObjectMeta: metav1.ObjectMeta{Name: "kube-apiserver-master-0", OwnerReferences: owned("Node", "master-0")},
Spec: corev1.PodSpec{NodeName: "master-0"},
}, "staticpod", "kube-apiserver"},
{"bare pod", corev1.Pod{}, "", ""},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
kind, name, _ := PodOwner(c.pod)
if kind != c.kind || name != c.want {
t.Fatalf("got %s/%s, want %s/%s", kind, name, c.kind, c.want)
}
})
}
}
func TestPodOwnerPrefersControllerRef(t *testing.T) {
t.Parallel()
yes := true
p := corev1.Pod{ObjectMeta: metav1.ObjectMeta{OwnerReferences: []metav1.OwnerReference{
{Kind: "ConfigMap", Name: "not-the-controller"},
{Kind: "StatefulSet", Name: "db", Controller: &yes},
}}}
if kind, name, _ := PodOwner(p); kind != "statefulset" || name != "db" {
t.Fatalf("got %s/%s", kind, name)
}
}
func TestSelectorMatches(t *testing.T) {
t.Parallel()
labels := map[string]string{"app": "web", "tier": "front"}
if !SelectorMatches(map[string]string{"app": "web"}, labels) {
t.Error("subset selector should match")
}
if SelectorMatches(map[string]string{"app": "db"}, labels) {
t.Error("different value should not match")
}
if SelectorMatches(nil, labels) {
t.Error("empty selector must not match anything")
}
}
func TestHealth(t *testing.T) {
t.Parallel()
for _, c := range []struct {
want, ready int
out string
}{{0, 0, "idle"}, {2, 2, "ok"}, {2, 0, "error"}, {3, 1, "warn"}} {
if got := Health(c.want, c.ready); got != c.out {
t.Errorf("Health(%d,%d)=%s want %s", c.want, c.ready, got, c.out)
}
}
}
func TestBuildGraph(t *testing.T) {
replicas := int32(2)
pathType := networkingv1.PathTypePrefix
client := fake.NewSimpleClientset(
&corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: "shop"}},
&corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: "d8-system"}},
&appsv1.Deployment{
ObjectMeta: metav1.ObjectMeta{Name: "web", Namespace: "shop"},
Spec: appsv1.DeploymentSpec{Replicas: &replicas, Template: corev1.PodTemplateSpec{
ObjectMeta: metav1.ObjectMeta{Labels: map[string]string{"app": "web"}},
}},
Status: appsv1.DeploymentStatus{ReadyReplicas: 1},
},
&corev1.Service{ObjectMeta: metav1.ObjectMeta{Name: "web", Namespace: "shop"}, Spec: corev1.ServiceSpec{Selector: map[string]string{"app": "web"}}},
&networkingv1.Ingress{ObjectMeta: metav1.ObjectMeta{Name: "web", Namespace: "shop"}, Spec: networkingv1.IngressSpec{Rules: []networkingv1.IngressRule{{
Host: "shop.example.com",
IngressRuleValue: networkingv1.IngressRuleValue{HTTP: &networkingv1.HTTPIngressRuleValue{Paths: []networkingv1.HTTPIngressPath{{
Path: "/", PathType: &pathType,
Backend: networkingv1.IngressBackend{Service: &networkingv1.IngressServiceBackend{Name: "web"}},
}}}},
}}}},
&corev1.Pod{
ObjectMeta: metav1.ObjectMeta{Name: "web-7d9f8c-abcde", Namespace: "shop", OwnerReferences: owned("ReplicaSet", "web-7d9f8c")},
Spec: corev1.PodSpec{NodeName: "node-a"},
},
&corev1.Pod{
ObjectMeta: metav1.ObjectMeta{Name: "pg-1", Namespace: "shop", Labels: map[string]string{"cnpg": "pg"}, OwnerReferences: owned("Cluster", "pg")},
Spec: corev1.PodSpec{NodeName: "node-b"},
Status: corev1.PodStatus{Phase: corev1.PodRunning, Conditions: []corev1.PodCondition{{Type: corev1.PodReady, Status: corev1.ConditionTrue}}},
},
&corev1.Node{ObjectMeta: metav1.ObjectMeta{Name: "node-a"}},
)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
cache, err := kube.Start(ctx, client, nil, 10*time.Second)
if err != nil {
t.Fatal(err)
}
g, err := Build(cache, func(ns string) bool { return ns == "d8-system" })
if err != nil {
t.Fatal(err)
}
nodes := map[string]Node{}
for _, n := range g.Nodes {
nodes[n.ID] = n
}
edges := map[string]string{}
for _, e := range g.Edges {
edges[e.ID] = e.Kind
}
web := nodes["wl/shop/deployment/web"]
if web.Facts["health"] != "warn" || web.Facts["replicas"] != "2" {
t.Errorf("deployment facts: %v", web.Facts)
}
if nodes["ns/d8-system"].Facts["system"] != "true" || nodes["ns/shop"].Facts["system"] != "false" {
t.Error("system namespace classification")
}
pg, ok := nodes["wl/shop/cluster/pg"]
if !ok || pg.Kind != "pod" || pg.Facts["foreign"] != "true" || pg.Facts["ready"] != "1" {
t.Errorf("foreign workload: %+v", pg)
}
for id, kind := range map[string]string{
"wl/shop/deployment/web->service/shop/web": "selects",
"ingress/shop/web->service/shop/web": "routes",
"wl/shop/deployment/web@node-a": "schedules-on",
"wl/shop/cluster/pg@node-b": "schedules-on",
} {
if edges[id] != kind {
t.Errorf("edge %s: got %q want %q", id, edges[id], kind)
}
}
}
@@ -0,0 +1,688 @@
/*
Copyright 2026 The cluster-map Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package topology
import (
"regexp"
"sort"
"strconv"
"strings"
"time"
appsv1 "k8s.io/api/apps/v1"
batchv1 "k8s.io/api/batch/v1"
corev1 "k8s.io/api/core/v1"
networkingv1 "k8s.io/api/networking/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
)
// Severity of a problem, which is the colour of the badge on its card.
const (
Critical = "critical"
Warning = "warning"
Info = "info"
)
// Problem is one reason a card carries a badge. Reason is a stable code the
// UI translates (CrashLoopBackOff, NoEndpoints, an alert name); Message is
// the text Kubernetes or Alertmanager gave, shown as is.
type Problem struct {
Severity string `json:"severity"`
Source string `json:"source"` // alert | state | event
Reason string `json:"reason"`
Message string `json:"message,omitempty"`
Object string `json:"object,omitempty"` // the pod or container it was seen on, when not the card itself
Count int `json:"count,omitempty"` // events folded into this problem
Since string `json:"since,omitempty"` // RFC 3339
}
// Time windows: a restart or a warning event older than this no longer
// marks the card, so a problem fixed an hour ago does not stay red.
var (
now = time.Now
restartWindow = 30 * time.Minute
// A container that keeps restarting stays marked much longer: one
// restart an hour ago is history, the fifth OOM kill in a day is a
// memory limit that is too low. Found when a panel was OOM-killed five
// times in 23 hours and the map showed nothing 40 minutes after the
// last one.
repeatedRestarts int32 = 3
repeatedWindow = 24 * time.Hour
eventWindow = 30 * time.Minute
pendingAfter = 5 * time.Minute
notReadyAfter = 2 * time.Minute // a pod starting or restarting is not yet a problem
maxPerCard = 20
// Warning events that mark a card even when seen once. Any other reason
// (a failed readiness probe during a restart, say) needs eventRepeats
// occurrences in the window; below that it is listed, not badged.
eventNotable = map[string]bool{
"FailedScheduling": true, "FailedMount": true, "FailedAttachVolume": true, "FailedCreate": true,
"FailedCreatePodSandBox": true, "BackOff": true, "Evicted": true, "OOMKilling": true, "FailedKillPod": true,
"ProvisioningFailed": true, "FailedBinding": true, "NetworkNotReady": true, "SystemOOM": true,
}
eventRepeats = 5
// Warnings Kubernetes emits for normal operation. UnexpectedJob comes
// from the CronJob controller for every Job of the CronJob it did not
// schedule itself, i.e. every manual run (kubectl create job --from).
eventBenign = map[string]bool{"UnexpectedJob": true}
waitingCritical = map[string]bool{
"CrashLoopBackOff": true, "ImagePullBackOff": true, "ErrImagePull": true, "InvalidImageName": true,
"CreateContainerConfigError": true, "CreateContainerError": true, "RunContainerError": true,
}
)
var severityRank = map[string]int{Critical: 3, Warning: 2, Info: 1}
// WorstSeverity is the severity of the most serious problem, empty for none.
func WorstSeverity(ps []Problem) string {
worst := ""
for _, p := range ps {
if severityRank[p.Severity] > severityRank[worst] {
worst = p.Severity
}
}
return worst
}
type problemSet struct {
byID map[string][]Problem
cluster []Problem
}
func (s *problemSet) add(id string, p Problem) {
if id == "" {
s.cluster = append(s.cluster, p)
return
}
s.byID[id] = append(s.byID[id], p)
}
type problemInputs struct {
pods []corev1.Pod
deployments []appsv1.Deployment
daemonsets []appsv1.DaemonSet
statefulsets []appsv1.StatefulSet
cronjobs []batchv1.CronJob
services []corev1.Service
ingresses []networkingv1.Ingress
nodes []corev1.Node
events []corev1.Event
alerts []*unstructured.Unstructured
}
// attachProblems fills Node.Problems and Graph.ClusterProblems. Problems
// for an ID the graph has no card for (a bare pod, a deleted object) go to
// the namespace card, and those without a namespace to the cluster list.
func attachProblems(g *Graph, in problemInputs) {
s := &problemSet{byID: map[string][]Problem{}}
podsByNs := map[string][]corev1.Pod{}
podOwner := map[string]string{} // ns/name -> workload ID
notReadySince := map[string]time.Time{} // workload ID -> the longest a pod of it has been not ready
for _, p := range in.pods {
podsByNs[p.Namespace] = append(podsByNs[p.Namespace], p)
id := OwnerWorkloadID(p)
podOwner[p.Namespace+"/"+p.Name] = id
if syntheticProbe(p.Namespace, p.Name) {
continue
}
podProblems(s, p)
if since, ok := notReadyFrom(p); ok && id != "" {
if old, seen := notReadySince[id]; !seen || since.Before(old) {
notReadySince[id] = since
}
}
}
for _, d := range in.deployments {
for _, c := range d.Status.Conditions {
if c.Type == appsv1.DeploymentProgressing && c.Status == corev1.ConditionFalse && c.Reason == "ProgressDeadlineExceeded" {
s.add(WorkloadID(d.Namespace, "deployment", d.Name), Problem{Severity: Critical, Source: "state", Reason: "ProgressDeadlineExceeded", Message: c.Message, Since: stamp(c.LastTransitionTime.Time)})
}
}
}
for _, cj := range in.cronjobs {
cronJobProblems(s, cj)
}
for _, svc := range in.services {
if !syntheticProbe(svc.Namespace, svc.Name) {
serviceProblems(s, svc, podsByNs[svc.Namespace], in)
}
}
services := map[string]bool{}
for _, svc := range in.services {
services[svc.Namespace+"/"+svc.Name] = true
}
for _, ing := range in.ingresses {
if redirects(ing) {
continue
}
for _, name := range IngressBackendServices(ing) {
// Deckhouse's ingress-nginx points its config-reload Ingresses at a
// service that does not exist on purpose
if !services[ing.Namespace+"/"+name] && name != "fakeservice" {
s.add("ingress/"+ing.Namespace+"/"+ing.Name, Problem{Severity: Warning, Source: "state", Reason: "BackendMissing", Object: name})
}
}
}
for _, n := range in.nodes {
nodeProblems(s, n)
}
eventProblems(s, in.events, podOwner, podsLive(in.pods), podsScheduled(in.pods), podsReady(in.pods))
for _, n := range g.Nodes {
if !syntheticProbe(n.Namespace, n.Label) {
readinessProblem(s, n, notReadySince)
}
}
for _, a := range in.alerts {
alertProblem(s, a, podOwner)
}
known := make(map[string]int, len(g.Nodes))
for i, n := range g.Nodes {
known[n.ID] = i
}
for id, ps := range s.byID {
i, ok := known[id]
if !ok {
ns := namespaceOfID(id)
if i, ok = known["ns/"+ns]; !ok {
s.cluster = append(s.cluster, ps...)
continue
}
}
g.Nodes[i].Problems = append(g.Nodes[i].Problems, ps...)
}
for i := range g.Nodes {
g.Nodes[i].Problems = sortProblems(g.Nodes[i].Problems)
if len(g.Nodes[i].Problems) > maxPerCard {
g.Nodes[i].Problems = g.Nodes[i].Problems[:maxPerCard]
}
}
g.ClusterProblems = sortProblems(s.cluster)
if g.ClusterProblems == nil {
g.ClusterProblems = []Problem{}
}
}
func sortProblems(ps []Problem) []Problem {
sort.SliceStable(ps, func(i, j int) bool {
if severityRank[ps[i].Severity] != severityRank[ps[j].Severity] {
return severityRank[ps[i].Severity] > severityRank[ps[j].Severity]
}
return ps[i].Since > ps[j].Since
})
return ps
}
// namespaceOfID reads the namespace out of "wl/<ns>/…", "service/<ns>/…",
// "ingress/<ns>/…" and "ns/<ns>".
func namespaceOfID(id string) string {
parts := strings.SplitN(id, "/", 3)
if len(parts) >= 2 && parts[0] != "node" {
return parts[1]
}
return ""
}
func stamp(t time.Time) string {
if t.IsZero() {
return ""
}
return t.UTC().Format(time.RFC3339)
}
func podProblems(s *problemSet, p corev1.Pod) {
id := OwnerWorkloadID(p)
if id == "" {
id = "ns/" + p.Namespace // a bare pod has no card; its namespace carries the badge
}
if p.Status.Phase == corev1.PodSucceeded {
return
}
if p.Status.Phase == corev1.PodFailed {
if p.Status.Reason == "Evicted" && now().Sub(p.CreationTimestamp.Time) < 24*time.Hour {
s.add(id, Problem{Severity: Warning, Source: "state", Reason: "Evicted", Message: p.Status.Message, Object: p.Name})
}
return
}
statuses := append(append([]corev1.ContainerStatus{}, p.Status.InitContainerStatuses...), p.Status.ContainerStatuses...)
for _, cs := range statuses {
obj := p.Name + "/" + cs.Name
if w := cs.State.Waiting; w != nil && waitingCritical[w.Reason] {
// a crash loop is also a restart; one problem, with the restart count
s.add(id, Problem{Severity: Critical, Source: "state", Reason: w.Reason, Message: w.Message, Object: obj, Count: int(cs.RestartCount)})
continue
}
if t := cs.LastTerminationState.Terminated; t != nil && recentRestart(t.FinishedAt.Time, cs.RestartCount, t.Reason) {
reason := "Restarted"
if t.Reason == "OOMKilled" {
reason = "OOMKilled"
}
s.add(id, Problem{Severity: Warning, Source: "state", Reason: reason, Object: obj, Count: int(cs.RestartCount),
Message: strings.TrimSpace(t.Reason + " exit " + strconv.Itoa(int(t.ExitCode))), Since: stamp(t.FinishedAt.Time)})
}
}
if p.Status.Phase == corev1.PodPending && now().Sub(p.CreationTimestamp.Time) > pendingAfter {
pr := Problem{Severity: Warning, Source: "state", Reason: "Pending", Object: p.Name, Since: stamp(p.CreationTimestamp.Time)}
for _, c := range p.Status.Conditions {
if c.Type == corev1.PodScheduled && c.Status == corev1.ConditionFalse {
pr.Reason, pr.Message = "Unschedulable", c.Message
}
}
s.add(id, pr)
}
}
// cronJobProblems: the last scheduled run ended without success. Job
// objects are not cached, so this reads the CronJob's own status: a
// schedule time later than the last success, with nothing running.
func cronJobProblems(s *problemSet, cj batchv1.CronJob) {
last := cj.Status.LastScheduleTime
if last == nil || len(cj.Status.Active) > 0 {
return
}
ok := cj.Status.LastSuccessfulTime
if ok != nil && !ok.Before(last) {
return
}
s.add(WorkloadID(cj.Namespace, "cronjob", cj.Name), Problem{Severity: Warning, Source: "state", Reason: "LastRunFailed", Since: stamp(last.Time)})
}
func serviceProblems(s *problemSet, svc corev1.Service, pods []corev1.Pod, in problemInputs) {
if len(svc.Spec.Selector) == 0 || svc.Spec.Type == corev1.ServiceTypeExternalName {
return
}
for _, p := range pods {
if podReady(p) && SelectorMatches(svc.Spec.Selector, p.Labels) {
return
}
}
p := Problem{Severity: Warning, Source: "state", Reason: "NoEndpoints"}
if serviceControllersIdle(svc, in) {
p.Severity = Info
p.Message = "No endpoints expected: all matching workload controllers have observed their configuration and currently require zero pods."
}
s.add("service/"+svc.Namespace+"/"+svc.Name, p)
}
// A zero-pod DaemonSet (no eligible nodes), or a scaled-down workload,
// can intentionally leave a Service empty. Unknown/stale state stays WARN.
func serviceControllersIdle(svc corev1.Service, in problemInputs) bool {
found := false
// A matching CronJob may be starting a Job whose pod is not listed yet.
for _, cj := range in.cronjobs {
if cj.Namespace == svc.Namespace && SelectorMatches(svc.Spec.Selector, cj.Spec.JobTemplate.Spec.Template.Labels) {
return false
}
}
for _, ds := range in.daemonsets {
if ds.Namespace != svc.Namespace || !SelectorMatches(svc.Spec.Selector, ds.Spec.Template.Labels) {
continue
}
found = true
if ds.Status.ObservedGeneration < ds.Generation || ds.Status.DesiredNumberScheduled != 0 {
return false
}
}
for _, d := range in.deployments {
if d.Namespace != svc.Namespace || !SelectorMatches(svc.Spec.Selector, d.Spec.Template.Labels) {
continue
}
found = true
if d.Status.ObservedGeneration < d.Generation || d.Spec.Replicas == nil || *d.Spec.Replicas != 0 {
return false
}
}
for _, st := range in.statefulsets {
if st.Namespace != svc.Namespace || !SelectorMatches(svc.Spec.Selector, st.Spec.Template.Labels) {
continue
}
found = true
if st.Status.ObservedGeneration < st.Generation || st.Spec.Replicas == nil || *st.Spec.Replicas != 0 {
return false
}
}
// An unmanaged matching pod could still be genuinely broken.
for _, p := range in.pods {
if p.Namespace == svc.Namespace && SelectorMatches(svc.Spec.Selector, p.Labels) && p.DeletionTimestamp == nil && p.Status.Phase != corev1.PodSucceeded {
return false
}
}
return found
}
func nodeProblems(s *problemSet, n corev1.Node) {
id := "node/" + n.Name
for _, c := range n.Status.Conditions {
switch {
case c.Type == corev1.NodeReady && c.Status != corev1.ConditionTrue:
s.add(id, Problem{Severity: Critical, Source: "state", Reason: "NodeNotReady", Message: c.Message, Since: stamp(c.LastTransitionTime.Time)})
case (c.Type == corev1.NodeMemoryPressure || c.Type == corev1.NodeDiskPressure || c.Type == corev1.NodePIDPressure) && c.Status == corev1.ConditionTrue:
s.add(id, Problem{Severity: Warning, Source: "state", Reason: string(c.Type), Message: c.Message, Since: stamp(c.LastTransitionTime.Time)})
}
}
if n.Spec.Unschedulable {
s.add(id, Problem{Severity: Info, Source: "state", Reason: "Cordoned"})
}
}
// eventTime is when an event last happened, whichever field the emitter set.
func eventTime(e corev1.Event) time.Time {
switch {
case e.Series != nil && !e.Series.LastObservedTime.IsZero():
return e.Series.LastObservedTime.Time
case !e.LastTimestamp.IsZero():
return e.LastTimestamp.Time
case !e.EventTime.IsZero():
return e.EventTime.Time
}
return e.CreationTimestamp.Time
}
// EventTargetID maps an event's involved object to a card ID, the way pods
// and their controllers map to workloads.
func EventTargetID(ref corev1.ObjectReference, podOwner map[string]string) string {
ns := ref.Namespace
switch ref.Kind {
case "Pod":
if id := podOwner[ns+"/"+ref.Name]; id != "" {
return id
}
return "ns/" + ns
case "ReplicaSet":
if i := strings.LastIndex(ref.Name, "-"); i > 0 {
return WorkloadID(ns, "deployment", ref.Name[:i])
}
case "Deployment", "StatefulSet", "DaemonSet", "CronJob":
return WorkloadID(ns, strings.ToLower(ref.Kind), ref.Name)
case "Job":
if cj, ok := CronJobFromJob(ref.Name); ok {
return WorkloadID(ns, "cronjob", cj)
}
case "Service":
return "service/" + ns + "/" + ref.Name
case "Ingress":
return "ingress/" + ns + "/" + ref.Name
case "Node":
return "node/" + ref.Name
}
if ns != "" {
return "ns/" + ns
}
return ""
}
// eventsInWindow estimates how many occurrences of an event fell in the
// window. The event's count is cumulative since its first occurrence: 40
// probe failures over two days is one an hour, not 40 in half an hour, so
// a long-lived event is scaled by the part of its lifetime the window
// covers.
func eventsInWindow(e corev1.Event, last time.Time) int {
count := int(e.Count)
if e.Series != nil {
count = int(e.Series.Count)
}
count = max(count, 1)
first := e.FirstTimestamp.Time
if first.IsZero() {
first = e.EventTime.Time
}
span := last.Sub(first)
if first.IsZero() || span <= eventWindow {
return count
}
return max(1, int(float64(count)*float64(eventWindow)/float64(span)+0.5))
}
// eventProblems folds recent Warning events into one problem per card and
// reason, keeping the latest message.
func eventProblems(s *problemSet, events []corev1.Event, podOwner map[string]string, live, scheduled, ready map[string]bool) {
type key struct{ id, reason string }
folded := map[key]*Problem{}
var order []key
for _, e := range events {
at := eventTime(e)
if e.Type != corev1.EventTypeWarning || now().Sub(at) > eventWindow || syntheticProbe(e.InvolvedObject.Namespace, e.InvolvedObject.Name) {
continue
}
id := EventTargetID(e.InvolvedObject, podOwner)
k := key{id, e.Reason}
count := eventsInWindow(e, at)
if p := folded[k]; p != nil {
p.Count += count
if stamp(at) > p.Since {
p.Since, p.Message, p.Object = stamp(at), e.Message, eventObject(e.InvolvedObject)
}
continue
}
folded[k] = &Problem{Severity: Warning, Source: "event", Reason: e.Reason, Message: e.Message, Object: eventObject(e.InvolvedObject), Count: count, Since: stamp(at)}
order = append(order, k)
}
for _, k := range order {
p := folded[k]
pod := namespaceOfID(k.id) + "/" + p.Object
// A pod that is running and ready already has its volumes: a
// FailedMount then is kubelet failing to refresh one, e.g. a
// ConfigMap prometheus-operator deletes and recreates. Once is
// noise; it has to repeat like any other event.
notable := eventNotable[p.Reason] && (p.Reason != "FailedMount" || !ready[pod])
if eventBenign[p.Reason] || (!notable && p.Count < eventRepeats) {
p.Severity = Info
}
// A failed probe of a pod that is ready now: the pod's own state
// already says more. Deckhouse answers /readyz with 500 while it
// works through its queue after a module change, and its probe
// tolerates 10 minutes of that (failureThreshold 120); a NotReady
// pod is reported from its state, a failed liveness probe as a
// restart.
if p.Reason == "Unhealthy" && ready[pod] {
p.Severity = Info
}
// the pod the latest event was about is gone: history, not state
if p.Object != "" && !live[pod] {
p.Severity = Info
}
// it could not be scheduled, but has been since: a CronJob pod
// that waited all night for its node to come back, then ran
if p.Reason == "FailedScheduling" && scheduled[pod] {
p.Severity = Info
}
s.add(k.id, *p)
}
}
// readinessProblem turns the card's own health into a problem, so a
// workload with nothing ready is red even when no pod says why. It waits
// notReadyAfter for its pods, so a rollout or a restart does not flash.
// A workload short of replicas with no pod at all (none could be created)
// is reported at once.
func readinessProblem(s *problemSet, n Node, notReadySince map[string]time.Time) {
if !nativeKinds[n.Kind] && n.Facts["foreign"] != "true" {
return
}
if since, ok := notReadySince[n.ID]; ok && now().Sub(since) < notReadyAfter {
return
}
switch n.Facts["health"] {
case "error":
s.add(n.ID, Problem{Severity: Critical, Source: "state", Reason: "NotReady"})
case "warn":
s.add(n.ID, Problem{Severity: Warning, Source: "state", Reason: "PartlyReady"})
}
}
// redirects reports whether an Ingress answers with a redirect instead of
// proxying, so its backends are never used. Deckhouse's prometheus module
// routes prometheus.<domain> to a Service that does not exist and sends
// every request to grafana.<domain> from a configuration snippet.
func redirects(ing networkingv1.Ingress) bool {
a := ing.Annotations
if a["nginx.ingress.kubernetes.io/permanent-redirect"] != "" || a["nginx.ingress.kubernetes.io/temporal-redirect"] != "" {
return true
}
for _, key := range []string{"nginx.ingress.kubernetes.io/configuration-snippet", "nginx.ingress.kubernetes.io/server-snippet"} {
if redirectSnippet.MatchString(a[key]) {
return true
}
}
return false
}
var redirectSnippet = regexp.MustCompile(`(?m)\brewrite\s+\S+\s+\S+\s+(permanent|redirect)\s*;|\breturn\s+30[1278]\b`)
// podsLive: pods whose warnings still describe the present. A pod that
// finished successfully is history, like one that is gone.
func podsLive(pods []corev1.Pod) map[string]bool {
out := make(map[string]bool, len(pods))
for _, p := range pods {
if p.Status.Phase != corev1.PodSucceeded {
out[p.Namespace+"/"+p.Name] = true
}
}
return out
}
func podsReady(pods []corev1.Pod) map[string]bool {
out := make(map[string]bool, len(pods))
for _, p := range pods {
for _, c := range p.Status.Conditions {
if c.Type == corev1.PodReady && c.Status == corev1.ConditionTrue {
out[p.Namespace+"/"+p.Name] = true
}
}
}
return out
}
func podsScheduled(pods []corev1.Pod) map[string]bool {
out := make(map[string]bool, len(pods))
for _, p := range pods {
if p.Spec.NodeName != "" {
out[p.Namespace+"/"+p.Name] = true
}
}
return out
}
// syntheticProbe: upmeter, Deckhouse's availability monitor, creates short
// lived StatefulSets and pods named upmeter-probe-* that are unschedulable
// on purpose (it measures how fast the control plane reacts). Their
// FailedScheduling and NotReady are the probe working, not a problem.
//
// smoke-mini-a…e are upmeter's synthetic service: upmeter moves their pods
// between nodes on purpose, so the Service goes without endpoints and the
// pods restart as part of the test. upmeter reports that availability
// itself.
func syntheticProbe(ns, name string) bool {
return ns == "d8-upmeter" && (strings.HasPrefix(name, "upmeter-probe-") || strings.HasPrefix(name, "smoke-mini-"))
}
// notReadyFrom is when a running or pending pod stopped being ready (or
// was created, if it never was); ok is false for ready and finished pods.
func notReadyFrom(p corev1.Pod) (time.Time, bool) {
if p.Status.Phase == corev1.PodSucceeded || p.Status.Phase == corev1.PodFailed || p.DeletionTimestamp != nil {
return time.Time{}, false
}
for _, c := range p.Status.Conditions {
if c.Type == corev1.PodReady {
if c.Status == corev1.ConditionTrue {
return time.Time{}, false
}
if !c.LastTransitionTime.IsZero() {
return c.LastTransitionTime.Time, true
}
}
}
return p.CreationTimestamp.Time, true
}
func eventObject(ref corev1.ObjectReference) string {
if ref.Kind == "Pod" {
return ref.Name
}
return ""
}
// AlertSeverity maps Deckhouse's severity_level (1 is the most severe) to a
// badge colour.
func AlertSeverity(level string) string {
n, err := strconv.Atoi(strings.TrimSpace(level))
switch {
case err != nil:
return Warning
case n <= 3:
return Critical
case n <= 6:
return Warning
}
return Info
}
// AlertTargetID picks the card an alert is about from its labels, most
// specific first. Unknown objects fall back to the namespace, alerts
// without a namespace to the cluster.
func AlertTargetID(labels map[string]string, podOwner map[string]string) string {
ns := labels["namespace"]
if n := labels["node"]; n != "" && ns == "" {
return "node/" + n
}
if ns == "" {
return ""
}
for _, kind := range []string{"deployment", "statefulset", "daemonset", "cronjob"} {
if name := labels[kind]; name != "" {
return WorkloadID(ns, kind, name)
}
}
if pod := labels["pod"]; pod != "" {
if id := podOwner[ns+"/"+pod]; id != "" {
return id
}
}
if job := labels["job_name"]; job != "" {
if cj, ok := CronJobFromJob(job); ok {
return WorkloadID(ns, "cronjob", cj)
}
}
if svc := labels["service"]; svc != "" {
return "service/" + ns + "/" + svc
}
if ing := labels["ingress"]; ing != "" {
return "ingress/" + ns + "/" + ing
}
return "ns/" + ns
}
func alertProblem(s *problemSet, a *unstructured.Unstructured, podOwner map[string]string) {
if st, _, _ := unstructured.NestedString(a.Object, "status", "alertStatus"); st != "" && st != "firing" {
return
}
name, _, _ := unstructured.NestedString(a.Object, "alert", "name")
summary, _, _ := unstructured.NestedString(a.Object, "alert", "summary")
level, _, _ := unstructured.NestedString(a.Object, "alert", "severityLevel")
labels, _, _ := unstructured.NestedStringMap(a.Object, "alert", "labels")
since, _, _ := unstructured.NestedString(a.Object, "status", "startsAt")
s.add(AlertTargetID(labels, podOwner), Problem{Severity: AlertSeverity(level), Source: "alert", Reason: name, Message: strings.TrimSpace(summary), Since: since})
}
// recentRestart includes recent restarts and the extended OOM diagnostic.
func recentRestart(finished time.Time, restarts int32, reason string) bool {
age := now().Sub(finished)
// The count is lifetime, not a rate. A reboot can increment an old
// count without proving repeated recent failures. Keep the extended
// memory-pressure diagnostic only for an observed OOM termination.
return age < restartWindow || (reason == "OOMKilled" && restarts >= repeatedRestarts && age < repeatedWindow)
}
@@ -0,0 +1,372 @@
/*
Copyright 2026 The cluster-map Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package topology
import (
"testing"
"time"
appsv1 "k8s.io/api/apps/v1"
batchv1 "k8s.io/api/batch/v1"
corev1 "k8s.io/api/core/v1"
networkingv1 "k8s.io/api/networking/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
)
var t0 = time.Date(2026, 9, 24, 12, 0, 0, 0, time.UTC)
func TestLifetimeRestartCountDoesNotExtendOrdinaryRestartWindow(t *testing.T) {
withNow(t)
for _, reason := range []string{"Unknown", "Error", "Completed"} {
t.Run(reason, func(t *testing.T) {
g := &Graph{Nodes: []Node{{ID: "ns/system"}}}
attachProblems(g, problemInputs{pods: []corev1.Pod{{ObjectMeta: metav1.ObjectMeta{Name: "recovered", Namespace: "system"}, Status: corev1.PodStatus{Phase: corev1.PodRunning, Conditions: []corev1.PodCondition{{Type: corev1.PodReady, Status: corev1.ConditionTrue}}, ContainerStatuses: []corev1.ContainerStatus{{Name: "app", RestartCount: 12, LastTerminationState: corev1.ContainerState{Terminated: &corev1.ContainerStateTerminated{Reason: reason, FinishedAt: metav1.NewTime(t0.Add(-40 * time.Minute))}}}}}}}})
if p, ok := problemsOf(g, "ns/system")["Restarted"]; ok {
t.Fatalf("lifetime count treated as recent recurrence: %+v", p)
}
})
}
}
func withNow(t *testing.T) {
t.Helper()
old := now
now = func() time.Time { return t0 }
t.Cleanup(func() { now = old })
}
func ingressTo(ns, name, svc string) networkingv1.Ingress {
return networkingv1.Ingress{ObjectMeta: metav1.ObjectMeta{Name: name, Namespace: ns}, Spec: networkingv1.IngressSpec{
DefaultBackend: &networkingv1.IngressBackend{Service: &networkingv1.IngressServiceBackend{Name: svc}},
}}
}
func problemsOf(g *Graph, id string) map[string]Problem {
out := map[string]Problem{}
for _, n := range g.Nodes {
if n.ID == id {
for _, p := range n.Problems {
out[p.Reason] = p
}
}
}
return out
}
func TestProblemsFromState(t *testing.T) {
withNow(t)
ready := []corev1.PodCondition{{Type: corev1.PodReady, Status: corev1.ConditionTrue}}
g := &Graph{Nodes: []Node{
{ID: "ns/shop"}, {ID: "wl/shop/deployment/web", Kind: "deployment", Facts: map[string]string{"health": "warn"}}, {ID: "wl/shop/deployment/api", Kind: "deployment"}, {ID: "service/shop/web"}, {ID: "service/shop/idle"},
{ID: "ingress/shop/web"}, {ID: "wl/shop/cronjob/backup"}, {ID: "node/node-a"},
}}
in := problemInputs{
pods: []corev1.Pod{
{ // crash-looping, restarted 10 min ago
ObjectMeta: metav1.ObjectMeta{Name: "web-5f-a", Namespace: "shop", Labels: map[string]string{"app": "web"}, OwnerReferences: owned("ReplicaSet", "web-5f")},
Status: corev1.PodStatus{Phase: corev1.PodRunning, ContainerStatuses: []corev1.ContainerStatus{{
Name: "app", RestartCount: 7,
State: corev1.ContainerState{Waiting: &corev1.ContainerStateWaiting{Reason: "CrashLoopBackOff"}},
LastTerminationState: corev1.ContainerState{Terminated: &corev1.ContainerStateTerminated{Reason: "Error", ExitCode: 1, FinishedAt: metav1.NewTime(t0.Add(-10 * time.Minute))}},
}}},
},
{ // ready, OOM-killed long ago: no problem
ObjectMeta: metav1.ObjectMeta{Name: "web-5f-b", Namespace: "shop", Labels: map[string]string{"app": "web"}, OwnerReferences: owned("ReplicaSet", "web-5f")},
Status: corev1.PodStatus{Phase: corev1.PodRunning, Conditions: ready, ContainerStatuses: []corev1.ContainerStatus{{
Name: "app", LastTerminationState: corev1.ContainerState{Terminated: &corev1.ContainerStateTerminated{Reason: "OOMKilled", FinishedAt: metav1.NewTime(t0.Add(-3 * time.Hour))}},
}}},
},
{ // OOM-killed five times, the last 70 minutes ago: still a problem
ObjectMeta: metav1.ObjectMeta{Name: "api-7c-a", Namespace: "shop", Labels: map[string]string{"app": "api"}, OwnerReferences: owned("ReplicaSet", "api-7c")},
Status: corev1.PodStatus{Phase: corev1.PodRunning, Conditions: ready, ContainerStatuses: []corev1.ContainerStatus{{
Name: "app", RestartCount: 5,
LastTerminationState: corev1.ContainerState{Terminated: &corev1.ContainerStateTerminated{Reason: "OOMKilled", ExitCode: 137, FinishedAt: metav1.NewTime(t0.Add(-70 * time.Minute))}},
}}},
},
{ // bare pod pending for 10 minutes: badge on the namespace
ObjectMeta: metav1.ObjectMeta{Name: "debug", Namespace: "shop", CreationTimestamp: metav1.NewTime(t0.Add(-10 * time.Minute))},
Status: corev1.PodStatus{Phase: corev1.PodPending, Conditions: []corev1.PodCondition{{Type: corev1.PodScheduled, Status: corev1.ConditionFalse, Message: "0/3 nodes are available"}}},
},
},
services: []corev1.Service{
{ObjectMeta: metav1.ObjectMeta{Name: "web", Namespace: "shop"}, Spec: corev1.ServiceSpec{Selector: map[string]string{"app": "web"}}},
{ObjectMeta: metav1.ObjectMeta{Name: "idle", Namespace: "shop"}, Spec: corev1.ServiceSpec{Selector: map[string]string{"app": "gone"}}},
},
ingresses: []networkingv1.Ingress{ingressTo("shop", "web", "missing")},
cronjobs: []batchv1.CronJob{{
ObjectMeta: metav1.ObjectMeta{Name: "backup", Namespace: "shop"},
Status: batchv1.CronJobStatus{LastScheduleTime: &metav1.Time{Time: t0.Add(-time.Hour)}, LastSuccessfulTime: &metav1.Time{Time: t0.Add(-25 * time.Hour)}},
}},
nodes: []corev1.Node{{
ObjectMeta: metav1.ObjectMeta{Name: "node-a"}, Spec: corev1.NodeSpec{Unschedulable: true},
Status: corev1.NodeStatus{Conditions: []corev1.NodeCondition{{Type: corev1.NodeReady, Status: corev1.ConditionTrue}, {Type: corev1.NodeDiskPressure, Status: corev1.ConditionTrue}}},
}},
deployments: []appsv1.Deployment{},
}
attachProblems(g, in)
web := problemsOf(g, "wl/shop/deployment/web")
if p := web["CrashLoopBackOff"]; p.Severity != Critical || p.Object != "web-5f-a/app" || p.Count != 7 {
t.Errorf("crash loop: %+v", web)
}
if web["PartlyReady"].Severity != Warning {
t.Errorf("partly ready workload: %+v", web)
}
if _, ok := web["Restarted"]; ok {
t.Error("a crash loop is reported once, not also as a restart")
}
if _, ok := web["OOMKilled"]; ok {
t.Error("an OOM kill three hours ago must not mark the card")
}
if p := problemsOf(g, "wl/shop/deployment/api")["OOMKilled"]; p.Severity != Warning || p.Count != 5 {
t.Errorf("repeated OOM kills 70 minutes ago: %+v", problemsOf(g, "wl/shop/deployment/api"))
}
if _, ok := problemsOf(g, "service/shop/web")["NoEndpoints"]; ok {
t.Error("service with a ready pod reported without endpoints")
}
if _, ok := problemsOf(g, "service/shop/idle")["NoEndpoints"]; !ok {
t.Error("service selecting nothing not reported")
}
if p := problemsOf(g, "ingress/shop/web")["BackendMissing"]; p.Object != "missing" {
t.Errorf("ingress to a missing service: %+v", p)
}
if _, ok := problemsOf(g, "wl/shop/cronjob/backup")["LastRunFailed"]; !ok {
t.Error("cronjob whose last run did not succeed")
}
if p := problemsOf(g, "ns/shop")["Unschedulable"]; p.Message == "" {
t.Errorf("bare pending pod on the namespace: %+v", problemsOf(g, "ns/shop"))
}
node := problemsOf(g, "node/node-a")
if node["DiskPressure"].Severity != Warning || node["Cordoned"].Severity != Info {
t.Errorf("node: %+v", node)
}
if got := g.Nodes[1].Problems[0].Severity; got != Critical {
t.Errorf("critical first, got %s", got)
}
}
func TestReadinessGraceAndProbes(t *testing.T) {
withNow(t)
notReady := func(name string, since time.Duration) corev1.Pod {
return corev1.Pod{
ObjectMeta: metav1.ObjectMeta{Name: name, Namespace: "shop", OwnerReferences: owned("ReplicaSet", name[:len(name)-2])},
Status: corev1.PodStatus{Phase: corev1.PodRunning, Conditions: []corev1.PodCondition{
{Type: corev1.PodReady, Status: corev1.ConditionFalse, LastTransitionTime: metav1.NewTime(t0.Add(-since))}}},
}
}
g := &Graph{Nodes: []Node{
{ID: "ns/shop"}, {ID: "ns/d8-upmeter"},
{ID: "wl/shop/deployment/fresh", Kind: "deployment", Facts: map[string]string{"health": "error"}},
{ID: "wl/shop/deployment/stuck", Kind: "deployment", Facts: map[string]string{"health": "error"}},
{ID: "wl/shop/deployment/nopods", Kind: "deployment", Facts: map[string]string{"health": "error"}},
}}
attachProblems(g, problemInputs{
pods: []corev1.Pod{notReady("fresh-5f-a", 30*time.Second), notReady("stuck-5f-a", 10*time.Minute)},
events: []corev1.Event{{Type: corev1.EventTypeWarning, Reason: "FailedScheduling", LastTimestamp: metav1.NewTime(t0),
InvolvedObject: corev1.ObjectReference{Kind: "Pod", Namespace: "d8-upmeter", Name: "upmeter-probe-controller-manager-9b2cc8b5-0"}}},
})
if _, ok := problemsOf(g, "wl/shop/deployment/fresh")["NotReady"]; ok {
t.Error("a pod not ready for 30 seconds marks the card")
}
if _, ok := problemsOf(g, "wl/shop/deployment/stuck")["NotReady"]; !ok {
t.Error("a pod not ready for 10 minutes does not mark the card")
}
if _, ok := problemsOf(g, "wl/shop/deployment/nopods")["NotReady"]; !ok {
t.Error("a workload with no pod at all must be reported")
}
if len(problemsOf(g, "ns/d8-upmeter")) != 0 {
t.Error("upmeter's synthetic probe reported as a problem")
}
}
func TestRedirectIngressAndGonePods(t *testing.T) {
withNow(t)
redirect := ingressTo("d8-monitoring", "grafana-v10", "grafana")
redirect.Annotations = map[string]string{"nginx.ingress.kubernetes.io/configuration-snippet": "if ($host = 'prometheus.example.com' ) {\n rewrite ^ https://grafana.example.com$request_uri permanent;\n}\n"}
g := &Graph{Nodes: []Node{{ID: "ns/shop"}, {ID: "ingress/d8-monitoring/grafana-v10"}, {ID: "wl/shop/deployment/web"}}}
attachProblems(g, problemInputs{
ingresses: []networkingv1.Ingress{redirect},
pods: []corev1.Pod{{ObjectMeta: metav1.ObjectMeta{Name: "web-5f-live", Namespace: "shop", OwnerReferences: owned("ReplicaSet", "web-5f")}}},
events: []corev1.Event{
{Type: corev1.EventTypeWarning, Reason: "FailedMount", LastTimestamp: metav1.NewTime(t0), InvolvedObject: corev1.ObjectReference{Kind: "Pod", Namespace: "shop", Name: "web-5f-live"}},
{Type: corev1.EventTypeWarning, Reason: "Failed", Count: 10, LastTimestamp: metav1.NewTime(t0), InvolvedObject: corev1.ObjectReference{Kind: "Pod", Namespace: "shop", Name: "verify-gone"}},
{Type: corev1.EventTypeWarning, Reason: "UnexpectedJob", Count: 6, LastTimestamp: metav1.NewTime(t0), InvolvedObject: corev1.ObjectReference{Kind: "CronJob", Namespace: "shop", Name: "backup"}},
},
})
if p := problemsOf(g, "ns/shop")["UnexpectedJob"]; p.Severity != Info {
t.Errorf("a manual CronJob run is not a problem: %+v", p)
}
if len(problemsOf(g, "ingress/d8-monitoring/grafana-v10")) != 0 {
t.Error("a redirecting Ingress reported for its unused backend")
}
if problemsOf(g, "wl/shop/deployment/web")["FailedMount"].Severity != Warning {
t.Error("event of a live pod must badge")
}
// the same pod once it is ready: a single FailedMount is a volume refresh
g2 := &Graph{Nodes: []Node{{ID: "ns/shop"}, {ID: "wl/shop/deployment/web"}}}
attachProblems(g2, problemInputs{
pods: []corev1.Pod{{ObjectMeta: metav1.ObjectMeta{Name: "web-5f-live", Namespace: "shop", OwnerReferences: owned("ReplicaSet", "web-5f")},
Status: corev1.PodStatus{Phase: corev1.PodRunning, Conditions: []corev1.PodCondition{{Type: corev1.PodReady, Status: corev1.ConditionTrue}}}}},
events: []corev1.Event{
{Type: corev1.EventTypeWarning, Reason: "FailedMount", LastTimestamp: metav1.NewTime(t0), InvolvedObject: corev1.ObjectReference{Kind: "Pod", Namespace: "shop", Name: "web-5f-live"}},
{Type: corev1.EventTypeWarning, Reason: "Unhealthy", Count: 11, LastTimestamp: metav1.NewTime(t0), InvolvedObject: corev1.ObjectReference{Kind: "Pod", Namespace: "shop", Name: "web-5f-live"}},
},
})
if p := problemsOf(g2, "wl/shop/deployment/web")["Unhealthy"]; p.Severity != Info {
t.Errorf("failed probes of a pod that is ready must be information: %+v", p)
}
if p := problemsOf(g2, "wl/shop/deployment/web")["FailedMount"]; p.Severity != Info {
t.Errorf("one FailedMount of a ready pod must be information: %+v", p)
}
if p := problemsOf(g, "ns/shop")["Failed"]; p.Severity != Info {
t.Errorf("event of a deleted pod must be information: %+v", p)
}
}
func TestEventRateAndSmokeMini(t *testing.T) {
withNow(t)
g := &Graph{Nodes: []Node{{ID: "ns/shop"}, {ID: "ns/d8-upmeter"}, {ID: "wl/shop/deployment/auth"}, {ID: "wl/shop/deployment/burst"}, {ID: "service/d8-upmeter/smoke-mini-a"}}}
attachProblems(g, problemInputs{
pods: []corev1.Pod{
{ObjectMeta: metav1.ObjectMeta{Name: "auth-5f-a", Namespace: "shop", OwnerReferences: owned("ReplicaSet", "auth-5f")}},
{ObjectMeta: metav1.ObjectMeta{Name: "burst-5f-a", Namespace: "shop", OwnerReferences: owned("ReplicaSet", "burst-5f")}},
},
services: []corev1.Service{{ObjectMeta: metav1.ObjectMeta{Name: "smoke-mini-a", Namespace: "d8-upmeter"}, Spec: corev1.ServiceSpec{Selector: map[string]string{"smoke-mini": "a"}}}},
events: []corev1.Event{
// 40 over two days: about one an hour
{Type: corev1.EventTypeWarning, Reason: "Unhealthy", Count: 40, FirstTimestamp: metav1.NewTime(t0.Add(-48 * time.Hour)), LastTimestamp: metav1.NewTime(t0.Add(-time.Minute)),
InvolvedObject: corev1.ObjectReference{Kind: "Pod", Namespace: "shop", Name: "auth-5f-a"}},
// 12 within ten minutes
{Type: corev1.EventTypeWarning, Reason: "Unhealthy", Count: 12, FirstTimestamp: metav1.NewTime(t0.Add(-10 * time.Minute)), LastTimestamp: metav1.NewTime(t0.Add(-time.Minute)),
InvolvedObject: corev1.ObjectReference{Kind: "Pod", Namespace: "shop", Name: "burst-5f-a"}},
{Type: corev1.EventTypeWarning, Reason: "FailedMount", LastTimestamp: metav1.NewTime(t0), InvolvedObject: corev1.ObjectReference{Kind: "Pod", Namespace: "d8-upmeter", Name: "smoke-mini-c-0"}},
},
})
if p := problemsOf(g, "wl/shop/deployment/auth")["Unhealthy"]; p.Severity != Info || p.Count > 2 {
t.Errorf("a slow trickle over two days must be information: %+v", p)
}
if p := problemsOf(g, "wl/shop/deployment/burst")["Unhealthy"]; p.Severity != Warning || p.Count != 12 {
t.Errorf("a burst inside the window must badge: %+v", p)
}
if len(problemsOf(g, "service/d8-upmeter/smoke-mini-a"))+len(problemsOf(g, "ns/d8-upmeter")) != 0 {
t.Error("upmeter's smoke-mini reported as a problem")
}
}
func alert(name, level string, labels map[string]string) *unstructured.Unstructured {
l := map[string]any{}
for k, v := range labels {
l[k] = v
}
return &unstructured.Unstructured{Object: map[string]any{
"alert": map[string]any{"name": name, "severityLevel": level, "summary": "summary of " + name, "labels": l},
"status": map[string]any{"alertStatus": "firing", "startsAt": "2026-09-24T10:00:00Z"},
}}
}
func TestAlertsAndEvents(t *testing.T) {
withNow(t)
g := &Graph{Nodes: []Node{{ID: "ns/shop"}, {ID: "wl/shop/deployment/web"}, {ID: "node/node-a"}}}
in := problemInputs{
pods: []corev1.Pod{{ObjectMeta: metav1.ObjectMeta{Name: "web-5f-a", Namespace: "shop", OwnerReferences: owned("ReplicaSet", "web-5f")}}},
alerts: []*unstructured.Unstructured{
alert("KubernetesDeploymentReplicasUnavailable", "3", map[string]string{"namespace": "shop", "deployment": "web"}),
alert("PodHighMemory", "5", map[string]string{"namespace": "shop", "pod": "web-5f-a"}),
alert("NamespaceQuota", "6", map[string]string{"namespace": "shop"}),
alert("NodeDiskFull", "4", map[string]string{"node": "node-a"}),
alert("ModuleConfigObsoleteVersion", "4", map[string]string{"name": "operator-trivy"}),
alert("GoneNamespace", "4", map[string]string{"namespace": "deleted"}),
},
events: []corev1.Event{
{Type: corev1.EventTypeWarning, Reason: "ProbeWarning", Count: 1, InvolvedObject: corev1.ObjectReference{Kind: "Node", Name: "node-a"}, LastTimestamp: metav1.NewTime(t0.Add(-time.Minute))},
{Type: corev1.EventTypeWarning, Reason: "Unhealthy", Message: "old", Count: 2, InvolvedObject: corev1.ObjectReference{Kind: "Pod", Namespace: "shop", Name: "web-5f-a"}, LastTimestamp: metav1.NewTime(t0.Add(-20 * time.Minute))},
{Type: corev1.EventTypeWarning, Reason: "Unhealthy", Message: "latest", Count: 3, InvolvedObject: corev1.ObjectReference{Kind: "Pod", Namespace: "shop", Name: "web-5f-a"}, LastTimestamp: metav1.NewTime(t0.Add(-time.Minute))},
{Type: corev1.EventTypeWarning, Reason: "FailedMount", InvolvedObject: corev1.ObjectReference{Kind: "Pod", Namespace: "shop", Name: "web-5f-a"}, LastTimestamp: metav1.NewTime(t0.Add(-2 * time.Hour))},
},
}
attachProblems(g, in)
web := problemsOf(g, "wl/shop/deployment/web")
if web["KubernetesDeploymentReplicasUnavailable"].Severity != Critical || web["PodHighMemory"].Severity != Warning {
t.Errorf("alerts on the workload: %+v", web)
}
if p := web["Unhealthy"]; p.Count != 5 || p.Message != "latest" || p.Severity != Warning {
t.Errorf("folded events: %+v", p)
}
if _, ok := web["FailedMount"]; ok {
t.Error("a warning two hours old must not mark the card")
}
if _, ok := problemsOf(g, "ns/shop")["NamespaceQuota"]; !ok {
t.Error("namespace-level alert")
}
if _, ok := problemsOf(g, "node/node-a")["NodeDiskFull"]; !ok {
t.Error("node alert")
}
if p := problemsOf(g, "node/node-a")["ProbeWarning"]; p.Severity != Info {
t.Errorf("a single ordinary warning is listed, not badged: %+v", p)
}
cluster := map[string]bool{}
for _, p := range g.ClusterProblems {
cluster[p.Reason] = true
}
if !cluster["ModuleConfigObsoleteVersion"] || !cluster["GoneNamespace"] || len(g.ClusterProblems) != 2 {
t.Errorf("cluster problems: %+v", g.ClusterProblems)
}
}
func TestAlertSeverity(t *testing.T) {
for level, want := range map[string]string{"1": Critical, "3": Critical, "4": Warning, "6": Warning, "7": Info, "": Warning} {
if got := AlertSeverity(level); got != want {
t.Errorf("level %q: %s, want %s", level, got, want)
}
}
}
func TestScheduledAndFinishedPodEvents(t *testing.T) {
withNow(t)
pod := func(name string, node string, phase corev1.PodPhase) corev1.Pod {
return corev1.Pod{ObjectMeta: metav1.ObjectMeta{Name: name, Namespace: "games", OwnerReferences: owned("Job", name[:len(name)-2])},
Spec: corev1.PodSpec{NodeName: node}, Status: corev1.PodStatus{Phase: phase}}
}
warn := func(reason, podName string) corev1.Event {
return corev1.Event{Type: corev1.EventTypeWarning, Reason: reason, Count: 28, LastTimestamp: metav1.NewTime(t0),
InvolvedObject: corev1.ObjectReference{Kind: "Pod", Namespace: "games", Name: podName}}
}
g := &Graph{Nodes: []Node{{ID: "ns/games"}}}
attachProblems(g, problemInputs{
pods: []corev1.Pod{
pod("waited-a", "games-vm", corev1.PodSucceeded), // waited for its node overnight, then ran
pod("stuck-a", "", corev1.PodPending), // still cannot be placed
pod("done-a", "xeon", corev1.PodSucceeded),
},
events: []corev1.Event{warn("FailedScheduling", "waited-a"), warn("FailedScheduling", "stuck-a"), warn("FailedMount", "done-a")},
})
var stuck, waited, done bool
for _, p := range g.Nodes[0].Problems {
switch p.Object {
case "stuck-a":
stuck = p.Severity == Warning
case "waited-a":
waited = p.Severity == Info
case "done-a":
done = p.Severity == Info
}
}
if !stuck || !waited || !done {
t.Errorf("pending pod must badge, scheduled or finished must not (stuck=%v waited=%v done=%v): %+v", stuck, waited, done, g.Nodes[0].Problems)
}
}
@@ -0,0 +1,62 @@
package topology
import (
"testing"
appsv1 "k8s.io/api/apps/v1"
batchv1 "k8s.io/api/batch/v1"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
func TestServiceWithoutEndpointsExpectedZero(t *testing.T) {
for _, tc := range []struct {
name string
desired int32
observed int64
activeDeployment bool
want string
}{
{"idle-daemonset", 0, 3, false, Info},
{"missing-daemonset-pod", 1, 3, false, Warning},
{"stale-controller-status", 0, 2, false, Warning},
{"another-active-controller", 0, 3, true, Warning},
} {
t.Run(tc.name, func(t *testing.T) {
labels := map[string]string{"app": "time"}
in := problemInputs{services: []corev1.Service{{ObjectMeta: metav1.ObjectMeta{Name: "time", Namespace: "system"}, Spec: corev1.ServiceSpec{Selector: labels}}},
daemonsets: []appsv1.DaemonSet{{ObjectMeta: metav1.ObjectMeta{Name: "masters", Namespace: "system", Generation: 3}, Spec: appsv1.DaemonSetSpec{Template: corev1.PodTemplateSpec{ObjectMeta: metav1.ObjectMeta{Labels: labels}}}, Status: appsv1.DaemonSetStatus{DesiredNumberScheduled: tc.desired, ObservedGeneration: tc.observed}}}}
if tc.activeDeployment {
one := int32(1)
in.deployments = []appsv1.Deployment{{ObjectMeta: metav1.ObjectMeta{Namespace: "system"}, Spec: appsv1.DeploymentSpec{Replicas: &one, Template: corev1.PodTemplateSpec{ObjectMeta: metav1.ObjectMeta{Labels: labels}}}}}
}
g := &Graph{Nodes: []Node{{ID: "service/system/time"}}}
attachProblems(g, in)
p := problemsOf(g, "service/system/time")["NoEndpoints"]
if p.Severity != tc.want {
t.Fatalf("got %+v, want %s", p, tc.want)
}
})
}
}
func TestIdleServiceStillWarnsForCronJobAndPendingPod(t *testing.T) {
zero := int32(0)
labels := map[string]string{"app": "time"}
for _, tc := range []struct {
name string
cron bool
}{{"cronjob-starting", true}, {"pod-pending", false}} {
t.Run(tc.name, func(t *testing.T) {
in := problemInputs{deployments: []appsv1.Deployment{{ObjectMeta: metav1.ObjectMeta{Namespace: "system"}, Spec: appsv1.DeploymentSpec{Replicas: &zero, Template: corev1.PodTemplateSpec{ObjectMeta: metav1.ObjectMeta{Labels: labels}}}}}}
if tc.cron {
in.cronjobs = []batchv1.CronJob{{ObjectMeta: metav1.ObjectMeta{Namespace: "system"}, Spec: batchv1.CronJobSpec{JobTemplate: batchv1.JobTemplateSpec{Spec: batchv1.JobSpec{Template: corev1.PodTemplateSpec{ObjectMeta: metav1.ObjectMeta{Labels: labels}}}}}}}
} else {
in.pods = []corev1.Pod{{ObjectMeta: metav1.ObjectMeta{Namespace: "system", Labels: labels}, Status: corev1.PodStatus{Phase: corev1.PodPending}}}
}
if serviceControllersIdle(corev1.Service{ObjectMeta: metav1.ObjectMeta{Namespace: "system"}, Spec: corev1.ServiceSpec{Selector: labels}}, in) {
t.Fatal("active controller/pod incorrectly treated as idle")
}
})
}
}
@@ -0,0 +1,203 @@
/*
Copyright 2026 The cluster-map Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package topology
import (
"sort"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
)
// VulnSummary is what a card shows about its images: counts of distinct
// CRITICAL and HIGH CVEs (operator-trivy keeps only those here) and how
// many of them a newer package version fixes. One CVE in six subpackages
// of openssh is one CVE.
type VulnSummary struct {
Critical int `json:"critical"`
High int `json:"high"`
FixableCritical int `json:"fixableCritical"`
Fixable int `json:"fixable"`
}
// Vuln is one finding in the details list.
type Vuln struct {
ID string `json:"id"`
Severity string `json:"severity"`
Package string `json:"package"` // comma-separated when the CVE hits several packages of one image
Installed string `json:"installed"`
Fixed string `json:"fixed,omitempty"`
Title string `json:"title,omitempty"`
Link string `json:"link,omitempty"`
Score float64 `json:"score,omitempty"`
Image string `json:"image"`
Container string `json:"container"`
}
// vulnTargetID maps a report to its card the way events are mapped: the
// report is labelled with the scanned object (a ReplicaSet, StatefulSet,
// CronJob, Job or bare Pod).
func vulnTargetID(r *unstructured.Unstructured, podOwner map[string]string) string {
l := r.GetLabels()
ref := corev1.ObjectReference{
Kind: l["trivy-operator.resource.kind"],
Name: l["trivy-operator.resource.name"],
Namespace: l["trivy-operator.resource.namespace"],
}
if ref.Namespace == "" {
ref.Namespace = r.GetNamespace()
}
return EventTargetID(ref, podOwner)
}
func reportImage(r *unstructured.Unstructured) string {
server, _, _ := unstructured.NestedString(r.Object, "report", "registry", "server")
repo, _, _ := unstructured.NestedString(r.Object, "report", "artifact", "repository")
tag, _, _ := unstructured.NestedString(r.Object, "report", "artifact", "tag")
img := repo
if server != "" {
img = server + "/" + repo
}
if tag != "" {
img += ":" + tag
}
return img
}
func reportVulns(r *unstructured.Unstructured) []Vuln {
raw, _, _ := unstructured.NestedSlice(r.Object, "report", "vulnerabilities")
image, container := reportImage(r), r.GetLabels()["trivy-operator.container.name"]
out := make([]Vuln, 0, len(raw))
for _, x := range raw {
m, ok := x.(map[string]any)
if !ok {
continue
}
str := func(k string) string { s, _ := m[k].(string); return s }
score, _ := m["score"].(float64)
out = append(out, Vuln{
ID: str("vulnerabilityID"), Severity: str("severity"), Package: str("resource"),
Installed: str("installedVersion"), Fixed: str("fixedVersion"), Title: str("title"),
Link: str("primaryLink"), Score: score, Image: image, Container: container,
})
}
return out
}
func podOwners(pods []corev1.Pod) map[string]string {
out := make(map[string]string, len(pods))
for _, p := range pods {
out[p.Namespace+"/"+p.Name] = OwnerWorkloadID(p)
}
return out
}
// attachVulns fills Node.Vulns. A CVE counts once per card, whatever the
// number of packages and containers it is found in.
func attachVulns(g *Graph, reports []*unstructured.Unstructured, pods []corev1.Pod) {
if len(reports) == 0 {
return
}
owners := podOwners(pods)
seen := map[string]map[string]bool{}
sums := map[string]*VulnSummary{}
for _, r := range reports {
card := vulnTargetID(r, owners)
if card == "" {
continue
}
if seen[card] == nil {
seen[card], sums[card] = map[string]bool{}, &VulnSummary{}
}
for _, v := range reportVulns(r) {
if seen[card][v.ID] {
continue
}
seen[card][v.ID] = true
s := sums[card]
switch v.Severity {
case "CRITICAL":
s.Critical++
if v.Fixed != "" {
s.FixableCritical++
}
case "HIGH":
s.High++
default:
continue
}
if v.Fixed != "" {
s.Fixable++
}
}
}
for i := range g.Nodes {
if s, ok := sums[g.Nodes[i].ID]; ok && (s.Critical > 0 || s.High > 0) {
g.Nodes[i].Vulns = s
}
}
}
var severityOrder = map[string]int{"CRITICAL": 0, "HIGH": 1, "MEDIUM": 2, "LOW": 3}
// VulnsFor lists the findings of one card, most severe first, fixable
// before unfixable, one entry per CVE and image with its packages joined.
func VulnsFor(reports []*unstructured.Unstructured, pods []corev1.Pod, cardID string, limit int) []Vuln {
owners := podOwners(pods)
type key struct{ id, image string }
at := map[key]int{}
pkgs := map[key]map[string]bool{}
out := []Vuln{}
for _, r := range reports {
if vulnTargetID(r, owners) != cardID {
continue
}
for _, v := range reportVulns(r) {
k := key{v.ID, v.Image}
i, ok := at[k]
if !ok {
at[k], pkgs[k] = len(out), map[string]bool{v.Package: true}
out = append(out, v)
continue
}
if !pkgs[k][v.Package] {
pkgs[k][v.Package] = true
out[i].Package += ", " + v.Package
}
if out[i].Fixed == "" {
out[i].Fixed = v.Fixed
}
}
}
sort.SliceStable(out, func(i, j int) bool {
a, b := out[i], out[j]
if severityOrder[a.Severity] != severityOrder[b.Severity] {
return severityOrder[a.Severity] < severityOrder[b.Severity]
}
if (a.Fixed != "") != (b.Fixed != "") {
return a.Fixed != ""
}
if a.Score != b.Score {
return a.Score > b.Score
}
return a.ID < b.ID
})
if limit > 0 && len(out) > limit {
out = out[:limit]
}
return out
}
@@ -0,0 +1,73 @@
/*
Copyright 2026 The cluster-map Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package topology
import (
"testing"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
)
func vulnReport(ns, kind, name, container, repo string, vulns ...map[string]any) *unstructured.Unstructured {
list := make([]any, len(vulns))
for i, v := range vulns {
list[i] = v
}
u := &unstructured.Unstructured{Object: map[string]any{
"report": map[string]any{
"registry": map[string]any{"server": "ghcr.io"},
"artifact": map[string]any{"repository": repo, "tag": "1.0"},
"vulnerabilities": list,
},
}}
u.SetNamespace(ns)
u.SetLabels(map[string]string{"trivy-operator.resource.kind": kind, "trivy-operator.resource.name": name, "trivy-operator.resource.namespace": ns, "trivy-operator.container.name": container})
return u
}
func cve(id, sev, pkg, fixed string, score float64) map[string]any {
return map[string]any{"vulnerabilityID": id, "severity": sev, "resource": pkg, "installedVersion": "1.0", "fixedVersion": fixed, "score": score}
}
func TestVulns(t *testing.T) {
g := &Graph{Nodes: []Node{{ID: "wl/shop/deployment/web"}, {ID: "wl/shop/cronjob/backup"}, {ID: "wl/shop/deployment/clean"}}}
reports := []*unstructured.Unstructured{
vulnReport("shop", "ReplicaSet", "web-5f", "app", "acme/web",
cve("CVE-1", "CRITICAL", "openssl", "3.0.2", 9.8), cve("CVE-1", "CRITICAL", "libssl3", "3.0.2", 9.8),
cve("CVE-2", "CRITICAL", "zlib", "", 9.1), cve("CVE-3", "HIGH", "curl", "8.1", 7.5)),
// the sidecar on the same base image repeats CVE-1: counted once
vulnReport("shop", "ReplicaSet", "web-5f", "sidecar", "acme/web-sidecar", cve("CVE-1", "CRITICAL", "openssl", "3.0.2", 9.8)),
vulnReport("shop", "Job", "backup-29100000", "dump", "library/alpine", cve("CVE-4", "HIGH", "busybox", "1.37", 7.0)),
}
attachVulns(g, reports, nil)
web := g.Nodes[0].Vulns
if web == nil || web.Critical != 2 || web.High != 1 || web.FixableCritical != 1 || web.Fixable != 2 {
t.Errorf("web summary: %+v", web)
}
if b := g.Nodes[1].Vulns; b == nil || b.High != 1 {
t.Errorf("a CronJob's job report attaches to the CronJob: %+v", b)
}
if g.Nodes[2].Vulns != nil {
t.Error("a card without reports carries no summary")
}
list := VulnsFor(reports, []corev1.Pod{{ObjectMeta: metav1.ObjectMeta{Name: "x"}}}, "wl/shop/deployment/web", 0)
if len(list) != 4 || list[0].ID != "CVE-1" || list[0].Package != "openssl, libssl3" || list[0].Image != "ghcr.io/acme/web:1.0" || list[2].ID != "CVE-2" || list[3].Severity != "HIGH" {
t.Errorf("order (critical fixable, critical fixable sidecar, critical unfixable, high): %+v", list)
}
}
@@ -0,0 +1,615 @@
/*
Copyright 2026 The cluster-map Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Package traffic aggregates Cilium Hubble flows into per-minute buckets of
// distinct connections between workloads.
//
// Why a collector instead of querying Hubble on demand: every agent keeps
// only its ring buffer (4095 flows by default), which at a few hundred
// flows per second is about ten seconds of history. A request for "the
// last 15 minutes" answered from the buffer silently returns the last few
// seconds. So flows are read from a follow stream and kept here.
package traffic
import (
"context"
"hash/fnv"
"log/slog"
"slices"
"sort"
"strconv"
"strings"
"sync"
"time"
flowpb "github.com/cilium/cilium/api/v1/flow"
observerpb "github.com/cilium/cilium/api/v1/observer"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/types/known/fieldmaskpb"
"google.golang.org/protobuf/types/known/timestamppb"
"git.project-chimera.ru/fanchji/cluster-map/internal/config"
"git.project-chimera.ru/fanchji/cluster-map/internal/metrics"
)
// maxTuplesPerKey bounds memory per edge per minute; beyond it the distinct
// count for that edge stops growing for the rest of the minute.
const maxTuplesPerKey = 20000
// InfraFilters (a blacklist) are applied at the agents, so the relay never
// serialises these flows. On a 12k-event sample from a real cluster they were ~74% of
// non-reply events: host-originated traffic (kubelet probes, hostNetwork
// pods) 43%, DNS 19%, remote-node 11%, cilium health 1%. None of them map
// to a workload card, and streaming them kept hubble-relay at ~400m CPU.
var InfraFilters = []*flowpb.FlowFilter{
{SourceLabel: []string{"reserved:host"}},
{SourceLabel: []string{"reserved:remote-node"}},
{SourceLabel: []string{"reserved:health"}},
{DestinationLabel: []string{"reserved:health"}},
{DestinationPort: []string{"53"}},
// Pod-to-pod across nodes is traced twice: to-overlay on the sender's
// node and to-endpoint on the receiver's. The second copy carries the
// same tuple, so the first is dropped when the receiver is a pod; to a
// hostNetwork pod or the API server, to-overlay is the only trace and
// stays. Measured on six nodes: ~20% of the events that reach the relay.
{
EventType: []*flowpb.EventTypeFilter{{Type: monitorTrace, MatchSubType: true, SubType: traceToOverlay}},
DestinationLabel: []string{"k8s:io.kubernetes.pod.namespace"},
},
}
// Cilium datapath codes (pkg/monitor/api): message type "trace" and its
// observation point "to-overlay", and the L7 access log type.
const (
monitorTrace = 4
traceToOverlay = 4
monitorAccessLog = 129
)
// flowFields: from L7 events only what the HTTP statistics use -- never
// headers, which carry cookies and Authorization.
var flowFields = []string{"time", "verdict", "IP", "l4", "source", "destination", "source_names", "destination_names", "node_name",
"l7.type", "l7.latency_ns", "l7.http.code", "l7.http.method", "l7.http.url"}
// Endpoint is one side of a traffic edge: a workload, a pod or an address.
type Endpoint struct {
ID string `json:"id"`
Label string `json:"label"`
Kind string `json:"kind"` // lowercased controller kind, "pod", or "external"
Namespace string `json:"namespace,omitempty"`
}
// Edge is aggregated traffic from Source to Target on one port.
type Edge struct {
Source string `json:"source"`
Target string `json:"target"`
Port string `json:"port"` // "443/TCP"
Connections int `json:"connections"` // distinct 5-tuples seen in the window
New int `json:"new"` // of those, opened by TCP SYN inside the window
Dropped int `json:"dropped"` // distinct 5-tuples with a DROPPED verdict
Last string `json:"last"`
// HTTP is set where Hubble sees L7 on this port (an L7 visibility
// policy sends it through Envoy).
HTTP *HTTPStats `json:"http,omitempty"`
}
// Result is the /api/flows response.
type Result struct {
Mode config.TrafficMode `json:"mode"`
WindowSec int `json:"windowSec"`
CoveredSec int `json:"coveredSec"` // how much of the window the collector has actually seen
Connected bool `json:"connected"`
Error string `json:"error,omitempty"`
Endpoints []Endpoint `json:"endpoints"`
Edges []Edge `json:"edges"`
}
// PodResolver maps a pod to the workload that owns it; ok is false for
// pods the cache doesn't know (already gone).
type PodResolver func(namespace, pod string) (Endpoint, bool)
type edgeKey struct{ src, dst, port string }
const (
tupleSYN uint8 = 1
tupleDrop uint8 = 2
)
type bucketEdge struct {
tuples map[uint64]uint8
last int64
}
type bucket struct {
minute int64
edges map[edgeKey]*bucketEdge
http map[edgeKey]*httpAgg // only where L7 visibility is on
}
// Collector keeps minute buckets of distinct connections for the
// configured retention.
type Collector struct {
cfg config.Config
obs observerpb.ObserverClient
resolve PodResolver
now func() time.Time
mu sync.Mutex
base context.Context // lifetime of Run; streams started by Query live under it
buckets []*bucket
endpoints map[string]Endpoint
coveredFrom time.Time // start of the current uninterrupted collection
running bool
connected bool
lastErr string
lastQuery time.Time
cancel context.CancelFunc
}
// NewCollector builds a collector; obs may be nil when traffic is off or
// the Hubble client could not be set up.
func NewCollector(cfg config.Config, obs observerpb.ObserverClient, resolve PodResolver) *Collector {
return &Collector{
cfg: cfg, obs: obs, resolve: resolve, now: time.Now,
buckets: make([]*bucket, int(cfg.Retention/time.Minute)),
endpoints: map[string]Endpoint{},
}
}
// Run blocks until ctx is done. In Continuous mode it streams all the
// time; in OnDemand mode it streams from the first Query until
// OnDemandIdle passes without one.
func (c *Collector) Run(ctx context.Context) {
c.mu.Lock()
c.base = ctx
c.mu.Unlock()
switch c.cfg.TrafficMode {
case config.TrafficDisabled:
return
case config.TrafficContinuous:
c.start(ctx)
<-ctx.Done()
case config.TrafficOnDemand:
t := time.NewTicker(30 * time.Second)
defer t.Stop()
for {
select {
case <-ctx.Done():
c.stop()
return
case <-t.C:
c.mu.Lock()
idle := c.running && c.now().Sub(c.lastQuery) > c.cfg.OnDemandIdle
c.mu.Unlock()
if idle {
slog.Info("traffic: no viewers, closing Hubble stream", "idle", c.cfg.OnDemandIdle)
c.stop()
}
}
}
}
}
func (c *Collector) start(parent context.Context) {
c.mu.Lock()
if c.running || c.obs == nil {
c.mu.Unlock()
return
}
ctx, cancel := context.WithCancel(parent)
c.running, c.cancel, c.coveredFrom = true, cancel, c.now()
c.mu.Unlock()
metrics.HubbleStreamActive.Set(1)
go c.loop(ctx)
}
func (c *Collector) stop() {
c.mu.Lock()
defer c.mu.Unlock()
if !c.running {
return
}
c.cancel()
c.running, c.connected = false, false
metrics.HubbleStreamActive.Set(0)
metrics.HubbleConnected.Set(0)
}
func (c *Collector) loop(ctx context.Context) {
useMask := true
backoff := time.Second
for ctx.Err() == nil {
req := &observerpb.GetFlowsRequest{
Follow: true,
// Backfill whatever the ring buffers still hold; tuples seen twice
// after a reconnect collapse in the per-minute sets.
Since: timestamppb.New(c.now().Add(-time.Minute)),
// requests and connections without replies, plus every L7 event:
// the HTTP status and latency are in the RESPONSE, a reply
Whitelist: []*flowpb.FlowFilter{{Reply: []bool{false}}, {EventType: []*flowpb.EventTypeFilter{{Type: monitorAccessLog}}}},
}
if !c.cfg.CollectInfra {
req.Blacklist = InfraFilters
}
if useMask {
req.FieldMask = &fieldmaskpb.FieldMask{Paths: flowFields}
}
received, err := c.stream(ctx, req)
if ctx.Err() != nil {
return
}
if status.Code(err) == codes.InvalidArgument && useMask {
useMask = false
slog.Warn("traffic: relay rejected the field mask, retrying without it", "err", err)
continue
}
c.setErr(err)
metrics.HubbleReconnects.Inc()
if received > 0 {
backoff = time.Second
}
select {
case <-ctx.Done():
return
case <-time.After(backoff):
}
backoff = min(backoff*2, 30*time.Second)
}
}
func (c *Collector) stream(ctx context.Context, req *observerpb.GetFlowsRequest) (int, error) {
s, err := c.obs.GetFlows(ctx, req)
if err != nil {
return 0, err
}
n := 0
for {
resp, err := s.Recv()
if err != nil {
return n, err
}
if f := resp.GetFlow(); f != nil {
c.Add(f)
n++
}
}
}
func (c *Collector) setErr(err error) {
c.mu.Lock()
defer c.mu.Unlock()
c.connected = false
if err != nil {
c.lastErr = err.Error()
}
metrics.HubbleConnected.Set(0)
slog.Warn("traffic: Hubble stream ended", "err", err)
}
// Add records one flow. Exported for tests and for replaying captures.
func (c *Collector) Add(f *flowpb.Flow) {
if proxiedLeg(f) {
metrics.FlowsProcessed.Inc()
return
}
src := c.endpoint(f.GetSource(), f.GetSourceNames(), f.GetNodeName())
dst := c.endpoint(f.GetDestination(), f.GetDestinationNames(), f.GetNodeName())
metrics.FlowsProcessed.Inc()
if src.ID == dst.ID {
return
}
// Not f.GetL7() != nil: with the field mask asking for l7.* subfields,
// Hubble returns an empty L7 message on every flow, L4 included; only
// a set type says the event is an L7 one.
l7 := f.GetL7().GetType() != flowpb.L7FlowType_UNKNOWN_L7_TYPE
port, tuple, syn := l4Info(f)
ts := c.now()
if t := f.GetTime(); t != nil {
ts = t.AsTime()
}
minute := ts.Unix() / 60
c.mu.Lock()
defer c.mu.Unlock()
if !c.connected {
c.connected, c.lastErr = true, ""
metrics.HubbleConnected.Set(1)
}
slot := int(minute % int64(len(c.buckets)))
b := c.buckets[slot]
if b == nil || b.minute != minute {
if b != nil && b.minute > minute {
return // older than retention
}
b = &bucket{minute: minute, edges: map[edgeKey]*bucketEdge{}}
c.buckets[slot] = b
c.pruneEndpoints()
}
c.endpoints[src.ID] = src
c.endpoints[dst.ID] = dst
if l7 {
// a RESPONSE goes server -> client; statistics are kept client -> server
c.addHTTP(b, f, dst, src, ts)
return
}
k := edgeKey{src.ID, dst.ID, port}
e := b.edges[k]
if e == nil {
e = &bucketEdge{tuples: map[uint64]uint8{}}
b.edges[k] = e
}
h := hashTuple(f.GetIP().GetSource(), f.GetIP().GetDestination(), tuple)
flags, seen := e.tuples[h]
if !seen && len(e.tuples) >= maxTuplesPerKey {
return
}
if syn {
flags |= tupleSYN
}
if f.GetVerdict() == flowpb.Verdict_DROPPED {
flags |= tupleDrop
}
e.tuples[h] = flags
e.last = max(e.last, ts.Unix())
}
// pruneEndpoints drops metadata for endpoints no retained bucket mentions.
// Called with c.mu held, once per minute rollover.
func (c *Collector) pruneEndpoints() {
used := map[string]bool{}
tuples := 0
for _, b := range c.buckets {
if b == nil {
continue
}
for k, e := range b.edges {
used[k.src], used[k.dst] = true, true
tuples += len(e.tuples)
}
for k := range b.http {
used[k.src], used[k.dst] = true, true
}
}
for id := range c.endpoints {
if !used[id] {
delete(c.endpoints, id)
}
}
metrics.TrackedTuples.Set(float64(tuples))
}
// Query returns traffic touching any of the namespaces over the last
// window. In OnDemand mode it also (re)starts collection.
func (c *Collector) Query(namespaces map[string]bool, window time.Duration) Result {
if c.cfg.TrafficMode == config.TrafficOnDemand {
c.mu.Lock()
c.lastQuery = c.now()
base := c.base
c.mu.Unlock()
if base != nil {
c.start(base)
}
}
window = min(window, c.cfg.Retention)
now := c.now()
fromMinute := now.Add(-window).Unix() / 60
c.mu.Lock()
defer c.mu.Unlock()
// Empty lists, not nil: the frontend iterates them, and JSON null is not iterable.
res := Result{Mode: c.cfg.TrafficMode, WindowSec: int(window.Seconds()), Connected: c.connected, Error: c.lastErr, Endpoints: []Endpoint{}, Edges: []Edge{}}
if c.running {
res.CoveredSec = min(res.WindowSec, int(now.Sub(c.coveredFrom).Seconds()))
}
touches := func(id string) bool { return namespaces[c.endpoints[id].Namespace] }
merged := map[edgeKey]*bucketEdge{}
httpAggs := map[edgeKey][]*httpAgg{}
for _, b := range c.buckets {
if b == nil || b.minute < fromMinute {
continue
}
for k, a := range b.http {
if touches(k.src) || touches(k.dst) {
httpAggs[k] = append(httpAggs[k], a)
}
}
for k, e := range b.edges {
if !touches(k.src) && !touches(k.dst) {
continue
}
m := merged[k]
if m == nil {
m = &bucketEdge{tuples: make(map[uint64]uint8, len(e.tuples))}
merged[k] = m
}
for h, fl := range e.tuples {
m.tuples[h] |= fl
}
m.last = max(m.last, e.last)
}
}
eps := map[string]bool{}
for k, m := range merged {
e := Edge{Source: k.src, Target: k.dst, Port: k.port, Connections: len(m.tuples), Last: time.Unix(m.last, 0).UTC().Format(time.RFC3339)}
for _, fl := range m.tuples {
if fl&tupleSYN != 0 {
e.New++
}
if fl&tupleDrop != 0 {
e.Dropped++
}
}
if aggs, ok := httpAggs[k]; ok {
e.HTTP = httpStats(aggs)
delete(httpAggs, k)
}
res.Edges = append(res.Edges, e)
eps[k.src], eps[k.dst] = true, true
}
// HTTP seen without a matching connection record (the proxy observed
// the requests, the L4 trace for that exact port did not reach us)
for k, aggs := range httpAggs {
last := int64(0)
for _, a := range aggs {
last = max(last, a.last)
}
res.Edges = append(res.Edges, Edge{Source: k.src, Target: k.dst, Port: k.port, Last: time.Unix(last, 0).UTC().Format(time.RFC3339), HTTP: httpStats(aggs)})
eps[k.src], eps[k.dst] = true, true
}
for id := range eps {
res.Endpoints = append(res.Endpoints, c.endpoints[id])
}
sort.Slice(res.Endpoints, func(i, j int) bool { return res.Endpoints[i].ID < res.Endpoints[j].ID })
sort.Slice(res.Edges, func(i, j int) bool {
if res.Edges[i].Connections != res.Edges[j].Connections {
return res.Edges[i].Connections > res.Edges[j].Connections
}
return res.Edges[i].Source+res.Edges[i].Target+res.Edges[i].Port < res.Edges[j].Source+res.Edges[j].Target+res.Edges[j].Port
})
return res
}
func hashTuple(srcIP, dstIP, rest string) uint64 {
h := fnv.New64a()
h.Write([]byte(srcIP))
h.Write([]byte{0})
h.Write([]byte(dstIP))
h.Write([]byte{0})
h.Write([]byte(rest))
return h.Sum64()
}
// l4Info returns the display port ("443/TCP"), the port part of the
// connection tuple, and whether this event opens a TCP connection.
func l4Info(f *flowpb.Flow) (port, tuple string, syn bool) {
l4 := f.GetL4()
p := func(n uint32) string { return strconv.FormatUint(uint64(n), 10) }
switch {
case l4.GetTCP() != nil:
t := l4.GetTCP()
return p(t.GetDestinationPort()) + "/TCP", "tcp:" + p(t.GetSourcePort()) + ":" + p(t.GetDestinationPort()),
t.GetFlags().GetSYN() && !t.GetFlags().GetACK()
case l4.GetUDP() != nil:
u := l4.GetUDP()
return p(u.GetDestinationPort()) + "/UDP", "udp:" + p(u.GetSourcePort()) + ":" + p(u.GetDestinationPort()), false
case l4.GetSCTP() != nil:
s := l4.GetSCTP()
return p(s.GetDestinationPort()) + "/SCTP", "sctp:" + p(s.GetSourcePort()) + ":" + p(s.GetDestinationPort()), false
case l4.GetICMPv4() != nil || l4.GetICMPv6() != nil:
return "ICMP", "icmp", false
}
return "?", "?", false
}
// ephemeralPorts is where Linux picks client ports (ip_local_port_range);
// NodePorts (30000-32767) stay below it.
const ephemeralPorts = 32768
// proxiedLeg: with L7 visibility Envoy re-opens each connection to the pod
// from the node, and both halves of that inner connection reach us as
// non-replies:
// - Envoy -> pod carries the client's security identity (its labels)
// but no pod name, so it cannot be attributed and would show as
// "world" (a pod that reached itself through its own Service looks
// the same: Cilium rewrites the source to 169.254.42.1);
// - the pod's answers to Envoy go to the node's host on an ephemeral
// port, and would show as one "pod -> node" edge per request.
//
// The connection itself is already counted on the client -> proxy leg.
// A pod that dials a host does so on a service port, never an ephemeral
// one (checked on the live cluster: API server 6443, kubelet 10250,
// exporters 42xx, Hubble 4244 all stay).
func proxiedLeg(f *flowpb.Flow) bool {
if f.GetL7().GetType() != flowpb.L7FlowType_UNKNOWN_L7_TYPE {
return false
}
s, d := f.GetSource(), f.GetDestination()
if s.GetPodName() == "" {
for _, l := range s.GetLabels() {
if strings.HasPrefix(l, "k8s:io.kubernetes.pod.namespace=") {
return true
}
}
}
if s.GetPodName() != "" && slices.Contains(d.GetLabels(), "reserved:host") {
if t := f.GetL4().GetTCP(); t != nil && t.GetDestinationPort() >= ephemeralPorts && t.GetSourcePort() < ephemeralPorts {
return true
}
}
return false
}
// Restricted stands for every peer in a namespace the viewer cannot see:
// the connection is shown, the workload behind it is not.
var Restricted = Endpoint{ID: "ext/restricted", Label: "restricted", Kind: "external"}
// Restrict hides peers outside the visible namespaces. Edges between two
// hidden endpoints are dropped (Query already returns only edges touching
// a requested namespace, so this is defence in depth); edges to a hidden
// peer keep their counts with the peer replaced by Restricted and merged.
func Restrict(res Result, visible func(string) bool) Result {
hide := map[string]bool{}
eps := []Endpoint{}
for _, e := range res.Endpoints {
if e.Namespace != "" && !visible(e.Namespace) {
hide[e.ID] = true
continue
}
eps = append(eps, e)
}
if len(hide) == 0 {
return res
}
type key struct{ src, dst, port string }
merged := map[key]*Edge{}
var order []key
for _, e := range res.Edges {
if hide[e.Source] && hide[e.Target] {
continue
}
if hide[e.Source] {
e.Source = Restricted.ID
}
if hide[e.Target] {
e.Target = Restricted.ID
}
k := key{e.Source, e.Target, e.Port}
if m := merged[k]; m != nil {
m.Connections += e.Connections
m.New += e.New
m.Dropped += e.Dropped
m.Last = max(m.Last, e.Last)
m.HTTP = mergeHTTP(m.HTTP, e.HTTP)
continue
}
c := e
merged[k] = &c
order = append(order, k)
}
res.Edges = make([]Edge, 0, len(order))
usedRestricted := false
for _, k := range order {
res.Edges = append(res.Edges, *merged[k])
usedRestricted = usedRestricted || k.src == Restricted.ID || k.dst == Restricted.ID
}
if usedRestricted {
eps = append(eps, Restricted)
}
res.Endpoints = eps
return res
}
@@ -0,0 +1,311 @@
/*
Copyright 2026 The cluster-map Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package traffic
import (
"encoding/json"
"strconv"
"strings"
"testing"
"time"
flowpb "github.com/cilium/cilium/api/v1/flow"
"google.golang.org/protobuf/types/known/timestamppb"
"google.golang.org/protobuf/types/known/wrapperspb"
"git.project-chimera.ru/fanchji/cluster-map/internal/config"
)
var t0 = time.Date(2026, 9, 23, 12, 0, 0, 0, time.UTC)
func newTestCollector(now *time.Time) *Collector {
cfg := config.Config{TrafficMode: config.TrafficContinuous, Retention: 60 * time.Minute}
c := NewCollector(cfg, nil, func(ns, pod string) (Endpoint, bool) {
if pod == "gone" {
return Endpoint{}, false
}
return Endpoint{ID: "wl/" + ns + "/deployment/" + pod, Label: pod, Kind: "deployment", Namespace: ns}, true
})
c.now = func() time.Time { return *now }
c.running, c.coveredFrom = true, t0
return c
}
func tcpFlow(at time.Time, srcNs, src, dstNs, dst string, srcPort uint32, syn bool, verdict flowpb.Verdict) *flowpb.Flow {
return &flowpb.Flow{
Time: timestamppb.New(at),
Verdict: verdict,
IP: &flowpb.IP{Source: "10.0.0.1", Destination: "10.0.0.2"},
L4: &flowpb.Layer4{Protocol: &flowpb.Layer4_TCP{TCP: &flowpb.TCP{SourcePort: srcPort, DestinationPort: 5432, Flags: &flowpb.TCPFlags{SYN: syn, ACK: !syn}}}},
Source: &flowpb.Endpoint{Namespace: srcNs, PodName: src},
Destination: &flowpb.Endpoint{Namespace: dstNs, PodName: dst},
}
}
func TestDistinctConnections(t *testing.T) {
now := t0.Add(2 * time.Minute)
c := newTestCollector(&now)
// one connection seen three times (SYN + two data events), one more opened
c.Add(tcpFlow(t0, "app", "web", "db", "pg", 40000, true, flowpb.Verdict_FORWARDED))
c.Add(tcpFlow(t0.Add(time.Second), "app", "web", "db", "pg", 40000, false, flowpb.Verdict_FORWARDED))
c.Add(tcpFlow(t0.Add(70*time.Second), "app", "web", "db", "pg", 40000, false, flowpb.Verdict_FORWARDED))
c.Add(tcpFlow(t0.Add(2*time.Second), "app", "web", "db", "pg", 40001, true, flowpb.Verdict_FORWARDED))
// a long-lived pooled connection: data only, no SYN in the window
c.Add(tcpFlow(t0, "app", "worker", "db", "pg", 50000, false, flowpb.Verdict_FORWARDED))
// dropped attempt
c.Add(tcpFlow(t0, "app", "web", "db", "pg", 40002, true, flowpb.Verdict_DROPPED))
res := c.Query(map[string]bool{"db": true}, 5*time.Minute)
got := map[string]Edge{}
for _, e := range res.Edges {
got[e.Source] = e
}
web := got["wl/app/deployment/web"]
if web.Connections != 3 || web.New != 3 || web.Dropped != 1 || web.Port != "5432/TCP" {
t.Errorf("web -> pg: %+v", web)
}
worker := got["wl/app/deployment/worker"]
if worker.Connections != 1 || worker.New != 0 {
t.Errorf("worker -> pg: %+v", worker)
}
if res.CoveredSec != 120 {
t.Errorf("coveredSec = %d, want 120", res.CoveredSec)
}
}
func TestWindowAndNamespaceFilter(t *testing.T) {
now := t0.Add(30 * time.Minute)
c := newTestCollector(&now)
c.Add(tcpFlow(t0, "app", "old", "db", "pg", 1, true, flowpb.Verdict_FORWARDED))
c.Add(tcpFlow(now.Add(-time.Minute), "app", "recent", "db", "pg", 2, true, flowpb.Verdict_FORWARDED))
c.Add(tcpFlow(now.Add(-time.Minute), "other", "a", "other", "b", 3, true, flowpb.Verdict_FORWARDED))
res := c.Query(map[string]bool{"db": true}, 5*time.Minute)
if len(res.Edges) != 1 || res.Edges[0].Source != "wl/app/deployment/recent" {
t.Fatalf("5 min window: %+v", res.Edges)
}
res = c.Query(map[string]bool{"db": true}, time.Hour)
if len(res.Edges) != 2 {
t.Fatalf("hour window should include the old flow: %+v", res.Edges)
}
}
func TestRetentionOverwritesOldBuckets(t *testing.T) {
now := t0
c := newTestCollector(&now)
c.Add(tcpFlow(t0, "app", "web", "db", "pg", 1, true, flowpb.Verdict_FORWARDED))
// exactly one retention later the same slot is reused
now = t0.Add(60 * time.Minute)
c.Add(tcpFlow(now, "app", "web", "db", "pg", 2, true, flowpb.Verdict_FORWARDED))
res := c.Query(map[string]bool{"db": true}, time.Hour)
if len(res.Edges) != 1 || res.Edges[0].Connections != 1 {
t.Fatalf("old bucket should have been replaced: %+v", res.Edges)
}
// a late flow for the replaced minute is ignored
c.Add(tcpFlow(t0, "app", "late", "db", "pg", 3, true, flowpb.Verdict_FORWARDED))
for _, e := range c.Query(map[string]bool{"db": true}, time.Hour).Edges {
if e.Source == "wl/app/deployment/late" {
t.Fatal("flow older than retention was recorded")
}
}
}
func TestEndpointMapping(t *testing.T) {
now := t0
c := newTestCollector(&now)
cases := []struct {
ep *flowpb.Endpoint
names []string
want string
}{
{&flowpb.Endpoint{Namespace: "app", PodName: "web"}, nil, "wl/app/deployment/web"},
{&flowpb.Endpoint{Namespace: "app", PodName: "gone", Workloads: []*flowpb.Workload{{Kind: "Job", Name: "backup-29316120"}}}, nil, "wl/app/cronjob/backup"},
{&flowpb.Endpoint{Namespace: "app", PodName: "gone"}, nil, "pod/app/gone"},
{&flowpb.Endpoint{Labels: []string{"reserved:kube-apiserver"}}, nil, "ext/kube-apiserver"},
{&flowpb.Endpoint{Labels: []string{"reserved:world"}}, []string{"api.github.com"}, "ext/dns/api.github.com"},
{&flowpb.Endpoint{Labels: []string{"reserved:world"}}, nil, "ext/world"},
{&flowpb.Endpoint{Labels: []string{"reserved:host"}}, nil, "ext/host/node-a"},
}
for _, tc := range cases {
if got := c.endpoint(tc.ep, tc.names, "node-a").ID; got != tc.want {
t.Errorf("%v: got %s want %s", tc.ep, got, tc.want)
}
}
}
func TestL4Info(t *testing.T) {
t.Parallel()
udp := &flowpb.Flow{L4: &flowpb.Layer4{Protocol: &flowpb.Layer4_UDP{UDP: &flowpb.UDP{SourcePort: 1234, DestinationPort: 53}}}}
if port, _, syn := l4Info(udp); port != "53/UDP" || syn {
t.Errorf("udp: %s %v", port, syn)
}
synAck := &flowpb.Flow{L4: &flowpb.Layer4{Protocol: &flowpb.Layer4_TCP{TCP: &flowpb.TCP{DestinationPort: 443, Flags: &flowpb.TCPFlags{SYN: true, ACK: true}}}}}
if _, _, syn := l4Info(synAck); syn {
t.Error("SYN-ACK is a reply, not an opened connection")
}
}
func TestDisabledModeNeverStreams(t *testing.T) {
t.Parallel()
c := NewCollector(config.Config{TrafficMode: config.TrafficDisabled, Retention: time.Hour}, nil, nil)
c.start(t.Context())
if c.running {
t.Fatal("collector without a Hubble client must not start")
}
}
// An empty window is sent as empty lists: the frontend iterates them, and a
// null there once left a namespace without traffic looking blank.
func TestEmptyWindowEncodesEmptyLists(t *testing.T) {
now := t0.Add(time.Minute)
c := newTestCollector(&now)
b, err := json.Marshal(c.Query(map[string]bool{"quiet": true}, 5*time.Minute))
if err != nil {
t.Fatal(err)
}
for _, want := range []string{`"endpoints":[]`, `"edges":[]`} {
if !strings.Contains(string(b), want) {
t.Errorf("response %s lacks %s", b, want)
}
}
}
func TestRestrictHidesForeignPeers(t *testing.T) {
res := Result{
Endpoints: []Endpoint{
{ID: "wl/shop/deployment/web", Namespace: "shop"}, {ID: "wl/bank/deployment/core", Namespace: "bank"},
{ID: "wl/bank/deployment/ledger", Namespace: "bank"}, {ID: "ext/world"},
},
Edges: []Edge{
{Source: "wl/shop/deployment/web", Target: "wl/bank/deployment/core", Port: "443/TCP", Connections: 2},
{Source: "wl/shop/deployment/web", Target: "wl/bank/deployment/ledger", Port: "443/TCP", Connections: 3},
{Source: "wl/bank/deployment/core", Target: "wl/bank/deployment/ledger", Port: "5432/TCP", Connections: 9},
{Source: "wl/shop/deployment/web", Target: "ext/world", Port: "443/TCP", Connections: 1},
},
}
out := Restrict(res, func(ns string) bool { return ns == "shop" })
for _, e := range out.Endpoints {
if e.Namespace == "bank" {
t.Fatalf("hidden endpoint leaked: %+v", e)
}
}
if len(out.Edges) != 2 {
t.Fatalf("edges: %+v", out.Edges)
}
if e := out.Edges[0]; e.Target != Restricted.ID || e.Connections != 5 {
t.Errorf("two hidden peers on one port merge into one restricted edge: %+v", e)
}
}
func TestPathTemplate(t *testing.T) {
for in, want := range map[string]string{
"http://web/": "/",
"http://web/api/42?token=secret": "/api/:id",
"/users/7f3a9c2e1b/avatar": "/users/:id/avatar",
"https://h/o/3fa85f64-5717-4562-b3fc-2c963f66afa6/x": "/o/:id/x",
"/static/app.js": "/static/app.js",
} {
if got := PathTemplate(in); got != want {
t.Errorf("%q: %q, want %q", in, got, want)
}
}
}
func httpResponse(at time.Time, code uint32, url string, latency time.Duration) *flowpb.Flow {
return &flowpb.Flow{
Time: timestamppb.New(at),
Verdict: flowpb.Verdict_FORWARDED,
IP: &flowpb.IP{Source: "10.0.0.2", Destination: "10.0.0.1"},
L4: &flowpb.Layer4{Protocol: &flowpb.Layer4_TCP{TCP: &flowpb.TCP{SourcePort: 8080, DestinationPort: 40000}}},
Source: &flowpb.Endpoint{Namespace: "shop", PodName: "web"},
Destination: &flowpb.Endpoint{Namespace: "shop", PodName: "client"},
IsReply: &wrapperspb.BoolValue{Value: true},
L7: &flowpb.Layer7{Type: flowpb.L7FlowType_RESPONSE, LatencyNs: uint64(latency.Nanoseconds()), //nolint:gosec // test durations are small and positive
Record: &flowpb.Layer7_Http{Http: &flowpb.HTTP{Code: code, Method: "GET", Url: url}}},
}
}
func TestHTTPStats(t *testing.T) {
now := t0.Add(2 * time.Minute)
c := newTestCollector(&now)
for i := 0; i < 18; i++ {
c.Add(httpResponse(t0, 200, "http://web/api/"+strconv.Itoa(i), 3*time.Millisecond))
}
c.Add(httpResponse(t0, 503, "http://web/api/1", 400*time.Millisecond))
c.Add(httpResponse(t0, 404, "http://web/missing", time.Millisecond))
// a REQUEST event carries no status and is not counted
req := httpResponse(t0, 0, "http://web/", 0)
req.L7.Type = flowpb.L7FlowType_REQUEST
c.Add(req)
res := c.Query(map[string]bool{"shop": true}, 5*time.Minute)
if len(res.Edges) != 1 {
t.Fatalf("edges: %+v", res.Edges)
}
e := res.Edges[0]
if e.Source != "wl/shop/deployment/client" || e.Target != "wl/shop/deployment/web" || e.Port != "8080/TCP" {
t.Errorf("a response must be recorded in the request's direction: %+v", e)
}
h := e.HTTP
if h == nil || h.Requests != 20 || h.Status["2xx"] != 18 || h.Status["5xx"] != 1 || h.Status["4xx"] != 1 {
t.Fatalf("http: %+v", h)
}
if h.P50Ms != 5 || h.P95Ms != 5 {
t.Errorf("p50/p95: %v/%v", h.P50Ms, h.P95Ms)
}
// 19 requests on the path: the 95th percentile is the 19th, the slow one
if top := h.Paths[0]; top.Path != "/api/:id" || top.Count != 19 || top.Errors != 1 || top.P95Ms != 500 {
t.Errorf("top path: %+v", top)
}
}
// With the field mask, Hubble sends an empty L7 message on L4 flows too;
// those must still count as connections (caught live: every edge in the
// cluster lost its connection count).
func TestMaskedL4FlowWithEmptyL7Counts(t *testing.T) {
now := t0.Add(time.Minute)
c := newTestCollector(&now)
f := tcpFlow(t0, "app", "web", "db", "pg", 40000, true, flowpb.Verdict_FORWARDED)
f.L7 = &flowpb.Layer7{}
c.Add(f)
res := c.Query(map[string]bool{"app": true}, 5*time.Minute)
if len(res.Edges) != 1 || res.Edges[0].Connections != 1 || res.Edges[0].HTTP != nil {
t.Fatalf("edges: %+v", res.Edges)
}
}
func TestProxiedLegIsSkipped(t *testing.T) {
now := t0.Add(time.Minute)
c := newTestCollector(&now)
leg := tcpFlow(t0, "", "", "shop", "web", 40000, true, flowpb.Verdict_FORWARDED)
leg.Source = &flowpb.Endpoint{Labels: []string{"k8s:app=client", "k8s:io.kubernetes.pod.namespace=shop"}}
c.Add(leg)
// the pod answering Envoy: to the node, on an ephemeral port
answer := tcpFlow(t0, "shop", "web", "", "", 8080, false, flowpb.Verdict_FORWARDED)
answer.Destination = &flowpb.Endpoint{Labels: []string{"reserved:host"}}
answer.L4 = &flowpb.Layer4{Protocol: &flowpb.Layer4_TCP{TCP: &flowpb.TCP{SourcePort: 8080, DestinationPort: 49726}}}
c.Add(answer)
// a pod dialling the API server on the host: a real connection
api := tcpFlow(t0, "shop", "web", "", "", 40001, true, flowpb.Verdict_FORWARDED)
api.Destination = &flowpb.Endpoint{Labels: []string{"reserved:host"}}
api.L4 = &flowpb.Layer4{Protocol: &flowpb.Layer4_TCP{TCP: &flowpb.TCP{SourcePort: 40001, DestinationPort: 6443, Flags: &flowpb.TCPFlags{SYN: true}}}}
c.Add(api)
res := c.Query(map[string]bool{"shop": true}, 5*time.Minute)
if len(res.Edges) != 1 || res.Edges[0].Port != "6443/TCP" {
t.Errorf("want only the pod -> API server edge, got %+v", res.Edges)
}
}
@@ -0,0 +1,69 @@
/*
Copyright 2026 The cluster-map Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package traffic
import (
"slices"
"strings"
flowpb "github.com/cilium/cilium/api/v1/flow"
"git.project-chimera.ru/fanchji/cluster-map/internal/topology"
)
// endpoint maps a Hubble endpoint to an ID that matches a graph node when
// the peer is one of our workloads. Hubble leaves Endpoint.Workloads empty
// on some flows (typically the half observed on the peer's node), so pods
// are resolved through the cache with the graph's own rules first, and
// Hubble's workload name is only a fallback for pods already gone.
func (c *Collector) endpoint(e *flowpb.Endpoint, names []string, nodeName string) Endpoint {
if pod := e.GetPodName(); pod != "" {
ns := e.GetNamespace()
if c.resolve != nil {
if ep, ok := c.resolve(ns, pod); ok {
return ep
}
}
for _, wl := range e.GetWorkloads() {
kind, name := strings.ToLower(wl.GetKind()), wl.GetName()
if kind == "job" {
if cj, ok := topology.CronJobFromJob(name); ok {
kind, name = "cronjob", cj
}
}
if kind != "" && name != "" {
return Endpoint{ID: topology.WorkloadID(ns, kind, name), Label: name, Kind: kind, Namespace: ns}
}
}
return Endpoint{ID: "pod/" + ns + "/" + pod, Label: pod, Kind: "pod", Namespace: ns}
}
labels := e.GetLabels()
switch {
case slices.Contains(labels, "reserved:host"):
return Endpoint{ID: "ext/host/" + nodeName, Label: "host " + nodeName, Kind: "external"}
case slices.Contains(labels, "reserved:remote-node"):
return Endpoint{ID: "ext/remote-node", Label: "remote nodes", Kind: "external"}
case slices.Contains(labels, "reserved:kube-apiserver"):
return Endpoint{ID: "ext/kube-apiserver", Label: "kube-apiserver", Kind: "external"}
case slices.Contains(labels, "reserved:health"):
return Endpoint{ID: "ext/health", Label: "cilium health", Kind: "external"}
}
if len(names) > 0 {
return Endpoint{ID: "ext/dns/" + names[0], Label: names[0], Kind: "external"}
}
return Endpoint{ID: "ext/world", Label: "world", Kind: "external"}
}
@@ -0,0 +1,259 @@
/*
Copyright 2026 The cluster-map Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package traffic
import (
"net/url"
"regexp"
"sort"
"strconv"
"strings"
"time"
flowpb "github.com/cilium/cilium/api/v1/flow"
)
// HTTP statistics come from Hubble's L7 events, which exist only where a
// CiliumNetworkPolicy sends a port through Envoy (see docs: "HTTP
// details"). Only RESPONSE events are read: they carry the method, URL,
// status and latency together. Headers are never stored (and not even
// requested, see flowFields); the query string is cut off the URL, since
// tokens travel there too.
// latencyBoundsMs are the histogram buckets; percentiles are reported as
// the upper bound of the bucket they fall in.
var latencyBoundsMs = []float64{1, 2, 5, 10, 25, 50, 100, 250, 500, 1000, 2500, 5000, 10000}
// maxPathsPerEdge bounds memory per edge per minute; beyond it requests
// still count, the path breakdown just stops growing.
const maxPathsPerEdge = 64
type hist [14]int // len(latencyBoundsMs)+1
func (h *hist) add(ms float64) {
i := sort.SearchFloat64s(latencyBoundsMs, ms)
h[i]++
}
func (h *hist) merge(o *hist) {
for i := range h {
h[i] += o[i]
}
}
// quantile returns the upper bound (ms) of the bucket holding the q-th
// request; for the overflow bucket, the largest bound.
func (h *hist) quantile(q float64) float64 {
total := 0
for _, n := range h {
total += n
}
if total == 0 {
return 0
}
target, seen := int(q*float64(total)+0.999999), 0
for i, n := range h {
seen += n
if seen >= target {
if i < len(latencyBoundsMs) {
return latencyBoundsMs[i]
}
return latencyBoundsMs[len(latencyBoundsMs)-1]
}
}
return latencyBoundsMs[len(latencyBoundsMs)-1]
}
type pathKey struct{ method, path string }
type pathAgg struct {
count, errors int
lat hist
}
type httpAgg struct {
status [6]int // index = first digit of the code, 0 for anything else
lat hist
paths map[pathKey]*pathAgg
last int64
}
// HTTPStats is the HTTP part of a traffic edge.
type HTTPStats struct {
Requests int `json:"requests"`
Status map[string]int `json:"status"` // "2xx", "3xx", "4xx", "5xx", "other"
P50Ms float64 `json:"p50Ms"`
P95Ms float64 `json:"p95Ms"`
Paths []HTTPPath `json:"paths"`
lat hist
}
// HTTPPath is one method and path template on an edge.
type HTTPPath struct {
Method string `json:"method"`
Path string `json:"path"`
Count int `json:"count"`
Errors int `json:"errors"` // 5xx
P95Ms float64 `json:"p95Ms"`
}
var idSegment = regexp.MustCompile(`^([0-9]+|[0-9a-fA-F]{8,}|[0-9a-fA-F]{8}-[0-9a-fA-F-]{27,}|.{41,})$`)
// PathTemplate reduces a URL to a low-cardinality path: no scheme, host
// or query, and segments that look like IDs (numbers, hex, UUIDs, long
// tokens) replaced by ":id".
func PathTemplate(raw string) string {
p := raw
if u, err := url.Parse(raw); err == nil {
p = u.Path
} else if i := strings.IndexAny(p, "?#"); i >= 0 {
p = p[:i]
}
if p == "" {
return "/"
}
segs := strings.Split(p, "/")
for i, s := range segs {
if s != "" && idSegment.MatchString(s) {
segs[i] = ":id"
}
}
out := strings.Join(segs, "/")
if len(out) > 100 {
out = out[:100] + "…"
}
return out
}
// addHTTP records one L7 RESPONSE event, turned around into the request's
// direction (client -> server). Called with c.mu held.
func (c *Collector) addHTTP(b *bucket, f *flowpb.Flow, client, server Endpoint, ts time.Time) {
h := f.GetL7().GetHttp()
if h == nil || f.GetL7().GetType() != flowpb.L7FlowType_RESPONSE {
return
}
port := "?"
if t := f.GetL4().GetTCP(); t != nil {
port = strconv.FormatUint(uint64(t.GetSourcePort()), 10) + "/TCP" // the server's side of the response
}
k := edgeKey{client.ID, server.ID, port}
if b.http == nil {
b.http = map[edgeKey]*httpAgg{}
}
a := b.http[k]
if a == nil {
a = &httpAgg{paths: map[pathKey]*pathAgg{}}
b.http[k] = a
}
code := int(h.GetCode())
class := 0
if code >= 100 && code < 600 {
class = code / 100
}
a.status[class]++
ms := float64(f.GetL7().GetLatencyNs()) / 1e6
a.lat.add(ms)
a.last = max(a.last, ts.Unix())
pk := pathKey{h.GetMethod(), PathTemplate(h.GetUrl())}
pa := a.paths[pk]
if pa == nil {
if len(a.paths) >= maxPathsPerEdge {
return
}
pa = &pathAgg{}
a.paths[pk] = pa
}
pa.count++
if class == 5 {
pa.errors++
}
pa.lat.add(ms)
}
// httpStats merges an edge's per-minute aggregates into its report.
func httpStats(aggs []*httpAgg) *HTTPStats {
var status [6]int
var lat hist
paths := map[pathKey]*pathAgg{}
for _, a := range aggs {
for i, n := range a.status {
status[i] += n
}
lat.merge(&a.lat)
for k, p := range a.paths {
m := paths[k]
if m == nil {
m = &pathAgg{}
paths[k] = m
}
m.count += p.count
m.errors += p.errors
m.lat.merge(&p.lat)
}
}
s := &HTTPStats{Status: map[string]int{}, lat: lat}
for i, n := range status {
if n == 0 {
continue
}
s.Requests += n
if i == 0 {
s.Status["other"] += n
} else {
s.Status[strconv.Itoa(i)+"xx"] = n
}
}
s.P50Ms, s.P95Ms = lat.quantile(0.5), lat.quantile(0.95)
for k, p := range paths {
s.Paths = append(s.Paths, HTTPPath{Method: k.method, Path: k.path, Count: p.count, Errors: p.errors, P95Ms: p.lat.quantile(0.95)})
}
sort.Slice(s.Paths, func(i, j int) bool {
if s.Paths[i].Count != s.Paths[j].Count {
return s.Paths[i].Count > s.Paths[j].Count
}
return s.Paths[i].Method+s.Paths[i].Path < s.Paths[j].Method+s.Paths[j].Path
})
if len(s.Paths) > 10 {
s.Paths = s.Paths[:10]
}
return s
}
// mergeHTTP folds b into a, for edges merged by Restrict.
func mergeHTTP(a, b *HTTPStats) *HTTPStats {
if a == nil {
return b
}
if b == nil {
return a
}
out := &HTTPStats{Requests: a.Requests + b.Requests, Status: map[string]int{}, lat: a.lat}
out.lat.merge(&b.lat)
for k, n := range a.Status {
out.Status[k] += n
}
for k, n := range b.Status {
out.Status[k] += n
}
out.P50Ms, out.P95Ms = out.lat.quantile(0.5), out.lat.quantile(0.95)
out.Paths = append(append([]HTTPPath{}, a.Paths...), b.Paths...)
sort.Slice(out.Paths, func(i, j int) bool { return out.Paths[i].Count > out.Paths[j].Count })
if len(out.Paths) > 10 {
out.Paths = out.Paths[:10]
}
return out
}
+35
View File
@@ -0,0 +1,35 @@
/*
Copyright 2026 The cluster-map Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Package web embeds the frontend so the binary needs no files on disk.
package web
import (
"embed"
"io/fs"
)
//go:embed static
var files embed.FS
// Static returns the frontend rooted at static/.
func Static() fs.FS {
sub, err := fs.Sub(files, "static")
if err != nil {
panic(err) // the embed directive guarantees the directory exists
}
return sub
}
@@ -66,7 +66,9 @@ select, input[type="search"] {
flex: none; flex: none;
} }
.brand { font-weight: 650; letter-spacing: 0.01em; } .brand { font-weight: 650; letter-spacing: 0.01em; }
.crumbs { display: flex; flex-wrap: wrap; align-items: center; gap: 0.35rem; flex: 1; min-width: 0; } .crumbs { display: flex; align-items: center; gap: 0.35rem; flex: 1; min-width: 0; overflow: hidden; white-space: nowrap; }
.crumbs > * { flex: none; }
.crumbs > :last-child { flex: 0 1 auto; min-width: 0; overflow: hidden; text-overflow: ellipsis; }
.crumbs button { .crumbs button {
background: none; border: none; color: var(--accent); font: inherit; cursor: pointer; padding: 0.1rem 0.2rem; border-radius: 4px; background: none; border: none; color: var(--accent); font: inherit; cursor: pointer; padding: 0.1rem 0.2rem; border-radius: 4px;
} }
@@ -147,6 +149,7 @@ select, input[type="search"] {
.legend .line { width: 22px; height: 0; border-top: 2px solid var(--muted); } .legend .line { width: 22px; height: 0; border-top: 2px solid var(--muted); }
.legend .line.traffic { border-top: 3px dashed var(--accent); } .legend .line.traffic { border-top: 3px dashed var(--accent); }
.legend .line.drop { border-top: 3px dashed var(--error); } .legend .line.drop { border-top: 3px dashed var(--error); }
.legend .line.http5xx { border-top: 3px dashed var(--warn); }
.legend .line.config { border-top: 1.5px solid var(--muted); } .legend .line.config { border-top: 1.5px solid var(--muted); }
/* details panel */ /* details panel */
@@ -181,11 +184,12 @@ select, input[type="search"] {
.section-title { font-size: 0.72rem; text-transform: uppercase; letter-spacing: 0.05em; color: var(--muted); margin: 1rem 0 0.4rem; } .section-title { font-size: 0.72rem; text-transform: uppercase; letter-spacing: 0.05em; color: var(--muted); margin: 1rem 0 0.4rem; }
.link-list { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 0.2rem; } .link-list { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 0.2rem; }
.link-list button { .link-list button {
width: 100%; display: flex; align-items: center; gap: 0.5rem; text-align: left; width: 100%; display: flex; flex-wrap: wrap; align-items: center; gap: 0.2rem 0.5rem; text-align: left;
background: var(--panel-2); border: 1px solid var(--line); border-radius: 6px; background: var(--panel-2); border: 1px solid var(--line); border-radius: 6px;
padding: 0.35rem 0.5rem; color: var(--text); font: inherit; cursor: pointer; padding: 0.35rem 0.5rem; color: var(--text); font: inherit; cursor: pointer;
} }
.link-list button:hover { border-color: var(--accent); } .link-list button:hover { border-color: var(--accent); }
.link-list button > span:nth-child(2) { flex: 1 1 10rem; min-width: 0; overflow-wrap: anywhere; }
.link-list .meta { margin-left: auto; color: var(--muted); font-size: 0.72rem; font-variant-numeric: tabular-nums; white-space: nowrap; } .link-list .meta { margin-left: auto; color: var(--muted); font-size: 0.72rem; font-variant-numeric: tabular-nums; white-space: nowrap; }
.link-list .drop { color: var(--error); } .link-list .drop { color: var(--error); }
.code { .code {
@@ -197,6 +201,118 @@ select, input[type="search"] {
.logs-bar { display: flex; gap: 0.4rem; margin-bottom: 0.5rem; flex-wrap: wrap; } .logs-bar { display: flex; gap: 0.4rem; margin-bottom: 0.5rem; flex-wrap: wrap; }
.logs-bar select { max-width: 100%; } .logs-bar select { max-width: 100%; }
/* problem badges */
.pbadge {
display: inline-grid; place-items: center; flex: none;
width: 15px; height: 15px; border-radius: 50%;
font-size: 0.65rem; font-weight: 800; line-height: 1; color: #fff;
}
.pbadge.warning { background: var(--warn); }
.pbadge.critical { background: var(--error); }
.pbadge.info { background: var(--idle); }
.tree .pbadge { width: 13px; height: 13px; font-size: 0.6rem; }
.legend .pbadge { display: inline-grid; width: 13px; height: 13px; font-size: 0.6rem; }
.problems-btn { display: inline-flex; align-items: center; gap: 0.4rem; }
.problems-btn.ok { color: var(--muted); }
.problems-btn.warning { border-color: var(--warn); }
.problems-btn.critical { border-color: var(--error); }
.whoami { max-width: 14rem; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.summary { display: flex; align-items: center; gap: 0.45rem; margin: 0 0 0.8rem; font-weight: 600; }
.summary.ok { color: var(--ok); }
.summary.warning { color: var(--warn); }
.summary.critical { color: var(--error); }
.summary.idle { color: var(--muted); }
.problem-list { list-style: none; margin: 0 0 0.8rem; padding: 0; display: flex; flex-direction: column; gap: 0.25rem; }
.problem .p-row {
width: 100%; display: flex; align-items: flex-start; gap: 0.5rem; text-align: left;
background: var(--panel-2); border: 1px solid var(--line); border-left-width: 3px; border-radius: 6px;
padding: 0.4rem 0.5rem; color: var(--text); font: inherit;
}
button.p-row { cursor: pointer; }
button.p-row:hover { border-color: var(--accent); }
.problem.warning .p-row { border-left-color: var(--warn); }
.problem.critical .p-row { border-left-color: var(--error); }
.problem.info .p-row { border-left-color: var(--idle); }
.p-body { display: flex; flex-direction: column; gap: 0.1rem; min-width: 0; flex: 1; }
.p-target { display: inline-flex; align-items: center; gap: 0.3rem; font-weight: 600; }
.p-reason { overflow-wrap: anywhere; }
.p-src { margin-left: 0.4rem; font-size: 0.66rem; text-transform: uppercase; letter-spacing: 0.04em; color: var(--muted); border: 1px solid var(--line); border-radius: 4px; padding: 0 0.25rem; }
.p-msg { font-size: 0.72rem; overflow-wrap: anywhere; display: -webkit-box; -webkit-line-clamp: 3; line-clamp: 3; -webkit-box-orient: vertical; overflow: hidden; }
.problem .meta { margin-left: auto; white-space: nowrap; }
.p-info summary { cursor: pointer; color: var(--muted); margin: 0.6rem 0 0.4rem; }
.p-filter { margin: 0 0.9rem 0.3rem; }
/* actions */
.d-actions { display: flex; flex-wrap: wrap; gap: 0.35rem; padding: 0 0.9rem 0.6rem; }
.d-actions:empty { display: none; }
.btn.small { padding: 0.15rem 0.5rem; font-size: 0.75rem; }
.btn.primary { background: var(--accent); border-color: var(--accent); color: #fff; }
.btn.primary.danger { background: var(--error); border-color: var(--error); }
#lock.unlocked { border-color: var(--warn); color: var(--warn); }
dialog {
background: var(--panel); color: var(--text);
border: 1px solid var(--line); border-radius: 10px; padding: 1rem 1.1rem;
width: min(28rem, calc(100vw - 2rem)); box-shadow: 0 10px 40px #0006;
}
dialog::backdrop { background: #0008; }
dialog h2 { margin: 0 0 0.5rem; font-size: 1rem; overflow-wrap: anywhere; }
dialog p { margin: 0 0 0.8rem; color: var(--muted); }
.confirm-input { display: flex; align-items: center; gap: 0.5rem; margin-bottom: 0.8rem; }
.confirm-input input { width: 6rem; background: var(--panel-2); color: var(--text); border: 1px solid var(--line); border-radius: 6px; padding: 0.3rem 0.5rem; font: inherit; }
.confirm-input[hidden] { display: none; }
.confirm-buttons { display: flex; justify-content: flex-end; gap: 0.5rem; }
.toast {
position: absolute; top: 2.6rem; left: 50%; transform: translateX(-50%); z-index: 5;
max-width: min(36rem, 90%); background: var(--panel); border: 1px solid var(--line); border-left: 3px solid var(--ok);
border-radius: 8px; padding: 0.45rem 0.8rem; box-shadow: 0 4px 16px #0004; overflow-wrap: anywhere;
}
.toast.error { border-left-color: var(--error); }
.toast[hidden] { display: none; }
/* load */
.usage-row { margin-bottom: 0.6rem; }
.usage-head { display: flex; align-items: baseline; gap: 0.5rem; flex-wrap: wrap; }
.usage-head span:first-child { color: var(--muted); min-width: 4rem; }
.usage-row meter { width: 100%; height: 0.55rem; }
table.pods { width: 100%; border-collapse: collapse; margin-top: 0.4rem; font-size: 0.75rem; }
table.pods th { text-align: left; color: var(--muted); font-weight: 500; padding: 0.2rem 0.3rem; border-bottom: 1px solid var(--line); }
table.pods td { padding: 0.3rem; border-bottom: 1px solid var(--line); vertical-align: top; overflow-wrap: anywhere; }
table.pods .warn-text { color: var(--warn); font-weight: 600; }
/* vulnerabilities */
.vuln-crit { color: var(--error); font-weight: 600; }
.sev-chip { display: inline-grid; place-items: center; width: 14px; height: 14px; border-radius: 3px; font-size: 0.6rem; font-weight: 800; color: #fff; }
.sev-chip.critical { background: var(--error); }
.sev-chip.high { background: var(--warn); }
table.vulns a { color: var(--accent); }
.shield-legend { display: inline-block; width: 10px; height: 12px; background: var(--error); clip-path: polygon(50% 0, 100% 15%, 100% 50%, 50% 100%, 0 50%, 0 15%); }
/* HTTP on traffic links */
.link-list .http-li { list-style: none; margin: -0.1rem 0 0.3rem 1.4rem; }
table.http-paths { margin-top: 0; font-size: 0.72rem; }
/* events */
.event-list { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 0.35rem; }
.event-list li { border-left: 3px solid var(--line); padding: 0.1rem 0 0.1rem 0.5rem; }
.event-list li.warning { border-left-color: var(--warn); }
.ev-head { display: flex; gap: 0.4rem; align-items: baseline; }
.ev-reason { font-weight: 600; }
.ev-time { margin-left: auto; white-space: nowrap; }
.ev-msg { overflow-wrap: anywhere; }
@media (max-width: 1280px) {
.whoami { display: none; }
}
@media (max-width: 1100px) {
#updated { display: none; }
.topbar { gap: 0.6rem; }
}
@media (prefers-reduced-motion: reduce) { @media (prefers-reduced-motion: reduce) {
* { transition: none !important; animation: none !important; } * { transition: none !important; animation: none !important; }
} }
File diff suppressed because it is too large Load Diff
+291
View File
@@ -0,0 +1,291 @@
'use strict';
/* UI strings in English and Russian. Language: ?lang=, then the saved
choice, then the browser. Plural forms go through Intl.PluralRules, so
every plural key has one entry per category the language uses. */
const I18N = {
en: {
'kind.pod': 'Controller', 'kind.external': 'External', 'folder.pod': 'Other controllers',
'health.ok': 'healthy', 'health.warn': 'partly ready', 'health.error': 'not ready', 'health.idle': 'stopped',
'sub.ready': '{ready}/{want} ready', 'sub.onNodes': '{ready}/{want} on nodes', 'sub.paused': '{schedule} · suspended',
'tree.cluster': 'Cluster', 'tree.apps': 'Applications', 'tree.system': 'System ({prefixes})', 'group.apps': 'Applications', 'group.system': 'System',
'node': 'node {name}',
'edge.conns': '{n} conn.', 'edge.new': ', {n} new', 'edge.drop': ' · drop {n}',
'status.loadingTraffic': 'loading traffic…', 'status.loadingGraph': 'loading graph…',
'status.graphFailed': 'could not load the graph: HTTP {code}', 'status.renderFailed': 'could not draw the map: {error}', 'status.empty': 'nothing here',
'status.noRelay': 'no connection to Hubble Relay', 'status.trafficFailed': 'traffic unavailable: {err}',
'status.partial': '{covered} (of {window}: collecting since start)',
'status.onDemandPartial': '{covered} (of {window}: collecting since the map was opened)',
'status.lost': 'lost connection to Hubble ({err}), data may be stale', 'status.noAnswer': 'no answer',
'status.hoverHint': ' — hover a card to see its traffic',
'status.more': '; {n} more — press "Refresh"',
'status.traffic': 'traffic over {window}: {edges}, {conns}{hint}{more}', 'status.noTraffic': 'no traffic over {window}{more}',
'status.trafficOff': 'traffic collection is disabled in the module settings',
'plural.direction': { one: '{n} direction', other: '{n} directions' },
'plural.newDirection': { one: '{n} new direction', other: '{n} new directions' },
'plural.connection': { one: '{n} connection', other: '{n} connections' },
'plural.second': { one: '{n} second', other: '{n} seconds' },
'plural.hour': { one: '{n} hour', other: '{n} hours' },
'unit.min': '{n} min',
'crumb.remove': 'Remove {ns}',
'legend.cluster': 'Card — namespace, dot — the worst state of its workloads:',
'legend.config': 'configuration (Ingress → Service → Pod)', 'legend.traffic': 'real traffic (Hubble)',
'legend.drop': 'dropped', 'legend.ghost': 'dashed card — from another namespace',
'legend.notCollected': 'not collected: kubelet probes and node host traffic, DNS, cilium health',
'fact.replicas': 'Replicas', 'fact.readyReplicas': 'Ready', 'fact.desired': 'Desired', 'fact.ready': 'Ready', 'fact.image': 'Image',
'fact.schedule': 'Schedule', 'fact.suspended': 'Suspended', 'fact.active': 'Active runs', 'fact.lastSuccess': 'Last success (UTC)',
'fact.type': 'Type', 'fact.ports': 'Ports', 'fact.hosts': 'Hosts', 'fact.class': 'IngressClass', 'fact.os': 'OS',
'fact.kubelet': 'kubelet', 'fact.controller': 'Controller', 'fact.pods': 'Pods',
'details.state': 'State', 'details.runsOn': 'Runs on nodes', 'details.namespace': 'namespace {ns}',
'details.outside': 'outside the cluster or a service address',
'details.ghostPod': 'This workload shows up in traffic but not in the graph: a pod without a controller, or already deleted.',
'details.external': 'An address the pods in this view talked to. The name comes from DNS if Hubble saw the lookup.',
'link.route': 'route', 'link.selector': 'selector', 'link.none': 'none',
'link.trafficOff': 'traffic is off', 'link.trafficFailed': 'traffic unavailable', 'link.noTraffic': 'none in the selected window',
'link.cfgIn': 'Configuration: what points here', 'link.cfgOut': 'Configuration: what this points to',
'link.trafficIn': 'Traffic: incoming connections', 'link.trafficOut': 'Traffic: outgoing connections',
'loading': 'loading…', 'yaml.failed': 'could not get the manifest: HTTP {code}',
'logs.noPods': 'no live pods', 'logs.noPodsText': 'This workload has no pods right now.', 'logs.loading': 'loading logs…',
'logs.empty': '(log is empty)', 'logs.failed': 'could not get logs: HTTP {code}',
'updated': 'updated {time}',
'ext.world': 'world', 'ext.remote-node': 'remote nodes', 'ext.kube-apiserver': 'kube-apiserver', 'ext.health': 'cilium health',
'html.traffic': 'Traffic', 'html.window': 'Traffic window', 'html.min5': '5 min', 'html.min15': '15 min', 'html.hour': '1 hour',
'html.refresh': 'Refresh', 'html.inventory': 'Inventory', 'html.grouping': 'Grouping', 'html.nodes': 'Nodes',
'html.search': 'Search: name, namespace, image…', 'html.searchLabel': 'Search the inventory', 'html.treeLabel': 'Cluster objects',
'html.hint': 'Click to open on the map. Ctrl+click a namespace to add it to the current view.',
'html.map': 'Map', 'html.zoomIn': 'Zoom in', 'html.zoomOut': 'Zoom out', 'html.fit': 'Fit', 'html.zoom': 'Zoom',
'html.details': 'Object details', 'html.close': 'Close panel', 'html.sections': 'Sections',
'html.overview': 'Overview', 'html.links': 'Links', 'html.logs': 'Logs', 'html.pod': 'Pod', 'html.container': 'Container',
'html.view': 'Current view', 'html.lang': 'Language',
'html.lock': 'Lock card positions', 'html.lockedTitle': 'Cards are locked. Click to move them', 'html.unlockedTitle': 'Cards can be dragged. Click to lock',
'html.exportPng': 'Save the map as a picture', 'html.actions': 'Actions', 'html.events': 'Events',
'html.problems': 'Problems', 'html.problemsScope': 'Which problems', 'html.scopeAll': 'All',
'lock.on': 'Cards are locked', 'lock.off': 'Cards unlocked: drag them, then lock again',
'png.failed': 'could not save the picture: {err}',
'sev.critical': 'error', 'sev.warning': 'warning', 'sev.info': 'for information',
'legend.warning': 'warning', 'legend.critical': 'error',
'ago': '{d} ago',
'summary.ok': 'Everything works', 'summary.idle': 'Stopped: nothing is supposed to run',
'summary.critical': 'Not working properly: {n}', 'summary.warning': 'Works, with {n}',
'plural.problem': { one: '{n} problem', other: '{n} problems' },
'plural.critical': { one: '{n} error', other: '{n} errors' },
'plural.warning': { one: '{n} warning', other: '{n} warnings' },
'details.problems': 'Problems',
'problems.none': 'No problems', 'problems.button': 'Problems: {n}', 'problems.cluster': 'Cluster',
'problems.alert': 'alert', 'problems.sub': '{crit}, {warn}', 'problems.allGood': 'No problems right now.',
'problems.info': 'For information, no badge: {n}',
'problems.noAlerts': 'Prometheus alerts are not shown: the ClusterAlert resource is not served in this cluster.',
'problem.NotReady': 'No replica is ready', 'problem.PartlyReady': 'Not all replicas are ready',
'problem.CrashLoopBackOff': 'Container keeps crashing', 'problem.ImagePullBackOff': 'Image cannot be pulled',
'problem.ErrImagePull': 'Image cannot be pulled', 'problem.InvalidImageName': 'Invalid image name',
'problem.CreateContainerConfigError': 'Container configuration error (a missing Secret or ConfigMap?)',
'problem.CreateContainerError': 'Container cannot be created', 'problem.RunContainerError': 'Container cannot be started',
'problem.OOMKilled': 'Killed for running out of memory', 'problem.Restarted': 'Restarted recently',
'problem.Pending': 'Pod has been pending for over 5 minutes', 'problem.Unschedulable': 'Pod cannot be scheduled',
'problem.Evicted': 'Pod was evicted', 'problem.ProgressDeadlineExceeded': 'Rollout is stuck',
'problem.LastRunFailed': 'Last run did not succeed', 'problem.NoEndpoints': 'No ready pod behind the Service',
'problem.BackendMissing': 'Routes to a Service that does not exist', 'problem.NodeNotReady': 'Node is not ready',
'problem.MemoryPressure': 'Node is short of memory', 'problem.DiskPressure': 'Node is short of disk',
'problem.PIDPressure': 'Node is short of process IDs', 'problem.Cordoned': 'Node is cordoned: no new pods',
'usage.title': 'Load', 'usage.memory': 'Memory', 'usage.request': 'request {v}', 'usage.limit': 'limit {v}',
'usage.capacity': 'of {v}', 'usage.failed': 'could not read the load: HTTP {code}',
'usage.noMetrics': 'Current usage is unknown: the metrics.k8s.io API did not answer.',
'usage.pod': 'Pod', 'usage.restarts': 'Restarts', 'usage.ready': 'ready', 'usage.notReady': 'not ready',
'events.failed': 'could not read events: HTTP {code}', 'events.none': 'No events in the last hour.',
'action.restart': 'Restart', 'action.scale': 'Scale', 'action.run': 'Run now', 'action.suspend': 'Suspend',
'action.resume': 'Resume', 'action.cordon': 'Cordon', 'action.uncordon': 'Uncordon', 'action.delete-pod': 'Delete',
'action.deletePodHint': 'Delete this pod; its controller starts a new one',
'action.cancel': 'Cancel', 'action.replicas': 'Replicas',
'action.noRights': 'Your role allows no actions here.',
'action.unavailable.noToken': 'Actions need the user token from the DexAuthenticator; it is not in the request.',
'action.unavailable.rejected': 'The API server did not accept your token; sign in again.',
'action.unavailable.disabled': '',
'action.badReplicas': 'Replicas must be a whole number from 0 to 100.',
'action.failed': 'Not done: {err}', 'action.done': '{what}: {target} — done',
'confirm.restart': 'All pods of {target} are replaced one by one, as with kubectl rollout restart.',
'confirm.scale': 'How many replicas should {target} run?',
'confirm.run': 'A Job is created from the {target} template right now, outside the schedule.',
'confirm.suspend': 'No new runs of {target} start until it is resumed.',
'confirm.resume': '{target} runs on its schedule again.',
'confirm.cordon': 'No new pods are scheduled on {target}. Running pods stay.',
'confirm.uncordon': 'New pods can be scheduled on {target} again.',
'confirm.delete-pod': 'Pod {target} in {ns} is deleted; its controller starts a new one.',
'vulns.title': 'Vulnerabilities', 'vulns.none': 'No CRITICAL or HIGH vulnerabilities found in the scanned images.',
'vulns.fixable': 'fixed in a newer version: {n}', 'vulns.failed': 'could not read vulnerabilities: HTTP {code}',
'vulns.cve': 'CVE', 'vulns.package': 'Package', 'vulns.version': 'Installed → fixed', 'vulns.noFix': 'no fix yet',
'vulns.more': 'and {n} more',
'plural.critical_cve': { one: '{n} critical', other: '{n} critical' },
'plural.high_cve': { one: '{n} high', other: '{n} high' },
'legend.vulns': 'critical vulnerabilities in the images (trivy)',
'ext.restricted': 'hidden by your permissions',
'status.noViewerToken': 'The map shows what your own permissions allow, but the request carries no user token. Sign in again; if it repeats, the DexAuthenticator does not pass the Authorization header.',
'plural.visibleNs': { one: '{n} namespace visible', other: '{n} namespaces visible' },
'visibility.namespaces': 'You see the namespaces where your role can list pods; peers elsewhere are shown as hidden.',
'http.summary': 'HTTP {n} req, p95 {p95}', 'http.errors': ', {pct}% 5xx', 'http.path': 'Path', 'http.requests': 'Requests',
'legend.http5xx': 'HTTP 5xx on the link',
},
ru: {
'kind.pod': 'Контроллер', 'kind.external': 'Внешний', 'folder.pod': 'Другие контроллеры',
'health.ok': 'в норме', 'health.warn': 'готов частично', 'health.error': 'не готов', 'health.idle': 'выключен',
'sub.ready': '{ready}/{want} готово', 'sub.onNodes': '{ready}/{want} на нодах', 'sub.paused': '{schedule} · пауза',
'tree.cluster': 'Кластер', 'tree.apps': 'Приложения', 'tree.system': 'Системные ({prefixes})', 'group.apps': 'Приложения', 'group.system': 'Системные',
'node': 'нода {name}',
'edge.conns': '{n} соед.', 'edge.new': ', новых {n}', 'edge.drop': ' · drop {n}',
'status.loadingTraffic': 'загрузка трафика…', 'status.loadingGraph': 'загрузка графа…',
'status.graphFailed': 'не удалось загрузить граф: HTTP {code}', 'status.renderFailed': 'не удалось нарисовать карту: {error}', 'status.empty': 'здесь нет объектов',
'status.noRelay': 'нет связи с Hubble Relay', 'status.trafficFailed': 'трафик недоступен: {err}',
'status.partial': '{covered} (из {window}: сбор идёт с запуска)',
'status.onDemandPartial': '{covered} (из {window}: сбор идёт с открытия карты)',
'status.lost': 'связь с Hubble потеряна ({err}), данные могут устареть', 'status.noAnswer': 'нет ответа',
'status.hoverHint': ' — наведите на карточку, чтобы увидеть её трафик',
'status.more': '; ещё {n} — «Обновить»',
'status.traffic': 'трафик за {window}: {edges}, {conns}{hint}{more}', 'status.noTraffic': 'трафика за {window} не видно{more}',
'status.trafficOff': 'сбор трафика выключен в настройках модуля',
'plural.direction': { one: '{n} направление', few: '{n} направления', many: '{n} направлений', other: '{n} направления' },
'plural.newDirection': { one: '{n} новое направление', few: '{n} новых направления', many: '{n} новых направлений', other: '{n} новых направления' },
'plural.connection': { one: '{n} соединение', few: '{n} соединения', many: '{n} соединений', other: '{n} соединения' },
'plural.second': { one: '{n} секунду', few: '{n} секунды', many: '{n} секунд', other: '{n} секунды' },
'plural.hour': { one: '{n} час', few: '{n} часа', many: '{n} часов', other: '{n} часа' },
'unit.min': '{n} мин',
'crumb.remove': 'Убрать {ns}',
'legend.cluster': 'Карточка — namespace, точка — худшее состояние его workload’ов:',
'legend.config': 'по конфигурации (Ingress → Service → Pod)', 'legend.traffic': 'реальный трафик (Hubble)',
'legend.drop': 'есть drop', 'legend.ghost': 'пунктирная карточка — из другого namespace',
'legend.notCollected': 'не собирается: пробы kubelet и трафик с хостов нод, DNS, cilium health',
'fact.replicas': 'Реплик', 'fact.readyReplicas': 'Готово', 'fact.desired': 'Нужно', 'fact.ready': 'Готово', 'fact.image': 'Образ',
'fact.schedule': 'Расписание', 'fact.suspended': 'Пауза', 'fact.active': 'Активных запусков', 'fact.lastSuccess': 'Последний успех (UTC)',
'fact.type': 'Тип', 'fact.ports': 'Порты', 'fact.hosts': 'Хосты', 'fact.class': 'IngressClass', 'fact.os': 'ОС',
'fact.kubelet': 'kubelet', 'fact.controller': 'Контроллер', 'fact.pods': 'Подов',
'details.state': 'Состояние', 'details.runsOn': 'Работает на нодах', 'details.namespace': 'namespace {ns}',
'details.outside': 'за пределами кластера или служебный адрес',
'details.ghostPod': 'Этот workload есть в трафике, но его нет в графе: под без контроллера или уже удалён.',
'details.external': 'Адрес, с которым общались поды из текущего вида. Имя — из DNS, если Hubble видел запрос.',
'link.route': 'маршрут', 'link.selector': 'селектор', 'link.none': 'нет',
'link.trafficOff': 'трафик выключен', 'link.trafficFailed': 'трафик недоступен', 'link.noTraffic': 'нет за выбранное окно',
'link.cfgIn': 'Конфигурация: кто ссылается сюда', 'link.cfgOut': 'Конфигурация: куда ссылается',
'link.trafficIn': 'Трафик: входящие соединения', 'link.trafficOut': 'Трафик: исходящие соединения',
'loading': 'загрузка…', 'yaml.failed': 'не удалось получить манифест: HTTP {code}',
'logs.noPods': 'нет живых подов', 'logs.noPodsText': 'У этого workload сейчас нет подов.', 'logs.loading': 'загрузка логов…',
'logs.empty': '(лог пуст)', 'logs.failed': 'не удалось получить логи: HTTP {code}',
'updated': 'обновлено {time}',
'ext.world': 'интернет', 'ext.remote-node': 'другие ноды', 'ext.kube-apiserver': 'kube-apiserver', 'ext.health': 'cilium health',
'html.traffic': 'Трафик', 'html.window': 'Окно трафика', 'html.min5': '5 мин', 'html.min15': '15 мин', 'html.hour': '1 час',
'html.refresh': 'Обновить', 'html.inventory': 'Инвентарь', 'html.grouping': 'Группировка', 'html.nodes': 'Ноды',
'html.search': 'Поиск: имя, namespace, образ…', 'html.searchLabel': 'Поиск по инвентарю', 'html.treeLabel': 'Объекты кластера',
'html.hint': 'Клик — открыть на карте. Ctrl+клик по namespace — добавить к текущему виду.',
'html.map': 'Карта', 'html.zoomIn': 'Приблизить', 'html.zoomOut': 'Отдалить', 'html.fit': 'Показать всё', 'html.zoom': 'Масштаб',
'html.details': 'Детали объекта', 'html.close': 'Закрыть панель', 'html.sections': 'Разделы',
'html.overview': 'Обзор', 'html.links': 'Связи', 'html.logs': 'Логи', 'html.pod': 'Под', 'html.container': 'Контейнер',
'html.view': 'Текущий вид', 'html.lang': 'Язык',
'html.lock': 'Закрепить карточки', 'html.lockedTitle': 'Карточки закреплены. Нажмите, чтобы двигать', 'html.unlockedTitle': 'Карточки можно перетаскивать. Нажмите, чтобы закрепить',
'html.exportPng': 'Сохранить карту картинкой', 'html.actions': 'Действия', 'html.events': 'События',
'html.problems': 'Проблемы', 'html.problemsScope': 'Какие проблемы', 'html.scopeAll': 'Все',
'lock.on': 'Карточки закреплены', 'lock.off': 'Карточки откреплены: передвиньте и закрепите снова',
'png.failed': 'не удалось сохранить картинку: {err}',
'sev.critical': 'ошибка', 'sev.warning': 'предупреждение', 'sev.info': 'для сведения',
'legend.warning': 'предупреждение', 'legend.critical': 'ошибка',
'ago': '{d} назад',
'summary.ok': 'Всё работает', 'summary.idle': 'Остановлено: ничего не должно работать',
'summary.critical': 'Работает с ошибками: {n}', 'summary.warning': 'Работает, но есть {n}',
'plural.problem': { one: '{n} проблема', few: '{n} проблемы', many: '{n} проблем', other: '{n} проблемы' },
'plural.critical': { one: '{n} ошибка', few: '{n} ошибки', many: '{n} ошибок', other: '{n} ошибки' },
'plural.warning': { one: '{n} предупреждение', few: '{n} предупреждения', many: '{n} предупреждений', other: '{n} предупреждения' },
'details.problems': 'Проблемы',
'problems.none': 'Проблем нет', 'problems.button': 'Проблемы: {n}', 'problems.cluster': 'Кластер',
'problems.alert': 'алерт', 'problems.sub': '{crit}, {warn}', 'problems.allGood': 'Сейчас проблем нет.',
'problems.info': 'Для сведения, без значка: {n}',
'problems.noAlerts': 'Алерты Prometheus не показаны: в кластере нет ресурса ClusterAlert.',
'problem.NotReady': 'Ни одна реплика не готова', 'problem.PartlyReady': 'Готовы не все реплики',
'problem.CrashLoopBackOff': 'Контейнер падает и перезапускается', 'problem.ImagePullBackOff': 'Не скачивается образ',
'problem.ErrImagePull': 'Не скачивается образ', 'problem.InvalidImageName': 'Неверное имя образа',
'problem.CreateContainerConfigError': 'Ошибка конфигурации контейнера (нет Secret или ConfigMap?)',
'problem.CreateContainerError': 'Контейнер не создаётся', 'problem.RunContainerError': 'Контейнер не запускается',
'problem.OOMKilled': 'Убит за нехватку памяти', 'problem.Restarted': 'Недавно перезапускался',
'problem.Pending': 'Под больше 5 минут ждёт запуска', 'problem.Unschedulable': 'Под некуда запустить',
'problem.Evicted': 'Под выселен с ноды', 'problem.ProgressDeadlineExceeded': 'Выкатка застряла',
'problem.LastRunFailed': 'Последний запуск не удался', 'problem.NoEndpoints': 'За сервисом нет готовых подов',
'problem.BackendMissing': 'Ведёт на несуществующий сервис', 'problem.NodeNotReady': 'Нода не готова',
'problem.MemoryPressure': 'На ноде не хватает памяти', 'problem.DiskPressure': 'На ноде не хватает диска',
'problem.PIDPressure': 'На ноде не хватает PID', 'problem.Cordoned': 'Нода закрыта для новых подов',
'usage.title': 'Нагрузка', 'usage.memory': 'Память', 'usage.request': 'запрос {v}', 'usage.limit': 'лимит {v}',
'usage.capacity': 'из {v}', 'usage.failed': 'не удалось получить нагрузку: HTTP {code}',
'usage.noMetrics': 'Текущее потребление неизвестно: API metrics.k8s.io не ответил.',
'usage.pod': 'Под', 'usage.restarts': 'Рестарты', 'usage.ready': 'готов', 'usage.notReady': 'не готов',
'events.failed': 'не удалось получить события: HTTP {code}', 'events.none': 'За последний час событий нет.',
'action.restart': 'Перезапустить', 'action.scale': 'Масштабировать', 'action.run': 'Запустить сейчас', 'action.suspend': 'Приостановить',
'action.resume': 'Возобновить', 'action.cordon': 'Закрыть для подов', 'action.uncordon': 'Открыть для подов', 'action.delete-pod': 'Удалить',
'action.deletePodHint': 'Удалить под; контроллер запустит новый',
'action.cancel': 'Отмена', 'action.replicas': 'Реплик',
'action.noRights': 'Ваша роль не разрешает здесь действий.',
'action.unavailable.noToken': 'Для действий нужен токен пользователя от DexAuthenticator, в запросе его нет.',
'action.unavailable.rejected': 'API-сервер не принял ваш токен, войдите заново.',
'action.unavailable.disabled': '',
'action.badReplicas': 'Число реплик — целое от 0 до 100.',
'action.failed': 'Не выполнено: {err}', 'action.done': '{what}: {target} — готово',
'confirm.restart': 'Все поды {target} заменяются по очереди, как при kubectl rollout restart.',
'confirm.scale': 'Сколько реплик должно работать у {target}?',
'confirm.run': 'Из шаблона {target} прямо сейчас создаётся Job, вне расписания.',
'confirm.suspend': 'Новые запуски {target} не начнутся, пока его не возобновят.',
'confirm.resume': '{target} снова запускается по расписанию.',
'confirm.cordon': 'На {target} не будут назначаться новые поды. Работающие остаются.',
'confirm.uncordon': 'На {target} снова можно назначать новые поды.',
'confirm.delete-pod': 'Под {target} в {ns} удаляется; контроллер запустит новый.',
'vulns.title': 'Уязвимости', 'vulns.none': 'В проверенных образах нет уязвимостей уровня CRITICAL и HIGH.',
'vulns.fixable': 'исправлено в новой версии: {n}', 'vulns.failed': 'не удалось получить уязвимости: HTTP {code}',
'vulns.cve': 'CVE', 'vulns.package': 'Пакет', 'vulns.version': 'Стоит → исправлено', 'vulns.noFix': 'исправления нет',
'vulns.more': 'и ещё {n}',
'plural.critical_cve': { one: '{n} критическая', few: '{n} критические', many: '{n} критических', other: '{n} критической' },
'plural.high_cve': { one: '{n} высокая', few: '{n} высокие', many: '{n} высоких', other: '{n} высокой' },
'legend.vulns': 'критические уязвимости в образах (trivy)',
'ext.restricted': 'скрыто вашими правами',
'status.noViewerToken': 'Карта показывает то, что разрешают ваши права, но в запросе нет токена пользователя. Войдите заново; если повторится — DexAuthenticator не передаёт заголовок Authorization.',
'plural.visibleNs': { one: 'виден {n} namespace', few: 'видны {n} namespace', many: 'видно {n} namespace', other: 'видны {n} namespace' },
'visibility.namespaces': 'Видны namespace, где ваша роль может смотреть поды; соседи из остальных показаны скрытыми.',
'http.summary': 'HTTP {n} запр., p95 {p95}', 'http.errors': ', {pct}% 5xx', 'http.path': 'Путь', 'http.requests': 'Запросов',
'legend.http5xx': 'есть ответы HTTP 5xx',
},
};
function pickLang() {
const q = new URLSearchParams(location.search).get('lang');
if (q && I18N[q]) return q;
try {
const saved = localStorage.getItem('cluster-map.lang');
if (saved && I18N[saved]) return saved;
} catch { /* storage unavailable */ }
return (navigator.language || 'en').toLowerCase().startsWith('ru') ? 'ru' : 'en';
}
const LANG = pickLang();
const pluralRules = new Intl.PluralRules(LANG);
function fill(s, params) {
return s.replace(/\{(\w+)\}/g, (_, k) => (params[k] ?? `{${k}}`));
}
// t('key', {param}) — plain string; t('plural.key', {n}) — picks the form.
function t(key, params = {}) {
const dict = I18N[LANG];
const v = dict[key] ?? I18N.en[key] ?? key;
if (typeof v === 'object') return fill(v[pluralRules.select(params.n)] ?? v.other, params);
return fill(v, params);
}
function setLang(lang) {
try { localStorage.setItem('cluster-map.lang', lang); } catch { /* storage unavailable */ }
const u = new URL(location.href);
u.searchParams.delete('lang');
location.replace(u);
}
// Elements with data-i18n get textContent, data-i18n-attr="attr:key;attr:key" gets attributes.
function applyStaticI18n(root = document) {
document.documentElement.lang = LANG;
for (const el of root.querySelectorAll('[data-i18n]')) el.textContent = t(el.dataset.i18n);
for (const el of root.querySelectorAll('[data-i18n-attr]')) {
for (const pair of el.dataset.i18nAttr.split(';')) {
const [attr, key] = pair.split(':');
el.setAttribute(attr, t(key));
}
}
}
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64"><rect width="64" height="64" rx="14" fill="#1d2a44"/><g fill="none" stroke="#6aa0ff" stroke-width="3" stroke-linecap="round"><path d="M20 22 32 32l12-10M32 32v14"/></g><g fill="#6aa0ff"><circle cx="20" cy="22" r="6"/><circle cx="44" cy="22" r="6"/><circle cx="32" cy="46" r="6"/></g><circle cx="32" cy="32" r="5" fill="#3fcf7f"/></svg>

After

Width:  |  Height:  |  Size: 396 B

@@ -0,0 +1,120 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="color-scheme" content="light dark">
<title>cluster-map</title>
<link rel="icon" href="icon.svg" type="image/svg+xml">
<link rel="stylesheet" href="app.css">
<script src="i18n.js"></script>
<script src="vendor/cytoscape.min.js"></script>
<script src="vendor/elk.bundled.js"></script>
</head>
<body>
<header class="topbar">
<div class="brand">cluster-map</div>
<nav class="crumbs" id="crumbs" data-i18n-attr="aria-label:html.view"></nav>
<div class="topbar-actions">
<button type="button" id="problems-btn" class="btn problems-btn" aria-controls="problems-panel" aria-expanded="false" hidden></button>
<label class="toggle"><input type="checkbox" id="traffic-on" checked> <span data-i18n="html.traffic"></span></label>
<select id="traffic-window" data-i18n-attr="aria-label:html.window">
<option value="300" data-i18n="html.min5"></option>
<option value="900" data-i18n="html.min15"></option>
<option value="3600" data-i18n="html.hour"></option>
</select>
<button type="button" id="reload" class="btn" data-i18n="html.refresh"></button>
<span class="muted small" id="updated"></span>
<span class="muted small whoami" id="whoami"></span>
<select id="lang" data-i18n-attr="aria-label:html.lang">
<option value="en">EN</option>
<option value="ru">RU</option>
</select>
</div>
</header>
<div class="layout">
<aside class="sidebar" data-i18n-attr="aria-label:html.inventory">
<div class="seg" role="tablist" data-i18n-attr="aria-label:html.grouping">
<button type="button" role="tab" id="view-ns" aria-selected="true" aria-controls="tree">Namespaces</button>
<button type="button" role="tab" id="view-nodes" aria-selected="false" aria-controls="tree" data-i18n="html.nodes"></button>
</div>
<input type="search" id="tree-filter" data-i18n-attr="placeholder:html.search;aria-label:html.searchLabel">
<ul class="tree" id="tree" role="tree" data-i18n-attr="aria-label:html.treeLabel"></ul>
<p class="hint" data-i18n="html.hint"></p>
</aside>
<main class="stage">
<div id="cy" data-i18n-attr="aria-label:html.map"></div>
<div class="stage-status" id="stage-status" role="status" aria-live="polite"></div>
<div class="zoom" role="group" data-i18n-attr="aria-label:html.zoom">
<button type="button" class="btn icon" id="zoom-in" data-i18n-attr="aria-label:html.zoomIn">+</button>
<button type="button" class="btn icon" id="zoom-out" data-i18n-attr="aria-label:html.zoomOut">−</button>
<button type="button" class="btn icon" id="zoom-fit" data-i18n-attr="aria-label:html.fit;title:html.fit">⤢</button>
<button type="button" class="btn icon" id="lock" aria-pressed="true" data-i18n-attr="aria-label:html.lock;title:html.lockedTitle"></button>
<button type="button" class="btn icon" id="export-png" data-i18n-attr="aria-label:html.exportPng;title:html.exportPng">⤓</button>
</div>
<div class="toast" id="toast" role="status" aria-live="polite" hidden></div>
<div class="legend" id="legend"></div>
</main>
<aside class="details" id="details" data-i18n-attr="aria-label:html.details" hidden>
<div class="details-head">
<div class="details-title">
<span class="kind-chip" id="d-kind"></span>
<h2 id="d-name"></h2>
<div class="muted small" id="d-sub"></div>
</div>
<button type="button" class="btn icon" id="d-close" data-i18n-attr="aria-label:html.close">×</button>
</div>
<div class="d-actions" id="d-actions" role="group" data-i18n-attr="aria-label:html.actions"></div>
<div class="tabs" role="tablist" data-i18n-attr="aria-label:html.sections">
<button type="button" role="tab" data-tab="overview" aria-selected="true" data-i18n="html.overview"></button>
<button type="button" role="tab" data-tab="links" aria-selected="false" data-i18n="html.links"></button>
<button type="button" role="tab" data-tab="yaml" aria-selected="false">YAML</button>
<button type="button" role="tab" data-tab="events" aria-selected="false" data-i18n="html.events"></button>
<button type="button" role="tab" data-tab="logs" aria-selected="false" data-i18n="html.logs"></button>
</div>
<section class="tab-panel" data-panel="overview" role="tabpanel"></section>
<section class="tab-panel" data-panel="links" role="tabpanel" hidden></section>
<section class="tab-panel" data-panel="yaml" role="tabpanel" hidden><pre class="code" id="d-yaml"></pre></section>
<section class="tab-panel" data-panel="events" role="tabpanel" hidden></section>
<section class="tab-panel" data-panel="logs" role="tabpanel" hidden>
<div class="logs-bar">
<select id="pod-select" data-i18n-attr="aria-label:html.pod"></select>
<select id="container-select" data-i18n-attr="aria-label:html.container"></select>
<button type="button" class="btn" id="logs-reload" data-i18n="html.refresh"></button>
</div>
<pre class="code" id="d-logs"></pre>
</section>
</aside>
<aside class="details" id="problems-panel" data-i18n-attr="aria-label:html.problems" hidden>
<div class="details-head">
<div class="details-title">
<h2 data-i18n="html.problems"></h2>
<div class="muted small" id="p-sub"></div>
</div>
<button type="button" class="btn icon" id="p-close" data-i18n-attr="aria-label:html.close">×</button>
</div>
<div class="seg p-filter" role="tablist" data-i18n-attr="aria-label:html.problemsScope">
<button type="button" role="tab" data-scope="all" aria-selected="true" data-i18n="html.scopeAll"></button>
<button type="button" role="tab" data-scope="apps" aria-selected="false" data-i18n="tree.apps"></button>
<button type="button" role="tab" data-scope="system" aria-selected="false" data-i18n="group.system"></button>
</div>
<section class="tab-panel" id="p-list"></section>
</aside>
</div>
<dialog id="confirm" closedby="any" aria-labelledby="confirm-title">
<h2 id="confirm-title"></h2>
<p id="confirm-text"></p>
<label class="confirm-input" id="confirm-input-row" hidden><span data-i18n="action.replicas"></span> <input type="number" id="confirm-input" min="0" max="100" step="1"></label>
<div class="confirm-buttons">
<button type="button" class="btn" id="confirm-cancel" data-i18n="action.cancel"></button>
<button type="button" class="btn primary" id="confirm-ok"></button>
</div>
</dialog>
<script src="app.js"></script>
</body>
</html>
+29
View File
@@ -0,0 +1,29 @@
---
image: {{ .ModuleName }}/{{ .ImageName }}-build
fromImage: builder/golang-alpine
final: false
git:
- add: {{ .ModuleDir }}images/{{ .ImageName }}/src
to: /src
stageDependencies:
install:
- go.mod
- go.sum
setup:
- '**/*'
shell:
install:
- cd /src && go mod download
setup:
- cd /src && CGO_ENABLED=0 GOOS=linux go build -trimpath -ldflags="-s -w" -o /cluster-map ./cmd/cluster-map
---
image: {{ .ModuleName }}/{{ .ImageName }}
fromImage: base/distroless
import:
- image: {{ .ModuleName }}/{{ .ImageName }}-build
add: /cluster-map
to: /cluster-map
before: setup
imageSpec:
config:
entrypoint: ["/cluster-map"]
-87
View File
@@ -1,87 +0,0 @@
package main
import (
"fmt"
"time"
"k8s.io/apimachinery/pkg/api/meta"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/client-go/informers"
appslisters "k8s.io/client-go/listers/apps/v1"
batchlisters "k8s.io/client-go/listers/batch/v1"
corelisters "k8s.io/client-go/listers/core/v1"
netlisters "k8s.io/client-go/listers/networking/v1"
)
var (
nsLister corelisters.NamespaceLister
podLister corelisters.PodLister
svcLister corelisters.ServiceLister
nodeLister corelisters.NodeLister
deployLister appslisters.DeploymentLister
stsLister appslisters.StatefulSetLister
dsLister appslisters.DaemonSetLister
cronLister batchlisters.CronJobLister
ingLister netlisters.IngressLister
)
func startInformers() error {
f := informers.NewSharedInformerFactoryWithOptions(clientset, 0,
// managedFields is most of a cached object's size and nothing here reads it
informers.WithTransform(func(obj any) (any, error) {
if a, err := meta.Accessor(obj); err == nil {
a.SetManagedFields(nil)
}
return obj, nil
}))
nsLister = f.Core().V1().Namespaces().Lister()
podLister = f.Core().V1().Pods().Lister()
svcLister = f.Core().V1().Services().Lister()
nodeLister = f.Core().V1().Nodes().Lister()
deployLister = f.Apps().V1().Deployments().Lister()
stsLister = f.Apps().V1().StatefulSets().Lister()
dsLister = f.Apps().V1().DaemonSets().Lister()
cronLister = f.Batch().V1().CronJobs().Lister()
ingLister = f.Networking().V1().Ingresses().Lister()
stop := make(chan struct{})
f.Start(stop)
done := make(chan map[string]bool, 1)
go func() {
synced := map[string]bool{}
for t, ok := range f.WaitForCacheSync(stop) {
synced[fmt.Sprint(t)] = ok
}
done <- synced
}()
select {
case synced := <-done:
for t, ok := range synced {
if !ok {
return fmt.Errorf("cache for %s did not sync", t)
}
}
return nil
case <-time.After(90 * time.Second):
return fmt.Errorf("caches did not sync in 90s")
}
}
type listOf[T any] struct{ Items []T }
// listAll reads a lister into the same shape a typed List() call returns,
// so graph code iterates .Items unchanged. Items are copies: callers may not
// mutate cached objects, and copying the top-level struct is cheap.
func listAll[T any](l interface {
List(labels.Selector) ([]*T, error)
}) (*listOf[T], error) {
ptrs, err := l.List(labels.Everything())
if err != nil {
return nil, err
}
out := &listOf[T]{Items: make([]T, len(ptrs))}
for i, p := range ptrs {
out.Items[i] = *p
}
return out, nil
}
-659
View File
@@ -1,659 +0,0 @@
// cluster-map: a live topology view of a Deckhouse/Kubernetes cluster.
//
// Builds a graph on every request to /api/graph from informer caches:
// namespaces group workloads, which connect to Services (by label-selector
// match) and Ingresses (by backend reference). Informers keep the caches
// in step with the API by watch; a fresh List per request cost ~0.9 s and
// timed out the 1 s probe.
package main
import (
"context"
"encoding/json"
"io"
"log"
"net/http"
"sort"
"strings"
appsv1 "k8s.io/api/apps/v1"
batchv1 "k8s.io/api/batch/v1"
corev1 "k8s.io/api/core/v1"
networkingv1 "k8s.io/api/networking/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
"sigs.k8s.io/yaml"
)
type Node struct {
ID string `json:"id"`
Label string `json:"label"`
Kind string `json:"kind"` // namespace | deployment | statefulset | daemonset | cronjob | service | ingress | node
Namespace string `json:"namespace"` // empty for namespace/node kind
Parent string `json:"parent,omitempty"`
NodeName string `json:"nodeName,omitempty"` // physical node a workload's pods land on, if known
Facts map[string]string `json:"facts,omitempty"` // short summary shown in the sidebar without a follow-up fetch
}
type Edge struct {
ID string `json:"id"`
Source string `json:"source"`
Target string `json:"target"`
Kind string `json:"kind"` // selects | routes | schedules-on
}
type Graph struct {
Nodes []Node `json:"nodes"`
Edges []Edge `json:"edges"`
}
var clientset *kubernetes.Clientset
func main() {
cfg, err := rest.InClusterConfig()
if err != nil {
log.Fatalf("not running in-cluster and no kubeconfig fallback wired up: %v", err)
}
clientset, err = kubernetes.NewForConfig(cfg)
if err != nil {
log.Fatalf("building clientset: %v", err)
}
if err := startInformers(); err != nil {
log.Fatalf("informers: %v", err)
}
startHubble()
mux := http.NewServeMux()
mux.HandleFunc("/healthz", func(w http.ResponseWriter, _ *http.Request) { w.Write([]byte("ok")) })
mux.HandleFunc("/api/flows", handleFlows)
mux.HandleFunc("/api/graph", handleGraph)
mux.HandleFunc("/api/resource", handleResource)
mux.HandleFunc("/api/pods", handlePods)
mux.HandleFunc("/api/logs", handleLogs)
mux.Handle("/", http.FileServer(http.Dir("./static")))
addr := ":8080"
log.Printf("cluster-map listening on %s", addr)
log.Fatal(http.ListenAndServe(addr, mux))
}
func handleGraph(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
g, err := buildGraph(ctx)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(g)
}
// selectorSubset reports whether every key/value in sel is present in labels --
// the standard Kubernetes rule for whether a Service's spec.selector matches a
// pod template's labels.
func selectorSubset(sel, labels map[string]string) bool {
if len(sel) == 0 {
return false // an empty selector matches everything in real k8s, but showing an edge to "everything" is useless noise here
}
for k, v := range sel {
if labels[k] != v {
return false
}
}
return true
}
func buildGraph(ctx context.Context) (*Graph, error) {
g := &Graph{}
namespaces, err := listAll[corev1.Namespace](nsLister)
if err != nil {
return nil, err
}
for _, ns := range namespaces.Items {
system := strings.HasPrefix(ns.Name, "d8-") || ns.Name == "kube-system" || ns.Name == "kube-public" || ns.Name == "kube-node-lease"
g.Nodes = append(g.Nodes, Node{
ID: "ns/" + ns.Name,
Label: ns.Name,
Kind: "namespace",
Facts: map[string]string{"system": boolStr(system)},
})
}
// pod-template-labels indexed by namespace, used to match Services to
// their owning workload below.
type workloadRef struct {
id string
labels map[string]string
}
var workloads []workloadRef
deployments, err := listAll[appsv1.Deployment](deployLister)
if err != nil {
return nil, err
}
for _, d := range deployments.Items {
id := workloadID(d.Namespace, "deployment", d.Name)
g.Nodes = append(g.Nodes, workloadNode(id, "deployment", d.Namespace, d.Name, deploymentFacts(d)))
workloads = append(workloads, workloadRef{id, d.Spec.Template.Labels})
}
statefulsets, err := listAll[appsv1.StatefulSet](stsLister)
if err != nil {
return nil, err
}
for _, s := range statefulsets.Items {
id := workloadID(s.Namespace, "statefulset", s.Name)
g.Nodes = append(g.Nodes, workloadNode(id, "statefulset", s.Namespace, s.Name, statefulsetFacts(s)))
workloads = append(workloads, workloadRef{id, s.Spec.Template.Labels})
}
daemonsets, err := listAll[appsv1.DaemonSet](dsLister)
if err != nil {
return nil, err
}
for _, ds := range daemonsets.Items {
id := workloadID(ds.Namespace, "daemonset", ds.Name)
g.Nodes = append(g.Nodes, workloadNode(id, "daemonset", ds.Namespace, ds.Name, daemonsetFacts(ds)))
workloads = append(workloads, workloadRef{id, ds.Spec.Template.Labels})
}
cronjobs, err := listAll[batchv1.CronJob](cronLister)
if err != nil {
return nil, err
}
for _, cj := range cronjobs.Items {
id := workloadID(cj.Namespace, "cronjob", cj.Name)
g.Nodes = append(g.Nodes, workloadNode(id, "cronjob", cj.Namespace, cj.Name, cronjobFacts(cj)))
// CronJob pods don't back a Service, so no labels needed for matching.
}
// Pods whose controller is not a native workload (kruise Advanced
// DaemonSet behind ingress-nginx, database operators, bare Jobs) would
// otherwise be invisible. They become workload nodes of their own, IDed
// the way Hubble names workloads, so traffic attaches to them too.
pods, err := listAll[corev1.Pod](podLister)
if err != nil {
return nil, err
}
known := map[string]bool{}
for _, n := range g.Nodes {
known[n.ID] = true
}
type foreignWl struct {
ns, kind, name, controller string
pods, ready int
labels map[string]string
}
foreign := map[string]*foreignWl{}
for _, p := range pods.Items {
kind, name, ctrl := podOwner(p)
if kind == "" {
continue
}
id := workloadID(p.Namespace, kind, name)
if known[id] {
continue
}
f := foreign[id]
if f == nil {
f = &foreignWl{ns: p.Namespace, kind: kind, name: name, controller: ctrl, labels: p.Labels}
foreign[id] = f
}
if p.Status.Phase == corev1.PodSucceeded {
continue
}
f.pods++
if podReady(p) {
f.ready++
}
}
for id, f := range foreign {
kind := f.kind
switch kind {
case "deployment", "statefulset", "daemonset", "cronjob":
default:
kind = "pod"
}
n := workloadNode(id, kind, f.ns, f.name, map[string]string{
"controller": f.controller,
"pods": itoa(f.pods),
"ready": itoa(f.ready),
"health": health(f.pods, f.ready),
"foreign": "true",
})
g.Nodes = append(g.Nodes, n)
workloads = append(workloads, workloadRef{id, f.labels})
}
services, err := listAll[corev1.Service](svcLister)
if err != nil {
return nil, err
}
for _, svc := range services.Items {
id := "service/" + svc.Namespace + "/" + svc.Name
g.Nodes = append(g.Nodes, Node{
ID: id, Label: svc.Name, Kind: "service", Namespace: svc.Namespace, Parent: "ns/" + svc.Namespace,
Facts: serviceFacts(svc),
})
for _, wl := range workloads {
if !strings.HasPrefix(wl.id, "wl/"+svc.Namespace+"/") {
continue
}
if selectorSubset(svc.Spec.Selector, wl.labels) {
g.Edges = append(g.Edges, Edge{ID: wl.id + "->" + id, Source: wl.id, Target: id, Kind: "selects"})
}
}
}
ingresses, err := listAll[networkingv1.Ingress](ingLister)
if err != nil {
return nil, err
}
for _, ing := range ingresses.Items {
id := "ingress/" + ing.Namespace + "/" + ing.Name
g.Nodes = append(g.Nodes, Node{
ID: id, Label: ing.Name, Kind: "ingress", Namespace: ing.Namespace, Parent: "ns/" + ing.Namespace,
Facts: ingressFacts(ing),
})
for _, svcName := range ingressBackendServices(ing) {
target := "service/" + ing.Namespace + "/" + svcName
g.Edges = append(g.Edges, Edge{ID: id + "->" + target, Source: id, Target: target, Kind: "routes"})
}
}
// Physical nodes as a separate, non-namespaced layer, linked from each
// workload to wherever its pods actually run right now -- this is the
// "what's deployed where" question specifically, not covered by the
// Service/Ingress graph above.
nodes, err := listAll[corev1.Node](nodeLister)
if err != nil {
return nil, err
}
for _, n := range nodes.Items {
g.Nodes = append(g.Nodes, Node{ID: "node/" + n.Name, Label: n.Name, Kind: "node", Facts: nodeFacts(n)})
}
seenPlacement := map[string]bool{}
for _, p := range pods.Items {
if p.Spec.NodeName == "" {
continue
}
ownerWl := ownerWorkloadID(p)
if ownerWl == "" {
continue
}
key := ownerWl + "@" + p.Spec.NodeName
if seenPlacement[key] {
continue
}
seenPlacement[key] = true
g.Edges = append(g.Edges, Edge{ID: key, Source: ownerWl, Target: "node/" + p.Spec.NodeName, Kind: "schedules-on"})
}
sort.Slice(g.Nodes, func(i, j int) bool { return g.Nodes[i].ID < g.Nodes[j].ID })
sort.Slice(g.Edges, func(i, j int) bool { return g.Edges[i].ID < g.Edges[j].ID })
return g, nil
}
// podOwner names the workload a pod belongs to the way Hubble does
// (cilium's GetWorkloadMetaFromPod): ReplicaSet -> its Deployment, a Job
// whose name ends in the scheduler's numeric suffix -> its CronJob, any
// other controller kind as-is. controller is "<apiVersion> <Kind>".
func podOwner(p corev1.Pod) (kind, name, controller string) {
var o *metav1.OwnerReference
for i := range p.OwnerReferences {
if p.OwnerReferences[i].Controller != nil && *p.OwnerReferences[i].Controller {
o = &p.OwnerReferences[i]
break
}
}
if o == nil && len(p.OwnerReferences) > 0 {
o = &p.OwnerReferences[0]
}
if o == nil {
return "", "", ""
}
controller = o.APIVersion + " " + o.Kind
switch o.Kind {
case "Node":
// static pod mirrored by the kubelet: "<component>-<node>", grouped
// per component across nodes like a DaemonSet would be
return "staticpod", strings.TrimSuffix(p.Name, "-"+p.Spec.NodeName), "static pod (kubelet)"
case "ReplicaSet":
if i := strings.LastIndex(o.Name, "-"); i > 0 {
return "deployment", o.Name[:i], controller
}
case "Job":
if i := strings.LastIndex(o.Name, "-"); i > 0 && allDigits(o.Name[i+1:]) {
return "cronjob", o.Name[:i], controller
}
}
return strings.ToLower(o.Kind), o.Name, controller
}
func allDigits(s string) bool {
if s == "" {
return false
}
for _, c := range s {
if c < '0' || c > '9' {
return false
}
}
return true
}
func podReady(p corev1.Pod) bool {
for _, c := range p.Status.Conditions {
if c.Type == corev1.PodReady {
return c.Status == corev1.ConditionTrue
}
}
return false
}
func ownerWorkloadID(p corev1.Pod) string {
kind, name, _ := podOwner(p)
if kind == "" {
return ""
}
return workloadID(p.Namespace, kind, name)
}
func workloadID(ns, kind, name string) string { return "wl/" + ns + "/" + kind + "/" + name }
func workloadNode(id, kind, ns, name string, facts map[string]string) Node {
return Node{ID: id, Label: name, Kind: kind, Namespace: ns, Parent: "ns/" + ns, Facts: facts}
}
func boolStr(b bool) string {
if b {
return "true"
}
return "false"
}
func ingressBackendServices(ing networkingv1.Ingress) []string {
seen := map[string]bool{}
var out []string
add := func(name string) {
if name != "" && !seen[name] {
seen[name] = true
out = append(out, name)
}
}
if ing.Spec.DefaultBackend != nil && ing.Spec.DefaultBackend.Service != nil {
add(ing.Spec.DefaultBackend.Service.Name)
}
for _, rule := range ing.Spec.Rules {
if rule.HTTP == nil {
continue
}
for _, path := range rule.HTTP.Paths {
if path.Backend.Service != nil {
add(path.Backend.Service.Name)
}
}
}
return out
}
func firstContainerImage(containers []corev1.Container) string {
if len(containers) == 0 {
return ""
}
return containers[0].Image
}
// health is what the status dot on a card shows: ok, warn (partly ready),
// error (nothing ready), idle (scaled to zero or suspended).
func health(want, ready int) string {
switch {
case want == 0:
return "idle"
case ready >= want:
return "ok"
case ready == 0:
return "error"
}
return "warn"
}
func replicasOf(p *int32) int {
if p == nil {
return 1
}
return int(*p)
}
func deploymentFacts(d appsv1.Deployment) map[string]string {
return map[string]string{
"replicas": itoa32(d.Spec.Replicas),
"readyReplicas": itoa(int(d.Status.ReadyReplicas)),
"image": firstContainerImage(d.Spec.Template.Spec.Containers),
"health": health(replicasOf(d.Spec.Replicas), int(d.Status.ReadyReplicas)),
}
}
func statefulsetFacts(s appsv1.StatefulSet) map[string]string {
return map[string]string{
"replicas": itoa32(s.Spec.Replicas),
"readyReplicas": itoa(int(s.Status.ReadyReplicas)),
"image": firstContainerImage(s.Spec.Template.Spec.Containers),
"health": health(replicasOf(s.Spec.Replicas), int(s.Status.ReadyReplicas)),
}
}
func daemonsetFacts(ds appsv1.DaemonSet) map[string]string {
return map[string]string{
"desired": itoa(int(ds.Status.DesiredNumberScheduled)),
"ready": itoa(int(ds.Status.NumberReady)),
"image": firstContainerImage(ds.Spec.Template.Spec.Containers),
"health": health(int(ds.Status.DesiredNumberScheduled), int(ds.Status.NumberReady)),
}
}
func cronjobFacts(cj batchv1.CronJob) map[string]string {
f := map[string]string{"schedule": cj.Spec.Schedule, "health": "ok", "active": itoa(len(cj.Status.Active))}
if cj.Spec.Suspend != nil && *cj.Spec.Suspend {
f["suspended"] = "true"
f["health"] = "idle"
}
if cj.Status.LastSuccessfulTime != nil {
f["lastSuccess"] = cj.Status.LastSuccessfulTime.UTC().Format("2006-01-02 15:04")
}
return f
}
func serviceFacts(svc corev1.Service) map[string]string {
var ports []string
for _, p := range svc.Spec.Ports {
ports = append(ports, itoa(int(p.Port))+"/"+string(p.Protocol))
}
return map[string]string{"type": string(svc.Spec.Type), "ports": strings.Join(ports, ", ")}
}
func ingressFacts(ing networkingv1.Ingress) map[string]string {
var hosts []string
for _, r := range ing.Spec.Rules {
if r.Host != "" {
hosts = append(hosts, r.Host)
}
}
class := ""
if ing.Spec.IngressClassName != nil {
class = *ing.Spec.IngressClassName
}
return map[string]string{"hosts": strings.Join(hosts, ", "), "class": class}
}
func nodeFacts(n corev1.Node) map[string]string {
ready := "False"
for _, c := range n.Status.Conditions {
if c.Type == corev1.NodeReady {
ready = string(c.Status)
}
}
h := "ok"
if ready != "True" {
h = "error"
}
return map[string]string{"ready": ready, "os": n.Status.NodeInfo.OSImage, "kubelet": n.Status.NodeInfo.KubeletVersion, "health": h}
}
func itoa(i int) string {
if i == 0 {
return "0"
}
neg := i < 0
if neg {
i = -i
}
var b []byte
for i > 0 {
b = append([]byte{byte('0' + i%10)}, b...)
i /= 10
}
if neg {
b = append([]byte{'-'}, b...)
}
return string(b)
}
func itoa32(p *int32) string {
if p == nil {
return "?"
}
return itoa(int(*p))
}
// handleResource returns the raw manifest (as YAML, easiest to read) for a
// single graph node, fetched fresh -- not cached alongside the graph, since
// most nodes are never clicked and a full spec dump for every workload on
// every /api/graph call would be wasteful.
func handleResource(w http.ResponseWriter, r *http.Request) {
kind := r.URL.Query().Get("kind")
ns := r.URL.Query().Get("namespace")
name := r.URL.Query().Get("name")
ctx := r.Context()
var obj interface{}
var err error
switch kind {
case "namespace":
obj, err = clientset.CoreV1().Namespaces().Get(ctx, name, metav1.GetOptions{})
case "deployment":
obj, err = clientset.AppsV1().Deployments(ns).Get(ctx, name, metav1.GetOptions{})
case "statefulset":
obj, err = clientset.AppsV1().StatefulSets(ns).Get(ctx, name, metav1.GetOptions{})
case "daemonset":
obj, err = clientset.AppsV1().DaemonSets(ns).Get(ctx, name, metav1.GetOptions{})
case "cronjob":
obj, err = clientset.BatchV1().CronJobs(ns).Get(ctx, name, metav1.GetOptions{})
case "service":
obj, err = clientset.CoreV1().Services(ns).Get(ctx, name, metav1.GetOptions{})
case "ingress":
obj, err = clientset.NetworkingV1().Ingresses(ns).Get(ctx, name, metav1.GetOptions{})
case "node":
obj, err = clientset.CoreV1().Nodes().Get(ctx, name, metav1.GetOptions{})
default:
http.Error(w, "unknown kind: "+kind, http.StatusBadRequest)
return
}
if err != nil {
http.Error(w, err.Error(), http.StatusNotFound)
return
}
if a, ok := obj.(metav1.Object); ok {
a.SetManagedFields(nil)
}
out, err := yaml.Marshal(obj)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
w.Write(out)
}
// podsForWorkload finds the live pods currently owned by a given workload,
// reusing the same ownerReferences-walking logic buildGraph uses for the
// schedules-on edges -- so "which pods back this node" stays consistent
// with what the graph already shows for placement.
func podsForWorkload(ctx context.Context, ns, target string) ([]corev1.Pod, error) {
pods, err := listAll[corev1.Pod](podLister.Pods(ns))
if err != nil {
return nil, err
}
var out []corev1.Pod
for _, p := range pods.Items {
if ownerWorkloadID(p) == target {
out = append(out, p)
}
}
sort.Slice(out, func(i, j int) bool { return out[i].Name < out[j].Name })
return out, nil
}
type PodInfo struct {
Name string `json:"name"`
NodeName string `json:"nodeName"`
Phase string `json:"phase"`
Containers []string `json:"containers"`
}
// handlePods lists the pods backing a workload node, with their containers --
// the frontend uses this to build the pod/container pickers before fetching
// logs, since a Deployment/StatefulSet/DaemonSet/CronJob isn't itself a log
// source, its pods are.
func handlePods(w http.ResponseWriter, r *http.Request) {
id := r.URL.Query().Get("id")
ns := r.URL.Query().Get("namespace")
if ns == "" || !strings.HasPrefix(id, "wl/"+ns+"/") {
http.Error(w, "namespace and a workload id (wl/<ns>/<kind>/<name>) are required", http.StatusBadRequest)
return
}
pods, err := podsForWorkload(r.Context(), ns, id)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
out := make([]PodInfo, 0, len(pods))
for _, p := range pods {
var containers []string
for _, c := range p.Spec.Containers {
containers = append(containers, c.Name)
}
out = append(out, PodInfo{Name: p.Name, NodeName: p.Spec.NodeName, Phase: string(p.Status.Phase), Containers: containers})
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(out)
}
// handleLogs streams a single container's recent log tail. Read-only,
// no follow -- this is a click-to-inspect tool, not a live tail viewer.
func handleLogs(w http.ResponseWriter, r *http.Request) {
ns := r.URL.Query().Get("namespace")
pod := r.URL.Query().Get("pod")
container := r.URL.Query().Get("container")
if ns == "" || pod == "" {
http.Error(w, "namespace and pod are required", http.StatusBadRequest)
return
}
var tail int64 = 500
opts := &corev1.PodLogOptions{TailLines: &tail}
if container != "" {
opts.Container = container
}
stream, err := clientset.CoreV1().Pods(ns).GetLogs(pod, opts).Stream(r.Context())
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
defer stream.Close()
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
io.Copy(w, stream)
}
+25
View File
@@ -0,0 +1,25 @@
name: cluster-map
stage: Experimental
namespace: d8-cluster-map
subsystems:
- observability
descriptions:
en: >-
Interactive topology map of the cluster: an inventory tree of namespaces
and nodes, workloads with their Services and Ingresses, live traffic
between them from Cilium Hubble, and per-object YAML and logs.
ru: >-
Интерактивная карта кластера: дерево namespace и нод, workload'ы с их
Service и Ingress, живой трафик между ними из Cilium Hubble, YAML и логи
каждого объекта.
tags: ["observability", "ui"]
requirements:
deckhouse: ">= 1.72"
kubernetes: ">= 1.29"
disable:
confirmation: false
accessibility:
editions:
_default:
available: true
enabledInBundles: []
@@ -0,0 +1,28 @@
- name: d8.cluster-map
rules:
- alert: ClusterMapHubbleDisconnected
expr: max by (pod) (cluster_map_hubble_stream_active == 1 and cluster_map_hubble_connected == 0)
for: 15m
labels:
severity_level: "8"
tier: cluster
annotations:
plk_markup_format: markdown
plk_protocol_version: "1"
summary: cluster-map has no flows from Hubble Relay.
description: |
The traffic layer of cluster-map has received no flows for 15 minutes while it is supposed to be collecting. The topology map still works; traffic windows go stale.
Check the pod log: `kubectl -n d8-cluster-map logs deploy/cluster-map`, and that hubble-relay is running: `kubectl -n d8-cni-cilium get pods -l app=hubble-relay`.
- alert: ClusterMapTrackedTuplesHigh
expr: max(cluster_map_traffic_tracked_tuples) > 2000000
for: 30m
labels:
severity_level: "9"
tier: cluster
annotations:
plk_markup_format: markdown
plk_protocol_version: "1"
summary: cluster-map keeps more than 2 million connection tuples.
description: |
Memory of the traffic collector grows with the number of distinct connections in the retention window. Lower `traffic.retentionMinutes` or switch `traffic.mode` to `OnDemand` in the `cluster-map` ModuleConfig.
+214
View File
@@ -0,0 +1,214 @@
type: object
properties:
traffic:
type: object
default: {}
description: Live traffic between workloads, read from Cilium Hubble Relay.
properties:
mode:
type: string
default: Continuous
enum: ["Continuous", "OnDemand", "Disabled"]
description: |
When flows are read from Hubble.
- `Continuous` — a Hubble follow stream is always open, so every traffic window is full as soon as the map is opened. Costs hubble-relay about 100–150m CPU on a busy cluster.
- `OnDemand` — the stream opens with the first traffic request and closes after `onDemandIdleMinutes` without one. Near-zero cost while nobody looks at the map, but windows only fill while it is in use.
- `Disabled` — no connection to Hubble; the map shows configuration links only.
Traffic also stays off when the `cilium-hubble` module is disabled.
retentionMinutes:
type: integer
default: 60
minimum: 5
maximum: 1440
description: |
How far back traffic windows can reach, in minutes. Memory grows with retention and with the number of distinct connections in the cluster.
onDemandIdleMinutes:
type: integer
default: 10
minimum: 1
maximum: 120
description: In `OnDemand` mode, how long the stream stays open after the last traffic request.
collectInfraTraffic:
type: boolean
default: false
description: |
Also collect kubelet probes and other traffic originating from node hosts, node-to-node traffic, Cilium health checks and DNS.
Off by default: on a typical cluster this is about three quarters of all flows, none of it maps to a workload, and filtering it at the Hubble agents keeps hubble-relay load several times lower.
actions:
type: object
default: {}
description: Changes the map can make to the cluster.
properties:
enabled:
type: boolean
default: true
description: |
Buttons to restart a workload, scale a Deployment or StatefulSet, delete a pod, run a CronJob now or suspend it, cordon a node.
Every action runs with the viewer's own Kubernetes identity: the DexAuthenticator passes the user's token to the module, and the API server checks it against the user's RBAC. The module's service account stays read-only, a button is shown only when the user's role allows it, and the API server's audit log records the user.
Needs the `user-authn` module, or an `externalAuthentication` that puts a token the API server accepts into the `Authorization` header. When disabled, the user's token is not passed to the module at all.
logs:
type: object
default: {}
properties:
tailLines:
type: integer
default: 500
minimum: 10
maximum: 10000
description: How many last lines of a container log the Logs tab shows.
systemNamespacePrefixes:
type: array
default: ["d8-", "kube-"]
items:
type: string
description: |
Namespaces grouped as "System" in the inventory tree. An entry ending in `-` matches by prefix, any other entry matches the whole name.
ingressClass:
type: string
pattern: '^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$'
description: |
The class of the Ingress controller used for the web interface.
Optional. By default, the `modules.ingressClass` global value is used.
nodeSelector:
type: object
additionalProperties:
type: string
description: |
The same as the `spec.nodeSelector` pod parameter in Kubernetes.
If the parameter is omitted or `false`, it will be determined [automatically](https://deckhouse.io/products/kubernetes-platform/documentation/v1/#advanced-scheduling).
tolerations:
type: array
description: |
The same as `spec.tolerations` for the Kubernetes Pod.
If the parameter is omitted or `false`, it will be determined [automatically](https://deckhouse.io/products/kubernetes-platform/documentation/v1/#advanced-scheduling).
items:
type: object
properties:
effect:
type: string
key:
type: string
operator:
type: string
tolerationSeconds:
type: integer
format: int64
value:
type: string
auth:
type: object
default: {}
description: |
Access to the web interface.
With `visibility: ViewerRBAC` (the default) each viewer sees only the namespaces their own RBAC lets them list pods in; with `Everything`, anyone admitted here sees every namespace, the manifests of workloads, Services and Ingresses (never Secrets) and container logs. Either way, restrict who is admitted with `allowedUserGroups`.
properties:
visibility:
type: string
default: ViewerRBAC
enum: ["ViewerRBAC", "Everything"]
description: |
What a viewer sees.
- `ViewerRBAC` — what the viewer's own permissions allow: the whole cluster for a viewer who can list pods in all namespaces, otherwise only the namespaces where they can list pods. Container logs additionally need `get pods/log`, node cards `list nodes`. Traffic to a hidden namespace is shown as coming from or going to a hidden peer. Checked with SelfSubjectAccessReviews as the viewer and cached for a minute.
- `Everything` — every admitted viewer sees the whole cluster, read with the module's service account.
`ViewerRBAC` needs the viewer's token: the `user-authn` module, or an `externalAuthentication` that puts a token the API server accepts into the `Authorization` header.
externalAuthentication:
type: object
description: |
Parameters to enable external authentication based on the Ingress NGINX [external-auth](https://kubernetes.github.io/ingress-nginx/examples/auth/external-auth/) mechanism.
> External authentication is enabled automatically if the [user-authn](https://deckhouse.io/modules/user-authn/) module is enabled.
properties:
authURL:
type: string
x-examples: ["https://example.com/dex/auth"]
description: The URL of the authentication service. If the user is authenticated, the service should return an HTTP 200 response code.
authSignInURL:
type: string
x-examples: ["https://example.com/dex/sign_in"]
description: The URL to redirect the user for authentication (if the authentication service returned a non-200 HTTP response code).
allowedUserEmails:
type: array
items:
type: string
description: |
Emails of users allowed to open the web interface.
Used if the `user-authn` module is enabled or `externalAuthentication` is set.
allowedUserGroups:
type: array
items:
type: string
x-examples:
- ["admins"]
description: |
User groups allowed to open the web interface.
Used if the `user-authn` module is enabled or `externalAuthentication` is set.
**Caution!** When used together with the [user-authn](https://deckhouse.io/modules/user-authn/) module, add these groups to the matching field of the DexProvider.
whitelistSourceRanges:
type: array
items:
type: string
x-examples:
- ["1.1.1.1/32"]
description: CIDRs allowed to open the web interface.
https:
type: object
x-examples:
- mode: Disabled
- mode: OnlyInURI
- mode: CustomCertificate
customCertificate:
secretName: "foobar"
- mode: CertManager
certManager:
clusterIssuerName: letsencrypt
description: |
What certificate type to use.
This parameter completely overrides the `global.modules.https` settings.
properties:
mode:
type: string
default: "CertManager"
description: |
The HTTPS usage mode:
- `CertManager` — the web interface is served over HTTPS with a certificate from the ClusterIssuer set in `certManager.clusterIssuerName`;
- `CustomCertificate` — the web interface is served over HTTPS with a certificate from the `d8-system` namespace;
- `Disabled` — the web interface is served over HTTP only;
- `OnlyInURI` — the web interface is served over HTTP behind an external HTTPS load balancer that terminates TLS; links are generated with the HTTPS scheme.
enum:
- "Disabled"
- "CertManager"
- "CustomCertificate"
- "OnlyInURI"
certManager:
type: object
properties:
clusterIssuerName:
type: string
default: "letsencrypt"
x-examples: ["letsencrypt", "letsencrypt-staging", "selfsigned"]
description: The ClusterIssuer used to get the certificate.
customCertificate:
type: object
default: {}
properties:
secretName:
type: string
description: |
The name of the Secret in the `d8-system` namespace to use for the web interface.
The Secret must have the [kubernetes.io/tls](https://kubernetes.github.io/ingress-nginx/user-guide/tls/#tls-secrets) format.
+118
View File
@@ -0,0 +1,118 @@
type: object
properties:
traffic:
description: Живой трафик между workload'ами из Cilium Hubble Relay.
properties:
mode:
description: |
Когда читать потоки из Hubble.
- `Continuous` — поток из Hubble открыт всегда, поэтому любое окно трафика заполнено сразу при открытии карты. На нагруженном кластере стоит hubble-relay около 100–150m CPU.
- `OnDemand` — поток открывается при первом запросе трафика и закрывается через `onDemandIdleMinutes` без запросов. Пока карту никто не смотрит, нагрузки почти нет, но окна заполняются только во время работы с картой.
- `Disabled` — без подключения к Hubble, карта показывает только связи по конфигурации.
Трафик выключен и тогда, когда выключен модуль `cilium-hubble`.
retentionMinutes:
description: |
На сколько минут назад могут смотреть окна трафика. Память растёт вместе с этим значением и с числом различных соединений в кластере.
onDemandIdleMinutes:
description: В режиме `OnDemand` — сколько минут поток остаётся открытым после последнего запроса трафика.
collectInfraTraffic:
description: |
Собирать также пробы kubelet и прочий трафик с хостов нод, трафик между нодами, проверки Cilium health и DNS.
По умолчанию выключено: на обычном кластере это около трёх четвертей всех потоков, ни один из них не привязан к workload'у, а отсев на агентах Hubble снижает нагрузку на hubble-relay в несколько раз.
actions:
description: Изменения, которые карта может вносить в кластер.
properties:
enabled:
description: |
Кнопки: перезапустить workload, масштабировать Deployment или StatefulSet, удалить под, запустить CronJob сейчас или приостановить его, закрыть ноду для новых подов (cordon).
Каждое действие выполняется от имени самого пользователя: DexAuthenticator передаёт модулю его токен, и API-сервер проверяет права по RBAC этого пользователя. Сервисный аккаунт модуля остаётся только на чтение, кнопка показывается, только если роль пользователя разрешает действие, а в аудит-логе API-сервера записан пользователь.
Нужен модуль `user-authn` или `externalAuthentication`, который кладёт в заголовок `Authorization` токен, принимаемый API-сервером. Если выключено, токен пользователя модулю не передаётся вовсе.
logs:
properties:
tailLines:
description: Сколько последних строк лога контейнера показывает вкладка «Логи».
systemNamespacePrefixes:
description: |
Namespace, которые в дереве инвентаря попадают в группу «Системные». Элемент, заканчивающийся на `-`, сравнивается как префикс, остальные — по имени целиком.
ingressClass:
description: |
Класс Ingress-контроллера для веб-интерфейса.
Опциональный параметр. По умолчанию используется глобальное значение `modules.ingressClass`.
nodeSelector:
description: |
Аналогично параметру Kubernetes `spec.nodeSelector` у подов.
Если параметр не указан или указано `false`, значение будет определено [автоматически](https://deckhouse.ru/products/kubernetes-platform/documentation/v1/#выделение-узлов-под-определенный-вид-нагрузки).
tolerations:
description: |
Аналогично параметру Kubernetes `spec.tolerations` у подов.
Если параметр не указан или указано `false`, значение будет определено [автоматически](https://deckhouse.ru/products/kubernetes-platform/documentation/v1/#выделение-узлов-под-определенный-вид-нагрузки).
auth:
description: |
Доступ к веб-интерфейсу.
При `visibility: ViewerRBAC` (по умолчанию) каждый видит только namespace, где его собственный RBAC разрешает смотреть поды; при `Everything` любой, кого сюда пустили, видит все namespace, манифесты workload'ов, Service и Ingress (Secret — никогда) и логи контейнеров. В обоих случаях ограничивайте круг допущенных через `allowedUserGroups`.
properties:
visibility:
description: |
Что видит пользователь.
- `ViewerRBAC` — то, что разрешают его собственные права: весь кластер, если он может смотреть поды во всех namespace, иначе только namespace, где он может смотреть поды. Для логов контейнеров нужно ещё `get pods/log`, для карточек нод — `list nodes`. Трафик в скрытый namespace показывается как соединение со скрытым соседом. Проверяется через SelfSubjectAccessReview от имени пользователя, ответ кешируется на минуту.
- `Everything` — каждый допущенный пользователь видит весь кластер, чтение идёт сервисным аккаунтом модуля.
Для `ViewerRBAC` нужен токен пользователя: модуль `user-authn` или `externalAuthentication`, который кладёт в заголовок `Authorization` токен, принимаемый API-сервером.
externalAuthentication:
description: |
Параметры для подключения внешней аутентификации на основе механизма Ingress NGINX [external-auth](https://kubernetes.github.io/ingress-nginx/examples/auth/external-auth/).
> Внешняя аутентификация включается автоматически, если включен модуль [user-authn](https://deckhouse.ru/modules/user-authn/).
properties:
authURL:
description: URL сервиса аутентификации. Если пользователь прошёл аутентификацию, сервис должен вернуть код ответа HTTP 200.
authSignInURL:
description: URL, куда будет перенаправлен пользователь для прохождения аутентификации (если сервис аутентификации вернул код ответа HTTP, отличный от 200).
allowedUserEmails:
description: |
Email пользователей, которым разрешено открывать веб-интерфейс.
Используется, если включен модуль `user-authn` или задан параметр `externalAuthentication`.
allowedUserGroups:
description: |
Группы пользователей, которым разрешено открывать веб-интерфейс.
Используется, если включен модуль `user-authn` или задан параметр `externalAuthentication`.
**Внимание!** При использовании совместно с модулем [user-authn](https://deckhouse.ru/modules/user-authn/) эти группы нужно добавить в соответствующее поле DexProvider.
whitelistSourceRanges:
description: Список CIDR, которым разрешено открывать веб-интерфейс.
https:
description: |
Тип сертификата.
Этот параметр полностью переопределяет глобальные настройки `global.modules.https`.
properties:
mode:
description: |
Режим работы HTTPS:
- `CertManager` — веб-интерфейс по HTTPS с сертификатом от ClusterIssuer из `certManager.clusterIssuerName`;
- `CustomCertificate` — веб-интерфейс по HTTPS с сертификатом из namespace `d8-system`;
- `Disabled` — веб-интерфейс только по HTTP;
- `OnlyInURI` — веб-интерфейс по HTTP за внешним HTTPS-балансировщиком, который терминирует TLS; ссылки формируются со схемой HTTPS.
certManager:
properties:
clusterIssuerName:
description: ClusterIssuer, через который получается сертификат.
customCertificate:
properties:
secretName:
description: |
Имя Secret в namespace `d8-system` с сертификатом для веб-интерфейса.
Secret должен быть в формате [kubernetes.io/tls](https://kubernetes.github.io/ingress-nginx/user-guide/tls/#tls-secrets).
+33
View File
@@ -0,0 +1,33 @@
x-extend:
schema: config-values.yaml
type: object
properties:
internal:
type: object
default: {}
properties:
deployDexAuthenticator:
type: boolean
hubbleCA:
type: string
default: ""
x-examples: ["-----BEGIN CERTIFICATE-----"]
description: Public certificate of the hubble CA, read by the hubble_ca hook. Empty when cilium-hubble is not installed.
customCertificateData:
type: object
properties:
tls.crt:
type: string
x-examples:
- plainstring
tls.key:
type: string
x-examples:
- plainstring
ca.crt:
type: string
x-examples:
- plainstring
registry:
type: object
description: "System field, overwritten by Deckhouse. Don't use"
+24
View File
@@ -0,0 +1,24 @@
- id: cytoscape
name: Cytoscape.js
version: 3.30.2
description: Graph rendering for the topology map.
link: https://js.cytoscape.org/
license: MIT
- id: elkjs
name: ELK.js
version: 0.9.3
description: Layered graph layout (Eclipse Layout Kernel compiled to JavaScript).
link: https://github.com/kieler/elkjs
license: EPL-2.0
- id: cilium
name: Cilium Hubble API
version: 1.17.4
description: Observer gRPC API used to read flows from Hubble Relay.
link: https://github.com/cilium/cilium
license: Apache License 2.0
- id: client-go
name: Kubernetes client-go
version: 0.32.0
description: Kubernetes API client and informers.
link: https://github.com/kubernetes/client-go
license: Apache License 2.0
-80
View File
@@ -1,80 +0,0 @@
<!doctype html>
<html lang="ru">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="color-scheme" content="light dark">
<title>cluster-map</title>
<link rel="stylesheet" href="app.css">
<script src="vendor/cytoscape.min.js"></script>
<script src="vendor/elk.bundled.js"></script>
</head>
<body>
<header class="topbar">
<div class="brand">cluster-map</div>
<nav class="crumbs" id="crumbs" aria-label="Текущий вид"></nav>
<div class="topbar-actions">
<label class="toggle"><input type="checkbox" id="traffic-on" checked> Трафик</label>
<select id="traffic-window" aria-label="Окно трафика">
<option value="300">5 мин</option>
<option value="900">15 мин</option>
<option value="3600">1 час</option>
</select>
<button type="button" id="reload" class="btn">Обновить</button>
<span class="muted small" id="updated"></span>
</div>
</header>
<div class="layout">
<aside class="sidebar" aria-label="Инвентарь">
<div class="seg" role="tablist" aria-label="Группировка">
<button type="button" role="tab" id="view-ns" aria-selected="true" aria-controls="tree">Namespaces</button>
<button type="button" role="tab" id="view-nodes" aria-selected="false" aria-controls="tree">Ноды</button>
</div>
<input type="search" id="tree-filter" placeholder="Поиск: имя, namespace, образ…" aria-label="Поиск по инвентарю">
<ul class="tree" id="tree" role="tree" aria-label="Объекты кластера"></ul>
<p class="hint">Клик — открыть на карте. Ctrl+клик по namespace — добавить к текущему виду.</p>
</aside>
<main class="stage">
<div id="cy" aria-label="Карта"></div>
<div class="stage-status" id="stage-status" role="status" aria-live="polite"></div>
<div class="zoom" role="group" aria-label="Масштаб">
<button type="button" class="btn icon" id="zoom-in" aria-label="Приблизить">+</button>
<button type="button" class="btn icon" id="zoom-out" aria-label="Отдалить">−</button>
<button type="button" class="btn icon" id="zoom-fit" aria-label="Показать всё">⤢</button>
</div>
<div class="legend" id="legend"></div>
</main>
<aside class="details" id="details" aria-label="Детали объекта" hidden>
<div class="details-head">
<div class="details-title">
<span class="kind-chip" id="d-kind"></span>
<h2 id="d-name"></h2>
<div class="muted small" id="d-sub"></div>
</div>
<button type="button" class="btn icon" id="d-close" aria-label="Закрыть панель">×</button>
</div>
<div class="tabs" role="tablist" aria-label="Разделы">
<button type="button" role="tab" data-tab="overview" aria-selected="true">Обзор</button>
<button type="button" role="tab" data-tab="links" aria-selected="false">Связи</button>
<button type="button" role="tab" data-tab="yaml" aria-selected="false">YAML</button>
<button type="button" role="tab" data-tab="logs" aria-selected="false">Логи</button>
</div>
<section class="tab-panel" data-panel="overview" role="tabpanel"></section>
<section class="tab-panel" data-panel="links" role="tabpanel" hidden></section>
<section class="tab-panel" data-panel="yaml" role="tabpanel" hidden><pre class="code" id="d-yaml"></pre></section>
<section class="tab-panel" data-panel="logs" role="tabpanel" hidden>
<div class="logs-bar">
<select id="pod-select" aria-label="Под"></select>
<select id="container-select" aria-label="Контейнер"></select>
<button type="button" class="btn" id="logs-reload">Обновить</button>
</div>
<pre class="code" id="d-logs"></pre>
</section>
</aside>
</div>
<script src="app.js"></script>
</body>
</html>
+6
View File
@@ -0,0 +1,6 @@
{{- /* "true" when the module needs the viewer's own token in each request:
for actions (they run as the viewer) and for ViewerRBAC visibility
(what the viewer may see is asked as the viewer). */}}
{{- define "cluster_map_viewer_token" -}}
{{- or .Values.clusterMap.actions.enabled (eq .Values.clusterMap.auth.visibility "ViewerRBAC") -}}
{{- end -}}
+3
View File
@@ -0,0 +1,3 @@
{{- if or (eq (include "helm_lib_module_ingress_enabled" .) "true") (eq (include "helm_lib_module_gateway_enabled" .) "true") }}
{{- include "helm_lib_module_https_copy_custom_certificate" (list . "d8-cluster-map" "ingress-tls") }}
{{- end }}
+144
View File
@@ -0,0 +1,144 @@
{{- $traffic := .Values.clusterMap.traffic }}
{{- /* Without the hubble CA there is no relay to talk to: cilium-hubble is off. */}}
{{- $trafficMode := ternary $traffic.mode "Disabled" (ne .Values.clusterMap.internal.hubbleCA "") }}
{{- if (.Capabilities.APIVersions.Has "autoscaling.k8s.io/v1/VerticalPodAutoscaler") }}
---
apiVersion: autoscaling.k8s.io/v1
kind: VerticalPodAutoscaler
metadata:
name: cluster-map
namespace: d8-cluster-map
{{- include "helm_lib_module_labels" (list . (dict "app" "cluster-map")) | nindent 2 }}
spec:
targetRef:
apiVersion: apps/v1
kind: Deployment
name: cluster-map
updatePolicy:
updateMode: "InPlaceOrRecreate"
resourcePolicy:
containerPolicies:
- containerName: cluster-map
minAllowed:
cpu: 10m
memory: 64Mi
maxAllowed:
cpu: 500m
# the traffic collector keeps distinct connections for the whole
# retention window; a day on a busy cluster needs more than an hour
memory: {{ ternary "2Gi" "512Mi" (gt (int $traffic.retentionMinutes) 180) }}
{{- end }}
---
apiVersion: policy/v1
kind: PodDisruptionBudget
metadata:
name: cluster-map
namespace: d8-cluster-map
{{- include "helm_lib_module_labels" (list . (dict "app" "cluster-map")) | nindent 2 }}
spec:
maxUnavailable: 1
selector:
matchLabels:
app: cluster-map
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: cluster-map
namespace: d8-cluster-map
{{- include "helm_lib_module_labels" (list . (dict "app" "cluster-map")) | nindent 2 }}
spec:
# One replica by design: traffic history lives in the process. Two replicas
# would each keep their own history and double the load on hubble-relay.
replicas: 1
revisionHistoryLimit: 2
strategy:
type: Recreate
selector:
matchLabels:
app: cluster-map
template:
metadata:
labels:
app: cluster-map
annotations:
checksum/hubble-ca: {{ .Values.clusterMap.internal.hubbleCA | sha256sum }}
spec:
serviceAccountName: cluster-map
automountServiceAccountToken: true
{{- include "helm_lib_priority_class" (tuple . "cluster-low") | nindent 6 }}
{{- include "helm_lib_node_selector" (tuple . "system") | nindent 6 }}
{{- include "helm_lib_tolerations" (tuple . "system") | nindent 6 }}
{{- include "helm_lib_module_pod_security_context_run_as_user_deckhouse" . | nindent 6 }}
{{- if .Values.clusterMap.registry.dockercfg }}
imagePullSecrets:
- name: deckhouse-registry
{{- end }}
containers:
- name: cluster-map
image: {{ include "helm_lib_module_image" (list . "clusterMap") }}
imagePullPolicy: IfNotPresent
{{- include "helm_lib_module_container_security_context_read_only_root_filesystem_capabilities_drop_all_pss_restricted" . | nindent 8 }}
env:
- name: LISTEN_ADDR
value: ":8080"
- name: METRICS_ADDR
value: ":9090"
- name: TRAFFIC_MODE
value: {{ $trafficMode | quote }}
- name: TRAFFIC_RETENTION
value: {{ printf "%dm" (int $traffic.retentionMinutes) | quote }}
- name: TRAFFIC_ON_DEMAND_IDLE
value: {{ printf "%dm" (int $traffic.onDemandIdleMinutes) | quote }}
- name: TRAFFIC_COLLECT_INFRA
value: {{ $traffic.collectInfraTraffic | quote }}
- name: HUBBLE_RELAY_ADDR
value: {{ printf "hubble-relay.d8-cni-cilium.svc.%s:443" .Values.global.discovery.clusterDomain | quote }}
- name: HUBBLE_CA_FILE
value: /etc/hubble-ca/ca.crt
- name: ACTIONS_ENABLED
value: {{ .Values.clusterMap.actions.enabled | quote }}
- name: VISIBILITY
value: {{ .Values.clusterMap.auth.visibility | quote }}
- name: LOG_TAIL_LINES
value: {{ .Values.clusterMap.logs.tailLines | quote }}
- name: SYSTEM_NAMESPACE_PREFIXES
value: {{ .Values.clusterMap.systemNamespacePrefixes | join "," | quote }}
ports:
- name: http
containerPort: 8080
protocol: TCP
- name: metrics
containerPort: 9090
protocol: TCP
livenessProbe:
httpGet:
path: /healthz
port: http
periodSeconds: 10
timeoutSeconds: 3
readinessProbe:
httpGet:
path: /readyz
port: http
periodSeconds: 5
timeoutSeconds: 3
resources:
requests:
{{- include "helm_lib_module_ephemeral_storage_only_logs" . | nindent 12 }}
{{- if not (.Capabilities.APIVersions.Has "autoscaling.k8s.io/v1/VerticalPodAutoscaler") }}
cpu: 25m
memory: 96Mi
{{- end }}
{{- if .Values.clusterMap.internal.hubbleCA }}
volumeMounts:
- name: hubble-ca
mountPath: /etc/hubble-ca
readOnly: true
{{- end }}
{{- if .Values.clusterMap.internal.hubbleCA }}
volumes:
- name: hubble-ca
configMap:
name: hubble-ca
{{- end }}
+50
View File
@@ -0,0 +1,50 @@
{{- $moduleGateway := dict }}
{{- include "helm_lib_module_gateway" (list . $moduleGateway) }}
{{- $ingressEnabled := eq (include "helm_lib_module_ingress_enabled" .) "true" }}
{{- $gatewayEnabled := eq (include "helm_lib_module_gateway_enabled" .) "true" }}
{{- if and .Values.clusterMap.internal.deployDexAuthenticator (or $ingressEnabled $gatewayEnabled) }}
---
apiVersion: deckhouse.io/v1
kind: DexAuthenticator
metadata:
name: cluster-map
namespace: d8-cluster-map
{{- include "helm_lib_module_labels" (list . (dict "app" "dex-authenticator" "name" "cluster-map")) | nindent 2 }}
{{- if eq (include "cluster_map_viewer_token" .) "true" }}
annotations:
# user-authn then asks Dex for a token with the kubernetes audience,
# which the API server accepts: actions and ViewerRBAC visibility use it
# (as the console does)
dexauthenticator.deckhouse.io/allow-access-to-kubernetes: "true"
{{- end }}
spec:
applicationDomain: {{ include "helm_lib_module_public_domain" (list . "cluster-map") }}
{{- if and $ingressEnabled (include "helm_lib_module_https_ingress_tls_enabled" .) }}
applicationIngressCertificateSecretName: {{ include "helm_lib_module_https_secret_name" (list . "ingress-tls") }}
{{- end }}
{{- if and $gatewayEnabled (include "helm_lib_module_https_route_tls_enabled" .) }}
gatewayAPI:
applicationHTTPRouteListenerSetName: cluster-map
{{- end }}
applicationIngressClassName: {{ include "helm_lib_module_ingress_class" . | quote }}
{{- if eq (include "cluster_map_viewer_token" .) "true" }}
# actions and visibility run as the viewer: the user's token goes to the
# module in the Authorization header
sendAuthorizationHeader: true
{{- end }}
{{- with .Values.clusterMap.auth.allowedUserEmails }}
allowedEmails:
{{- . | toYaml | nindent 2 }}
{{- end }}
{{- with .Values.clusterMap.auth.allowedUserGroups }}
allowedGroups:
{{- . | toYaml | nindent 2 }}
{{- end }}
{{- with .Values.clusterMap.auth.whitelistSourceRanges }}
whitelistSourceRanges:
{{- . | toYaml | nindent 2 }}
{{- end }}
{{- include "helm_lib_node_selector" (tuple . "system") | nindent 2 }}
{{- include "helm_lib_tolerations" (tuple . "system") | nindent 2 }}
highAvailability: false
{{- end }}
+123
View File
@@ -0,0 +1,123 @@
{{- $moduleGateway := dict }}
{{- include "helm_lib_module_gateway" (list . $moduleGateway) }}
{{- if and (eq (include "helm_lib_module_gateway_enabled" .) "true") .Values.global.modules.publicDomainTemplate .Values.global.clusterIsBootstrapped }}
---
apiVersion: gateway.networking.k8s.io/v1
kind: ListenerSet
metadata:
name: cluster-map
namespace: d8-cluster-map
{{- include "helm_lib_module_labels" (list . (dict "app" "cluster-map")) | nindent 2 }}
spec:
listeners:
{{- if (include "helm_lib_module_https_route_tls_enabled" .) }}
- allowedRoutes:
namespaces:
from: Same
hostname: {{ include "helm_lib_module_public_domain" (list . "cluster-map") }}
name: cluster-map
port: 443
protocol: HTTPS
tls:
certificateRefs:
- group: ""
kind: Secret
name: {{ include "helm_lib_module_https_secret_name" (list . "ingress-tls" "httproute-tls") }}
namespace: d8-cluster-map
mode: Terminate
- allowedRoutes:
namespaces:
from: Same
hostname: {{ include "helm_lib_module_public_domain" (list . "cluster-map") }}
name: cluster-map-redirect
port: 80
protocol: HTTP
{{- else }}
- allowedRoutes:
namespaces:
from: Same
hostname: {{ include "helm_lib_module_public_domain" (list . "cluster-map") }}
name: cluster-map
port: 80
protocol: HTTP
{{- end }}
parentRef:
group: gateway.networking.k8s.io
kind: Gateway
name: {{ $moduleGateway.name }}
namespace: {{ $moduleGateway.namespace }}
---
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
name: cluster-map
namespace: d8-cluster-map
{{- include "helm_lib_module_labels" (list . (dict "app" "cluster-map")) | nindent 2 }}
annotations:
web.deckhouse.io/export-name: "cluster-map"
web.deckhouse.io/export-icon: "/icon.svg"
{{- if and (ne (include "helm_lib_module_https_mode" .) "Disabled") .Values.clusterMap.auth.externalAuthentication }}
alb.network.deckhouse.io/auth-signin: {{ replace "$host" (include "helm_lib_module_public_domain" (list . "cluster-map")) .Values.clusterMap.auth.externalAuthentication.authSignInURL | quote }}
alb.network.deckhouse.io/auth-url: {{ .Values.clusterMap.auth.externalAuthentication.authURL | quote }}
alb.network.deckhouse.io/auth-response-headers: {{ ternary "X-Auth-Request-User,X-Auth-Request-Email,Authorization" "X-Auth-Request-User,X-Auth-Request-Email" (eq (include "cluster_map_viewer_token" .) "true") | quote }}
{{- end }}
{{- if .Values.clusterMap.auth.whitelistSourceRanges }}
alb.network.deckhouse.io/whitelist-source-range: {{ .Values.clusterMap.auth.whitelistSourceRanges | join "," | quote }}
{{- end }}
spec:
hostnames:
- {{ include "helm_lib_module_public_domain" (list . "cluster-map") }}
parentRefs:
- group: gateway.networking.k8s.io
kind: ListenerSet
name: cluster-map
namespace: d8-cluster-map
sectionName: cluster-map
rules:
- backendRefs:
- group: ""
kind: Service
name: cluster-map
port: 80
weight: 1
matches:
- path:
type: PathPrefix
value: /
{{- if or (eq (include "helm_lib_module_https_mode" .) "CertManager") (eq (include "helm_lib_module_https_mode" .) "CustomCertificate") }}
filters:
- type: ResponseHeaderModifier
responseHeaderModifier:
add:
- name: Strict-Transport-Security
value: max-age=31536000; includeSubDomains
{{- end }}
{{- if (include "helm_lib_module_https_route_tls_enabled" .) }}
---
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
name: cluster-map-redirect
namespace: d8-cluster-map
{{- include "helm_lib_module_labels" (list . (dict "app" "cluster-map")) | nindent 2 }}
spec:
hostnames:
- {{ include "helm_lib_module_public_domain" (list . "cluster-map") }}
parentRefs:
- group: gateway.networking.k8s.io
kind: ListenerSet
name: cluster-map
namespace: d8-cluster-map
sectionName: cluster-map-redirect
rules:
- filters:
- type: RequestRedirect
requestRedirect:
scheme: https
statusCode: 301
matches:
- path:
type: PathPrefix
value: /
{{- end }}
{{- end }}
+13
View File
@@ -0,0 +1,13 @@
{{- if .Values.clusterMap.internal.hubbleCA }}
---
# Public certificate of the hubble CA, copied by the hubble_ca hook from
# d8-cni-cilium. Used to verify hubble-relay's server certificate.
apiVersion: v1
kind: ConfigMap
metadata:
name: hubble-ca
namespace: d8-cluster-map
{{- include "helm_lib_module_labels" (list . (dict "app" "cluster-map")) | nindent 2 }}
data:
ca.crt: {{ .Values.clusterMap.internal.hubbleCA | quote }}
{{- end }}
+85
View File
@@ -0,0 +1,85 @@
{{- if and .Values.global.modules.publicDomainTemplate .Values.global.clusterIsBootstrapped }}
{{- $moduleGateway := dict }}
{{- include "helm_lib_module_gateway" (list . $moduleGateway) }}
{{- if eq (include "helm_lib_module_ingress_enabled" .) "true" }}
---
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: cluster-map
namespace: d8-cluster-map
{{- include "helm_lib_module_labels" (list . (dict "app" "cluster-map")) | nindent 2 }}
annotations:
web.deckhouse.io/export-name: "cluster-map"
web.deckhouse.io/export-icon: "/icon.svg"
{{- if and (ne (include "helm_lib_module_https_mode" .) "Disabled") .Values.clusterMap.auth.externalAuthentication }}
nginx.ingress.kubernetes.io/auth-signin: {{ .Values.clusterMap.auth.externalAuthentication.authSignInURL | quote }}
nginx.ingress.kubernetes.io/auth-url: {{ .Values.clusterMap.auth.externalAuthentication.authURL | quote }}
nginx.ingress.kubernetes.io/auth-response-headers: {{ ternary "X-Auth-Request-User,X-Auth-Request-Email,Authorization" "X-Auth-Request-User,X-Auth-Request-Email" (eq (include "cluster_map_viewer_token" .) "true") | quote }}
{{- end }}
{{- if .Values.clusterMap.auth.whitelistSourceRanges }}
nginx.ingress.kubernetes.io/whitelist-source-range: {{ .Values.clusterMap.auth.whitelistSourceRanges | join "," | quote }}
{{- end }}
nginx.ingress.kubernetes.io/configuration-snippet: |
{{- include "helm_lib_module_ingress_configuration_snippet" . | nindent 6 }}
spec:
ingressClassName: {{ include "helm_lib_module_ingress_class" . | quote }}
rules:
- host: {{ include "helm_lib_module_public_domain" (list . "cluster-map") }}
http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: cluster-map
port:
name: http
{{- if (include "helm_lib_module_https_ingress_tls_enabled" .) }}
tls:
- hosts:
- {{ include "helm_lib_module_public_domain" (list . "cluster-map") }}
secretName: {{ include "helm_lib_module_https_secret_name" (list . "ingress-tls") }}
{{- end }}
{{- end }}
{{- if and (eq (include "helm_lib_module_ingress_enabled" .) "true") (eq (include "helm_lib_module_https_mode" .) "CertManager") }}
---
apiVersion: cert-manager.io/v1
kind: Certificate
metadata:
name: cluster-map
namespace: d8-cluster-map
{{- include "helm_lib_module_labels" (list . (dict "app" "cluster-map")) | nindent 2 }}
spec:
certificateOwnerRef: false
secretName: {{ include "helm_lib_module_https_secret_name" (list . "ingress-tls") }}
{{- include "helm_lib_module_generate_common_name" (list . "cluster-map") | nindent 2 }}
dnsNames:
- {{ include "helm_lib_module_public_domain" (list . "cluster-map") }}
issuerRef:
name: {{ include "helm_lib_module_https_cert_manager_cluster_issuer_name" . }}
kind: ClusterIssuer
{{- end }}
{{- if and (eq (include "helm_lib_module_gateway_enabled" .) "true") (eq (include "helm_lib_module_https_mode" .) "CertManager") }}
{{- $issuerName := include "helm_lib_module_https_cert_manager_cluster_issuer_name" . }}
{{- if or (eq $issuerName "letsencrypt") (eq $issuerName "letsencrypt-staging") }}
{{- $issuerName = printf "%s-gateway-%s" $issuerName $moduleGateway.name }}
{{- end }}
---
apiVersion: cert-manager.io/v1
kind: Certificate
metadata:
name: cluster-map-httproute
namespace: d8-cluster-map
{{- include "helm_lib_module_labels" (list . (dict "app" "cluster-map")) | nindent 2 }}
spec:
certificateOwnerRef: false
secretName: {{ include "helm_lib_module_https_secret_name" (list . "httproute-tls") }}
{{- include "helm_lib_module_generate_common_name" (list . "cluster-map") | nindent 2 }}
dnsNames:
- {{ include "helm_lib_module_public_domain" (list . "cluster-map") }}
issuerRef:
name: {{ $issuerName }}
kind: ClusterIssuer
{{- end }}
{{- end }}
+36
View File
@@ -0,0 +1,36 @@
{{- if (.Capabilities.APIVersions.Has "monitoring.coreos.com/v1/PodMonitor") }}
---
apiVersion: monitoring.coreos.com/v1
kind: PodMonitor
metadata:
name: cluster-map
namespace: d8-cluster-map
{{- include "helm_lib_module_labels" (list . (dict "app" "cluster-map" "prometheus" "main")) | nindent 2 }}
spec:
selector:
matchLabels:
app: cluster-map
podMetricsEndpoints:
- port: metrics
scheme: http
path: /metrics
relabelings:
- regex: endpoint|namespace|pod|service
action: labeldrop
- targetLabel: job
replacement: cluster-map
- sourceLabels: [__meta_kubernetes_pod_node_name]
targetLabel: node
- targetLabel: tier
replacement: cluster
- sourceLabels: [__meta_kubernetes_pod_ready]
regex: "true"
action: keep
{{- end }}
{{- /* helm_lib_prometheus_rules only renders when "operator-prometheus-crd"
is among enabled modules; on DKP 1.76 the CRDs ship with
operator-prometheus and that module name no longer exists, so the
rules were silently dropped. Gate on the API itself instead. */}}
{{- if (.Capabilities.APIVersions.Has "monitoring.coreos.com/v1/PrometheusRule") }}
{{- include "helm_lib_prometheus_rules_recursion" (list . "d8-cluster-map" "monitoring/prometheus-rules") }}
{{- end }}
+6
View File
@@ -0,0 +1,6 @@
---
apiVersion: v1
kind: Namespace
metadata:
name: d8-cluster-map
{{- include "helm_lib_module_labels" (list . (dict "prometheus.deckhouse.io/rules-watcher-enabled" "true" "prometheus.deckhouse.io/monitor-watcher-enabled" "true")) | nindent 2 }}
+61
View File
@@ -0,0 +1,61 @@
---
apiVersion: v1
kind: ServiceAccount
metadata:
name: cluster-map
namespace: d8-cluster-map
{{- include "helm_lib_module_labels" (list . (dict "app" "cluster-map")) | nindent 2 }}
automountServiceAccountToken: true
---
# Read-only on exactly what the map shows. No Secrets, no ConfigMaps, no
# write verbs. pods/log backs the Logs tab, events and clusteralerts the
# problem badges, vulnerabilityreports (operator-trivy) the shield on
# cards, metrics.k8s.io the Load section. Actions (restart, scale…) never
# use this account: they run with the viewer's own token.
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
name: d8:cluster-map
{{- include "helm_lib_module_labels" (list . (dict "app" "cluster-map")) | nindent 2 }}
rules:
- apiGroups: [""]
resources: ["namespaces", "pods", "services", "nodes"]
verbs: ["get", "list", "watch"]
- apiGroups: [""]
resources: ["pods/log"]
verbs: ["get"]
- apiGroups: [""]
resources: ["events"]
verbs: ["get", "list", "watch"]
- apiGroups: ["deckhouse.io"]
resources: ["clusteralerts"]
verbs: ["get", "list", "watch"]
- apiGroups: ["aquasecurity.github.io"]
resources: ["vulnerabilityreports"]
verbs: ["get", "list", "watch"]
- apiGroups: ["metrics.k8s.io"]
resources: ["pods", "nodes"]
verbs: ["get", "list"]
- apiGroups: ["apps"]
resources: ["deployments", "statefulsets", "daemonsets"]
verbs: ["get", "list", "watch"]
- apiGroups: ["batch"]
resources: ["cronjobs"]
verbs: ["get", "list", "watch"]
- apiGroups: ["networking.k8s.io"]
resources: ["ingresses"]
verbs: ["get", "list", "watch"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
name: d8:cluster-map
{{- include "helm_lib_module_labels" (list . (dict "app" "cluster-map")) | nindent 2 }}
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: ClusterRole
name: d8:cluster-map
subjects:
- kind: ServiceAccount
name: cluster-map
namespace: d8-cluster-map
+12
View File
@@ -0,0 +1,12 @@
{{- if .Values.clusterMap.registry.dockercfg }}
---
apiVersion: v1
kind: Secret
type: kubernetes.io/dockerconfigjson
metadata:
name: deckhouse-registry
namespace: d8-cluster-map
{{- include "helm_lib_module_labels" (list . (dict "app" "cluster-map")) | nindent 2 }}
data:
.dockerconfigjson: {{ .Values.clusterMap.registry.dockercfg }}
{{- end }}
+16
View File
@@ -0,0 +1,16 @@
---
apiVersion: v1
kind: Service
metadata:
name: cluster-map
namespace: d8-cluster-map
{{- include "helm_lib_module_labels" (list . (dict "app" "cluster-map")) | nindent 2 }}
spec:
type: ClusterIP
selector:
app: cluster-map
ports:
- name: http
port: 80
targetPort: http
protocol: TCP
+45
View File
@@ -0,0 +1,45 @@
# Values as Deckhouse would pass them for a typical cluster: user-authn on,
# CertManager https, cilium-hubble installed. Used by `make render`.
global:
clusterIsBootstrapped: true
enabledModules: ["user-authn", "cert-manager", "vertical-pod-autoscaler", "operator-prometheus", "cilium-hubble"]
discovery:
clusterDomain: cluster.local
clusterControlPlaneIsHighlyAvailable: false
d8SpecificNodeCountByRole: {}
highAvailability: false
modules:
publicDomainTemplate: "%s.example.com"
ingressClass: nginx
https:
mode: CertManager
certManager:
clusterIssuerName: letsencrypt
placement: {}
modulesImages:
registry:
base: registry.example.com/modules
digests:
clusterMap:
clusterMap: "sha256:0000000000000000000000000000000000000000000000000000000000000000"
clusterMap:
traffic:
mode: Continuous
retentionMinutes: 60
onDemandIdleMinutes: 10
collectInfraTraffic: false
actions:
enabled: true
logs:
tailLines: 500
systemNamespacePrefixes: ["d8-", "kube-"]
auth:
visibility: ViewerRBAC
allowedUserGroups: ["admins"]
externalAuthentication:
authURL: https://cluster-map-dex-authenticator.d8-cluster-map.svc.cluster.local/dex-authenticator/auth
authSignInURL: https://$host/dex-authenticator/sign_in
internal:
deployDexAuthenticator: true
hubbleCA: "-----BEGIN CERTIFICATE-----\n-----END CERTIFICATE-----\n"
registry: {}
+4
View File
@@ -0,0 +1,4 @@
# cilium-hubble absent: the hook leaves hubbleCA empty and traffic turns off.
clusterMap:
internal:
hubbleCA: ""
+9
View File
@@ -0,0 +1,9 @@
giterminismConfigVersion: 1
config:
goTemplateRendering: # The rules for the Go-template functions to be able to pass build context to the release
allowEnvVariables:
- /CI_.+/
- MODULES_MODULE_TAG
- STAGED_DOCKERFILE # Allow the use of these variable in the .werf/stages/images.yaml file
allowUncommittedFiles:
- "base_images.yml"
+17
View File
@@ -0,0 +1,17 @@
project: cluster-map
configVersion: 1
build:
imageSpec:
author: "cluster-map authors"
clearHistory: true
config:
clearWerfLabels: true
removeLabels:
- /.*/
---
{{ tpl (.Files.Get ".werf/stages/base-images.yaml") $ }}
{{ tpl (.Files.Get ".werf/stages/images.yaml") $ }}
{{ tpl (.Files.Get ".werf/stages/images-digests.yaml") $ }}
{{ tpl (.Files.Get ".werf/stages/batch-go.yaml") $ }}
{{ tpl (.Files.Get ".werf/stages/bundle.yaml") $ }}
{{ tpl (.Files.Get ".werf/stages/release.yaml") $ }}
+32
View File
@@ -0,0 +1,32 @@
configVersion: 1
project: echoserver
cleanup:
keepPolicies:
- references:
branch: /.*/
limit:
in: 168h
- references:
branch: /release-[0-9]+.*/
limit:
last: 3
imagesPerReference:
last: 1
- references:
tag: /^v([0-9]\d*)\.([0-9]\d*)\.([0-9]\d*)(-.*)?/
limit:
last: 3
imagesPerReference:
last: 1
- references:
tag: /.*/
limit:
last: 3
imagesPerReference:
last: 1
- references:
branch: /master|main/
limit:
last: 1
imagesPerReference:
last: 1