1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
use super::*;
impl App {
// ----- navigation ----------------------------------------------------
/// Switch the active resource kind by user input. Pushes the current view
/// so `esc` can return.
pub fn switch_kind(&mut self, input: &str) {
self.switch_kind_ns(input, None);
}
/// Switch kind and (optionally) namespace in one move (`:deploy social`).
/// `all`/`*` as the namespace selects all namespaces.
pub fn switch_kind_ns(&mut self, input: &str, ns: Option<&str>) {
match self.cluster.resolve(input) {
Some(kind) => {
if let Some(ns) = ns {
self.namespace = normalize_ns(ns);
}
let title = kind.title();
self.set_root_view(kind);
self.flash = if ns.is_some() {
format!("Viewing {title} in {}", self.namespace_label())
} else {
format!("Viewing {title}")
};
self.flash_err = false;
self.record_history();
self.start_watch();
}
None => {
self.flash = format!("No resource matches '{}'", input.trim());
self.flash_err = true;
}
}
}
/// Install `kind` as a fresh root view (not a drill-down): clear the
/// breadcrumb so `esc` doesn't replay command history, drop drill
/// selectors, and reset filter/sort/cursor. A stale selection from the
/// previous kind (e.g. row 5 on pods) would otherwise carry over — the new
/// view always starts with its first row selected.
fn set_root_view(&mut self, kind: Kind) {
self.stack.clear();
self.kind_plural = kind.ar.plural.to_lowercase();
self.kind = Some(kind);
self.labels = None;
self.fields = None;
self.scope_label = None;
self.filter.clear();
self.reset_sort();
self.table_state.select(Some(0));
}
/// Open the Helm release list (`:helm`): one row per release at its
/// latest revision, like `helm list`. Backed by the `secrets` kind
/// scoped to Helm's own storage labels/type — see `crate::helm` and the
/// `"helm"` dedup case in `rows::ensure_rows_cache`.
pub(super) fn open_helm_releases(&mut self) {
let Some(secrets) = self.cluster.resolve("secrets") else {
self.flash_warn("secrets kind unavailable");
return;
};
self.stack.clear();
self.kind = Some(secrets);
self.kind_plural = "helm".into();
self.labels = Some("owner=helm".into());
self.fields = Some("type=helm.sh/release.v1".into());
self.scope_label = None;
self.filter.clear();
self.reset_sort();
self.table_state.select(Some(0));
self.flash = "Viewing Helm releases".into();
self.flash_err = false;
// Deliberately not recorded in the `[`/`]` root-view history: that
// history replays entries via `cluster.resolve(kind_plural)` +
// `set_root_view`, neither of which know about the synthetic "helm"
// plural (resolve would fail, and set_root_view would reset it back
// to "secrets" even if it didn't) — recording it would produce a
// history entry that can't be replayed correctly.
self.start_watch();
}
pub(super) fn namespace_label(&self) -> String {
if self.namespace.is_empty() {
"all namespaces".to_string()
} else {
self.namespace.clone()
}
}
/// Display name for synthetic views (Helm releases/history), which are
/// backed by a real kind (`secrets`) that has nothing to do with what's
/// on screen. `None` for ordinary kind-backed views.
fn synthetic_title(&self) -> Option<&'static str> {
match self.kind_plural.as_str() {
"helm" => Some("helm"),
"helmhistory" => Some("helm history"),
_ => None,
}
}
/// The "Resource:" label shown in the header. Usually just `self.kind`'s
/// title, but naming synthetic views after `kind_plural` instead keeps
/// the header honest about what's actually being browsed.
pub fn resource_title(&self) -> String {
match self.synthetic_title() {
Some(t) => t.to_string(),
None => self
.kind
.as_ref()
.map(|k| k.title())
.unwrap_or_else(|| "—".into()),
}
}
/// The list panel's border title (k9s-style bare plural), with the same
/// synthetic-view exception as `resource_title` so the Helm views don't
/// leak their backing `secrets` kind.
pub fn list_title(&self) -> String {
match self.synthetic_title() {
Some(t) => t.to_string(),
None => self
.kind
.as_ref()
.map(|k| k.ar.plural.clone())
.unwrap_or_else(|| "resources".into()),
}
}
// ----- view history (`[` / `]`) ---------------------------------------
/// Record the current root view (kind + namespace). Called after every
/// root switch; navigating with `[`/`]` bypasses this so hopping through
/// history doesn't rewrite it. A new entry truncates the forward tail.
pub(super) fn record_history(&mut self) {
if self.kind.is_none() {
return;
}
let entry = ViewEntry {
kind_plural: self.kind_plural.clone(),
namespace: self.namespace.clone(),
};
if self.history.get(self.history_pos) == Some(&entry) {
return;
}
self.history.truncate(self.history_pos + 1);
self.history.push(entry);
if self.history.len() > HISTORY_MAX {
self.history.remove(0);
}
self.history_pos = self.history.len() - 1;
}
pub(super) fn history_back(&mut self) {
if self.history_pos == 0 {
self.flash_warn("already at oldest view");
return;
}
self.history_pos -= 1;
self.apply_history_entry();
}
pub(super) fn history_forward(&mut self) {
if self.history_pos + 1 >= self.history.len() {
self.flash_warn("already at newest view");
return;
}
self.history_pos += 1;
self.apply_history_entry();
}
fn apply_history_entry(&mut self) {
let Some(entry) = self.history.get(self.history_pos).cloned() else {
return;
};
let Some(kind) = self.cluster.resolve(&entry.kind_plural) else {
self.flash_warn(&format!("cannot resolve '{}' anymore", entry.kind_plural));
return;
};
self.namespace = entry.namespace;
let title = kind.title();
self.set_root_view(kind);
self.flash = format!(
"history {}/{}: {title} in {}",
self.history_pos + 1,
self.history.len(),
self.namespace_label()
);
self.flash_err = false;
self.start_watch();
}
pub(super) fn push_frame(&mut self) {
if self.kind.is_none() {
return;
}
self.stack.push(Frame {
kind: self.kind.clone(),
kind_plural: self.kind_plural.clone(),
namespace: self.namespace.clone(),
labels: self.labels.clone(),
fields: self.fields.clone(),
filter: self.filter.clone(),
scope_label: self.scope_label.clone(),
selected: self.table_state.selected(),
});
}
pub(super) fn restore(&mut self, f: Frame) {
self.kind = f.kind;
self.kind_plural = f.kind_plural;
self.namespace = f.namespace;
self.labels = f.labels;
self.fields = f.fields;
self.filter = f.filter;
self.scope_label = f.scope_label;
self.reset_sort();
self.table_state.select(f.selected.or(Some(0)));
}
pub(super) fn pop_frame(&mut self) -> bool {
if let Some(f) = self.stack.pop() {
self.restore(f);
self.start_watch();
true
} else {
false
}
}
/// (Re)start the watch for the current kind/namespace/selectors.
pub fn start_watch(&mut self) {
let Some(kind) = self.kind.clone() else {
return;
};
self.generation += 1;
self.gen_flag.store(self.generation, Ordering::SeqCst);
for t in self.tasks.drain(..) {
t.abort();
}
self.store.clear();
self.metrics.clear();
self.marked.clear();
self.invalidate_rows();
if self.table_state.selected().is_none() {
self.table_state.select(Some(0));
}
let handle = self.cluster.spawn_watch(
&kind,
&self.namespace,
self.labels.clone(),
self.fields.clone(),
self.generation,
self.tx.clone(),
);
self.tasks.push(handle);
if matches!(self.kind_plural.as_str(), "pods" | "nodes") {
self.spawn_metrics_poll();
}
// Refresh RBAC allow-list when the namespace changes.
if self.last_rbac_ns.as_deref() != Some(self.namespace.as_str()) {
self.last_rbac_ns = Some(self.namespace.clone());
self.refresh_rbac();
}
}
/// Query SelfSubjectRulesReview for the active namespace to learn which
/// resources the user can list, so the palette can hide the rest.
pub(super) fn refresh_rbac(&self) {
use k8s_openapi::api::authorization::v1::{
SelfSubjectRulesReview, SelfSubjectRulesReviewSpec,
};
let client = self.cluster.client.clone();
let tx = self.tx.clone();
let genr = self.generation;
// Namespace this review is computed for (echoed back so a stale result
// from a previous namespace/context is dropped). SelfSubjectRulesReview
// needs a concrete namespace, so "" falls back to "default".
let current_ns = self.namespace.clone();
let review_ns = if current_ns.is_empty() {
"default".to_string()
} else {
current_ns.clone()
};
tokio::spawn(async move {
let review = SelfSubjectRulesReview {
spec: SelfSubjectRulesReviewSpec {
namespace: Some(review_ns),
},
..Default::default()
};
let api: Api<SelfSubjectRulesReview> = Api::all(client);
let Ok(resp) = api.create(&kube::api::PostParams::default(), &review).await else {
return; // can't review → leave palette unfiltered
};
let Some(status) = resp.status else { return };
// On clusters that delegate authorization (e.g. GKE → Google IAM),
// the review comes back `incomplete` and can't enumerate what we can
// actually access. Filtering on a partial list would wrongly hide
// everything, so leave the palette unfiltered in that case.
if status.incomplete {
return;
}
let mut allowed = HashSet::new();
for rule in status.resource_rules {
let can_list = rule.verbs.iter().any(|v| v == "list" || v == "*");
if !can_list {
continue;
}
for res in rule.resources.unwrap_or_default() {
if res == "*" {
allowed.insert("*".to_string());
} else {
// strip subresources like "pods/log"
allowed.insert(res.split('/').next().unwrap_or(&res).to_string());
}
}
}
// Parsed nothing usable → don't hide the whole palette.
if allowed.is_empty() {
return;
}
let _ = tx
.send(Msg::Rbac {
generation: genr,
ns: current_ns,
allowed,
})
.await;
});
}
/// Whether a resource plural is visible under the current RBAC allow-list.
pub(super) fn rbac_visible(&self, plural: &str) -> bool {
match &self.rbac_allowed {
None => true,
Some(set) => set.contains("*") || set.contains(plural),
}
}
/// Poll the metrics API every few seconds for the current pods/nodes view.
pub(super) fn spawn_metrics_poll(&mut self) {
let base = self.kind_plural.clone();
let Some(mkind) = self.cluster.resolve(&format!("{base}.metrics.k8s.io")) else {
return; // metrics-server not installed
};
let client = self.cluster.client.clone();
let tx = self.tx.clone();
let genr = self.generation;
let flag = self.gen_flag.clone();
let ns = self.namespace.clone();
let ar = mkind.ar.clone();
let namespaced = mkind.namespaced;
let is_node = base == "nodes";
let handle = tokio::spawn(async move {
loop {
if flag.load(Ordering::SeqCst) != genr {
break;
}
let api: Api<DynamicObject> = if namespaced && !ns.is_empty() {
Api::namespaced_with(client.clone(), &ns, &ar)
} else {
Api::all_with(client.clone(), &ar)
};
if let Ok(list) = api.list(&ListParams::default()).await {
let mut data = HashMap::new();
for item in list {
let name = item.metadata.name.clone().unwrap_or_default();
let key = match &item.metadata.namespace {
Some(n) => format!("{n}/{name}"),
None => name,
};
data.insert(key, usage_of(&item, is_node));
}
if tx
.send(Msg::Metrics {
generation: genr,
data,
})
.await
.is_err()
{
break;
}
}
tokio::time::sleep(Duration::from_secs(5)).await;
}
});
self.tasks.push(handle);
}
pub(super) fn bump_generation(&mut self) {
self.stop_event_stream();
self.generation += 1;
self.gen_flag.store(self.generation, Ordering::SeqCst);
for t in self.tasks.drain(..) {
t.abort();
}
}
pub fn handle_msg(&mut self, msg: Msg) {
match msg {
Msg::Reset { generation } if generation == self.generation => {
self.store.clear();
self.clear_rows_cache();
}
Msg::Applied {
generation,
key,
obj,
} if generation == self.generation => {
self.store.apply(key.clone(), *obj);
self.invalidate_row(&key);
}
Msg::Deleted { generation, key } if generation == self.generation => {
self.store.remove(&key);
self.invalidate_row(&key);
}
Msg::Synced { generation } if generation == self.generation => self.store.synced = true,
Msg::Error { generation, error } if generation == self.generation => {
self.flash = format!("error: {error}");
self.flash_err = true;
}
Msg::LogLines { generation, lines } if generation == self.log_gen => {
self.push_log_lines(lines);
}
Msg::Metrics { generation, data } if generation == self.generation => {
let sort_uses_metrics = self
.sort_column
.and_then(|i| self.display_headers().get(i).copied())
.is_some_and(|h| matches!(h, "CPU" | "MEM"));
self.metrics = data;
if sort_uses_metrics {
self.invalidate_rows();
}
}
Msg::PulseData { generation, data } if generation == self.generation => {
self.pulse = data;
}
Msg::Rbac {
generation,
ns,
allowed,
} if generation == self.generation && ns == self.namespace => {
self.rbac_allowed = Some(allowed);
}
Msg::XrayData { generation, items } if generation == self.generation => {
let keep = self.xray_state.selected().unwrap_or(0);
self.xray_items = items;
self.xray_state
.select(Some(keep.min(self.xray_items.len().saturating_sub(1))));
}
Msg::Detail {
generation,
title,
lines,
warn,
} if generation == self.generation => {
self.detail = Scrollable {
title,
lines: lines.into(),
..Default::default()
};
self.mode = Mode::Detail;
if let Some(w) = warn {
self.flash_warn(&w);
}
}
Msg::Events {
generation,
title,
lines,
} if generation == self.event_gen => {
self.detail.title = title;
self.detail.lines = lines.into();
self.detail.scroll = self
.detail
.scroll
.min(self.detail.lines.len().saturating_sub(1));
}
Msg::LogsSaved { generation, result } if generation == self.log_gen => match result {
Ok(path) => {
self.flash = format!("saved logs → {}", path.display());
self.flash_err = false;
}
Err(e) => self.flash_warn(&format!("save failed: {e}")),
},
Msg::ClipboardCopied {
generation,
copied,
success,
failure,
} if generation == self.generation => {
if copied {
self.flash = success;
self.flash_err = false;
} else {
self.flash_warn(&failure);
}
}
Msg::Namespaces { generation, list } if generation == self.generation => {
// Keep the picker open and preserve the selection if possible.
let keep = self.ns_state.selected().unwrap_or(0);
self.ns_list = list;
self.ns_state
.select(Some(keep.min(self.ns_list.len().saturating_sub(1))));
}
Msg::Contexts { generation, list } if generation == self.generation => {
if list.is_empty() {
self.mode = Mode::Table;
self.flash_warn("no contexts found in kubeconfig");
} else {
let cur = self.cluster.context.clone();
let idx = list.iter().position(|c| *c == cur).unwrap_or(0);
self.ctx_list = list;
self.ctx_state.select(Some(idx));
}
}
Msg::ContextSwitched {
generation,
name,
result,
} if generation == self.generation => match result {
Ok(cluster) => self.apply_context_switch(name, cluster),
Err(e) => self.flash_warn(&format!("context switch failed: {e}")),
},
_ => {} // stale generation, drop
}
}
}