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
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
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
- **Phase 2 (v1.1.0)**: Advanced features, enhanced workloads, and real-time updates
**Current version: v1.1.0**
## Features
---
### Phase 1: Basic Management
## Page Layout
- **Cluster Management**: Add, remove, list clusters with kubeconfig support
- **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
The Kubernetes page uses a Lens-style shell layout:
### 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
- **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
**Keyboard shortcut**: `Ctrl+K` opens the Command Palette for quick navigation.
## Architecture
---
### Frontend
## Resource Types (26 total)
- **State Management**: Zustand `kubernetesStore` for clusters, namespaces, resources, terminals, search, bulk selection
- **Components**: 26 resource list components, 8 detail views, 8 advanced components, 6 UX components
- **Event System**: Simple event bus for frontend event handling
### Workloads (7)
| Resource | Component | Actions |
|----------|-----------|---------|
| 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`
- **Client**: Kubernetes client with kubeconfig support
- **Port Forwarding**: Complete port forward runtime with kubeconfig injection
- **Watchers**: Resource watchers with channel-based communication (placeholder implementation)
### Config & Storage (8)
| Resource | Component | Actions |
|----------|-----------|---------|
| 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)
- Pod
- Deployment
- Service
- StatefulSet
- DaemonSet
- ReplicaSet
- Job
- CronJob
- Ingress
- HPA
### Cluster (4)
| Resource | Component | Notes |
|----------|-----------|-------|
| Overview | `ClusterOverview` | Live node/pod/deployment counts |
| Nodes | `NodeList` | Cordon, uncordon, drain |
| Events | `EventList` | Filterable by namespace |
| Port Forwarding | `PortForwardList` + `PortForwardForm` | Start/stop/delete tunnels |
### Infrastructure (5)
- Node
- Namespace
- PVC
- PV
- ServiceAccount
---
### Configuration (2)
- ConfigMap
- Secret
## Advanced Features
### RBAC (4)
- Role
- ClusterRole
- RoleBinding
- ClusterRoleBinding
### Terminal (`Terminal.tsx`)
- Full xterm.js implementation with multi-tab session management
- Shell selection: `sh`, `bash`, `zsh`
- Connects to pods via `exec_pod` IPC command
- `xterm-addon-fit` for automatic resize
- `xterm-addon-web-links` for clickable URLs in output
- Sessions identified by `pod/container/namespace`
### Events (1)
- Event
### YAML Editor (`YamlEditor.tsx`)
- 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
- `list_clusters()` - List all clusters
- `add_cluster()` - Add cluster with kubeconfig
- `remove_cluster()` - Remove cluster
- `set_active_cluster()` - Set active cluster
### Command Palette (`CommandPalette.tsx`)
- Triggered with `Ctrl+K` from anywhere in the Kubernetes page
- 12 navigation commands covering all major resource types
- Keyboard navigation: ↑/↓ arrows, Enter to execute, Escape to close
- Filter commands by typing
### Port Forwarding
- `list_port_forwards()` - List active port forwards
- `start_port_forward()` - Start port forward
- `stop_port_forward()` - Stop port forward
- `delete_port_forward()` - Delete port forward
- `shutdown_port_forwards()` - Shutdown all port forwards
### RBAC Management (`RbacViewer.tsx` / `RbacEditor.tsx`)
- Viewer: live data from `listRolesCmd`, `listClusterrolesCmd`, `listRolebindingsCmd`, `listClusterrolebindingsCmd`
- Editor: YAML editor with template generation for Roles, ClusterRoles, RoleBindings, ClusterRoleBindings
- Create via `createResourceCmd`, delete via `deleteResourceCmd`
### Resource Discovery
- `list_pods()` - List pods
- `list_services()` - List services
- `list_deployments()` - List deployments
- `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
### Cluster Overview (`ClusterOverview.tsx`)
- Real-time counts: nodes (ready/total), pods (running/total), deployments, namespaces
- Node table with status, roles, version, age
- All data loaded from `listNodesCmd`, `listPodsCmd`, `listDeploymentsCmd`, `listNamespacesCmd`
### 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
- `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
## Backend Architecture
## 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
interface KubernetesState {
clusters: Cluster[];
activeClusterId: string | null;
namespaces: Namespace[];
activeNamespace: string | null;
resources: Record<string, Resource[]>;
resourceLoading: Record<string, boolean>;
terminals: TerminalSession[];
searchQuery: string;
searchResults: Resource[];
bulkSelection: Set<string>;
```rust
pub struct AppState {
pub clusters: Arc<TokioMutex<HashMap<String, ClusterClient>>>,
pub port_forwards: Arc<TokioMutex<HashMap<String, PortForwardSession>>>,
pub watchers: Arc<Mutex<HashMap<String, WatcherHandle>>>,
// ...
}
```
## 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
// Subscribe to events
const unsubscribe = eventBus.on('k8s:resource:updated', (data) => {
console.log('Resource updated:', data);
});
- **Input validation**: `validate_resource_name()` enforces Kubernetes DNS subdomain rules and prevents command injection
- **Temp file cleanup**: `TempFileCleanup` guard auto-deletes kubeconfig temp files on scope exit
- **No credential logging**: kubeconfig content never appears in audit logs
- **Three-tier command safety**: shell commands additionally classified by `classifier.rs` (Tier 1 auto, Tier 2 approval, Tier 3 deny)
// Unsubscribe
unsubscribe();
### Commands (48 total)
// Emit events
eventBus.emit('k8s:resource:updated', {
clusterId: 'cluster-1',
namespace: 'default',
resourceType: 'pod',
resource: podData
});
```
#### Cluster Management (5)
- `add_cluster`, `remove_cluster`, `list_clusters`, `test_cluster_connection`, `discover_pods`
## 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
- **Extension System**: Plugin architecture for custom features
- **Advanced Metrics**: Custom metrics and dashboards
- **Bulk Actions**: Batch operations on resources
- **Resource Creation**: Form-based resource creation
- **Health Monitoring**: Cluster and resource health status
#### Resource Discovery (26)
- `list_namespaces`, `list_pods`, `list_services`, `list_deployments`, `list_statefulsets`, `list_daemonsets`
- `list_replicasets`, `list_jobs`, `list_cronjobs`
- `list_configmaps`, `list_secrets`, `list_nodes`, `list_events`
- `list_ingresses`, `list_persistentvolumeclaims`, `list_persistentvolumes`
- `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
### Frontend
- `xterm` - Terminal rendering
- `xterm-addon-fit` - Terminal resizing
- `xterm-addon-web-links` - Web link detection
- `@monaco-editor/react` - YAML editor
- `react-chartjs-2` - Metrics charts
- `chart.js` - Chart rendering
### Frontend (npm)
| Package | Version | Purpose |
|---------|---------|---------|
| `xterm` | 5.x | Terminal emulator |
| `xterm-addon-fit` | 0.8.x | Auto-resize |
| `xterm-addon-web-links` | 0.9.x | Clickable URLs |
| `@monaco-editor/react` | 4.x | YAML editor |
| `recharts` | 2.x | Metrics charts |
### Backend
- `k8s-openapi` with `watch` feature - Kubernetes API watchers
- `tokio-stream` - Async streams for watchers
### Backend (Cargo)
No external Kubernetes client libraries. Uses `tokio::process::Command` + bundled kubectl binary.
## Testing
---
### Frontend Tests
- 114 tests passing
- Unit tests for stores, components, and utilities
## Known Limitations
### Backend Tests
- 331 tests passing
- Tests for kube commands, port forwarding, and resource management
## Documentation
- [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)
1. **Metrics**: CPU/memory charts show placeholder data — requires metrics-server integration (future work)
2. **Real-time updates**: Watcher backend exists but frontend integration is polling-based; true watch streams pending
3. **Helm**: Not yet integrated (planned for v1.2.0)
4. **StorageClasses**: Cluster-scoped, no namespace filter
5. **Node metrics**: Cordon/drain requires cluster admin privileges