diff --git a/ROADMAP.md b/ROADMAP.md index a9051c1..01d3949 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -144,9 +144,17 @@ Root problem: full object JSON kept for every entity. --- ## Phase 4 — Readonly parity vs k9s (HARD REQUIREMENT: all readonly k9s functions) -- [ ] **4.1 Dynamic resource discovery + CRDs** — biggest functional gap. Today 24 fixed - kinds (`ResourceKind::ORDERED`, model.rs:36). Add API discovery + arbitrary GVK browse so - any resource/CRD is listable/describable (readonly). +- [~] **4.1 Dynamic resource discovery + CRDs** — biggest functional gap. Hybrid design (curated 24 + + generic dynamic), `docs/design/phase-4.1-dynamic-resources.md`. Shipped incrementally: + - [x] **4.1a-1 provider layer** — `ResourceProvider::{discover,list_dynamic,get_dynamic}` via + `kube::discovery` + `Api` (cluster/mod.rs, kube_provider.rs); `DiscoveredResource` + /`DynamicRow` types; hidden `--discover[ --discover-resource X]` headless check; `scripts/scale/crds.sh` + adds a sample CRD. Verified against lab: 68 resources incl. CRD `widgets.demo.krust.io`, listed + + described 3 Widgets. 75 tests pass. + - [ ] **4.1a-2 UI** — `:api` discovery catalog overlay + interactive dynamic-browse overlay + (generic columns) + describe-on-select, wiring the `:` command fallback to the dynamic path. + - [ ] **4.1b dynamic watches + KindId/ResourceKey refactor** (fold 24 typed watches into the dynamic path). + - [ ] **4.1c navigation/UX** (discovered kinds in kind-cycle / resource picker, short names from discovery). - [ ] **4.2 Metrics integration** — `metrics.k8s.io` for real pod/node CPU+mem (top-style). Current numbers are from spec requests/limits, not usage. - [ ] **4.3 Resource-correlated events** — selecting a pod shows its events; today Events pane diff --git a/docs/design/phase-4.1-dynamic-resources.md b/docs/design/phase-4.1-dynamic-resources.md new file mode 100644 index 0000000..2825a30 --- /dev/null +++ b/docs/design/phase-4.1-dynamic-resources.md @@ -0,0 +1,95 @@ +# Design: Phase 4.1 — Dynamic resources / CRDs + +Status: **proposed** (awaiting sign-off). Related: ROADMAP.md Phase 4.1. + +## Problem + +krust supports a fixed set of 24 built-in kinds (`ResourceKind` enum, model.rs). Operators on real +clusters need to browse **any** resource — CRDs (the M3/Infor platform alone has many), plus core +kinds we don't enumerate (endpoints, leases, storageclasses, etc.). This is the biggest readonly +parity gap vs k9s. Today `:crd`, `:sc`, etc. report "recognized but not implemented". + +## Constraint that shapes the design + +The watch layer is **typed-generic**: `spawn_namespaced_watch::`, `::`, … — 24 +hard-coded dispatches (kube_provider.rs). Arbitrary kinds cannot be typed at compile time, so they +**must** be watched via `Api` + a runtime `ApiResource`. We already use exactly this +path for `get_object` (Phase 1.1) and proved `DynamicObject` watches parse fine (1.2 micro-bench: +~7.9µs/obj vs 5µs typed — acceptable). + +## Approach: hybrid (curated built-ins + generic dynamic) — like k9s + +Do **not** rip out `ResourceKind`. Keep the 24 curated kinds with their tailored columns/status +extraction (pod phase, deploy ready, node capacity, …). Add a **dynamic resource layer** that can +list/watch/describe **any** discovered GVK with generic columns. Known kinds render rich; everything +else renders generic (name / namespace / age / best-effort status) — exactly k9s's model. + +### New core type + +A resource is identified by a `ResourceRef` (runtime), superseding the enum *as the key* while the +enum remains an optional "curated profile": + +```rust +struct GvkKey { group: String, version: String, kind: String } // e.g. ("apps","v1","Deployment") +``` + +- `ResourceKey` changes `kind: ResourceKind` → a key that carries the GVK (plus a cheap interned id). + This is the invasive part (ResourceKey is in every delta/index/cache). Mitigation below. +- A `ResourceCatalog` (per context, from discovery) maps GVK ↔ `ApiResource` (plural, namespaced, + short names) and flags whether a curated profile exists. + +### Migration that limits blast radius + +`ResourceKey`/`StateStore`/projection are generic over "kind identity". To avoid editing ~290 sites +at once, introduce an interned `KindId` (u32) that both the enum and dynamic GVKs resolve to: + +- `KindId` is the hash-keyed identity used in `ResourceKey`, indexes, watch keys (cheap Copy, no + String churn in the hot path — important after we just made keys lean). +- A registry resolves `KindId → ResourceDescriptor { gvk, api_resource, curated: Option, namespaced, columns }`. +- Built-in kinds register deterministic `KindId`s at startup; discovered kinds register on demand. + +This keeps the store/projection/key hot paths Copy-cheap and confines GVK strings to the registry. + +## Incremental sub-phases (each shippable) + +- **4.1a — discovery + dynamic list/describe (read-only, command-driven).** Add `kube::discovery` + per context; a `:api`/`:` command lists any discovered resource via `Api` + (one-shot list, not yet watched) with generic columns; describe already works via `get_object`. + Lowest risk, immediately closes "can I even see my CRDs". No change to the enum/key yet — dynamic + results held in a parallel path. +- **4.1b — dynamic watches.** Replace the one-shot list with a `DynamicObject` watcher reusing + `run_watch_loop` (generalized) + the relist generation logic; introduce `KindId` and fold the 24 + typed watches into the dynamic path (keeping curated extraction by GVK match). This is the + ResourceKey refactor. +- **4.1c — navigation/UX.** Discovered kinds in the kind cycle / a resource picker (`:res`), short + names from discovery, namespaced/cluster scoping from discovery. + +We ship 4.1a first and reassess before the deeper 4.1b key refactor. + +## Touch list (4.1b, the deep one) +`model.rs` (KindId, ResourceKey), `cluster/kube_provider.rs` (discovery, dynamic watch, drop 24 +typed dispatches), `cluster/extract.rs` (extract by curated GVK match), `state/store.rs` (KindId +indexes), `view/projector.rs`, `ui/*` (kind nav, commands, columns). Curated column/status code +keyed by GVK instead of enum variant. + +## Risks +1. **ResourceKey churn** — it's in every delta/index. Mitigated by interned Copy `KindId` (no perf + regression vs today's enum, which is also Copy). +2. **Discovery cost/RBAC** — discovery is one call per context, cached; handle 403 gracefully + (show only what's discoverable). +3. **Watch load** — arbitrary kinds still go through `replace_watch_plan` (lazy, scoped) — no change + to the activation model; a CRD is only watched when viewed. +4. **Generic columns** — best-effort status for unknown kinds; acceptable and matches k9s. +5. **CRD scale** — clusters with hundreds of CRDs: discovery list is fine; we only watch what's open. + +## Validation +- 4.1a: against the lab, `:` a core kind not in the 24 (e.g. endpoints) and a CRD → lists + describes. +- 4.1b: bench shows no regression on the 24 built-ins (KindId Copy vs enum Copy); relist still works. +- Tests: discovery parsing, KindId registry, generic column projection, curated-vs-generic dispatch. + +## Open questions for sign-off +1. OK with the **hybrid** model (keep curated 24 + generic for the rest), not a full dynamic rewrite? +2. OK to **ship 4.1a first** (discovery + dynamic list/describe, command-driven) and reassess before + the deeper `KindId`/ResourceKey refactor in 4.1b? +3. `KindId` interning approach for the key (vs carrying GVK strings in ResourceKey) — agree it's worth + it to protect the hot path? diff --git a/scripts/scale/crds.sh b/scripts/scale/crds.sh new file mode 100755 index 0000000..a190642 --- /dev/null +++ b/scripts/scale/crds.sh @@ -0,0 +1,52 @@ +#!/usr/bin/env bash +# Install a sample CRD + a few custom resources on the kwok cluster, so the dynamic +# resource discovery path (Phase 4.1) has a real CRD to find and browse. +source "$(dirname "${BASH_SOURCE[0]}")/lib.sh" + +require kubectl + +kc apply -f - <<'EOF' +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + name: widgets.demo.krust.io +spec: + group: demo.krust.io + scope: Namespaced + names: + plural: widgets + singular: widget + kind: Widget + shortNames: [wdg] + versions: + - name: v1 + served: true + storage: true + schema: + openAPIV3Schema: + type: object + properties: + spec: + type: object + properties: + size: { type: string } + status: + type: object + properties: + phase: { type: string } +EOF + +echo "waiting for CRD to register ..." +kc wait --for=condition=Established crd/widgets.demo.krust.io --timeout=30s || true + +for i in 0 1 2; do + kc apply -f - <, } diff --git a/src/cluster/kube_provider.rs b/src/cluster/kube_provider.rs index 00aca45..e382cda 100644 --- a/src/cluster/kube_provider.rs +++ b/src/cluster/kube_provider.rs @@ -26,9 +26,10 @@ use k8s_openapi::{ }; use kube::{ Api, Client, Config, Resource, ResourceExt, - api::{DeleteParams, LogParams, PostParams}, + api::{DeleteParams, ListParams, LogParams, PostParams}, config::{KubeConfigOptions, Kubeconfig}, core::{ApiResource, DynamicObject, GroupVersionKind}, + discovery::{Discovery, Scope}, }; use kube_runtime::watcher::{self, Event}; use serde::Serialize; @@ -38,10 +39,13 @@ use tracing::{error, warn}; use crate::model::{ResourceEntity, ResourceKey, ResourceKind, StateDelta}; use super::{ - ActionError, ActionExecutor, ActionResult, PodLogEvent, PodLogRequest, PodLogStream, - ResourceProvider, WatchTarget, extract::extracted_for, + ActionError, ActionExecutor, ActionResult, DiscoveredResource, DynamicRow, PodLogEvent, + PodLogRequest, PodLogStream, ResourceProvider, WatchTarget, extract::extracted_for, }; +/// Bounded one-shot dynamic list size (Phase 4.1 read-only browse). +const DYNAMIC_LIST_LIMIT: u32 = 500; + #[derive(Debug, Clone)] pub struct KubeProviderOptions { pub kubeconfig: Option, @@ -336,6 +340,83 @@ impl ResourceProvider for KubeResourceProvider { Ok(serde_json::to_value(obj)?) } + + async fn discover(&self, context: &str) -> anyhow::Result> { + let client = self.client_for_context(context).await?; + let discovery = Discovery::new(client).run().await?; + let mut out = Vec::new(); + for group in discovery.groups() { + for (api_resource, caps) in group.recommended_resources() { + out.push(DiscoveredResource { + api_resource, + namespaced: matches!(caps.scope, Scope::Namespaced), + }); + } + } + out.sort_by(|a, b| a.full_name().cmp(&b.full_name())); + out.dedup_by(|a, b| a.full_name() == b.full_name()); + Ok(out) + } + + async fn list_dynamic( + &self, + context: &str, + resource: &DiscoveredResource, + namespace: Option<&str>, + ) -> anyhow::Result> { + let client = self.client_for_context(context).await?; + let ar = &resource.api_resource; + let api: Api = match (resource.namespaced, namespace) { + (true, Some(ns)) => Api::namespaced_with(client, ns, ar), + _ => Api::all_with(client, ar), + }; + let list = api + .list(&ListParams::default().limit(DYNAMIC_LIST_LIMIT)) + .await?; + let rows = list + .into_iter() + .map(|obj| DynamicRow { + namespace: obj.namespace(), + age: obj + .creation_timestamp() + .map(|ts| DateTime::::from(std::time::SystemTime::from(ts.0))), + status: dynamic_status(&obj), + name: obj.name_any(), + }) + .collect(); + Ok(rows) + } + + async fn get_dynamic( + &self, + context: &str, + resource: &DiscoveredResource, + namespace: Option<&str>, + name: &str, + ) -> anyhow::Result { + let client = self.client_for_context(context).await?; + let ar = &resource.api_resource; + let api: Api = match (resource.namespaced, namespace) { + (true, Some(ns)) => Api::namespaced_with(client, ns, ar), + (true, None) => Api::namespaced_with(client, "default", ar), + (false, _) => Api::all_with(client, ar), + }; + Ok(serde_json::to_value(api.get(name).await?)?) + } +} + +/// Best-effort status string for a dynamic object (no curated extractor for unknown kinds). +fn dynamic_status(obj: &DynamicObject) -> String { + obj.data + .pointer("/status/phase") + .and_then(serde_json::Value::as_str) + .or_else(|| { + obj.data + .pointer("/status/conditions/0/type") + .and_then(serde_json::Value::as_str) + }) + .unwrap_or("-") + .to_string() } fn select_warm_contexts( diff --git a/src/cluster/mod.rs b/src/cluster/mod.rs index 8448256..b00194e 100644 --- a/src/cluster/mod.rs +++ b/src/cluster/mod.rs @@ -2,12 +2,54 @@ mod extract; mod kube_provider; use async_trait::async_trait; +use chrono::{DateTime, Utc}; +use kube::core::ApiResource; use tokio::{sync::mpsc, task::JoinHandle}; use crate::model::{ResourceKey, ResourceKind}; pub use kube_provider::{KubeProviderOptions, KubeResourceProvider}; +/// An API resource discovered on a cluster (built-in or CRD), beyond krust's curated kinds. +/// Phase 4.1: enables read-only browse/describe of arbitrary GVKs via the dynamic path. +#[derive(Debug, Clone)] +pub struct DiscoveredResource { + pub api_resource: ApiResource, + pub namespaced: bool, +} + +impl DiscoveredResource { + pub fn group(&self) -> &str { + &self.api_resource.group + } + pub fn version(&self) -> &str { + &self.api_resource.version + } + pub fn kind(&self) -> &str { + &self.api_resource.kind + } + pub fn plural(&self) -> &str { + &self.api_resource.plural + } + /// `kind.group` (or just `kind` for core), lowercased — a stable display/match handle. + pub fn full_name(&self) -> String { + if self.api_resource.group.is_empty() { + self.api_resource.plural.clone() + } else { + format!("{}.{}", self.api_resource.plural, self.api_resource.group) + } + } +} + +/// A generic row from a one-shot dynamic list (no curated columns). +#[derive(Debug, Clone)] +pub struct DynamicRow { + pub namespace: Option, + pub name: String, + pub age: Option>, + pub status: String, +} + #[derive(Debug, Clone)] pub struct ActionResult { pub message: String, @@ -74,6 +116,27 @@ pub trait ResourceProvider: Send + Sync { /// Fetch the full object for a single resource on demand (for detail/describe/decode/edit). /// Not retained per row — see the lean entity model (docs/design/phase-1.1-lean-entity-model.md). async fn get_object(&self, key: &ResourceKey) -> anyhow::Result; + + /// Discover all API resources available on a context (built-ins + CRDs). One cached call per + /// context. Phase 4.1 (dynamic resources). + async fn discover(&self, context: &str) -> anyhow::Result>; + + /// One-shot list of a discovered resource's objects (bounded), with generic columns. + async fn list_dynamic( + &self, + context: &str, + resource: &DiscoveredResource, + namespace: Option<&str>, + ) -> anyhow::Result>; + + /// Fetch a single dynamic object's full manifest for describe. + async fn get_dynamic( + &self, + context: &str, + resource: &DiscoveredResource, + namespace: Option<&str>, + name: &str, + ) -> anyhow::Result; } #[async_trait] diff --git a/src/lib.rs b/src/lib.rs index 1bb7f0d..3192e63 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -65,6 +65,16 @@ pub async fn run() -> anyhow::Result<()> { let action_executor: Arc = provider.clone(); let resource_provider: Arc = provider; + if cli.discover { + return run_discover( + resource_provider.as_ref(), + &initial_context, + cli.discover_resource.as_deref(), + initial_namespace.as_deref(), + ) + .await; + } + if cli.bench { return ui::run_bench( contexts, @@ -97,6 +107,74 @@ pub async fn run() -> anyhow::Result<()> { .await } +/// Headless Phase 4.1 check: print discovered API resources for a context, and optionally list + +/// describe one resource. Verifies the dynamic discovery/list/get path against a real cluster. +async fn run_discover( + provider: &dyn ResourceProvider, + context: &str, + resource: Option<&str>, + namespace: Option<&str>, +) -> anyhow::Result<()> { + let catalog = provider.discover(context).await?; + println!( + "Discovered {} API resources on context '{context}':", + catalog.len() + ); + for r in &catalog { + println!( + " {:<44} {:<22} {}", + r.full_name(), + r.kind(), + if r.namespaced { + "namespaced" + } else { + "cluster" + } + ); + } + + if let Some(token) = resource { + let Some(res) = catalog.iter().find(|r| { + r.plural().eq_ignore_ascii_case(token) + || r.kind().eq_ignore_ascii_case(token) + || r.full_name().eq_ignore_ascii_case(token) + }) else { + println!("\nresource '{token}' not found in discovery"); + return Ok(()); + }; + + println!( + "\nListing {} (namespace={namespace:?}) ...", + res.full_name() + ); + let rows = provider.list_dynamic(context, res, namespace).await?; + println!(" {} object(s) returned (bounded):", rows.len()); + for row in rows.iter().take(20) { + println!( + " {}/{} status={}", + row.namespace.as_deref().unwrap_or("-"), + row.name, + row.status + ); + } + + if let Some(first) = rows.first() { + let obj = provider + .get_dynamic(context, res, first.namespace.as_deref(), &first.name) + .await?; + let yaml = serde_yaml::to_string(&obj).unwrap_or_default(); + let preview: Vec<&str> = yaml.lines().take(15).collect(); + println!( + "\ndescribe {} (first 15 lines):\n{}", + first.name, + preview.join("\n") + ); + } + } + + Ok(()) +} + fn init_tracing() { if std::env::var_os("RUST_LOG").is_none() { return; diff --git a/src/ui/app.rs b/src/ui/app.rs index 284828a..0928fdd 100644 --- a/src/ui/app.rs +++ b/src/ui/app.rs @@ -2253,6 +2253,32 @@ mod tests { async fn get_object(&self, _key: &ResourceKey) -> anyhow::Result { Ok(serde_json::json!({})) } + + async fn discover( + &self, + _context: &str, + ) -> anyhow::Result> { + Ok(Vec::new()) + } + + async fn list_dynamic( + &self, + _context: &str, + _resource: &crate::cluster::DiscoveredResource, + _namespace: Option<&str>, + ) -> anyhow::Result> { + Ok(Vec::new()) + } + + async fn get_dynamic( + &self, + _context: &str, + _resource: &crate::cluster::DiscoveredResource, + _namespace: Option<&str>, + _name: &str, + ) -> anyhow::Result { + Ok(serde_json::json!({})) + } } struct NoopExecutor;