1 // Copyright (c) 2024 Huawei Technologies Co.,Ltd. All rights reserved.
2 //
3 // StratoVirt is licensed under Mulan PSL v2.
4 // You can use this software according to the terms and conditions of the Mulan
5 // PSL v2.
6 // You may obtain a copy of Mulan PSL v2 at:
7 //         http://license.coscl.org.cn/MulanPSL2
8 // THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY
9 // KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
10 // NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
11 // See the Mulan PSL v2 for more details.
12 
13 use std::{fs, path::Path};
14 
15 use anyhow::{bail, Result};
16 use clap::{builder::NonEmptyStringValueParser, Parser};
17 
18 use crate::{
19     container::{Container, State},
20     linux::LinuxContainer,
21 };
22 
23 /// Release container resources after the container process has exited
24 #[derive(Debug, Parser)]
25 pub struct Delete {
26     /// Specify the container id
27     #[arg(value_parser = NonEmptyStringValueParser::new(), required = true)]
28     pub container_id: String,
29     /// Force to delete the container (kill the container using SIGKILL)
30     #[arg(short, long)]
31     pub force: bool,
32 }
33 
34 impl Delete {
run(&self, root: &Path) -> Result<()>35     pub fn run(&self, root: &Path) -> Result<()> {
36         let state_dir = root.join(&self.container_id);
37         if !state_dir.exists() {
38             bail!("{} doesn't exist", state_dir.display());
39         }
40 
41         let state = if let Ok(s) = State::load(root, &self.container_id) {
42             s
43         } else {
44             fs::remove_dir_all(state_dir)?;
45             return Ok(());
46         };
47 
48         let container = LinuxContainer::load_from_state(&state, &None)?;
49         container.delete(&state, self.force)?;
50         Ok(())
51     }
52 }
53