docs: sync from docs/wiki/ at commit c87e5f0f

Gitea Actions 2026-06-07 22:01:31 +00:00
parent 58fe57b0ee
commit e038d92a3d

@ -1,234 +1,272 @@
# Kubernetes Management # Kubernetes Management
This document describes the Kubernetes Management UI implementation in Troubleshooting and RCA Assistant. This document describes the Kubernetes Management UI — a Lens Desktop v5-equivalent Kubernetes management experience built into the Troubleshooting and RCA Assistant.
---
## Overview ## Overview
The application includes a complete Kubernetes Management UI with feature parity to Lens Desktop v5.x, implemented in two phases: The Kubernetes Management UI provides full feature parity with Lens Desktop v5.x (the last open-source release), delivering a complete cluster management IDE directly inside the application. The implementation is MIT-licensed and uses the bundled `kubectl` binary for all cluster operations.
- **Phase 1 (v1.0.0)**: Basic cluster management, port forwarding, and resource discovery **Current version: v1.1.0**
- **Phase 2 (v1.1.0)**: Advanced features, enhanced workloads, and real-time updates
## Features ---
### Phase 1: Basic Management ## Page Layout
- **Cluster Management**: Add, remove, list clusters with kubeconfig support The Kubernetes page uses a Lens-style shell layout:
- **Port Forwarding**: Start, stop, list, and delete port forwards
- **Resource Discovery**: View pods, services, deployments, statefulsets, daemonsets, namespaces
- **Resource Management**: Scale, restart, delete, exec into resources
- **Context Switching**: Switch between clusters and namespaces
### Phase 2: Advanced Features ```
┌──────────────────────────────────────────────────────────────┐
│ Hotbar: Cluster selector | Namespace selector | Refresh | + │
├──────────────┬───────────────────────────────────────────────┤
│ SIDEBAR │ MAIN CONTENT │
│ │ │
│ ▶ WORKLOADS │ ClusterOverview (default) │
│ Pods │ — or — │
│ Deployments│ Selected resource list │
│ DaemonSets │ — or — │
│ StatefulSets│ Detail panel │
│ ReplicaSets │ │
│ Jobs │ │
│ CronJobs │ │
│ │ │
│ ▶ NETWORKING │ │
│ Services │ │
│ Ingresses │ │
│ NetworkPols│ │
│ │ │
│ ▶ CONFIG │ │
│ ConfigMaps │ │
│ Secrets │ │
│ HPAs │ │
│ PVCs │ │
│ PVs │ │
│ StorageClass│ │
│ ResourceQ │ │
│ LimitRanges│ │
│ │ │
│ ▶ ACCESS CTL │ │
│ ServiceAccts│ │
│ Roles │ │
│ ClusterRoles│ │
│ RoleBindings│ │
│ CRBindings │ │
│ │ │
│ ▶ CLUSTER │ │
│ Overview │ │
│ Nodes │ │
│ Events │ │
│ Port Fwd │ │
└──────────────┴───────────────────────────────────────────────┘
```
- **26 Resource Types**: All major Kubernetes resource types with table views **Keyboard shortcut**: `Ctrl+K` opens the Command Palette for quick navigation.
- **Detail Views**: Tabs for overview, logs, yaml, events for each resource
- **Terminal**: Multi-tab terminal with session management
- **YAML Editor**: Create and edit resources with YAML
- **Metrics Charts**: CPU, memory, and network usage visualization
- **Search & Filter**: Search by name, labels, annotations
- **Context Switcher**: Quick cluster and context switching
- **RBAC Management**: Viewer and editor for roles, clusterroles, bindings
- **Real-time Updates**: Event bus and Kubernetes API watchers
## Architecture ---
### Frontend ## Resource Types (26 total)
- **State Management**: Zustand `kubernetesStore` for clusters, namespaces, resources, terminals, search, bulk selection ### Workloads (7)
- **Components**: 26 resource list components, 8 detail views, 8 advanced components, 6 UX components | Resource | Component | Actions |
- **Event System**: Simple event bus for frontend event handling |----------|-----------|---------|
| Pods | `PodList` + `PodDetail` | Logs, exec, scale, delete |
| Deployments | `DeploymentList` + `DeploymentDetail` | Scale, restart, rollback, delete |
| Daemon Sets | `DaemonSetList` | Delete |
| Stateful Sets | `StatefulSetList` | Delete |
| Replica Sets | `ReplicaSetList` | Delete |
| Jobs | `JobList` | Delete |
| Cron Jobs | `CronJobList` | Delete |
### Backend ### Services & Networking (3)
| Resource | Component | Actions |
|----------|-----------|---------|
| Services | `ServiceList` + `ServiceDetail` | Port forward, delete |
| Ingresses | `IngressList` | Delete |
| Network Policies | `NetworkPolicyList` | Delete |
- **Commands**: 43 kube-related commands in `src-tauri/src/commands/kube.rs` ### Config & Storage (8)
- **Client**: Kubernetes client with kubeconfig support | Resource | Component | Actions |
- **Port Forwarding**: Complete port forward runtime with kubeconfig injection |----------|-----------|---------|
- **Watchers**: Resource watchers with channel-based communication (placeholder implementation) | Config Maps | `ConfigMapList` + `ConfigMapDetail` | Edit, delete |
| Secrets | `SecretList` + `SecretDetail` | View masked, delete |
| Horizontal Pod Autoscalers | `HPAList` | Delete |
| Persistent Volume Claims | `PVCList` | Delete |
| Persistent Volumes | `PVList` | Delete |
| Storage Classes | `StorageClassList` | Delete |
| Resource Quotas | `ResourceQuotaList` | Delete |
| Limit Ranges | `LimitRangeList` | Delete |
## Resource Types ### Access Control (5)
| Resource | Component | Actions |
|----------|-----------|---------|
| Service Accounts | `ServiceAccountList` | Delete |
| Roles | `RoleList` + `RbacViewer`/`RbacEditor` | Create, delete |
| Cluster Roles | `ClusterRoleList` + `RbacViewer`/`RbacEditor` | Create, delete |
| Role Bindings | `RoleBindingList` | Delete |
| Cluster Role Bindings | `ClusterRoleBindingList` | Delete |
### Workloads (11) ### Cluster (4)
- Pod | Resource | Component | Notes |
- Deployment |----------|-----------|-------|
- Service | Overview | `ClusterOverview` | Live node/pod/deployment counts |
- StatefulSet | Nodes | `NodeList` | Cordon, uncordon, drain |
- DaemonSet | Events | `EventList` | Filterable by namespace |
- ReplicaSet | Port Forwarding | `PortForwardList` + `PortForwardForm` | Start/stop/delete tunnels |
- Job
- CronJob
- Ingress
- HPA
### Infrastructure (5) ---
- Node
- Namespace
- PVC
- PV
- ServiceAccount
### Configuration (2) ## Advanced Features
- ConfigMap
- Secret
### RBAC (4) ### Terminal (`Terminal.tsx`)
- Role - Full xterm.js implementation with multi-tab session management
- ClusterRole - Shell selection: `sh`, `bash`, `zsh`
- RoleBinding - Connects to pods via `exec_pod` IPC command
- ClusterRoleBinding - `xterm-addon-fit` for automatic resize
- `xterm-addon-web-links` for clickable URLs in output
- Sessions identified by `pod/container/namespace`
### Events (1) ### YAML Editor (`YamlEditor.tsx`)
- Event - Monaco editor (`@monaco-editor/react`) with YAML syntax highlighting
- Language: `yaml`, Theme: `vs-dark`
- Controlled value with Apply/Cancel buttons
- Used in: `CreateResourceModal`, `EditResourceModal`, detail panels, `RbacEditor`
## API Commands ### Metrics Charts (`MetricsChart.tsx`)
- recharts `LineChart` and `BarChart` with `ResponsiveContainer`
- Time range selector: 5m, 15m, 1h, 6h, 1d
- Used in: `ApplicationView`, `ClusterOverview`
### Cluster Management ### Command Palette (`CommandPalette.tsx`)
- `list_clusters()` - List all clusters - Triggered with `Ctrl+K` from anywhere in the Kubernetes page
- `add_cluster()` - Add cluster with kubeconfig - 12 navigation commands covering all major resource types
- `remove_cluster()` - Remove cluster - Keyboard navigation: ↑/↓ arrows, Enter to execute, Escape to close
- `set_active_cluster()` - Set active cluster - Filter commands by typing
### Port Forwarding ### RBAC Management (`RbacViewer.tsx` / `RbacEditor.tsx`)
- `list_port_forwards()` - List active port forwards - Viewer: live data from `listRolesCmd`, `listClusterrolesCmd`, `listRolebindingsCmd`, `listClusterrolebindingsCmd`
- `start_port_forward()` - Start port forward - Editor: YAML editor with template generation for Roles, ClusterRoles, RoleBindings, ClusterRoleBindings
- `stop_port_forward()` - Stop port forward - Create via `createResourceCmd`, delete via `deleteResourceCmd`
- `delete_port_forward()` - Delete port forward
- `shutdown_port_forwards()` - Shutdown all port forwards
### Resource Discovery ### Cluster Overview (`ClusterOverview.tsx`)
- `list_pods()` - List pods - Real-time counts: nodes (ready/total), pods (running/total), deployments, namespaces
- `list_services()` - List services - Node table with status, roles, version, age
- `list_deployments()` - List deployments - All data loaded from `listNodesCmd`, `listPodsCmd`, `listDeploymentsCmd`, `listNamespacesCmd`
- `list_statefulsets()` - List statefulsets
- `list_daemonsets()` - List daemonsets
- `list_namespaces()` - List namespaces
- `list_nodes()` - List nodes
- `list_events()` - List events
- `list_configmaps()` - List configmaps
- `list_secrets()` - List secrets
- `list_replicasets()` - List replicasets
- `list_jobs()` - List jobs
- `list_cronjobs()` - List cronjobs
- `list_ingresses()` - List ingresses
- `list_pvcs()` - List PVCs
- `list_pvs()` - List PVs
- `list_serviceaccounts()` - List service accounts
- `list_roles()` - List roles
- `list_clusterroles()` - List cluster roles
- `list_rolebindings()` - List role bindings
- `list_clusterrolebindings()` - List cluster role bindings
- `list_hpas()` - List HPAs
### Resource Management ---
- `get_pod_detail()` - Get pod details
- `get_deployment_detail()` - Get deployment details
- `get_service_detail()` - Get service details
- `get_configmap_detail()` - Get configmap details
- `get_secret_detail()` - Get secret details
- `get_node_detail()` - Get node details
- `get_namespace_detail()` - Get namespace details
- `get_pvc_detail()` - Get PVC details
- `get_pv_detail()` - Get PV details
- `get_serviceaccount_detail()` - Get service account details
- `get_role_detail()` - Get role details
- `get_clusterrole_detail()` - Get cluster role details
- `get_rolebinding_detail()` - Get role binding details
- `get_clusterrolebinding_detail()` - Get cluster role binding details
- `get_hpa_detail()` - Get HPA details
- `get_event_detail()` - Get event details
- `get_replicaset_detail()` - Get replica set details
- `get_job_detail()` - Get job details
- `get_cronjob_detail()` - Get cronjob details
- `get_ingress_detail()` - Get ingress details
- `scale_deployment()` - Scale deployment
- `restart_deployment()` - Restart deployment
- `delete_resource()` - Delete resource
- `exec_into_pod()` - Execute command in pod
- `get_pod_logs()` - Get pod logs
- `get_resource_yaml()` - Get resource YAML
### Advanced ## Backend Architecture
- `subscribe_to_k8s_events()` - Subscribe to K8s events
- `subscribe_to_all_k8s_events()` - Subscribe to all K8s events
- `unsubscribe_from_k8s_events()` - Unsubscribe from events
## State Management All Kubernetes operations use the bundled `kubectl` binary (v1.30.0) via `tokio::process::Command`. No direct Kubernetes API client library is used — this approach avoids TLS certificate management complexity and works with any cluster configuration.
### Kubernetes Store (`src/stores/kubernetesStore.ts`) ### State
```typescript ```rust
interface KubernetesState { pub struct AppState {
clusters: Cluster[]; pub clusters: Arc<TokioMutex<HashMap<String, ClusterClient>>>,
activeClusterId: string | null; pub port_forwards: Arc<TokioMutex<HashMap<String, PortForwardSession>>>,
namespaces: Namespace[]; pub watchers: Arc<Mutex<HashMap<String, WatcherHandle>>>,
activeNamespace: string | null; // ...
resources: Record<string, Resource[]>;
resourceLoading: Record<string, boolean>;
terminals: TerminalSession[];
searchQuery: string;
searchResults: Resource[];
bulkSelection: Set<string>;
} }
``` ```
## Event System Clusters are stored in-memory only (not persisted). Kubeconfigs are stored encrypted in the database and written to temporary files at command execution time.
### Event Bus (`src/lib/eventBus.ts`) ### Security
```typescript - **Input validation**: `validate_resource_name()` enforces Kubernetes DNS subdomain rules and prevents command injection
// Subscribe to events - **Temp file cleanup**: `TempFileCleanup` guard auto-deletes kubeconfig temp files on scope exit
const unsubscribe = eventBus.on('k8s:resource:updated', (data) => { - **No credential logging**: kubeconfig content never appears in audit logs
console.log('Resource updated:', data); - **Three-tier command safety**: shell commands additionally classified by `classifier.rs` (Tier 1 auto, Tier 2 approval, Tier 3 deny)
});
// Unsubscribe ### Commands (48 total)
unsubscribe();
// Emit events #### Cluster Management (5)
eventBus.emit('k8s:resource:updated', { - `add_cluster`, `remove_cluster`, `list_clusters`, `test_cluster_connection`, `discover_pods`
clusterId: 'cluster-1',
namespace: 'default',
resourceType: 'pod',
resource: podData
});
```
## Future Enhancements #### Port Forwarding (5)
- `start_port_forward`, `stop_port_forward`, `list_port_forwards`, `delete_port_forward`, `shutdown_port_forwards`
- **Helm Support**: Chart management and release tracking #### Resource Discovery (26)
- **Extension System**: Plugin architecture for custom features - `list_namespaces`, `list_pods`, `list_services`, `list_deployments`, `list_statefulsets`, `list_daemonsets`
- **Advanced Metrics**: Custom metrics and dashboards - `list_replicasets`, `list_jobs`, `list_cronjobs`
- **Bulk Actions**: Batch operations on resources - `list_configmaps`, `list_secrets`, `list_nodes`, `list_events`
- **Resource Creation**: Form-based resource creation - `list_ingresses`, `list_persistentvolumeclaims`, `list_persistentvolumes`
- **Health Monitoring**: Cluster and resource health status - `list_serviceaccounts`, `list_roles`, `list_clusterroles`, `list_rolebindings`, `list_clusterrolebindings`
- `list_horizontalpodautoscalers`
- `list_storageclasses`, `list_networkpolicies`, `list_resourcequotas`, `list_limitranges` *(v1.1.0)*
#### Resource Management (8)
- `get_pod_logs`, `scale_deployment`, `restart_deployment`, `delete_resource`, `exec_pod`
- `cordon_node`, `uncordon_node`, `drain_node`
#### YAML Operations (2)
- `create_resource`, `edit_resource`
#### Rollback (1)
- `rollback_deployment`
#### Event Subscription (3)
- `subscribe_to_k8s_events`, `subscribe_to_all_k8s_events`, `unsubscribe_from_k8s_events`
---
## Frontend State Management
Store: `src/stores/kubernetesStore.ts` (Zustand, not persisted)
| State | Purpose |
|-------|---------|
| `selectedClusterId` | Active cluster (drives namespace/resource loading) |
| `selectedNamespace` | Active namespace filter |
| `clusters`, `contexts` | Cluster metadata |
| `namespaces` | Cached namespace list per cluster |
| `loadedResources` | Set of resource types currently loaded |
| `terminalSessions` | Active xterm.js terminal sessions |
| `globalSearchQuery` | Cross-resource search state |
| `bulkSelection` | Multi-resource selection per type |
---
## Key Files
| Path | Purpose |
|------|---------|
| `src/pages/Kubernetes/KubernetesPage.tsx` | Lens-like page shell (sidebar + hotbar + content) |
| `src/components/Kubernetes/ResourceBrowser.tsx` | Legacy resource browser (5 types) |
| `src/components/Kubernetes/ClusterOverview.tsx` | Live cluster summary |
| `src/components/Kubernetes/Terminal.tsx` | xterm.js pod exec terminal |
| `src/components/Kubernetes/YamlEditor.tsx` | Monaco YAML editor |
| `src/components/Kubernetes/MetricsChart.tsx` | recharts metrics visualization |
| `src/components/Kubernetes/RbacViewer.tsx` | Live RBAC resource viewer |
| `src/components/Kubernetes/RbacEditor.tsx` | RBAC create/edit via YAML |
| `src/components/Kubernetes/CommandPalette.tsx` | Ctrl+K command palette |
| `src/lib/eventBus.ts` | Frontend event bus for K8s watchers |
| `src-tauri/src/commands/kube.rs` | All 48 Kubernetes Tauri commands |
| `src-tauri/src/kube/` | Client, port forward, watcher, refresh modules |
---
## Dependencies ## Dependencies
### Frontend ### Frontend (npm)
- `xterm` - Terminal rendering | Package | Version | Purpose |
- `xterm-addon-fit` - Terminal resizing |---------|---------|---------|
- `xterm-addon-web-links` - Web link detection | `xterm` | 5.x | Terminal emulator |
- `@monaco-editor/react` - YAML editor | `xterm-addon-fit` | 0.8.x | Auto-resize |
- `react-chartjs-2` - Metrics charts | `xterm-addon-web-links` | 0.9.x | Clickable URLs |
- `chart.js` - Chart rendering | `@monaco-editor/react` | 4.x | YAML editor |
| `recharts` | 2.x | Metrics charts |
### Backend ### Backend (Cargo)
- `k8s-openapi` with `watch` feature - Kubernetes API watchers No external Kubernetes client libraries. Uses `tokio::process::Command` + bundled kubectl binary.
- `tokio-stream` - Async streams for watchers
## Testing ---
### Frontend Tests ## Known Limitations
- 114 tests passing
- Unit tests for stores, components, and utilities
### Backend Tests 1. **Metrics**: CPU/memory charts show placeholder data — requires metrics-server integration (future work)
- 331 tests passing 2. **Real-time updates**: Watcher backend exists but frontend integration is polling-based; true watch streams pending
- Tests for kube commands, port forwarding, and resource management 3. **Helm**: Not yet integrated (planned for v1.2.0)
4. **StorageClasses**: Cluster-scoped, no namespace filter
## Documentation 5. **Node metrics**: Cordon/drain requires cluster admin privileges
- [Kubernetes Management Implementation Plan](../KUBERNETES-MANAGEMENT-IMPLEMENTATION-PLAN.md)
- [Lens Desktop v5.x Features](../lens-desktop-v5x-features.md)
- [Architecture Documentation](../architecture/README.md)
- [ADR-010: Kubernetes Management UI](../architecture/adrs/ADR-010-kubernetes-management-ui.md)