k8_config/
lib.rs

1mod config;
2mod error;
3mod pod;
4
5#[cfg(feature = "context")]
6pub mod context;
7
8pub use config::{KubeConfig, ClusterDetail, Context, Cluster, ContextDetail, User, UserDetail};
9pub use error::ConfigError;
10pub use pod::PodConfig;
11
12pub use config::{AuthProviderDetail, GcpAuthProviderConfig};
13
14use tracing::debug;
15
16const KUBECONFIG: &str = "KUBECONFIG";
17
18#[derive(Debug)]
19pub struct KubeContext {
20    pub namespace: String,
21    pub api_path: String,
22    pub config: KubeConfig,
23}
24
25#[derive(Debug)]
26pub enum K8Config {
27    Pod(PodConfig),
28    KubeConfig(KubeContext),
29}
30
31impl Default for K8Config {
32    fn default() -> Self {
33        Self::Pod(PodConfig::default())
34    }
35}
36
37impl K8Config {
38    pub fn load() -> Result<Self, ConfigError> {
39        if let Some(pod_config) = PodConfig::load() {
40            debug!("found pod config: {:#?}", pod_config);
41            Ok(K8Config::Pod(pod_config))
42        } else {
43            debug!("no pod config is found. trying to read kubeconfig");
44            let config =
45                std::env::var(KUBECONFIG).map_or(KubeConfig::from_home(), KubeConfig::from_file)?;
46            debug!("kube config: {:#?}", config);
47            // check if we have current cluster
48
49            if let Some(current_cluster) = config.current_cluster() {
50                let ctx = config
51                    .current_context()
52                    .expect("current context should exists");
53                Ok(K8Config::KubeConfig(KubeContext {
54                    namespace: ctx.context.namespace().to_owned(),
55                    api_path: current_cluster.cluster.server.clone(),
56                    config,
57                }))
58            } else {
59                Err(ConfigError::NoCurrentContext)
60            }
61        }
62    }
63
64    pub fn api_path(&self) -> &str {
65        match self {
66            Self::Pod(pod) => pod.api_path(),
67            Self::KubeConfig(config) => &config.api_path,
68        }
69    }
70
71    pub fn namespace(&self) -> &str {
72        match self {
73            Self::Pod(pod) => &pod.namespace,
74            Self::KubeConfig(config) => &config.namespace,
75        }
76    }
77}