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
mod data;

use data::*;

use crate::k8s::ago;
use crate::{app::state::list::ListResource, client::Client, input::key::Key};
use k8s_openapi::api::core::v1::Pod;
use kube::{
    api::{DeleteParams, Preconditions},
    Api, Resource, ResourceExt,
};
use std::{fmt::Debug, future::Future, hash::Hash, pin::Pin, sync::Arc};
use tui::{layout::*, style::*, widgets::*};

impl ListResource for Pod {
    type Resource = Self;
    type Message = Msg;

    fn render_table<'r, 'a>(items: &'r mut [Arc<Self::Resource>]) -> Table<'a>
    where
        <<Self as ListResource>::Resource as Resource>::DynamicType: Hash + Eq,
    {
        items.sort_unstable_by(|a, b| a.name().cmp(&b.name()));

        let selected_style = Style::default().add_modifier(Modifier::REVERSED);
        let normal_style = Style::default();
        let header_cells = ["Name", "Ready", "State", "Restarts", "Age"]
            .iter()
            .map(|h| Cell::from(*h).style(Style::default().add_modifier(Modifier::BOLD)));
        let header = Row::new(header_cells).style(normal_style).height(1);

        let rows: Vec<Row> = items.iter().map(|pod| make_row(pod)).collect();

        Table::new(rows)
            .header(header)
            .block(Block::default().borders(Borders::ALL).title("Pods"))
            .highlight_style(selected_style)
            .highlight_symbol(">> ")
            .widths(&[
                Constraint::Min(64),
                Constraint::Min(10),
                Constraint::Min(20),
                Constraint::Min(15),
                Constraint::Min(10),
            ])
    }

    fn on_key(items: &[Arc<Self::Resource>], state: &TableState, key: Key) -> Option<Self::Message>
    where
        <<Self as ListResource>::Resource as kube::Resource>::DynamicType: Hash + Eq,
    {
        match key {
            Key::Char('k') => trigger_kill(items, state),
            _ => None,
        }
    }

    fn process(
        client: Arc<Client>,
        msg: Self::Message,
    ) -> Pin<Box<dyn Future<Output = ()> + Send>> {
        Box::pin(async {
            match msg {
                Msg::KillPod(pod) => execute_kill(client, &pod).await,
            }
        })
    }
}

fn trigger_kill(pods: &[Arc<Pod>], state: &TableState) -> Option<Msg> {
    let mut pods = pods.to_vec();
    pods.sort_unstable_by(|a, b| a.name().cmp(&b.name()));

    if let Some(pod) = state.selected().and_then(|i| pods.get(i)) {
        Some(Msg::KillPod(pod.clone()))
    } else {
        None
    }
}

fn make_row<'r, 'a>(pod: &'r Pod) -> Row<'a> {
    let mut style = Style::default();

    let name = pod.name();
    let ready = pod.status.as_ref().and_then(make_ready).unwrap_or_default();

    let state = if pod.meta().deletion_timestamp.is_some() {
        PodState::Terminating
    } else {
        pod.status.as_ref().map(make_state).unwrap_or_default()
    };
    let restarts = pod
        .status
        .as_ref()
        .and_then(make_restarts)
        .unwrap_or_else(|| String::from("0"));
    let age = pod
        .creation_timestamp()
        .as_ref()
        .and_then(ago)
        .unwrap_or_default();

    match &state {
        PodState::Pending => {
            style = style.bg(Color::Rgb(128, 0, 128));
        }
        PodState::Error => {
            style = style.bg(Color::Rgb(128, 0, 0)).add_modifier(Modifier::BOLD);
        }
        PodState::CrashLoopBackOff => {
            style = style.bg(Color::Rgb(128, 0, 0));
        }
        PodState::Terminating => {
            style = style.bg(Color::Rgb(128, 128, 0));
        }
        _ => {}
    }

    Row::new(vec![name, ready, state.to_string(), restarts, age]).style(style)
}

#[derive(Debug)]
pub enum Msg {
    KillPod(Arc<Pod>),
}

async fn execute_kill(client: Arc<Client>, pod: &Pod) {
    let result = client
        .run(|context| async move {
            if let Some(namespace) = pod.namespace() {
                let pods: Api<Pod> = Api::namespaced(context.client, &namespace);

                pods.delete(
                    &pod.name(),
                    &DeleteParams::default().preconditions(Preconditions {
                        uid: pod.uid(),
                        ..Default::default()
                    }),
                )
                .await?;
            }
            Ok::<_, anyhow::Error>(())
        })
        .await;

    match result {
        Ok(_) => {
            log::info!("Pod killed");
        }
        Err(err) => {
            log::warn!("Failed to kill pod: {err}");
        }
    }
}