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>
This commit is contained in:
Vitaliy Chefanov
2026-09-23 21:17:52 +03:00
co-authored by Claude Opus 5.5
parent 41f9b47556
commit 4518393ce1
82 changed files with 5712 additions and 1415 deletions
+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,148 @@
/*
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/kubernetes"
"k8s.io/client-go/rest"
"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()
srv := server.New(cfg, web.Static())
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)
restCfg, err := rest.InClusterConfig()
if err != nil {
return fmt.Errorf("in-cluster config: %w", err)
}
client, err := kubernetes.NewForConfig(restCfg)
if err != nil {
return err
}
cache, err := kube.Start(ctx, client, 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))
}
// 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
}
}
+58
View File
@@ -0,0 +1,58 @@
module git.project-chimera.ru/fanchji/cluster-map
go 1.25.0
require (
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/protobuf v1.36.11
k8s.io/api v0.32.0
k8s.io/apimachinery v0.32.0
k8s.io/client-go v0.32.0
sigs.k8s.io/yaml v1.4.0
)
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/emicklei/go-restful/v3 v3.12.0 // indirect
github.com/fxamacker/cbor/v2 v2.7.0 // indirect
github.com/go-logr/logr v1.4.3 // indirect
github.com/go-openapi/jsonpointer v0.21.0 // indirect
github.com/go-openapi/jsonreference v0.21.0 // indirect
github.com/go-openapi/swag v0.23.0 // indirect
github.com/gogo/protobuf v1.3.2 // indirect
github.com/golang/protobuf v1.5.4 // indirect
github.com/google/gnostic-models v0.6.8 // indirect
github.com/google/go-cmp v0.7.0 // indirect
github.com/google/gofuzz v1.2.0 // indirect
github.com/google/uuid v1.6.0 // indirect
github.com/josharian/intern v1.0.0 // indirect
github.com/json-iterator/go v1.1.12 // indirect
github.com/mailru/easyjson v0.7.7 // indirect
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // 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/x448/float16 v0.8.4 // indirect
golang.org/x/net v0.57.0 // indirect
golang.org/x/oauth2 v0.36.0 // indirect
golang.org/x/sys v0.47.0 // indirect
golang.org/x/term v0.45.0 // indirect
golang.org/x/text v0.40.0 // indirect
golang.org/x/time v0.8.0 // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20260706201446-f0a921348800 // 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/klog/v2 v2.130.1 // indirect
k8s.io/kube-openapi v0.0.0-20241105132330-32ad38e42d3f // indirect
k8s.io/utils v0.0.0-20241210054802-24370beab758 // indirect
sigs.k8s.io/json v0.0.0-20241010143419-9aa6b5e7a4b3 // indirect
sigs.k8s.io/structured-merge-diff/v4 v4.4.2 // indirect
)
+171
View File
@@ -0,0 +1,171 @@
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/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.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/emicklei/go-restful/v3 v3.12.0 h1:y2DdzBAURM29NFF94q6RaY4vjIH1rtwDapwQtU84iWk=
github.com/emicklei/go-restful/v3 v3.12.0/go.mod h1:6n3XBCmQQb25CM2LCACGz8ukIrRry+4bhvbpWn3mrbc=
github.com/fxamacker/cbor/v2 v2.7.0 h1:iM5WgngdRBanHcxugY4JySA0nk1wZorNOpTgCMedv5E=
github.com/fxamacker/cbor/v2 v2.7.0/go.mod h1:pxXPTn3joSm21Gbwsv0w9OSA2y1HFR9qXEeXQVeNoDQ=
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-openapi/jsonpointer v0.21.0 h1:YgdVicSA9vH5RiHs9TZW5oyafXZFc6+2Vc1rr/O9oNQ=
github.com/go-openapi/jsonpointer v0.21.0/go.mod h1:IUyH9l/+uyhIYQ/PXVA41Rexl+kOkAPDdXEYns6fzUY=
github.com/go-openapi/jsonreference v0.21.0 h1:Rs+Y7hSXT83Jacb7kFyjn4ijOuVGSvOdF2+tg1TRrwQ=
github.com/go-openapi/jsonreference v0.21.0/go.mod h1:LmZmgsrTkVg9LG4EaHeY8cBDslNPMo06cago5JNLkm4=
github.com/go-openapi/swag v0.23.0 h1:vsEVJDUo2hPJ2tu0/Xc+4noaxyEffXNIs3cOULZ+GrE=
github.com/go-openapi/swag v0.23.0/go.mod h1:esZ8ITTYEsH1V2trKHjAN8Ai7xHb8RV+YSZ577vPjgQ=
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/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=
github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=
github.com/google/gnostic-models v0.6.8 h1:yo/ABAfM5IMRsS1VnXjTBvUb61tFIHozhlYvRgGre9I=
github.com/google/gnostic-models v0.6.8/go.mod h1:5n7qKqH0f5wFt+aWF8CW6pZLLNOfYuF5OpfBSENuI8U=
github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
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/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/josharian/intern v1.0.0 h1:vlS4z54oSdjm0bgjRigI+G1HpF+tI+9rE5LLzOg8HmY=
github.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFFd8Hwg//Y=
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.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/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
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/mailru/easyjson v0.7.7 h1:UGYAvKxe3sBsEDzO8ZeWOSlIQfWFlxbzLZe7hwFURr0=
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-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 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=
github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
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 v1.16.5 h1:8xi0RTUf59SOSfEtZMvwTvXYMzG4gV23XVHOZiXNtnE=
github.com/onsi/ginkgo/v2 v2.21.0 h1:7rg/4f3rB88pb5obDgNZrNHrQ4e6WpjonchcpuBRnZM=
github.com/onsi/ginkgo/v2 v2.21.0/go.mod h1:7Du3c42kxCUegi0IImZ1wUQzMBVecgIHjR1C+NkhLQo=
github.com/onsi/gomega v1.35.1 h1:Cwbd75ZBPxFSuZ6T+rN/WCb/gOc6YgFBXLlZLhC7Ds4=
github.com/onsi/gomega v1.35.1/go.mod h1:PvZbdDc8J6XJEpDK4HCuRBm8a6Fzp9/DmhC9C7yFlog=
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.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/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/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
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.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
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/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=
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-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
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/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-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.57.0 h1:K5+3DljvIuDG9/Jv9rvyMywYNFCQ9RSUY6OOTTkT+tE=
golang.org/x/net v0.57.0/go.mod h1:KpXc8iv+r3XplLAG/f7Jsf9RPszJzdR0f58q9vGOuEU=
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/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-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
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.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.40.0 h1:Ub2Z6/xjgF1WrYQz2nuITOEegKFtiIy+rieRJ5lHZKs=
golang.org/x/text v0.40.0/go.mod h1:hpnzDAfGV753zIKo+wk3u1bVKCGPbrnF7+7LBF/UHVY=
golang.org/x/time v0.8.0 h1:9i3RxcPv3PZnitoVGMPDKZSq1xW1gK1Xy3ArNOGZfEg=
golang.org/x/time v0.8.0/go.mod h1:3BpzKBy/shNhVucY/MWOyx10tF3SFh9QdLuxbVysPQM=
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.47.0 h1:7Kn5x/d1svx/PzryTsqeoZN4TZwqeH5pGWjefhLi/1Q=
golang.org/x/tools v0.47.0/go.mod h1:dFHnyTvFWY212G+h7ZY4Vsp/K3U4/7W9TyVaAul8uCA=
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=
gonum.org/v1/gonum v0.17.0 h1:VbpOemQlsSMrYmn7T2OUvQ4dqxQXU+ouZFQsZOx50z4=
gonum.org/v1/gonum v0.17.0/go.mod h1:El3tOrEuMpv2UdMrbNlKEh9vd86bmQ6vqIcDwxEOc1E=
google.golang.org/genproto/googleapis/rpc v0.0.0-20260706201446-f0a921348800 h1:qEHAMpSaUhtD0p3NbEEI83HwNGFxEwaSJ1G9PLnCBZE=
google.golang.org/genproto/googleapis/rpc v0.0.0-20260706201446-f0a921348800/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8=
google.golang.org/grpc v1.84.0 h1:soMyaPJ8pAak5PIQ0DGBUir0XRo2fRoMqhNWMLlLxO0=
google.golang.org/grpc v1.84.0/go.mod h1:ljCht0DrxQrXBDRTZp52Qxh3Ffk8CdYm2sj4O2QN2C0=
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-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.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
k8s.io/api v0.32.0 h1:OL9JpbvAU5ny9ga2fb24X8H6xQlVp+aJMFlgtQjR9CE=
k8s.io/api v0.32.0/go.mod h1:4LEwHZEf6Q/cG96F3dqR965sYOfmPM7rq81BLgsE0p0=
k8s.io/apimachinery v0.32.0 h1:cFSE7N3rmEEtv4ei5X6DaJPHHX0C+upp+v5lVPiEwpg=
k8s.io/apimachinery v0.32.0/go.mod h1:GpHVgxoKlTxClKcteaeuF1Ul/lDVb74KpZcxcmLDElE=
k8s.io/client-go v0.32.0 h1:DimtMcnN/JIKZcrSrstiwvvZvLjG0aSxy8PxN8IChp8=
k8s.io/client-go v0.32.0/go.mod h1:boDWvdM1Drk4NJj/VddSLnx59X3OPgwrOo0vGbtq9+8=
k8s.io/klog/v2 v2.130.1 h1:n9Xl7H1Xvksem4KFG4PYbdQCQxqc/tTUyrgXaOhHSzk=
k8s.io/klog/v2 v2.130.1/go.mod h1:3Jpz1GvMt720eyJH1ckRHK1EDfpxISzJ7I9OYgaDtPE=
k8s.io/kube-openapi v0.0.0-20241105132330-32ad38e42d3f h1:GA7//TjRY9yWGy1poLzYYJJ4JRdzg3+O6e8I+e+8T5Y=
k8s.io/kube-openapi v0.0.0-20241105132330-32ad38e42d3f/go.mod h1:R/HEjbvWI0qdfb8viZUeVZm0X6IZnxAydC7YU42CMw4=
k8s.io/utils v0.0.0-20241210054802-24370beab758 h1:sdbE21q2nlQtFh65saZY+rRM6x6aJJI8IUa1AmH/qa0=
k8s.io/utils v0.0.0-20241210054802-24370beab758/go.mod h1:OLgZIPagt7ERELqWJFomSt595RzquPNLL48iOWgYOg0=
sigs.k8s.io/json v0.0.0-20241010143419-9aa6b5e7a4b3 h1:/Rv+M11QRah1itp8VhT6HoVx1Ray9eB4DBr+K+/sCJ8=
sigs.k8s.io/json v0.0.0-20241010143419-9aa6b5e7a4b3/go.mod h1:18nIHnGi6636UCz6m8i4DhaJ65T6EruyzmoQqI2BVDo=
sigs.k8s.io/structured-merge-diff/v4 v4.4.2 h1:MdmvkGuXi/8io6ixD5wud3vOLwc1rj0aNqRlpuvjmwA=
sigs.k8s.io/structured-merge-diff/v4 v4.4.2/go.mod h1:N8f93tFZh9U6vpxwRArLiikrE5/2tiu1w1AGfACIGE4=
sigs.k8s.io/yaml v1.4.0 h1:Mk1wCc2gy/F0THH0TAp1QYyJNzRm2KCLy3o5ASXVI5E=
sigs.k8s.io/yaml v1.4.0/go.mod h1:Ejl7/uTz7PSA4eKMyQCUTnhZYNmLIl+5c2lQPGR2BPY=
@@ -0,0 +1,132 @@
/*
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
}
// 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)
}
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,100 @@
/*
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"
"time"
"k8s.io/apimachinery/pkg/api/meta"
"k8s.io/apimachinery/pkg/labels"
"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"
)
// Cache holds synced listers plus a client for reads that must be live
// (YAML view, logs).
type Cache struct {
Client kubernetes.Interface
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
}
// Start runs the informers and blocks until every cache has synced or ctx
// is done.
func Start(ctx context.Context, client kubernetes.Interface, syncTimeout time.Duration) (*Cache, error) {
f := informers.NewSharedInformerFactoryWithOptions(client, 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
}))
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(),
}
f.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)
}
}
return c, nil
}
// 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,61 @@
/*
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"})
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,
)
}
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,271 @@
/*
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 (
"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/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
ready atomic.Bool
}
// New returns a server that answers 503 on the API until SetReady.
func New(cfg config.Config, static fs.FS) *Server {
return &Server{cfg: cfg, static: static}
}
// 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 /", http.FileServerFS(s.static))
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, _ *http.Request) {
g, err := topology.Build(s.cache, s.cfg.IsSystemNamespace)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
writeJSON(w, g)
}
func (s *Server) handleFlows(w http.ResponseWriter, r *http.Request) {
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
}
writeJSON(w, s.traffic.Query(namespaces, window))
}
// 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")
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
}
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
}
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)
}
}
@@ -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>")}})
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, 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,466 @@
/*
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
}
// 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"`
}
// 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{}
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)...)
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"
}
return map[string]string{"ready": ready, "os": n.Status.NodeInfo.OSImage, "kubelet": n.Status.NodeInfo.KubeletVersion, "health": h}
}
@@ -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, 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,452 @@
/*
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"
"sort"
"strconv"
"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 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"}},
}
var flowFields = []string{"time", "verdict", "IP", "l4", "source", "destination", "source_names", "destination_names", "node_name"}
// 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"`
}
// 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
}
// 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)),
Whitelist: []*flowpb.FlowFilter{{Reply: []bool{false}}},
}
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) {
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
}
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
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 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()
res := Result{Mode: c.cfg.TrafficMode, WindowSec: int(window.Seconds()), Connected: c.connected, Error: c.lastErr}
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{}
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
}
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++
}
}
res.Edges = append(res.Edges, e)
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
}
@@ -0,0 +1,165 @@
/*
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 (
"testing"
"time"
flowpb "github.com/cilium/cilium/api/v1/flow"
"google.golang.org/protobuf/types/known/timestamppb"
"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")
}
}
@@ -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"}
}
+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
}
+202
View File
@@ -0,0 +1,202 @@
:root {
color-scheme: light dark;
--bg: light-dark(#f4f5f7, #0f1115);
--panel: light-dark(#ffffff, #161920);
--panel-2: light-dark(#f0f2f5, #1c2029);
--line: light-dark(#d9dde3, #2a2f3a);
--text: light-dark(#1d2129, #e3e6eb);
--muted: light-dark(#5d6573, #98a1b0);
--accent: light-dark(#2f6fe0, #6aa0ff);
--accent-soft: light-dark(#e3edfd, #1d2a44);
--ok: light-dark(#1f9d55, #3fcf7f);
--warn: light-dark(#c98200, #f0b429);
--error: light-dark(#d33a3a, #ff6b6b);
--idle: light-dark(#8a93a3, #6b7383);
--focus: light-dark(#2f6fe0, #8fb8ff);
accent-color: var(--accent);
scrollbar-color: light-dark(#b9c0cb, #3a4150) transparent;
scrollbar-width: thin;
}
* { box-sizing: border-box; }
html, body { margin: 0; height: 100%; }
body {
background: var(--bg);
color: var(--text);
font: 0.8125rem/1.45 system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;
display: flex;
flex-direction: column;
}
.muted { color: var(--muted); }
.small { font-size: 0.75rem; }
:where(button, input, select, [role="treeitem"], [role="tab"]):focus-visible {
outline: 2px solid var(--focus);
outline-offset: 1px;
}
.btn {
background: var(--panel-2);
color: var(--text);
border: 1px solid var(--line);
border-radius: 6px;
padding: 0.25rem 0.6rem;
font: inherit;
cursor: pointer;
}
.btn:hover { border-color: var(--muted); }
.btn.icon { width: 2rem; height: 2rem; padding: 0; font-size: 1rem; line-height: 1; }
select, input[type="search"] {
background: var(--panel-2);
color: var(--text);
border: 1px solid var(--line);
border-radius: 6px;
padding: 0.3rem 0.5rem;
font: inherit;
}
/* top bar */
.topbar {
display: flex;
align-items: center;
gap: 1rem;
padding: 0.5rem 0.9rem;
background: var(--panel);
border-bottom: 1px solid var(--line);
flex: none;
}
.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 button {
background: none; border: none; color: var(--accent); font: inherit; cursor: pointer; padding: 0.1rem 0.2rem; border-radius: 4px;
}
.crumbs .sep { color: var(--muted); }
.crumbs .chip {
display: inline-flex; align-items: center; gap: 0.25rem;
background: var(--accent-soft); color: var(--text); border-radius: 999px; padding: 0.05rem 0.25rem 0.05rem 0.6rem;
}
.crumbs .chip button { color: var(--muted); padding: 0 0.35rem; }
.topbar-actions { display: flex; align-items: center; gap: 0.6rem; flex: none; }
.toggle { display: inline-flex; align-items: center; gap: 0.3rem; cursor: pointer; }
/* main layout */
.layout { flex: 1; display: flex; min-height: 0; }
.sidebar {
width: 19rem; flex: none;
display: flex; flex-direction: column; gap: 0.6rem;
padding: 0.75rem;
background: var(--panel);
border-right: 1px solid var(--line);
min-height: 0;
}
.seg { display: flex; background: var(--panel-2); border: 1px solid var(--line); border-radius: 7px; padding: 2px; }
.seg [role="tab"] {
flex: 1; border: none; background: none; color: var(--muted); font: inherit; padding: 0.3rem; border-radius: 5px; cursor: pointer;
}
.seg [role="tab"][aria-selected="true"] { background: var(--panel); color: var(--text); box-shadow: 0 1px 2px #0002; }
.hint { margin: 0; color: var(--muted); font-size: 0.72rem; }
/* inventory tree */
.tree, .tree ul { list-style: none; margin: 0; padding: 0; }
.tree { flex: 1; overflow-y: auto; min-height: 0; padding-right: 2px; }
.tree ul { padding-left: 0.9rem; }
.tree [role="treeitem"] > .row {
display: flex; align-items: center; gap: 0.35rem;
padding: 0.18rem 0.35rem; border-radius: 5px; cursor: pointer;
white-space: nowrap;
}
.tree [role="treeitem"] > .row:hover { background: var(--panel-2); }
.tree [role="treeitem"][aria-selected="true"] > .row { background: var(--accent-soft); }
.tree [role="treeitem"].in-scope > .row .label { font-weight: 600; }
.tree [role="treeitem"]:focus-visible { outline: none; }
.tree [role="treeitem"]:focus-visible > .row { outline: 2px solid var(--focus); outline-offset: -2px; }
.tree [role="treeitem"][aria-expanded="false"] > ul { display: none; }
.tree .twisty { width: 0.9rem; flex: none; color: var(--muted); text-align: center; font-size: 0.65rem; }
.tree [aria-expanded="true"] > .row .twisty::before { content: "▾"; }
.tree [aria-expanded="false"] > .row .twisty::before { content: "▸"; }
.tree .icon { width: 14px; height: 14px; flex: none; }
.tree .label { overflow: hidden; text-overflow: ellipsis; flex: 1; min-width: 0; }
.tree .count { color: var(--muted); font-size: 0.7rem; font-variant-numeric: tabular-nums; }
.tree mark { background: none; color: var(--accent); font-weight: 650; }
.dot { width: 8px; height: 8px; border-radius: 50%; flex: none; display: inline-block; }
.dot.ok { background: var(--ok); }
.dot.warn { background: var(--warn); }
.dot.error { background: var(--error); }
.dot.idle { background: var(--idle); }
/* canvas */
.stage { flex: 1; position: relative; min-width: 0; }
#cy { position: absolute; inset: 0; }
.stage-status {
position: absolute; top: 0.6rem; left: 50%; transform: translateX(-50%);
background: var(--panel); border: 1px solid var(--line); border-radius: 999px;
padding: 0.2rem 0.8rem; font-size: 0.75rem; color: var(--muted);
}
.stage-status:empty { display: none; }
.stage-status.error { color: var(--error); }
.zoom { position: absolute; right: 0.75rem; bottom: 0.75rem; display: flex; flex-direction: column; gap: 0.3rem; }
.legend {
position: absolute; left: 0.75rem; bottom: 0.75rem;
display: flex; flex-wrap: wrap; gap: 0.35rem 0.9rem; max-width: 70%;
background: color-mix(in srgb, var(--panel) 88%, transparent);
border: 1px solid var(--line); border-radius: 8px; padding: 0.4rem 0.7rem;
font-size: 0.72rem; color: var(--muted);
}
.legend span { display: inline-flex; align-items: center; gap: 0.35rem; }
.legend .line { width: 22px; height: 0; border-top: 2px solid var(--muted); }
.legend .line.traffic { border-top: 3px dashed var(--accent); }
.legend .line.drop { border-top: 3px dashed var(--error); }
.legend .line.config { border-top: 1.5px solid var(--muted); }
/* details panel */
.details {
width: 27rem; flex: none;
display: flex; flex-direction: column;
background: var(--panel);
border-left: 1px solid var(--line);
min-height: 0;
}
.details[hidden] { display: none; }
.details-head { display: flex; align-items: flex-start; gap: 0.5rem; padding: 0.8rem 0.9rem 0.5rem; }
.details-title { flex: 1; min-width: 0; }
.details-title h2 { margin: 0.2rem 0 0; font-size: 1rem; overflow-wrap: anywhere; }
.kind-chip {
display: inline-block; font-size: 0.68rem; font-weight: 600; letter-spacing: 0.02em;
padding: 0.05rem 0.45rem; border-radius: 4px; color: #fff;
}
.tabs { display: flex; gap: 0.2rem; padding: 0 0.9rem; border-bottom: 1px solid var(--line); }
.tabs [role="tab"] {
border: none; background: none; color: var(--muted); font: inherit;
padding: 0.45rem 0.6rem; cursor: pointer; border-bottom: 2px solid transparent; margin-bottom: -1px;
}
.tabs [role="tab"][aria-selected="true"] { color: var(--text); border-bottom-color: var(--accent); }
.tabs [role="tab"][hidden] { display: none; }
.tab-panel { flex: 1; overflow-y: auto; padding: 0.8rem 0.9rem; min-height: 0; }
.tab-panel[hidden] { display: none; }
.facts { display: grid; grid-template-columns: max-content 1fr; gap: 0.3rem 0.8rem; margin: 0 0 1rem; }
.facts dt { color: var(--muted); }
.facts dd { margin: 0; overflow-wrap: anywhere; }
.status { display: inline-flex; align-items: center; gap: 0.35rem; }
.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 button {
width: 100%; display: flex; align-items: center; gap: 0.5rem; text-align: left;
background: var(--panel-2); border: 1px solid var(--line); border-radius: 6px;
padding: 0.35rem 0.5rem; color: var(--text); font: inherit; cursor: pointer;
}
.link-list button:hover { border-color: var(--accent); }
.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); }
.code {
margin: 0; white-space: pre; overflow: auto;
font: 0.72rem/1.5 ui-monospace, "JetBrains Mono", Menlo, Consolas, monospace;
background: var(--panel-2); border: 1px solid var(--line); border-radius: 6px; padding: 0.6rem;
}
#d-logs { white-space: pre-wrap; overflow-wrap: anywhere; }
.logs-bar { display: flex; gap: 0.4rem; margin-bottom: 0.5rem; flex-wrap: wrap; }
.logs-bar select { max-width: 100%; }
@media (prefers-reduced-motion: reduce) {
* { transition: none !important; animation: none !important; }
}
File diff suppressed because it is too large Load Diff
+159
View File
@@ -0,0 +1,159 @@
'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.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',
},
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.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': 'Язык',
},
};
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,86 @@
<!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">
<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>
<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">⤢</button>
</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="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="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="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>
</div>
<script src="app.js"></script>
</body>
</html>
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+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"]