Skip to main content

fakecloud_ecs/runtime/
task_lifecycle.rs

1//! `EcsRuntime` `task_lifecycle` family — extracted from service.rs by audit-2026-05-19.
2
3use super::*;
4
5impl EcsRuntime {
6    /// Spawn the task asynchronously. Returns immediately after transitioning
7    /// the task to `PENDING`; the background task advances it to `RUNNING`
8    /// once the container is created and to `STOPPED` once the container
9    /// exits.
10    pub fn run_task(self: Arc<Self>, state: SharedEcsState, task_id: String, account_id: String) {
11        let rt = self.clone();
12        tokio::spawn(async move {
13            if let Err(err) = rt.run_task_inner(&state, &task_id, &account_id).await {
14                tracing::warn!(%err, task = %task_id, "ecs task execution failed");
15                // Also surface on stderr so nextest's captured-output for a
16                // failed E2E shows the reason instead of just "empty logs".
17                eprintln!("[ecs] task {task_id} failed: {err}");
18                finalize_failure(&state, &account_id, &task_id, &err.to_string());
19                rt.emit_state_change(
20                    &state,
21                    &account_id,
22                    &task_id,
23                    "STOPPED",
24                    Some(("TaskFailedToStart", err.to_string())),
25                );
26            }
27        });
28    }
29
30    pub async fn run_task_inner(
31        &self,
32        state: &SharedEcsState,
33        task_id: &str,
34        account_id: &str,
35    ) -> Result<(), RuntimeError> {
36        if self.k8s.is_some() {
37            return self.k8s_run_task_inner(state, task_id, account_id).await;
38        }
39        // Build a per-container launch plan up-front so we hold the read
40        // lock once. Each entry carries everything needed to compose a
41        // `docker run` invocation for one container in the task.
42        let plans = build_container_plans(state, account_id, task_id, self.server_port)?;
43        if plans.is_empty() {
44            return Err(RuntimeError::ContainerStart(
45                "task has no containers".into(),
46            ));
47        }
48
49        // Resolve secrets for each plan. Failures fail the whole task to
50        // match real ECS's "failed to retrieve secret" behaviour — there's
51        // no point starting a sidecar when the app container will fail.
52        let mut resolved_plans: Vec<ResolvedContainerPlan> = Vec::with_capacity(plans.len());
53        for plan in plans {
54            let mut env = plan.env.clone();
55            for (name, value_from) in &plan.secrets_refs {
56                match self.resolve_secret(account_id, value_from) {
57                    Some(v) => env.push((name.clone(), v)),
58                    None => {
59                        return Err(RuntimeError::ContainerStart(format!(
60                            "failed to resolve secret {name} from {value_from}"
61                        )));
62                    }
63                }
64            }
65            // The agent/metadata endpoints live on fakecloud (the host);
66            // the container reaches them via the platform host alias —
67            // `host.docker.internal` for docker, `host.containers.internal`
68            // for podman (issue #1539).
69            let host_alias = &self.net.host_alias;
70            if plan.has_task_role {
71                env.push((
72                    "AWS_CONTAINER_CREDENTIALS_FULL_URI".into(),
73                    format!(
74                        "http://{host_alias}:{}/_fakecloud/ecs/creds/{}",
75                        self.server_port, task_id
76                    ),
77                ));
78            }
79            env.push((
80                "ECS_CONTAINER_METADATA_URI".into(),
81                format!(
82                    "http://{host_alias}:{}/_fakecloud/ecs/v3/{}",
83                    self.server_port, task_id
84                ),
85            ));
86            env.push((
87                "ECS_CONTAINER_METADATA_URI_V4".into(),
88                format!(
89                    "http://{host_alias}:{}/_fakecloud/ecs/v4/{}",
90                    self.server_port, task_id
91                ),
92            ));
93            resolved_plans.push(ResolvedContainerPlan { plan, env });
94        }
95
96        // Pull every distinct image up-front so a second container's pull
97        // failure surfaces before we leave the first container running.
98        mark_pull_started(state, account_id, task_id);
99        let mut run_images: Vec<String> = Vec::with_capacity(resolved_plans.len());
100        let mut image_digests: Vec<Option<String>> = Vec::with_capacity(resolved_plans.len());
101        for rp in &resolved_plans {
102            // Rewrite ECR URIs to fakecloud's local registry at the sibling
103            // host (`127.0.0.1` on the host, `host.docker.internal` when
104            // fakecloud is containerized) so the daemon/sibling can reach
105            // fakecloud's published registry port (issue #1539, bug 0.8).
106            let local_pull_uri = fakecloud_core::ecr_uri::translate_to_local_at(
107                &rp.plan.image,
108                &self.net.sibling_host,
109                self.server_port,
110            );
111            let pull_uri = local_pull_uri.as_deref().unwrap_or(&rp.plan.image);
112            let pull_out = self
113                .cli_command()
114                .args(["pull", pull_uri])
115                .output()
116                .await
117                .map_err(|e| RuntimeError::ImagePull(e.to_string()))?;
118            if !pull_out.status.success() {
119                let err = String::from_utf8_lossy(&pull_out.stderr).to_string();
120                return Err(RuntimeError::ImagePull(err));
121            }
122            // Retag the local pull URI to the AWS URI so `docker run` finds
123            // the image under the user-facing name. Digest-pinned refs
124            // can't be `docker tag` targets, so we fall through and run
125            // under the local URI in that case.
126            let run_image = if let Some(ref local_uri) = local_pull_uri {
127                if fakecloud_core::ecr_uri::is_digest_ref(&rp.plan.image) {
128                    local_uri.clone()
129                } else {
130                    let _ = self
131                        .cli_command()
132                        .args(["tag", local_uri, &rp.plan.image])
133                        .output()
134                        .await;
135                    rp.plan.image.clone()
136                }
137            } else {
138                rp.plan.image.clone()
139            };
140            // Best-effort image digest extraction so DescribeTasks emits
141            // the resolved digest the way real ECS does. Failures here
142            // (e.g. CLI without RepoDigests) are silent — digest stays
143            // `None` rather than failing the task.
144            let digest = self.lookup_image_digest(pull_uri).await;
145            run_images.push(run_image);
146            image_digests.push(digest);
147        }
148        mark_pull_stopped(state, account_id, task_id);
149
150        // For awsvpc network mode, create a per-task docker network so
151        // containers share an isolated bridge. Clean it up when the task
152        // stops. Network creation is best-effort: on failure we fall back
153        // to the default bridge and continue.
154        let awsvpc_network = resolved_plans
155            .iter()
156            .any(|rp| rp.plan.network_mode.as_deref() == Some("awsvpc"));
157        let network_name = format!("fakecloud-ecs-{}", task_id);
158        let network_created = if awsvpc_network {
159            let create = Command::new(&self.cli)
160                .args([
161                    "network",
162                    "create",
163                    "--driver",
164                    "bridge",
165                    "--label",
166                    &format!("fakecloud-ecs-task={}", task_id),
167                    &network_name,
168                ])
169                .output()
170                .await;
171            match create {
172                Ok(out) if out.status.success() => {
173                    tracing::info!(
174                        task = %task_id,
175                        network = %network_name,
176                        "created awsvpc docker network"
177                    );
178                    true
179                }
180                Ok(out) => {
181                    let err = String::from_utf8_lossy(&out.stderr);
182                    tracing::warn!(
183                        task = %task_id,
184                        network = %network_name,
185                        error = %err,
186                        "awsvpc network creation failed; falling back to default bridge"
187                    );
188                    false
189                }
190                Err(e) => {
191                    tracing::warn!(
192                        task = %task_id,
193                        network = %network_name,
194                        error = %e,
195                        "awsvpc network creation failed; falling back to default bridge"
196                    );
197                    false
198                }
199            }
200        } else {
201            false
202        };
203
204        if network_created {
205            let eni_id = format!(
206                "eni-{}",
207                uuid::Uuid::new_v4()
208                    .to_string()
209                    .replace('-', "")
210                    .get(..17)
211                    .unwrap_or("")
212            );
213            let mac = format!(
214                "02:{:02x}:{:02x}:{:02x}:{:02x}:{:02x}",
215                rand::random::<u8>(),
216                rand::random::<u8>(),
217                rand::random::<u8>(),
218                rand::random::<u8>(),
219                rand::random::<u8>()
220            );
221            let ip = format!("10.0.{}.{}", rand::random::<u8>(), rand::random::<u8>());
222            let mut accounts = state.write();
223            if let Some(st) = accounts.get_mut(account_id) {
224                if let Some(task) = st.tasks.get_mut(task_id) {
225                    task.attachments.push(crate::state::TaskAttachment {
226                        id: eni_id.clone(),
227                        attachment_type: "eni".into(),
228                        status: "ATTACHED".into(),
229                        details: vec![
230                            crate::state::AttachmentDetail {
231                                name: "subnetId".into(),
232                                value: "subnet-fakecloud".into(),
233                            },
234                            crate::state::AttachmentDetail {
235                                name: "privateIPv4Address".into(),
236                                value: ip.clone(),
237                            },
238                            crate::state::AttachmentDetail {
239                                name: "macAddress".into(),
240                                value: mac.clone(),
241                            },
242                        ],
243                    });
244                }
245            }
246            tracing::info!(
247                task = %task_id,
248                eni = %eni_id,
249                ip = %ip,
250                "populated awsvpc ENI attachment"
251            );
252        }
253
254        // Launch every container detached, in topological order. Before
255        // each `docker run` we honour the dependent's `dependsOn[]` by
256        // polling docker until each upstream container reaches the
257        // requested condition (START/COMPLETE/SUCCESS/HEALTHY). If any
258        // fails to start (or an upstream gate times out), kill the
259        // already-started containers and bail — partial-launch state is
260        // harder to reason about than a clean failure.
261        let mut started: Vec<RunningContainer> = Vec::with_capacity(resolved_plans.len());
262        for (idx, (rp, run_image)) in resolved_plans.iter().zip(run_images.iter()).enumerate() {
263            // Wait for every dependsOn[] entry on this container. Upstreams
264            // declared in the same task always show up earlier in the
265            // launch order thanks to topo_sort_plans, so we only ever look
266            // backwards into `started`.
267            for dep in &rp.plan.depends_on {
268                let upstream = match started.iter().find(|c| c.name == dep.container_name) {
269                    Some(u) => u,
270                    // Upstream not in this task definition (we ignored it
271                    // during topo-sort too). Skip the gate — this matches
272                    // the existing "ignore unknown dependency" behaviour.
273                    None => continue,
274                };
275                // Whether the upstream has a healthCheck configured —
276                // governs the HEALTHY shortcut: AWS treats HEALTHY as
277                // immediately satisfied when the upstream has no probe.
278                let upstream_has_health_check = resolved_plans
279                    .iter()
280                    .find(|p| p.plan.container_name == dep.container_name)
281                    .is_some_and(|p| p.plan.health_check.is_some());
282                if let Err(err) = self
283                    .wait_for_depends_on(upstream, dep.condition, upstream_has_health_check)
284                    .await
285                {
286                    self.cleanup_partial_start(&started, task_id);
287                    return Err(err);
288                }
289            }
290            let argv = build_run_argv(
291                &rp.plan,
292                &rp.env,
293                task_id,
294                &self.net.host_alias,
295                self.net.add_host_arg.as_deref(),
296                run_image,
297                network_created,
298            );
299            let mut cmd = Command::new(&self.cli);
300            cmd.args(&argv);
301            let run_out = cmd.output().await.map_err(|e| {
302                // Cleanup already-started containers on launch failure.
303                self.cleanup_partial_start(&started, task_id);
304                RuntimeError::ContainerStart(e.to_string())
305            })?;
306            if !run_out.status.success() {
307                let err = String::from_utf8_lossy(&run_out.stderr).to_string();
308                self.cleanup_partial_start(&started, task_id);
309                return Err(RuntimeError::ContainerStart(err));
310            }
311            let container_id = String::from_utf8_lossy(&run_out.stdout).trim().to_string();
312            started.push(RunningContainer {
313                name: rp.plan.container_name.clone(),
314                container_id,
315                essential: rp.plan.essential,
316                exit_code: None,
317                network_bindings: network_bindings_for(&rp.plan),
318                image_digest: image_digests.get(idx).cloned().unwrap_or(None),
319            });
320        }
321
322        // Stash all (name, container_id) pairs so StopTask/stop_all can
323        // reach every container backing this task.
324        {
325            let mut guard = self.containers.write();
326            guard.insert(
327                task_id.to_string(),
328                started
329                    .iter()
330                    .map(|c| (c.name.clone(), c.container_id.clone()))
331                    .collect(),
332            );
333        }
334        mark_running_multi(state, account_id, task_id, &started);
335        self.register_lb_targets(state, account_id, task_id);
336        self.emit_state_change(state, account_id, task_id, "RUNNING", None);
337
338        // Wait for the first essential container (or, if none are
339        // essential, any container) to exit. ECS task lifetime is
340        // bounded by the first essential exit, after which all remaining
341        // containers are stopped. While polling we also refresh each
342        // container's `healthStatus` from `docker inspect` so
343        // DescribeTasks reflects HEALTHCHECK transitions in near real
344        // time.
345        let wait_outcome = self
346            .wait_for_task_exit_with_health(state, account_id, task_id, &started)
347            .await?;
348
349        // Stop and reap any sidecars still running. Best-effort — failures
350        // here shouldn't keep the task from transitioning to STOPPED.
351        let mut final_containers = started.clone();
352        for (i, rc) in started.iter().enumerate() {
353            if Some(i) == wait_outcome.exited_index {
354                final_containers[i].exit_code = Some(wait_outcome.exit_code);
355                continue;
356            }
357            // Try to grab the exit code if the container already exited
358            // on its own (non-essential exits don't stop the task), then
359            // fall back to `docker stop` for stragglers.
360            let inspect = Command::new(&self.cli)
361                .args(["inspect", "-f", "{{.State.ExitCode}}", &rc.container_id])
362                .output()
363                .await;
364            let still_running = match inspect {
365                Ok(out) if out.status.success() => {
366                    let s = String::from_utf8_lossy(&out.stdout).trim().to_string();
367                    // `docker inspect` returns 0 for not-yet-exited
368                    // containers, so we additionally check `State.Running`.
369                    let running = Command::new(&self.cli)
370                        .args(["inspect", "-f", "{{.State.Running}}", &rc.container_id])
371                        .output()
372                        .await
373                        .map(|o| String::from_utf8_lossy(&o.stdout).trim() == "true")
374                        .unwrap_or(false);
375                    if !running {
376                        if let Ok(code) = s.parse::<i64>() {
377                            final_containers[i].exit_code = Some(code);
378                        }
379                    }
380                    running
381                }
382                _ => false,
383            };
384            if still_running {
385                let _ = Command::new(&self.cli)
386                    .args(["stop", "--time", "10", &rc.container_id])
387                    .output()
388                    .await;
389                let wait_out = Command::new(&self.cli)
390                    .args(["wait", &rc.container_id])
391                    .output()
392                    .await;
393                if let Ok(out) = wait_out {
394                    let code: i64 = String::from_utf8_lossy(&out.stdout)
395                        .trim()
396                        .parse()
397                        .unwrap_or(-1);
398                    final_containers[i].exit_code = Some(code);
399                }
400            }
401        }
402
403        // Capture combined stdout+stderr from every container so the
404        // introspection endpoint shows logs from sidecars too.
405        let mut captured = String::new();
406        for rc in &started {
407            let logs_out = Command::new(&self.cli)
408                .args(["logs", &rc.container_id])
409                .output()
410                .await
411                .map_err(|e| RuntimeError::Wait(e.to_string()))?;
412            captured.push_str(&format!("[{}] ", rc.name));
413            captured.push_str(&String::from_utf8_lossy(&logs_out.stdout));
414            captured.push_str(&String::from_utf8_lossy(&logs_out.stderr));
415        }
416
417        // Reap every container we own.
418        for rc in &started {
419            let _ = Command::new(&self.cli)
420                .args(["rm", "-f", &rc.container_id])
421                .output()
422                .await;
423        }
424        // Clean up the per-task docker network for awsvpc.
425        if network_created {
426            let _ = Command::new(&self.cli)
427                .args(["network", "rm", &network_name])
428                .output()
429                .await;
430        }
431        self.containers.write().remove(task_id);
432
433        // Forward logs BEFORE flipping the task to STOPPED so a client
434        // that polls DescribeTasks and immediately queries
435        // DescribeLogStreams can't observe the STOPPED transition before
436        // the awslogs group/stream has been materialised.
437        self.forward_awslogs_if_configured(state, account_id, task_id, &captured);
438        let exit_code = wait_outcome.exit_code;
439        finalize_stopped_multi(
440            state,
441            account_id,
442            task_id,
443            &final_containers,
444            exit_code,
445            &captured,
446            wait_outcome.stop_code,
447            None,
448        );
449        self.deregister_lb_targets(state, account_id, task_id);
450        self.emit_state_change(
451            state,
452            account_id,
453            task_id,
454            "STOPPED",
455            Some((wait_outcome.stop_code, format!("Exit code {}", exit_code))),
456        );
457        Ok(())
458    }
459
460    /// Wait for the task to reach a stop condition (any essential
461    /// container exits, or every container exits when none are
462    /// essential) while also polling `docker inspect .State.Health.Status`
463    /// on every iteration to push the latest `healthStatus` onto each
464    /// task container — so DescribeTasks shows live HEALTHCHECK
465    /// transitions instead of the boot-time `UNKNOWN`. Returns the
466    /// index into `started` of the container whose exit determined the
467    /// task lifetime, its exit code, and the stopCode.
468    pub(super) async fn wait_for_task_exit_with_health(
469        &self,
470        state: &SharedEcsState,
471        account_id: &str,
472        task_id: &str,
473        started: &[RunningContainer],
474    ) -> Result<TaskExitOutcome, RuntimeError> {
475        let any_essential = started.iter().any(|c| c.essential);
476        let mut working: Vec<RunningContainer> = started.to_vec();
477        let mut first_exited: Option<usize> = None;
478        loop {
479            // Refresh health status before checking exits so a container
480            // that goes UNHEALTHY -> exits in the same iteration leaves
481            // its final health state on the task before we transition to
482            // STOPPED.
483            self.refresh_health_status(state, account_id, task_id, started)
484                .await;
485            for (i, rc) in started.iter().enumerate() {
486                if working[i].exit_code.is_some() {
487                    continue;
488                }
489                let inspect = Command::new(&self.cli)
490                    .args(["inspect", "-f", "{{.State.Running}}", &rc.container_id])
491                    .output()
492                    .await;
493                let running = match inspect {
494                    Ok(out) if out.status.success() => {
495                        String::from_utf8_lossy(&out.stdout).trim() == "true"
496                    }
497                    _ => false,
498                };
499                if running {
500                    continue;
501                }
502                let wait_out = Command::new(&self.cli)
503                    .args(["wait", &rc.container_id])
504                    .output()
505                    .await
506                    .map_err(|e| RuntimeError::Wait(e.to_string()))?;
507                if !wait_out.status.success() {
508                    let err = String::from_utf8_lossy(&wait_out.stderr).to_string();
509                    return Err(RuntimeError::Wait(err));
510                }
511                let exit_code: i64 = String::from_utf8_lossy(&wait_out.stdout)
512                    .trim()
513                    .parse()
514                    .unwrap_or(-1);
515                working[i].exit_code = Some(exit_code);
516                if first_exited.is_none() && (rc.essential || !any_essential) {
517                    first_exited = Some(i);
518                }
519            }
520            if task_should_stop(&working) {
521                let idx = first_exited
522                    .or_else(|| working.iter().position(|c| c.exit_code.is_some()))
523                    .unwrap_or(0);
524                let exit_code = working[idx].exit_code.unwrap_or(-1);
525                return Ok(TaskExitOutcome {
526                    exited_index: Some(idx),
527                    exit_code,
528                    stop_code: if any_essential {
529                        "EssentialContainerExited"
530                    } else {
531                        "TaskCompleted"
532                    },
533                });
534            }
535            sleep(Duration::from_millis(200)).await;
536        }
537    }
538
539    /// Block the launch of a dependent container until its upstream
540    /// reaches the requested `dependsOn[].condition`. We poll
541    /// `docker inspect` at a small interval; the wait is bounded by an
542    /// AWS-style timeout (120s by default — long enough for image
543    /// startup but short enough to surface bugs as a clean
544    /// `ContainerStart` failure).
545    ///
546    /// `upstream_has_health_check` is needed for the `HEALTHY` branch:
547    /// when the upstream has no healthCheck, AWS treats `HEALTHY` as
548    /// immediately satisfied (otherwise the dependent would block
549    /// forever, since docker reports `Health.Status` only when the
550    /// container has a HEALTHCHECK directive).
551    pub(super) async fn wait_for_depends_on(
552        &self,
553        upstream: &RunningContainer,
554        condition: DependsOnCondition,
555        upstream_has_health_check: bool,
556    ) -> Result<(), RuntimeError> {
557        // Bounded wait — chosen to comfortably cover slow init scripts
558        // without letting a wedged dependency stall a task indefinitely.
559        const WAIT_TIMEOUT: Duration = Duration::from_secs(120);
560        const POLL_INTERVAL: Duration = Duration::from_millis(200);
561
562        // HEALTHY against an upstream without a healthCheck: AWS treats
563        // this as immediately satisfied because there's no probe to
564        // observe. Skip the polling loop entirely so the dependent isn't
565        // wedged forever waiting for a status that docker will never set.
566        if matches!(condition, DependsOnCondition::Healthy) && !upstream_has_health_check {
567            return Ok(());
568        }
569
570        let deadline = std::time::Instant::now() + WAIT_TIMEOUT;
571        loop {
572            let inspect = inspect_container_state(&self.cli, &upstream.container_id).await;
573            if let Some(state) = inspect {
574                if condition_is_met(condition, &state) {
575                    return Ok(());
576                }
577                // SUCCESS specifically: if the container exited with a
578                // non-zero code, the gate can never be satisfied. Bail
579                // immediately rather than waiting for the timeout — this
580                // matches ECS's "stoppedReason: dependency failed" path.
581                if matches!(condition, DependsOnCondition::Success)
582                    && state.exited
583                    && state.exit_code != 0
584                {
585                    return Err(RuntimeError::ContainerStart(format!(
586                        "dependency on container {} ({}) failed: upstream exited with code {}",
587                        upstream.name,
588                        DependsOnCondition::Success.as_aws_str(),
589                        state.exit_code,
590                    )));
591                }
592            }
593            if std::time::Instant::now() >= deadline {
594                return Err(RuntimeError::ContainerStart(format!(
595                    "timed out waiting for container {} to reach condition {}",
596                    upstream.name,
597                    condition.as_aws_str(),
598                )));
599            }
600            tokio::time::sleep(POLL_INTERVAL).await;
601        }
602    }
603
604    /// Best-effort cleanup of containers we already started when a later
605    /// container in the task failed to launch. Without this, half-launched
606    /// tasks leak docker containers. `task_id` mirrors the value used at
607    /// network creation so `network rm` targets the right name —
608    /// deriving it from a container_id prefix was wrong (container ids
609    /// are docker-assigned, not task-shaped).
610    pub(super) fn cleanup_partial_start(&self, started: &[RunningContainer], task_id: &str) {
611        let cli = self.cli.clone();
612        let ids: Vec<String> = started.iter().map(|c| c.container_id.clone()).collect();
613        let network = format!("fakecloud-ecs-{task_id}");
614        tokio::spawn(async move {
615            for id in ids {
616                let _ = Command::new(&cli).args(["rm", "-f", &id]).output().await;
617            }
618            let _ = Command::new(&cli)
619                .args(["network", "rm", &network])
620                .output()
621                .await;
622        });
623    }
624
625    /// Kill every container behind a task with the configured stop
626    /// timeout. Returns true if at least one container was killed. Called
627    /// synchronously from `StopTask`; the wait loop in `run_task_inner`
628    /// observes the exits and transitions the task to `STOPPED`.
629    pub async fn stop_task(&self, task_id: &str, reason: &str) -> bool {
630        if let Some(k) = &self.k8s {
631            tracing::info!(task = %task_id, reason = %reason, "ecs task stop requested (k8s)");
632            return k.stop_task(task_id).await;
633        }
634        let containers = self.containers.read().get(task_id).cloned();
635        let Some(list) = containers else {
636            return false;
637        };
638        if list.is_empty() {
639            return false;
640        }
641        // `docker stop` sends SIGTERM then SIGKILL after a timeout.
642        for (_name, id) in &list {
643            let _ = Command::new(&self.cli)
644                .args(["stop", "--time", "10", id])
645                .output()
646                .await;
647        }
648        tracing::info!(task = %task_id, reason = %reason, "ecs task stop requested");
649        true
650    }
651
652    /// Kill every running container the runtime owns. Called on reset /
653    /// shutdown so docker state matches fakecloud state after a fresh
654    /// boot.
655    pub async fn stop_all(&self) {
656        if let Some(k) = &self.k8s {
657            k.stop_all().await;
658            return;
659        }
660        let ids: Vec<String> = self
661            .containers
662            .read()
663            .values()
664            .flat_map(|list| list.iter().map(|(_, id)| id.clone()))
665            .collect();
666        for id in ids {
667            let _ = Command::new(&self.cli).args(["kill", &id]).output().await;
668            let _ = Command::new(&self.cli).args(["rm", &id]).output().await;
669        }
670        self.containers.write().clear();
671    }
672}