v0.8.0: problem badges, actions as the viewer, load, events, lock

Problems: cards, namespace and node boxes and the tree carry a yellow or
red badge, computed on the server from object state (crash loops, image
pulls, pending and unschedulable pods, readiness older than 2 minutes, a
stuck rollout, a failed CronJob run, Services without endpoints,
Ingresses to missing Services, node conditions), recent Warning events
(notable reasons at once, others after five repeats) and Deckhouse
ClusterAlerts mapped by their labels. A Problems panel lists them all.
Checked against the live cluster: upmeter's synthetic probe pods and
ingress-nginx's fakeservice Ingresses are excluded, they fail on purpose.

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

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

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

KUBECONFIG is honoured for running the binary on a workstation.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Виталий Чефанов
2026-09-24 17:25:36 +03:00
co-authored by Claude Opus 5.5
parent 8b8fe341d5
commit 3cdc2583ee
36 changed files with 2909 additions and 83 deletions
+11
View File
@@ -40,3 +40,14 @@ spec:
```
Memory grows with retention; watch `cluster_map_traffic_tracked_tuples` and the `ClusterMapTrackedTuplesHigh` alert.
## A read-only map
```yaml
spec:
settings:
actions:
enabled: false
```
No action buttons, and the user's token is no longer passed to the module.
+11
View File
@@ -40,3 +40,14 @@ spec:
```
Память растёт вместе с глубиной хранения — следите за `cluster_map_traffic_tracked_tuples` и алертом `ClusterMapTrackedTuplesHigh`.
## Карта только для просмотра
```yaml
spec:
settings:
actions:
enabled: false
```
Кнопок действий нет, и токен пользователя модулю больше не передаётся.
+36 -4
View File
@@ -14,10 +14,39 @@ The `cluster-map` module answers "where does this service live and what does it
- Solid arrows are configuration links: Ingress backends and Service selectors.
- Dashed animated arrows are real connections from Hubble over the chosen window (5 minutes, 15 minutes, 1 hour); red when Cilium dropped some of them. Peers from other namespaces appear as dashed cards in their own boxes.
- With more than 30 traffic directions on screen, lines stay faint until a card is hovered or selected.
- **Details** (right). Overview, Links (configuration and traffic, clickable), live YAML, and container logs.
- **Details** (right). Overview (a one-line verdict, the object's problems, its facts, CPU and memory against requests and limits, its pods), Links (configuration and traffic, clickable), live YAML, Events, container logs, and the actions the viewer is allowed to run.
- **Problems** (the button in the top bar). Everything that is wrong right now, most severe first, filterable to applications or system namespaces; a click opens the object.
Cards cannot be dragged until the padlock under the zoom buttons is opened, so a stray click does not rearrange the map. The last button saves the current map as a PNG picture.
Workloads managed by non-native controllers are included: Advanced DaemonSets of OpenKruise, database operator clusters, static pods, standalone Jobs. They are named the way Hubble names workloads, so their traffic attaches to the same cards.
## Problems and alerts
A card with a problem carries a badge: yellow `!` for a warning, red `!` for an error. Namespace boxes and cards, node boxes and the tree take the colour of the worst problem inside. Sources:
- **Object state**: containers in `CrashLoopBackOff`, `ImagePullBackOff` and similar, recent restarts and OOM kills, pods pending or unschedulable, workloads with no or not all replicas ready for more than 2 minutes, a stuck rollout, a CronJob whose last run failed, a Service with no ready pod, an Ingress routing to a Service that does not exist, a node that is not ready or is under memory, disk or PID pressure.
- **Warning events** of the last 30 minutes, folded per object and reason. Scheduling, volume and back-off failures badge the card at once; any other reason needs five repeats and is listed without a badge before that, so a single failed probe during a restart does not colour the map.
- **Prometheus alerts** that Deckhouse mirrors into `ClusterAlert` objects. An alert is attached by its labels (`deployment`, `statefulset`, `daemonset`, `pod`, `service`, `ingress`, `node`, `namespace`); one without an object or namespace goes to the cluster list. `severity_level` 1–3 is an error, 4–6 a warning, 7–9 information.
Information-level entries (a cordoned node, a single ordinary warning) are listed and never badge a card. Problems are recomputed on every map request and the open page refreshes them every minute.
## Actions
With `actions.enabled` (the default), the details panel offers:
| Object | Actions |
|---|---|
| Deployment, StatefulSet | restart (as `kubectl rollout restart`), scale to 0–100 replicas |
| DaemonSet | restart |
| CronJob | run now (as `kubectl create job --from=cronjob/…`), suspend, resume |
| Pod (in the Load table) | delete, so its controller starts a new one |
| Node (click the node box) | cordon, uncordon |
Every action asks for confirmation and runs **as the viewer**: the DexAuthenticator passes the user's own token to the module, the module sends the request to the API server with that token, and the API server checks the user's RBAC. A button is shown only when a `SelfSubjectAccessReview` says the user may do it. The module's service account never gets write permissions, and the API server's audit log records the user; the module also logs each action with the user's name.
Write requests from another site are refused: the module checks `Sec-Fetch-Site`, `Origin` and the JSON content type.
## How traffic is collected
Every Cilium agent keeps only a ring buffer of flows (4095 by default); at a few hundred flows per second this is about ten seconds of history. A one-off query "for the last 15 minutes" would silently return the last few seconds. The module therefore keeps a follow stream from Hubble Relay and aggregates it into per-minute buckets for the configured retention.
@@ -26,6 +55,8 @@ Counts are **distinct connections** (source and destination address and port), n
Kubelet probes and other traffic originating from node hosts, node-to-node traffic, Cilium health checks and DNS are filtered at the agents and never reach the module. On a typical cluster this is about three quarters of all flows and none of it maps to a workload. Set `traffic.collectInfraTraffic` to collect it anyway.
Pod-to-pod traffic between nodes is traced twice, as it leaves the sender's node (`to-overlay`) and as it reaches the receiving pod (`to-endpoint`). The first copy is also filtered at the agents when the receiver is a pod; this removes about a fifth of the remaining flows without changing any count.
The collector runs in one of three modes, see `traffic.mode`:
| Mode | Cost | Traffic windows |
@@ -44,9 +75,9 @@ History is kept in memory: after a pod restart the windows fill again. The statu
## Security
The web interface reads the cluster through the module's own service account (`d8:cluster-map` ClusterRole): `get`, `list`, `watch` on namespaces, pods, services, nodes, deployments, statefulsets, daemonsets, cronjobs and ingresses, and `get` on `pods/log`. It never reads Secrets or ConfigMaps and has no write verbs.
The web interface reads the cluster through the module's own service account (`d8:cluster-map` ClusterRole): `get`, `list`, `watch` on namespaces, pods, services, nodes, events, deployments, statefulsets, daemonsets, cronjobs, ingresses and Deckhouse `clusteralerts`, `get` and `list` on `metrics.k8s.io` pods and nodes, and `get` on `pods/log`. It never reads Secrets or ConfigMaps and has no write verbs. Changes go through [actions](#actions), which use the viewer's own identity.
This means **anyone admitted to the web interface sees every namespace and can read container logs**, whatever their own RBAC permissions are. Restrict access with `auth.allowedUserGroups` (and optionally `auth.allowedUserEmails` and `auth.whitelistSourceRanges`).
This means **anyone admitted to the web interface sees every namespace and can read container logs**, whatever their own RBAC permissions are; what they can change is limited by their own RBAC. Restrict access with `auth.allowedUserGroups` (and optionally `auth.allowedUserEmails` and `auth.whitelistSourceRanges`).
The frontend is served with a strict Content Security Policy: only its own scripts, styles and API, no inline code, no framing.
@@ -62,5 +93,6 @@ The pod exposes Prometheus metrics on port `9090` (`cluster_map_*`: Hubble strea
## Limitations
- One replica: traffic history lives in the process. A second replica would keep its own history and double the load on hubble-relay.
- Access is all-or-nothing, as described in [Security](#security). Showing each user only what their RBAC allows is planned.
- Reading is all-or-nothing, as described in [Security](#security). Showing each user only what their RBAC allows to read is planned; actions already follow the user's RBAC.
- Alerts need the `prometheus` module, which creates `ClusterAlert` objects. Without it the map shows problems from object state and events only.
- Traffic is L3/L4. HTTP-level details (paths, status codes) need Cilium L7 visibility and are not shown yet.
+36 -4
View File
@@ -14,10 +14,39 @@ webIfaces:
- Сплошные стрелки — связи по конфигурации: backend Ingress и селектор Service.
- Пунктир с анимацией — реальные соединения из Hubble за выбранное окно (5 минут, 15 минут, час); красный, если Cilium часть из них отбросил. Пиры из других namespace — пунктирные карточки в своих рамках.
- Если на экране больше 30 направлений трафика, линии бледные, пока не наведёшь курсор на карточку или не выберешь её.
- **Детали** (справа). Обзор, Связи (по конфигурации и по трафику, с переходом), живой YAML и логи контейнеров.
- **Детали** (справа). Обзор (одна строка — работает или нет, проблемы объекта, его параметры, CPU и память относительно запросов и лимитов, его поды), Связи (по конфигурации и по трафику, с переходом), живой YAML, События, логи контейнеров и действия, которые разрешены пользователю.
- **Проблемы** (кнопка в верхней панели). Всё, что сломано прямо сейчас, сначала самое серьёзное, с фильтром по приложениям и системным namespace; клик открывает объект.
Карточки нельзя перетащить, пока не открыт замок под кнопками масштаба, — случайный клик не перестроит карту. Последняя кнопка сохраняет текущую карту картинкой PNG.
Workload'ы под нестандартными контроллерами тоже на карте: Advanced DaemonSet из OpenKruise, кластеры операторов баз данных, статические поды, одиночные Job. Они названы так же, как их называет Hubble, поэтому трафик привязывается к тем же карточкам.
## Проблемы и алерты
Карточка с проблемой несёт значок: жёлтый `!` — предупреждение, красный `!` — ошибка. Рамки и карточки namespace, рамки нод и дерево окрашиваются по самой серьёзной проблеме внутри. Источники:
- **Состояние объектов**: контейнеры в `CrashLoopBackOff`, `ImagePullBackOff` и подобном, недавние перезапуски и убийства за нехватку памяти, поды в ожидании или без места для запуска, workload'ы, у которых больше 2 минут не готовы все или часть реплик, застрявшая выкатка, CronJob с неудачным последним запуском, Service без готовых подов, Ingress на несуществующий Service, нода не готова или ей не хватает памяти, диска или PID.
- **Warning-события** за последние 30 минут, сгруппированные по объекту и причине. Сбои планирования, томов и back-off дают значок сразу; любой другой причине нужно пять повторов, до этого она в списке без значка — одна проваленная проба во время рестарта не красит карту.
- **Алерты Prometheus**, которые Deckhouse зеркалирует в объекты `ClusterAlert`. Алерт привязывается по меткам (`deployment`, `statefulset`, `daemonset`, `pod`, `service`, `ingress`, `node`, `namespace`); алерт без объекта и namespace попадает в список кластера. `severity_level` 1–3 — ошибка, 4–6 — предупреждение, 7–9 — информация.
Записи уровня «для сведения» (нода закрыта для новых подов, одиночное обычное предупреждение) есть в списке, но значка не дают. Проблемы пересчитываются при каждом запросе карты, открытая страница обновляет их раз в минуту.
## Действия
При `actions.enabled` (по умолчанию включено) в панели деталей есть:
| Объект | Действия |
|---|---|
| Deployment, StatefulSet | перезапуск (как `kubectl rollout restart`), масштабирование на 0–100 реплик |
| DaemonSet | перезапуск |
| CronJob | запустить сейчас (как `kubectl create job --from=cronjob/…`), приостановить, возобновить |
| Под (в таблице «Нагрузка») | удалить, чтобы контроллер запустил новый |
| Нода (клик по рамке ноды) | закрыть для новых подов (cordon) и открыть обратно |
Каждое действие требует подтверждения и выполняется **от имени пользователя**: DexAuthenticator передаёт модулю собственный токен пользователя, модуль отправляет запрос в API-сервер с этим токеном, и API-сервер проверяет RBAC пользователя. Кнопка показывается, только если `SelfSubjectAccessReview` подтверждает право. Сервисный аккаунт модуля не получает прав на запись, в аудит-логе API-сервера записан пользователь; модуль тоже пишет каждое действие в лог с именем пользователя.
Запросы на запись с других сайтов отклоняются: модуль проверяет `Sec-Fetch-Site`, `Origin` и тип содержимого JSON.
## Как собирается трафик
Каждый агент Cilium хранит только кольцевой буфер потоков (по умолчанию 4095); при нескольких сотнях потоков в секунду это около десяти секунд истории. Разовый запрос «за последние 15 минут» молча вернул бы последние секунды. Поэтому модуль держит постоянный поток из Hubble Relay и раскладывает его по минутным корзинам на заданную глубину.
@@ -26,6 +55,8 @@ Workload'ы под нестандартными контроллерами то
Пробы kubelet и прочий трафик с хостов нод, трафик между нодами, проверки Cilium health и DNS отсекаются на агентах и до модуля не доходят. На обычном кластере это около трёх четвертей всех потоков, и ни один из них не привязан к workload'у. Чтобы всё же собирать их, включите `traffic.collectInfraTraffic`.
Трафик между подами на разных нодах трассируется дважды: при выходе с ноды отправителя (`to-overlay`) и при доставке в под получателя (`to-endpoint`). Первая копия тоже отсекается на агентах, если получатель — под; это убирает около пятой части оставшихся потоков, ни одно число при этом не меняется.
Режимы сбора — параметр `traffic.mode`:
| Режим | Цена | Окна трафика |
@@ -44,9 +75,9 @@ Workload'ы под нестандартными контроллерами то
## Безопасность
Веб-интерфейс читает кластер через собственную учётку модуля (ClusterRole `d8:cluster-map`): `get`, `list`, `watch` на namespaces, pods, services, nodes, deployments, statefulsets, daemonsets, cronjobs и ingresses и `get` на `pods/log`. Secret и ConfigMap он не читает, прав на запись нет.
Веб-интерфейс читает кластер через собственную учётку модуля (ClusterRole `d8:cluster-map`): `get`, `list`, `watch` на namespaces, pods, services, nodes, events, deployments, statefulsets, daemonsets, cronjobs, ingresses и `clusteralerts` Deckhouse, `get` и `list` на pods и nodes из `metrics.k8s.io` и `get` на `pods/log`. Secret и ConfigMap он не читает, прав на запись нет. Изменения идут через [действия](#действия), которые выполняются от имени пользователя.
Отсюда следует: **любой, кого пустили в веб-интерфейс, видит все namespace и может читать логи контейнеров** — независимо от собственных прав RBAC. Ограничивайте доступ через `auth.allowedUserGroups` (а также `auth.allowedUserEmails` и `auth.whitelistSourceRanges`).
Отсюда следует: **любой, кого пустили в веб-интерфейс, видит все namespace и может читать логи контейнеров** — независимо от собственных прав RBAC; изменить он может только то, что разрешает его RBAC. Ограничивайте доступ через `auth.allowedUserGroups` (а также `auth.allowedUserEmails` и `auth.whitelistSourceRanges`).
Фронтенд отдаётся со строгой Content Security Policy: только собственные скрипты, стили и API, без inline-кода, без встраивания во фреймы.
@@ -62,5 +93,6 @@ Workload'ы под нестандартными контроллерами то
## Ограничения
- Одна реплика: история трафика живёт в процессе. Вторая реплика держала бы свою историю и удвоила бы нагрузку на hubble-relay.
- Доступ по принципу «всё или ничего», см. раздел [Безопасность](#безопасность). Показ каждому пользователю только того, что разрешает его RBAC, — в планах.
- Чтение по принципу «всё или ничего», см. раздел [Безопасность](#безопасность). Показ каждому пользователю только того, что его RBAC разрешает читать, — в планах; действия уже следуют RBAC пользователя.
- Для алертов нужен модуль `prometheus`, он создаёт объекты `ClusterAlert`. Без него карта показывает проблемы только по состоянию объектов и событиям.
- Трафик на уровне L3/L4. Подробности HTTP (пути, коды ответа) требуют L7-видимости Cilium и пока не показываются.