Skip to content

Commit 701382d

Browse files
authored
fix(podman): wait for container stop completion (#2820)
* fix(podman): wait for container stop completion Signed-off-by: Piotr Mlocek <pmlocek@nvidia.com> * docs(podman): clarify stop restart race Signed-off-by: Piotr Mlocek <pmlocek@nvidia.com> --------- Signed-off-by: Piotr Mlocek <pmlocek@nvidia.com>
1 parent c90fd64 commit 701382d

3 files changed

Lines changed: 134 additions & 2 deletions

File tree

‎architecture/compute-runtimes.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -99,6 +99,10 @@ same resource. The gateway requires a fresh supervisor session before a
9999
starting sandbox returns to `Ready`; stale driver snapshots and supervisor
100100
sessions cannot promote a `Stopped` row.
101101

102+
A driver stop operation does not complete while its backend still reports an
103+
in-progress stop. This prevents an immediate start from racing the previous
104+
run's delayed exit event and regressing the new run to `Error`.
105+
102106
Persisted `Stopping` and `Starting` rows are retried at startup. Stable
103107
`Stopped` rows remain stopped. Docker and Podman retain the stopped container
104108
and attached storage, Kubernetes retains the Sandbox CR and PVC while scaling

‎crates/openshell-driver-podman/README.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,10 @@ volume. Stopped managed containers remain visible through list and watch
2828
reconciliation. Delete remains responsible for removing the container,
2929
driver-owned secrets, and workspace volume.
3030

31+
The stop call waits until Podman reports the container as stopped or exited.
32+
This keeps an immediate start from racing a rootless Podman stop that is still
33+
finishing after its API request returns.
34+
3135
## Architecture
3236

3337
The Podman driver communicates with the Podman daemon over a Unix socket and

‎crates/openshell-driver-podman/src/driver.rs‎

Lines changed: 126 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,9 @@ use std::time::Duration;
3636
use tracing::{debug, info, warn};
3737
use url::Url;
3838

39+
const STOP_COMPLETION_POLL_INTERVAL: Duration = Duration::from_millis(50);
40+
const STOP_COMPLETION_TIMEOUT_HEADROOM: Duration = Duration::from_secs(5);
41+
3942
impl From<PodmanApiError> for ComputeDriverError {
4043
fn from(value: PodmanApiError) -> Self {
4144
match value {
@@ -914,22 +917,65 @@ impl PodmanComputeDriver {
914917
Ok(entries.into_iter().next())
915918
}
916919

920+
async fn wait_for_container_stopped(
921+
&self,
922+
sandbox_id: &str,
923+
container_id: &str,
924+
) -> Result<(), ComputeDriverError> {
925+
let timeout = Duration::from_secs(u64::from(self.config.stop_timeout_secs))
926+
+ STOP_COMPLETION_TIMEOUT_HEADROOM;
927+
let deadline = tokio::time::Instant::now() + timeout;
928+
929+
loop {
930+
let inspect = self
931+
.client
932+
.inspect_container(container_id)
933+
.await
934+
.map_err(ComputeDriverError::from)?;
935+
if matches!(inspect.state.status.as_str(), "exited" | "stopped") {
936+
return Ok(());
937+
}
938+
939+
let now = tokio::time::Instant::now();
940+
if now >= deadline {
941+
return Err(ComputeDriverError::Message(format!(
942+
"container {container_id} for sandbox {sandbox_id} did not finish stopping within {timeout:?} (last state: {})",
943+
inspect.state.status,
944+
)));
945+
}
946+
tokio::time::sleep(STOP_COMPLETION_POLL_INTERVAL.min(deadline - now)).await;
947+
}
948+
}
949+
917950
/// Stop a sandbox container without deleting it.
918951
pub async fn stop_sandbox(&self, sandbox_id: &str) -> Result<(), ComputeDriverError> {
919952
let container = self
920953
.find_container(sandbox_id)
921954
.await?
922955
.ok_or(ComputeDriverError::NotFound)?;
956+
let container_id = container.id;
957+
if container.state == "stopping" {
958+
return self
959+
.wait_for_container_stopped(sandbox_id, &container_id)
960+
.await;
961+
}
923962
if container.state != "running" {
924963
return Ok(());
925964
}
926-
let container_id = container.id;
927965
info!(sandbox_id = %sandbox_id, container = %container_id, "Stopping sandbox container");
928966

929967
self.client
930968
.stop_container(&container_id, self.config.stop_timeout_secs)
931969
.await
932-
.map_err(ComputeDriverError::from)
970+
.map_err(ComputeDriverError::from)?;
971+
972+
// Podman can return from the stop request before inspect reports the
973+
// container as exited. If start runs during that interval, the exit
974+
// event from the previous run can arrive after the gateway has moved
975+
// the same sandbox to Starting, causing it to regress to Error. Wait
976+
// for the terminal container state before allowing a restart.
977+
self.wait_for_container_stopped(sandbox_id, &container_id)
978+
.await
933979
}
934980

935981
/// Start a previously stopped sandbox container.
@@ -1437,6 +1483,10 @@ mod tests {
14371483
vec![
14381484
StubResponse::new(StatusCode::OK, r#"[{"Id":"ctr-1","State":"running"}]"#),
14391485
StubResponse::new(StatusCode::NO_CONTENT, ""),
1486+
StubResponse::new(
1487+
StatusCode::OK,
1488+
r#"{"Id":"ctr-1","Name":"sandbox","State":{"Status":"exited","Running":false,"FinishedAt":"2026-08-12T16:39:13Z"},"Config":{}}"#,
1489+
),
14401490
],
14411491
);
14421492
test_driver(stop_socket.clone())
@@ -1453,6 +1503,12 @@ mod tests {
14531503
api_path("/libpod/containers/ctr-1/stop?timeout=10")
14541504
)
14551505
);
1506+
assert_eq!(
1507+
stop_requests
1508+
.lock()
1509+
.expect("request log lock should not be poisoned")[2],
1510+
format!("GET {}", api_path("/libpod/containers/ctr-1/json"))
1511+
);
14561512

14571513
let (start_socket, start_requests, start_handle) = spawn_podman_stub(
14581514
"lifecycle-start",
@@ -1487,6 +1543,74 @@ mod tests {
14871543
let _ = fs::remove_file(start_socket);
14881544
}
14891545

1546+
#[tokio::test]
1547+
async fn stop_waits_for_the_container_to_leave_stopping_state() {
1548+
let (socket, requests, handle) = spawn_podman_stub(
1549+
"lifecycle-stop-wait",
1550+
vec![
1551+
StubResponse::new(StatusCode::OK, r#"[{"Id":"ctr-1","State":"running"}]"#),
1552+
StubResponse::new(StatusCode::NO_CONTENT, ""),
1553+
StubResponse::new(
1554+
StatusCode::OK,
1555+
r#"{"Id":"ctr-1","Name":"sandbox","State":{"Status":"stopping","Running":true},"Config":{}}"#,
1556+
),
1557+
StubResponse::new(
1558+
StatusCode::OK,
1559+
r#"{"Id":"ctr-1","Name":"sandbox","State":{"Status":"exited","Running":false,"FinishedAt":"2026-08-12T16:39:13Z"},"Config":{}}"#,
1560+
),
1561+
],
1562+
);
1563+
1564+
test_driver(socket.clone())
1565+
.stop_sandbox("sandbox-1")
1566+
.await
1567+
.expect("stop should wait for the terminal container state");
1568+
handle.await.expect("stop stub should finish");
1569+
1570+
let requests = requests
1571+
.lock()
1572+
.expect("request log lock should not be poisoned");
1573+
assert_eq!(requests.len(), 4);
1574+
assert_eq!(
1575+
requests[2],
1576+
format!("GET {}", api_path("/libpod/containers/ctr-1/json"))
1577+
);
1578+
assert_eq!(requests[3], requests[2]);
1579+
1580+
let _ = fs::remove_file(socket);
1581+
}
1582+
1583+
#[tokio::test]
1584+
async fn stop_retry_waits_for_an_existing_stopping_container() {
1585+
let (socket, requests, handle) = spawn_podman_stub(
1586+
"lifecycle-stop-retry",
1587+
vec![
1588+
StubResponse::new(StatusCode::OK, r#"[{"Id":"ctr-1","State":"stopping"}]"#),
1589+
StubResponse::new(
1590+
StatusCode::OK,
1591+
r#"{"Id":"ctr-1","Name":"sandbox","State":{"Status":"exited","Running":false,"FinishedAt":"2026-08-12T16:39:13Z"},"Config":{}}"#,
1592+
),
1593+
],
1594+
);
1595+
1596+
test_driver(socket.clone())
1597+
.stop_sandbox("sandbox-1")
1598+
.await
1599+
.expect("stop retry should wait for the terminal container state");
1600+
handle.await.expect("stop retry stub should finish");
1601+
1602+
let requests = requests
1603+
.lock()
1604+
.expect("request log lock should not be poisoned");
1605+
assert_eq!(requests.len(), 2);
1606+
assert_eq!(
1607+
requests[1],
1608+
format!("GET {}", api_path("/libpod/containers/ctr-1/json"))
1609+
);
1610+
1611+
let _ = fs::remove_file(socket);
1612+
}
1613+
14901614
#[test]
14911615
fn validate_gpu_request_accepts_gpu_count_request_shape() {
14921616
let gpu = GpuResourceRequirements { count: Some(2) };

0 commit comments

Comments
 (0)