Skip to content

Commit

Permalink
Get secrets
Browse files Browse the repository at this point in the history
  • Loading branch information
byrnedo committed Aug 2, 2024
1 parent ab975c4 commit f878700
Show file tree
Hide file tree
Showing 7 changed files with 142 additions and 13 deletions.
13 changes: 10 additions & 3 deletions src/get.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ mod cronjob;
mod pod;
mod lister;
mod daemonset;
mod secret;


use std::error::Error;
Expand All @@ -28,7 +29,7 @@ use crate::get::ingress::IngresssLister;
use crate::get::lister::Lister;
use crate::get::node::NodeLister;
use crate::get::pod::PodLister;

use crate::get::secret::SecretLister;


#[derive(Debug, Clone, Args)]
Expand Down Expand Up @@ -76,11 +77,11 @@ pub async fn get(args: GetArgs) -> Result<(), Box<dyn Error>> {
match args.commands {
GetCommands::Pod(args) => get_pod(global_args, args).await,
GetCommands::Deployment(args) => get_deployment(global_args, args).await,
GetCommands::Daemonset(args) => todo!(),
GetCommands::Daemonset(args) => get_daemonsets(global_args, args).await,
GetCommands::Node(args) => get_nodes(global_args, args).await,
GetCommands::Ingress(args) => get_ingress(global_args, args).await,
GetCommands::Cronjob(args) => get_cronjobs(global_args, args).await,
GetCommands::Secret(args) => todo!(),
GetCommands::Secret(args) => get_secrets(global_args, args).await,
}
}

Expand Down Expand Up @@ -146,3 +147,9 @@ async fn get_nodes(global_args: GetArgs, args: GetObjectArgs) -> Result<(), Box<
let lister = NodeLister {};
get_objects(global_args, args, &lister).await
}

async fn get_secrets(global_args: GetArgs, args: GetObjectArgs) -> Result<(), Box<dyn Error>> {
let lister = SecretLister{};
get_objects(global_args, args, &lister).await
}

5 changes: 3 additions & 2 deletions src/get/daemonset.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ use itertools::Itertools;
use crate::get::{GetObjectArgs, IdCommand, Lister};
use crate::skatelet::{PodmanPodInfo, PodmanPodStatus, SystemInfo};
use crate::state::state::ClusterState;
use crate::util::age;

pub(crate) struct DaemonsetLister {}

