kdash 0.3.7

A fast and simple dashboard for Kubernetes
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
use std::fmt;

use anyhow::anyhow;
use k8s_openapi::{
  api::{
    apps::v1::{DaemonSet, Deployment, ReplicaSet, StatefulSet},
    batch::v1::{CronJob, Job},
    core::v1::{
      ConfigMap, Namespace, Node, PersistentVolume, PersistentVolumeClaim, Pod,
      ReplicationController, Secret, Service, ServiceAccount,
    },
    networking::v1::Ingress,
    rbac::v1::{ClusterRole, ClusterRoleBinding, Role, RoleBinding},
    storage::v1::StorageClass,
  },
  NamespaceResourceScope,
};
use kube::{
  api::{ListMeta, ListParams, ObjectList},
  config::Kubeconfig,
  Api, Resource as ApiResource,
};
use kubectl_view_allocations::{
  extract_allocatable_from_nodes, extract_allocatable_from_pods,
  extract_utilizations_from_pod_metrics, make_qualifiers, metrics::PodMetrics, Resource,
};
use serde::de::DeserializeOwned;

use super::Network;
use crate::app::{
  configmaps::KubeConfigMap,
  contexts,
  cronjobs::KubeCronJob,
  daemonsets::KubeDaemonSet,
  deployments::KubeDeployment,
  ingress::KubeIngress,
  jobs::KubeJob,
  metrics::{self, KubeNodeMetrics},
  nodes::KubeNode,
  ns::KubeNs,
  pods::KubePod,
  pvcs::KubePVC,
  pvs::KubePV,
  replicasets::KubeReplicaSet,
  replication_controllers::KubeReplicationController,
  roles::{KubeClusterRole, KubeClusterRoleBinding, KubeRole, KubeRoleBinding},
  secrets::KubeSecret,
  serviceaccounts::KubeSvcAcct,
  statefulsets::KubeStatefulSet,
  storageclass::KubeStorageClass,
  svcs::KubeSvc,
};

impl<'a> Network<'a> {
  pub async fn get_kube_config(&self) {
    match Kubeconfig::read() {
      Ok(config) => {
        let mut app = self.app.lock().await;
        let selected_ctx = app.data.selected.context.to_owned();
        app.set_contexts(contexts::get_contexts(&config, selected_ctx));
        app.data.kubeconfig = Some(config);
      }
      Err(e) => {
        self
          .handle_error(anyhow!("Failed to load Kubernetes config. {:?}", e))
          .await;
      }
    }
  }

  pub async fn get_node_metrics(&self) {
    let api_node_metrics: Api<metrics::NodeMetrics> = Api::all(self.client.clone());

    match api_node_metrics.list(&ListParams::default()).await {
      Ok(node_metrics) => {
        let mut app = self.app.lock().await;

        let items = node_metrics
          .iter()
          .map(|metric| KubeNodeMetrics::from_api(metric, &app))
          .collect();

        app.data.node_metrics = items;
      }
      Err(_) => {
        let mut app = self.app.lock().await;
        app.data.node_metrics = vec![];
        // lets not show error as it will always be showing up and be annoying
        // TODO may be show once and then disable polling
      }
    };
  }

  pub async fn get_utilizations(&self) {
    let mut resources: Vec<Resource> = vec![];

    let api: Api<Node> = Api::all(self.client.clone());
    match api.list(&ListParams::default()).await {
      Ok(node_list) => {
        if let Err(e) = extract_allocatable_from_nodes(node_list, &mut resources).await {
          self
            .handle_error(anyhow!(
              "Failed to extract node allocation metrics. {:?}",
              e
            ))
            .await;
        }
      }
      Err(e) => {
        self
          .handle_error(anyhow!(
            "Failed to extract node allocation metrics. {:?}",
            e
          ))
          .await
      }
    }

    let api: Api<Pod> = self.get_namespaced_api().await;
    match api.list(&ListParams::default()).await {
      Ok(pod_list) => {
        if let Err(e) = extract_allocatable_from_pods(pod_list, &mut resources).await {
          self
            .handle_error(anyhow!("Failed to extract pod allocation metrics. {:?}", e))
            .await;
        }
      }
      Err(e) => {
        self
          .handle_error(anyhow!("Failed to extract pod allocation metrics. {:?}", e))
          .await
      }
    }

    let api_pod_metrics: Api<PodMetrics> = Api::all(self.client.clone());

    match api_pod_metrics
    .list(&ListParams::default())
    .await
    {
      Ok(pod_metrics) => {
        if let Err(e) = extract_utilizations_from_pod_metrics(pod_metrics, &mut resources).await {
          self.handle_error(anyhow!("Failed to extract pod utilization metrics. {:?}", e)).await;
        }
      }
      Err(_e) => self.handle_error(anyhow!("Failed to extract pod utilization metrics. Make sure you have a metrics-server deployed on your cluster.")).await,
    };

    let mut app = self.app.lock().await;

    let data = make_qualifiers(&resources, &app.utilization_group_by, &[]);

    app.data.metrics.set_items(data);
  }

