Skip to content

Commit

Permalink
Cleanup executor cmds
Browse files Browse the repository at this point in the history
  • Loading branch information
byrnedo committed Aug 10, 2024
1 parent bd3ee3d commit bebc7fa
Show file tree
Hide file tree
Showing 3 changed files with 72 additions and 45 deletions.
4 changes: 4 additions & 0 deletions src/delete.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@ pub enum DeleteCommands {
Ingress(DeleteResourceArgs),
Cronjob(DeleteResourceArgs),
Secret(DeleteResourceArgs),
Deployment(DeleteResourceArgs),
Daemonset(DeleteResourceArgs),
}

#[derive(Debug, Args)]
Expand All @@ -39,6 +41,8 @@ pub struct DeleteResourceArgs {
pub async fn delete(args: DeleteArgs) -> Result<(), Box<dyn Error>> {
match args.command {
DeleteCommands::Node(args) => delete_node(args).await?,
DeleteCommands::Daemonset(args) => delete_resource(ResourceType::DaemonSet, args).await?,
DeleteCommands::Deployment(args) => delete_resource(ResourceType::Deployment, args).await?,
DeleteCommands::Ingress(args) => delete_resource(ResourceType::Ingress, args).await?,
DeleteCommands::Cronjob(args) => delete_resource(ResourceType::CronJob, args).await?,
DeleteCommands::Secret(args) => delete_resource(ResourceType::Secret, args).await?,
Expand Down
73 changes: 29 additions & 44 deletions src/executor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ use std::process::Stdio;
use anyhow::anyhow;
use handlebars::Handlebars;
use itertools::Itertools;
use k8s_openapi::api::apps::v1::{DaemonSet, Deployment};
use k8s_openapi::api::batch::v1::CronJob;
use k8s_openapi::api::core::v1::{Pod, Secret};
use k8s_openapi::api::networking::v1::Ingress;
Expand Down Expand Up @@ -267,42 +268,33 @@ impl DefaultExecutor {
args.push("--network=podman")
}

let output = process::Command::new("podman")
.args(&args)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.output()
.expect(&format!("failed to apply resource via `podman {}`", &args.join(" ")));
let result = exec_cmd("podman", &args)?;

if !output.status.success() {
return Err(anyhow!("`podman {}` exited with code {}, stderr: {}", args.join(" "), output.status.code().unwrap(), String::from_utf8_lossy(&output.stderr).to_string()).into());
if !result.is_empty() {
println!("{}", result);
}


Ok(())
}

fn remove_secret(&self, secret: Secret) -> Result<(), Box<dyn Error>> {
let fqn = format!("{}.{}", secret.metadata.name.unwrap(), secret.metadata.namespace.unwrap());
let output = exec_cmd("podman", &["secret", "rm", &fqn])?;

let output = process::Command::new("podman")
.args(["secret", "rm", &fqn])
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.output()
.expect("failed to remove secret");

if !output.status.success() {
return Err(anyhow!("`podman secret rm {}` exited with code {}, stderr: {}", fqn, output.status.code().unwrap(), String::from_utf8_lossy(&output.stderr).trim().to_string()).into());
}

if !output.stdout.is_empty() {
println!("{}", String::from_utf8_lossy(&output.stdout).trim());
if !output.is_empty() {
println!("{}", output);
}

Ok(())
}

fn remove_deployment(&self, deployment: Deployment) -> Result<(), Box<dyn Error>> {
todo!("not implemented")
}

fn remove_daemonset(&self, daemonset: DaemonSet) -> Result<(), Box<dyn Error>> {
todo!("not implemented")
}

fn remove_pod(&self, id: &str, grace_period: Option<usize>) -> Result<(), Box<dyn Error>> {
if id.is_empty() {
return Err(anyhow!("no metadata.name found").into());
Expand All @@ -315,31 +307,24 @@ impl DefaultExecutor {
vec!("pod", "stop", "-t", &grace_str),
vec!(&id),
].concat();
let _output = process::Command::new("podman")
.args(stop_cmd.clone())
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.output()
.expect("failed to stop pod");

// if !output.status.success() {
// return Err(anyhow!("{:?} - exit code {}, stderr: {}", stop_cmd, output.status, String::from_utf8_lossy(&output.stderr).to_string()).into());
// }
let result = exec_cmd("podman", &stop_cmd);

if result.is_err() {
eprintln!("{}", result.unwrap_err());
}

let rm_cmd = [
vec!("pod", "rm", "--force"),
vec!(&id),
].concat();
let output = process::Command::new("podman")
.args(rm_cmd.clone())
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.output()
.expect("failed to remove pod");

if !output.status.success() {
return Err(anyhow!("{:?} - exit code {}, stderr: {}", rm_cmd, output.status, String::from_utf8_lossy(&output.stderr).to_string()).into());
let output = exec_cmd("podman", &rm_cmd)?;

if !output.is_empty() {
println!("{}", output);
}

Ok(())
}
}
Expand Down Expand Up @@ -368,11 +353,11 @@ impl Executor for DefaultExecutor {
let name = p.metadata.name.unwrap();
self.remove_pod(&name, grace_period)
}
SupportedResources::Deployment(_d) => {
Err(anyhow!("removing a deployment is not supported, instead supply it's individual pods").into())
SupportedResources::Deployment(d) => {
self.remove_deployment(d)
}
SupportedResources::DaemonSet(_) => {
Err(anyhow!("removing a daemonset is not supported, instead supply it's individual pods").into())
SupportedResources::DaemonSet(d) => {
self.remove_daemonset(d)
}
SupportedResources::Ingress(ingress) => {
self.remove_ingress(ingress)
Expand Down
40 changes: 39 additions & 1 deletion src/skatelet/delete.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@ pub enum DeleteResourceCommands {
Ingress(DeleteResourceArgs),
Cronjob(DeleteResourceArgs),
Secret(DeleteResourceArgs),
Deployment(DeleteResourceArgs),
Daemonset(DeleteResourceArgs),
}

#[derive(Debug, Args, Clone)]
Expand All @@ -45,6 +47,8 @@ pub fn delete(args: DeleteArgs) -> Result<(), Box<dyn Error>> {
DeleteResourceCommands::StdinCommand(_) => delete_stdin(args),
DeleteResourceCommands::Cronjob(resource_args) => delete_cronjob(args.clone(), resource_args.clone()),
DeleteResourceCommands::Secret(resource_args) => delete_secret(args.clone(), resource_args.clone()),
DeleteResourceCommands::Daemonset(resource_args) => delete_daemonset(args.clone(), resource_args.clone()),
DeleteResourceCommands::Deployment(resource_args) => delete_deployment(args.clone(), resource_args.clone()),
}
}

Expand Down Expand Up @@ -93,7 +97,7 @@ pub fn delete_secret(delete_args: DeleteArgs, resource_args: DeleteResourceArgs)
("skate.io/namespace".to_string(), resource_args.namespace),
]));

executor.manifest_delete(SupportedResources::Secret(Secret{
executor.manifest_delete(SupportedResources::Secret(Secret {
data: None,
immutable: None,
metadata: meta,
Expand All @@ -114,3 +118,37 @@ pub fn delete_stdin(args: DeleteArgs) -> Result<(), Box<dyn Error>> {
let object: SupportedResources = serde_yaml::from_str(&manifest).expect("failed to deserialize manifest");
executor.manifest_delete(object, args.termination_grace_period)
}

pub fn delete_deployment(delete_args: DeleteArgs, resource_args: DeleteResourceArgs) -> Result<(), Box<dyn Error>> {
let executor = DefaultExecutor::new();
let mut meta = ObjectMeta::default();
meta.name = Some(resource_args.name.clone());
meta.namespace = Some(resource_args.namespace.clone());
meta.labels = Some(BTreeMap::from([
("skate.io/name".to_string(), resource_args.name),
("skate.io/namespace".to_string(), resource_args.namespace),
]));

executor.manifest_delete(SupportedResources::Deployment(k8s_openapi::api::apps::v1::Deployment {
metadata: meta,
spec: None,
status: None,
}), delete_args.termination_grace_period)
}

pub fn delete_daemonset(delete_args: DeleteArgs, resource_args: DeleteResourceArgs) -> Result<(), Box<dyn Error>> {
let executor = DefaultExecutor::new();
let mut meta = ObjectMeta::default();
meta.name = Some(resource_args.name.clone());
meta.namespace = Some(resource_args.namespace.clone());
meta.labels = Some(BTreeMap::from([
("skate.io/name".to_string(), resource_args.name),
("skate.io/namespace".to_string(), resource_args.namespace),
]));

executor.manifest_delete(SupportedResources::DaemonSet(k8s_openapi::api::apps::v1::DaemonSet {
metadata: meta,
spec: None,
status: None,
}), delete_args.termination_grace_period)
}

0 comments on commit bebc7fa

Please sign in to comment.