Expand Down Expand Up @@ -52,7 +53,7 @@ impl Lister<(String, PodmanPodInfo)> for DaemonsetLister {
fn print(&self, items: Vec<(String, PodmanPodInfo)>) {
println!(
"{0: <30} {1: <10} {2: <10} {3: <10} {4: <30}",
"NAME", "READY", "STATUS", "RESTARTS", "CREATED"
"NAME", "READY", "STATUS", "RESTARTS", "AGE"
);
let pods = items.into_iter().fold(HashMap::<String, Vec<PodmanPodInfo>>::new(), |mut acc, (depl, pod)| {
acc.entry(depl).or_insert(vec![]).push(pod);
Expand All @@ -71,7 +72,7 @@ impl Lister<(String, PodmanPodInfo)> for DaemonsetLister {

println!(
"{0: <30} {1: <10} {2: <10} {3: <10} {4: <30}",
deployment, format!("{}/{}", health_pods, all_pods), "", "", created.to_rfc3339_opts(SecondsFormat::Secs, true)
deployment, format!("{}/{}", health_pods, all_pods), "", "", age(created)
)
}
}
Expand Down
5 changes: 3 additions & 2 deletions src/get/deployment.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ use itertools::Itertools;
use crate::get::{GetObjectArgs, IdCommand, Lister};
use crate::skatelet::{PodmanPodInfo, PodmanPodStatus, SystemInfo};
use crate::state::state::ClusterState;
use crate::util::age;

pub(crate) struct DeploymentLister {}

Expand Down Expand Up @@ -56,7 +57,7 @@ impl Lister<(String, PodmanPodInfo)> for DeploymentLister {
fn print(&self, items: Vec<(String, PodmanPodInfo)>) {
println!(
"{0: <30} {1: <10} {2: <10} {3: <10} {4: <30}",
"NAME", "READY", "STATUS", "RESTARTS", "CREATED"
"NAME", "READY", "STATUS", "RESTARTS", "AGE"
);
let pods = items.into_iter().fold(HashMap::<String, Vec<PodmanPodInfo>>::new(), |mut acc, (depl, pod)| {
acc.entry(depl).or_insert(vec![]).push(pod);
Expand All @@ -75,7 +76,7 @@ impl Lister<(String, PodmanPodInfo)> for DeploymentLister {

println!(
"{0: <30} {1: <10} {2: <10} {3: <10} {4: <30}",
deployment, format!("{}/{}", health_pods, all_pods), "", "", created.to_rfc3339_opts(SecondsFormat::Secs, true)
deployment, format!("{}/{}", health_pods, all_pods), "", "", age(created)
)
}
}
Expand Down
5 changes: 3 additions & 2 deletions src/get/pod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ use chrono::SecondsFormat;
use crate::get::{Lister};
use crate::get::lister::NameFilters;
use crate::skatelet::{PodmanPodInfo, SystemInfo};
use crate::util::age;

pub (crate) struct PodLister {}

Expand Down Expand Up @@ -32,7 +33,7 @@ impl Lister<PodmanPodInfo> for PodLister {
fn print(&self, pods: Vec<PodmanPodInfo>) {
println!(
"{0: <30} {1: <10} {2: <10} {3: <10} {4: <30}",
"NAME", "READY", "STATUS", "RESTARTS", "CREATED"
"NAME", "READY", "STATUS", "RESTARTS", "AGE"
);
for pod in pods {
let num_containers = pod.containers.clone().unwrap_or_default().len();
Expand All @@ -46,7 +47,7 @@ impl Lister<PodmanPodInfo> for PodLister {
.reduce(|a, c| a + c).unwrap_or_default();
println!(
"{0: <30} {1: <10} {2: <10} {3: <10} {4: <30}",
pod.name, format!("{}/{}", healthy_containers, num_containers), pod.status, restarts, pod.created.to_rfc3339_opts(SecondsFormat::Secs, true)
pod.name, format!("{}/{}", healthy_containers, num_containers), pod.status, restarts, age(pod.created)
)
}
}
Expand Down
39 changes: 39 additions & 0 deletions src/get/secret.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
use std::collections::HashMap;
use chrono::{Local, SecondsFormat};
use itertools::Itertools;
use crate::filestore::ObjectListItem;
use crate::get::{GetObjectArgs, IdCommand, Lister};
use crate::skatelet::{PodmanPodInfo, PodmanPodStatus, SystemInfo};
use crate::state::state::ClusterState;
use crate::util::age;

pub(crate) struct SecretLister {}

impl Lister<ObjectListItem> for SecretLister {
fn selector(&self, si: &SystemInfo, ns: &str, id: &str) -> Option<Vec<ObjectListItem>> {
si.secrets.clone()
}

fn print(&self, items: Vec<ObjectListItem>) {
let map = items.iter().fold(HashMap::<String, Vec<ObjectListItem>>::new(), |mut acc, item| {
acc.entry(item.name.to_string()).or_insert(vec![]).push(item.clone());
acc
});

macro_rules! cols {
() => ("{0: <15} {1: <15} {2: <15} {3: <15} {4: <10}")
}
println!(
cols!(),
"NAMESPACE", "NAME", "TYPE", "DATA", "AGE",
);

// TODO - get from manifest
let data = 1;

for item in map {
let item = item.1.first().unwrap();
println!(cols!(), item.name.namespace, item.name.name, "Opaque", data, age(item.created_at))
}
}
}
59 changes: 55 additions & 4 deletions src/skatelet/system.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
mod podman;

use std::collections::{BTreeMap};
use std::env::consts::ARCH;
use sysinfo::{CpuRefreshKind, DiskKind, Disks, MemoryRefreshKind, RefreshKind, System};
Expand All @@ -8,14 +10,16 @@ use anyhow::anyhow;
use chrono::{DateTime, Local};
use clap::{Args, Subcommand};

use k8s_openapi::api::core::v1::{Pod, PodSpec, PodStatus as K8sPodStatus};
use k8s_openapi::api::core::v1::{Pod, PodSpec, PodStatus as K8sPodStatus, Secret};
use k8s_openapi::apimachinery::pkg::apis::meta::v1::ObjectMeta;
use serde::{Deserialize, Serialize};
use serde_yaml::Value;
use strum_macros::{Display, EnumString};
use crate::filestore::{FileStore, ObjectListItem};

use crate::skate::{Distribution, exec_cmd, Platform};

use crate::skatelet::system::podman::PodmanSecret;
use crate::util::NamespacedName;


#[derive(Debug, Args)]
Expand Down Expand Up @@ -57,6 +61,7 @@ pub struct SystemInfo {
pub pods: Option<Vec<PodmanPodInfo>>,
pub ingresses: Option<Vec<ObjectListItem>>,
pub cronjobs: Option<Vec<ObjectListItem>>,
pub secrets: Option<Vec<ObjectListItem>>,
pub cpu_freq_mhz: u64,
pub cpu_usage: f32,
pub cpu_brand: String,
Expand Down Expand Up @@ -295,7 +300,7 @@ async fn info() -> Result<(), Box<dyn Error>> {
.with_memory(MemoryRefreshKind::everything())
);

let result = match exec_cmd(
let pod_list_result = match exec_cmd(
"sudo",
&["podman", "pod", "ps", "--filter", "label=skate.io/namespace", "--format", "json"],
) {
Expand All @@ -310,7 +315,7 @@ async fn info() -> Result<(), Box<dyn Error>> {
}
};

let podman_pod_info: Vec<PodmanPodInfo> = serde_json::from_str(&result).map_err(|e| anyhow!(e).context("failed to deserialize pod info"))?;
let podman_pod_info: Vec<PodmanPodInfo> = serde_json::from_str(&pod_list_result).map_err(|e| anyhow!(e).context("failed to deserialize pod info"))?;


let store = FileStore::new();
Expand All @@ -319,6 +324,48 @@ async fn info() -> Result<(), Box<dyn Error>> {
let cronjobs = store.list_objects("cronjob")?;


let secrets = exec_cmd("podman", &["secret", "ls", "--noheading"]).unwrap_or_else(|e| {
eprintln!("failed to list secrets: {}", e);
"".to_string()
});

let secret_names: Vec<&str> = secrets.split("\n").filter_map(|line| {
let parts: Vec<&str> = line.split_whitespace().collect();
if parts.len() < 5 {
return None;
}
let secret_name = parts[1];
match secret_name.rsplit_once(".") {
Some((_, _)) => Some(secret_name),
None => None,
}
}).collect();

let secret_json = exec_cmd("podman", &[vec!["secret", "inspect", "--showsecret"], secret_names].concat()).unwrap_or_else(|e| {
eprintln!("failed to get secret info: {}", e);
"[]".to_string()
});


let secret_info: Vec<PodmanSecret> = serde_json::from_str(&secret_json).map_err(|e| anyhow!(e).context("failed to deserialize secret info"))?;
let secret_info: Vec<ObjectListItem> = secret_info.iter().filter_map(|s| {

let yaml: Value = serde_yaml::from_str(&s.secret_data).unwrap();

let manifest_result: Result<Secret, _> = serde_yaml::from_value(yaml.clone());
if manifest_result.is_err() {
return None;
}

Some(ObjectListItem {
name: NamespacedName::from(s.spec.name.as_str()),
manifest_hash: "".to_string(), // TODO get from manifest
manifest: Some(yaml),
created_at: s.created_at,
})
}).collect();


let internal_ip_addr = internal_ip().unwrap_or_else(|e| {
eprintln!("failed to get interface ipv4 addresses: {}", e);
None
Expand Down Expand Up @@ -361,6 +408,10 @@ async fn info() -> Result<(), Box<dyn Error>> {
true => None,
false => Some(cronjobs),
},
secrets: match secrets.is_empty() {
true => None,
false => Some(secret_info),
},
hostname: sysinfo::System::host_name().unwrap_or("".to_string()),
internal_ip_address: internal_ip_addr,
};
Expand Down
29 changes: 29 additions & 0 deletions src/skatelet/system/podman.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
use std::collections::HashMap;
use chrono::{DateTime, Local};
use serde::{Deserialize, Serialize};

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub(crate) struct PodmanSecret {
#[serde(rename = "ID")]
pub id: String,
pub created_at: DateTime<Local>,
pub updated_at: DateTime<Local>,
pub spec: PodmanSecretSpec,
pub secret_data: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub(crate) struct PodmanSecretSpec {
pub name: String,
pub driver: PodmanSecretDriver,
pub labels: HashMap<String, String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub(crate) struct PodmanSecretDriver {
pub name: String,
pub options: HashMap<String, String>,
}

0 comments on commit f878700

Please sign in to comment.