  pub async fn get_nodes(&self) {
    let lp = ListParams::default();
    let api_pods: Api<Pod> = Api::all(self.client.clone());
    let api_nodes: Api<Node> = Api::all(self.client.clone());

    match api_nodes.list(&lp).await {
      Ok(node_list) => {
        self.get_node_metrics().await;

        let pods_list = match api_pods.list(&lp).await {
          Ok(list) => list,
          Err(_) => ObjectList {
            metadata: ListMeta::default(),
            items: vec![],
          },
        };

        let mut app = self.app.lock().await;

        let items = node_list
          .iter()
          .map(|node| KubeNode::from_api_with_pods(node, &pods_list, &mut app))
          .collect::<Vec<_>>();

        app.data.nodes.set_items(items);
      }
      Err(e) => {
        self
          .handle_error(anyhow!("Failed to get nodes. {:?}", e))
          .await;
      }
    }
  }

  pub async fn get_namespaces(&self) {
    let api: Api<Namespace> = Api::all(self.client.clone());

    let lp = ListParams::default();
    match api.list(&lp).await {
      Ok(ns_list) => {
        let items = ns_list.into_iter().map(KubeNs::from).collect::<Vec<_>>();
        let mut app = self.app.lock().await;
        app.data.namespaces.set_items(items);
      }
      Err(e) => {
        self
          .handle_error(anyhow!("Failed to get namespaces. {:?}", e))
          .await;
      }
    }
  }

  pub async fn get_pods(&self) {
    let items: Vec<KubePod> = self.get_namespaced_resources(Pod::into).await;

    let mut app = self.app.lock().await;
    if app.data.selected.pod.is_some() {
      let containers = &items.iter().find_map(|pod| {
        if pod.name == app.data.selected.pod.clone().unwrap() {
          Some(&pod.containers)
        } else {
          None
        }
      });
      if containers.is_some() {
        app.data.containers.set_items(containers.unwrap().clone());
      }
    }
    app.data.pods.set_items(items);
  }

  pub async fn get_services(&self) {
    let items: Vec<KubeSvc> = self.get_namespaced_resources(Service::into).await;

    let mut app = self.app.lock().await;
    app.data.services.set_items(items);
  }

  pub async fn get_config_maps(&self) {
    let items: Vec<KubeConfigMap> = self.get_namespaced_resources(ConfigMap::into).await;

    let mut app = self.app.lock().await;
    app.data.config_maps.set_items(items);
  }

  pub async fn get_stateful_sets(&self) {
    let items: Vec<KubeStatefulSet> = self.get_namespaced_resources(StatefulSet::into).await;

    let mut app = self.app.lock().await;
    app.data.stateful_sets.set_items(items);
  }

  pub async fn get_replica_sets(&self) {
    let items: Vec<KubeReplicaSet> = self.get_namespaced_resources(ReplicaSet::into).await;

    let mut app = self.app.lock().await;
    app.data.replica_sets.set_items(items);
  }

  pub async fn get_jobs(&self) {
    let items: Vec<KubeJob> = self.get_namespaced_resources(Job::into).await;

    let mut app = self.app.lock().await;
    app.data.jobs.set_items(items);
  }

  pub async fn get_cron_jobs(&self) {
    let items: Vec<KubeCronJob> = self.get_namespaced_resources(CronJob::into).await;

    let mut app = self.app.lock().await;
    app.data.cronjobs.set_items(items);
  }

  pub async fn get_secrets(&self) {
    let items: Vec<KubeSecret> = self.get_namespaced_resources(Secret::into).await;

    let mut app = self.app.lock().await;
    app.data.secrets.set_items(items);
  }

  pub async fn get_replication_controllers(&self) {
    let items: Vec<KubeReplicationController> = self
      .get_namespaced_resources(ReplicationController::into)
      .await;

    let mut app = self.app.lock().await;
    app.data.rpl_ctrls.set_items(items);
  }

