Skip to content

Commit daecb45

Browse files
committed
Gracefully shut down containers on Ctrl+C
1 parent e13c53a commit daecb45

File tree

2 files changed

+20
-7
lines changed

2 files changed

+20
-7
lines changed

Cargo.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ libc = "0.2.80"
1313
tempfile = "3.1.0"
1414
serde = { version = "1.0", features = ["derive"] }
1515
serde_json = "1.0"
16-
tokio = { version = "0.3", features = ["fs", "macros", "net", "process", "io-util", "rt-multi-thread", "time"] }
16+
tokio = { version = "0.3", features = ["fs", "macros", "net", "process", "io-util", "rt-multi-thread", "signal", "time"] }
1717
tokio-seqpacket = "0.3"
1818
uuid = { version = "0.8.1", features = ["v4"] }
1919
warp = "0.2.5"

src/main.rs

Lines changed: 19 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,8 @@
1+
use std::sync::Arc;
2+
3+
use anyhow::anyhow;
14
use dashmap::DashMap;
5+
use fallible_collections::FallibleArc;
26

37
use self::container::Container;
48
use self::image::OciImage;
@@ -9,14 +13,23 @@ mod pipe;
913

1014
#[derive(Debug)]
1115
pub struct Engine {
12-
containers: DashMap<String, Container>,
16+
containers: Arc<DashMap<String, Container>>,
1317
}
1418

1519
impl Engine {
16-
pub fn new() -> Self {
17-
Engine {
18-
containers: DashMap::new(),
19-
}
20+
pub async fn new() -> anyhow::Result<Self> {
21+
let containers = Arc::try_new(DashMap::new()).map_err(|e| anyhow!("OOM error: {:?}", e))?;
22+
let running = containers.clone();
23+
24+
// TODO: Find a way to avoid using `tokio::spawn()` and convert to `join!()` instead.
25+
tokio::spawn(async move {
26+
if let Ok(_) = tokio::signal::ctrl_c().await {
27+
running.clear();
28+
std::process::exit(130);
29+
}
30+
});
31+
32+
Ok(Engine { containers })
2033
}
2134

2235
pub async fn fetch(&mut self, container_name: &str) -> anyhow::Result<()> {
@@ -34,7 +47,7 @@ impl Engine {
3447
#[tokio::main]
3548
async fn main() -> anyhow::Result<()> {
3649
// TODO: Use `warp` to host REST endpoints.
37-
let mut engine = Engine::new();
50+
let mut engine = Engine::new().await?;
3851
engine.fetch("busybox").await?;
3952
tokio::time::sleep(std::time::Duration::from_secs(1000)).await;
4053
Ok(())

0 commit comments

Comments
 (0)