  pub async fn get_deployments(&self) {
    let items: Vec<KubeDeployment> = self.get_namespaced_resources(Deployment::into).await;

    let mut app = self.app.lock().await;
    app.data.deployments.set_items(items);
  }

  pub async fn get_daemon_sets_jobs(&self) {
    let items: Vec<KubeDaemonSet> = self.get_namespaced_resources(DaemonSet::into).await;

    let mut app = self.app.lock().await;
    app.data.daemon_sets.set_items(items);
  }

  pub async fn get_storage_classes(&self) {
    let items: Vec<KubeStorageClass> = self.get_resources(StorageClass::into).await;

    let mut app = self.app.lock().await;
    app.data.storage_classes.set_items(items);
  }

  pub async fn get_roles(&self) {
    let items: Vec<KubeRole> = self.get_namespaced_resources(Role::into).await;

    let mut app = self.app.lock().await;
    app.data.roles.set_items(items);
  }

  pub async fn get_role_bindings(&self) {
    let items: Vec<KubeRoleBinding> = self.get_namespaced_resources(RoleBinding::into).await;

    let mut app = self.app.lock().await;
    app.data.role_bindings.set_items(items);
  }

  pub async fn get_cluster_roles(&self) {
    let items: Vec<KubeClusterRole> = self.get_resources(ClusterRole::into).await;

    let mut app = self.app.lock().await;
    app.data.cluster_roles.set_items(items);
  }

  pub async fn get_cluster_role_binding(&self) {
    let items: Vec<KubeClusterRoleBinding> = self.get_resources(ClusterRoleBinding::into).await;

    let mut app = self.app.lock().await;
    app.data.cluster_role_bindings.set_items(items);
  }

  pub async fn get_ingress(&self) {
    let items: Vec<KubeIngress> = self.get_namespaced_resources(Ingress::into).await;

    let mut app = self.app.lock().await;
    app.data.ingress.set_items(items);
  }

  pub async fn get_pvcs(&self) {
    let items: Vec<KubePVC> = self
      .get_namespaced_resources(PersistentVolumeClaim::into)
      .await;

    let mut app = self.app.lock().await;
    app.data.pvcs.set_items(items);
  }

  pub async fn get_pvs(&self) {
    let items: Vec<KubePV> = self.get_resources(PersistentVolume::into).await;

    let mut app = self.app.lock().await;
    app.data.pvs.set_items(items);
  }

  pub async fn get_service_accounts(&self) {
    let items: Vec<KubeSvcAcct> = self.get_namespaced_resources(ServiceAccount::into).await;

    let mut app = self.app.lock().await;
    app.data.service_accounts.set_items(items);
  }

  /// calls the kubernetes API to list the given resource for either selected namespace or all namespaces
  async fn get_namespaced_resources<K: ApiResource, T, F>(&self, map_fn: F) -> Vec<T>
  where
    <K as ApiResource>::DynamicType: Default,
    K: kube::Resource<Scope = NamespaceResourceScope>,
    K: Clone + DeserializeOwned + fmt::Debug,
    F: Fn(K) -> T,
  {
    let api: Api<K> = self.get_namespaced_api().await;
    let lp = ListParams::default();
    match api.list(&lp).await {
      Ok(list) => list.into_iter().map(map_fn).collect::<Vec<_>>(),
      Err(e) => {
        self
          .handle_error(anyhow!(
            "Failed to get namespaced resource {}. {:?}",
            std::any::type_name::<T>(),
            e
          ))
          .await;
        vec![]
      }
    }
  }

  async fn get_resources<K: ApiResource, T, F>(&self, map_fn: F) -> Vec<T>
  where
    <K as ApiResource>::DynamicType: Default,
    K: Clone + DeserializeOwned + fmt::Debug,
    F: Fn(K) -> T,
  {
    let api: Api<K> = Api::all(self.client.clone());
    let lp = ListParams::default();
    match api.list(&lp).await {
      Ok(list) => list.into_iter().map(map_fn).collect::<Vec<_>>(),
      Err(e) => {
        self
          .handle_error(anyhow!(
            "Failed to get resource {}. {:?}",
            std::any::type_name::<T>(),
            e
          ))
          .await;
        vec![]
      }
    }
  }

  async fn get_namespaced_api<K: ApiResource>(&self) -> Api<K>
  where
    <K as ApiResource>::DynamicType: Default,
    K: kube::Resource<Scope = NamespaceResourceScope>,
  {
    let app = self.app.lock().await;
    match &app.data.selected.ns {
      Some(ns) => Api::namespaced(self.client.clone(), ns),
      None => Api::all(self.client.clone()),
    }
  }
}