1use std::fs;
23use std::io::Write;
24use std::path::PathBuf;
25
26use chrono::{SecondsFormat, Utc};
27use serde_json::{json, Value};
28
29use crate::cgroup_memory::{
30 cgroup_shell_vars, format_cgroup_memory_log_line, parse_cgroup_memory_sample,
31};
32use crate::detached_finalize::{normalize_bool, normalize_container_error};
33use crate::docker_cleanup::{
34 docker_command, get_docker_container_cleanup_policy,
35 start_detached_docker_completion_watcher_with, DockerWatcherOptions,
36};
37use crate::docker_post_mortem::{
38 format_container_post_mortem, normalize_docker_timestamp, shell_vars, ContainerPostMortem,
39};
40use crate::docker_resource_limits::{
41 build_resource_limits_status_line, read_docker_resource_limits,
42};
43use crate::execution_control::{CommandRunOutput, CommandRunner, SystemCommandRunner};
44use crate::execution_resume::build_launch_options;
45use crate::execution_store::{
46 ExecutionRecord, ExecutionStatus, ExecutionStore, ExecutionStoreOptions,
47};
48use crate::exit_reason::describe_exit_code_str;
49use crate::isolation::isolation_log::shell_quote;
50use crate::recovery_delay::{
51 format_recovery_delay, pick_recovery_delay_ms, record_on_kill_resume_delay, system_random,
52 system_sleep, wait_for_recovery_delay,
53};
54
55pub const INTERNAL_RECOVER_FLAG: &str = "--internal-recover-detached-docker";
57
58pub const RECOVERY_MARKER_PATH: &str = "/.start-command-recovery";
60
61pub const RECOVERY_ATTEMPT_ENV: &str = "START_COMMAND_RECOVERY_ATTEMPT";
63
64pub const KILLED_EXIT_CODE: i32 = 137;
66
67pub fn recovery_selector() -> String {
70 format!(
71 "s=$1; f=$2; r=$3; shift 3; if [ -e {marker} ]; then {env}=$(cat {marker} 2>/dev/null); export {env}; if [ -n \"$f\" ]; then exec \"$s\" \"$f\" -c \"$r\"; fi; exec \"$s\" -c \"$r\"; fi; exec \"$@\"",
72 marker = RECOVERY_MARKER_PATH,
73 env = RECOVERY_ATTEMPT_ENV
74 )
75}
76
77pub fn build_recovery_selector_args(
80 main_args: &[String],
81 shell: &str,
82 shell_flag: Option<&str>,
83 recovery_command: &str,
84) -> Vec<String> {
85 let mut args = vec![
86 "sh".to_string(),
87 "-c".to_string(),
88 recovery_selector(),
89 "start-command".to_string(),
90 if shell.is_empty() { "sh" } else { shell }.to_string(),
91 shell_flag.unwrap_or("").to_string(),
92 recovery_command.to_string(),
93 ];
94 args.extend(main_args.iter().cloned());
95 args
96}
97
98pub fn is_killed_exit(exit_code: &str, oom_killed: &str) -> bool {
108 let code = describe_exit_code_str(exit_code).code;
109 if code == Some(KILLED_EXIT_CODE) {
110 return true;
111 }
112 normalize_bool(oom_killed) == Some(true) && code.is_none_or(|code| code < 0)
113}
114
115pub fn build_recovery_snippet(execution_id: &str) -> String {
119 let executable = std::env::current_exe()
120 .map(|path| path.to_string_lossy().to_string())
121 .unwrap_or_else(|_| "start".to_string());
122 format!(
123 "{{ [ \"${exit}\" = {code} ] || {{ [ \"${oom}\" = true ] && ! [ \"${exit}\" -ge 0 ] 2>/dev/null; }}; }} && {exe} {flag} {id} \"${exit}\" \"${oom}\" \"${started}\" \"${finished}\" \"${error}\" \"${cgroup}\" >/dev/null 2>&1",
124 exit = shell_vars::EXIT,
125 oom = shell_vars::OOM,
126 started = shell_vars::STARTED,
127 finished = shell_vars::FINISHED,
128 error = shell_vars::ERROR,
129 cgroup = cgroup_shell_vars::SAMPLE,
130 code = KILLED_EXIT_CODE,
131 exe = shell_quote(&executable),
132 flag = INTERNAL_RECOVER_FLAG,
133 id = shell_quote(execution_id),
134 )
135}
136
137pub struct RecoverySeparator<'a> {
139 pub attempt: u64,
140 pub max_attempts: u64,
141 pub exit_code: &'a str,
142 pub oom_killed: &'a str,
143 pub container_name: &'a str,
144 pub command: Option<&'a str>,
145 pub delay_ms: u64,
147}
148
149pub fn format_recovery_separator(params: &RecoverySeparator) -> String {
151 let described = describe_exit_code_str(params.exit_code);
152 let code = described
153 .code
154 .map(|code| code.to_string())
155 .unwrap_or_else(|| "unknown".to_string());
156 let signal = described
157 .signal
158 .map(|name| format!(", {}", name))
159 .unwrap_or_default();
160 let what = match params.command {
161 Some(command) => format!("running recovery command: {}", command),
162 None => "running the original command again".to_string(),
163 };
164 let delay = if params.delay_ms > 0 {
165 format!(" after a {} delay", format_recovery_delay(params.delay_ms))
166 } else {
167 String::new()
168 };
169 format!(
170 "\n[Recovery {}/{}] Main process was killed (exit {}{}, oomKilled={}); resuming container {}{}, {}\n",
171 params.attempt,
172 params.max_attempts,
173 code,
174 signal,
175 normalize_bool(params.oom_killed) == Some(true),
176 params.container_name,
177 delay,
178 what
179 )
180}
181
182#[derive(Debug, Clone, Default)]
184pub struct RecoveryFacts {
185 pub exit_code: String,
186 pub oom_killed: String,
187 pub started_at: String,
188 pub finished_at: String,
189 pub container_error: String,
190 pub cgroup_memory: String,
192}
193
194#[derive(Debug, Clone, PartialEq, Eq)]
197pub struct RecoveryOutcome {
198 pub recovered: bool,
199 pub reason: String,
200 pub attempt: Option<u64>,
201 pub delay_ms: Option<u64>,
203}
204
205impl RecoveryOutcome {
206 fn not(reason: &str) -> Self {
207 RecoveryOutcome {
208 recovered: false,
209 reason: reason.to_string(),
210 attempt: None,
211 delay_ms: None,
212 }
213 }
214}
215
216pub struct RecoveryDelayHooks<'a> {
219 pub random: &'a dyn Fn() -> f64,
220 pub sleep: &'a dyn Fn(u64),
221}
222
223impl Default for RecoveryDelayHooks<'_> {
224 fn default() -> Self {
225 RecoveryDelayHooks {
226 random: &system_random,
227 sleep: &system_sleep,
228 }
229 }
230}
231
232fn is_stop_requested(store: &ExecutionStore, execution_id: &str) -> bool {
233 store
234 .get(execution_id)
235 .is_some_and(|record| option_str(&record, "stopRequestedAt").is_some())
236}
237
238pub type WatcherStarter<'a> = &'a dyn Fn(&str, &ExecutionRecord, &DockerWatcherOptions);
240
241fn append_to_log(log_path: &str, text: &str) {
242 if log_path.is_empty() {
243 return;
244 }
245 if let Ok(mut file) = fs::OpenOptions::new()
247 .create(true)
248 .append(true)
249 .open(log_path)
250 {
251 let _ = file.write_all(text.as_bytes());
252 }
253}
254
255fn failure_detail(result: &CommandRunOutput) -> String {
256 let stderr = result.stderr.trim();
257 if !stderr.is_empty() {
258 return stderr.to_string();
259 }
260 result.error.clone().unwrap_or_else(|| {
261 format!(
262 "exit code {}",
263 result
264 .status
265 .map(|code| code.to_string())
266 .unwrap_or_else(|| "unknown".to_string())
267 )
268 })
269}
270
271fn write_recovery_marker<R: CommandRunner + ?Sized>(
272 container_name: &str,
273 attempt: u64,
274 runner: &R,
275) -> CommandRunOutput {
276 let dir = std::env::temp_dir().join(format!("start-recovery-{}", uuid::Uuid::new_v4()));
277 let file = dir.join("marker");
278 let written = fs::create_dir_all(&dir).and_then(|_| fs::write(&file, format!("{}\n", attempt)));
279 #[cfg(unix)]
280 {
281 use std::os::unix::fs::PermissionsExt;
282 let _ = fs::set_permissions(&file, fs::Permissions::from_mode(0o644));
283 }
284 let result = match written {
285 Ok(()) => runner.run(
286 &docker_command().to_string_lossy(),
287 &[
288 "cp".to_string(),
289 file.to_string_lossy().to_string(),
290 format!("{}:{}", container_name, RECOVERY_MARKER_PATH),
291 ],
292 ),
293 Err(err) => CommandRunOutput {
294 success: false,
295 error: Some(err.to_string()),
296 ..CommandRunOutput::default()
297 },
298 };
299 let _ = fs::remove_dir_all(&dir);
300 result
301}
302
303fn option_u64(record: &ExecutionRecord, key: &str) -> u64 {
304 match record.options.get(key) {
305 Some(Value::Number(n)) => n.as_u64().unwrap_or(0),
306 Some(Value::String(s)) => s.trim().parse().unwrap_or(0),
307 _ => 0,
308 }
309}
310
311fn option_str<'a>(record: &'a ExecutionRecord, key: &str) -> Option<&'a str> {
312 record
313 .options
314 .get(key)
315 .and_then(Value::as_str)
316 .filter(|value| !value.is_empty())
317}
318
319pub fn recover_killed_execution<R: CommandRunner + ?Sized>(
321 store: &ExecutionStore,
322 execution_id: &str,
323 facts: &RecoveryFacts,
324 runner: &R,
325 start_watcher: WatcherStarter,
326) -> RecoveryOutcome {
327 recover_killed_execution_with_delay(
328 store,
329 execution_id,
330 facts,
331 runner,
332 start_watcher,
333 &RecoveryDelayHooks::default(),
334 )
335}
336
337pub fn recover_killed_execution_with_delay<R: CommandRunner + ?Sized>(
340 store: &ExecutionStore,
341 execution_id: &str,
342 facts: &RecoveryFacts,
343 runner: &R,
344 start_watcher: WatcherStarter,
345 delay: &RecoveryDelayHooks,
346) -> RecoveryOutcome {
347 if execution_id.is_empty() {
348 return RecoveryOutcome::not("missing-arguments");
349 }
350 let Some(mut record) = store.get(execution_id) else {
351 return RecoveryOutcome::not("record-not-found");
352 };
353 let max_attempts = option_u64(&record, "onKillResume");
354 let container_name = option_str(&record, "sessionName").map(str::to_string);
355 let Some(container_name) = container_name
356 .filter(|_| option_str(&record, "isolated") == Some("docker") && max_attempts >= 1)
357 else {
358 return RecoveryOutcome::not("not-configured");
359 };
360 if !is_killed_exit(&facts.exit_code, &facts.oom_killed) {
361 return RecoveryOutcome::not("not-killed");
362 }
363 let log_path = record.log_path.clone();
364 let log = |text: &str| append_to_log(&log_path, text);
365 if option_str(&record, "stopRequestedAt").is_some() {
366 log("\n[Recovery] Not resuming: the session was stopped on request.\n");
367 return RecoveryOutcome::not("stop-requested");
368 }
369 let used = option_u64(&record, "recoveryAttempts");
370 if used >= max_attempts {
371 log(&format!(
372 "\n[Recovery] Not resuming: all {} recovery attempt(s) used.\n",
373 max_attempts
374 ));
375 return RecoveryOutcome::not("attempts-exhausted");
376 }
377
378 let attempt = used + 1;
379 let delay_range = record_on_kill_resume_delay(record.options.get("onKillResumeDelay"));
380 let delay_ms = pick_recovery_delay_ms(delay_range.as_deref(), delay.random);
381 let give_up = |reason: String| {
382 log(&format!(
383 "[Recovery {}/{}] Failed: {}\n",
384 attempt, max_attempts, reason
385 ));
386 RecoveryOutcome {
387 recovered: false,
388 reason: "resume-failed".to_string(),
389 attempt: Some(attempt),
390 delay_ms: None,
391 }
392 };
393
394 let oom_killed = normalize_bool(&facts.oom_killed);
395 log(&format!(
396 "\n{}",
397 format_container_post_mortem(&ContainerPostMortem {
398 container_name: container_name.clone(),
399 exit_code: describe_exit_code_str(&facts.exit_code).code,
400 oom_killed,
401 started_at: Some(facts.started_at.clone()),
402 finished_at: Some(facts.finished_at.clone()),
403 error: normalize_container_error(&facts.container_error),
404 })
405 ));
406 let memory_line = format_cgroup_memory_log_line(&facts.cgroup_memory).unwrap_or_else(|| {
407 let limit = runner.run(&docker_command().to_string_lossy(), &["inspect".into(),"-f".into(),"{{.HostConfig.Memory}}".into(),container_name.clone()]);
408 format!("Memory: unavailable (local cgroup hidden; remote sampling requires private cgroup namespace and sh) memory.limit={} (HostConfig)", if limit.success {limit.stdout.trim()} else {"unknown"})
409 });
410 log(&format!("{}\n", memory_line));
411 let recovery_command = option_str(&record, "recoveryCommand").map(str::to_string);
412 log(&format_recovery_separator(&RecoverySeparator {
413 attempt,
414 max_attempts,
415 exit_code: &facts.exit_code,
416 oom_killed: &facts.oom_killed,
417 container_name: &container_name,
418 command: recovery_command.as_deref(),
419 delay_ms,
420 }));
421
422 if delay_ms > 0
427 && wait_for_recovery_delay(delay_ms, delay.sleep, &|| {
428 is_stop_requested(store, execution_id)
429 })
430 {
431 log(&format!(
432 "[Recovery {}/{}] Not resuming: the session was stopped on request during the delay.\n",
433 attempt, max_attempts
434 ));
435 return RecoveryOutcome {
436 recovered: false,
437 reason: "stop-requested".to_string(),
438 attempt: Some(attempt),
439 delay_ms: Some(delay_ms),
440 };
441 }
442
443 let mut resource_limits = crate::resume_resources::restore_base_cpu(
447 read_docker_resource_limits(&container_name, runner).unwrap_or_else(|| {
448 crate::docker_resource_limits::normalize_resource_limits(
449 record.options.get("resourceLimits"),
450 )
451 }),
452 &record,
453 );
454 if record.options.contains_key("cpuPenaltyConfig") {
455 resource_limits =
456 match crate::resume_resources::clamp_cpu_to_daemon(resource_limits, runner) {
457 Ok(limits) => limits,
458 Err(error) => return give_up(error),
459 };
460 }
461 let tail = crate::execution_attempt::read_attempt_log_tail(
462 &record,
463 crate::isolation::isolation_log::FATAL_MARKER_TAIL_BYTES,
464 );
465 let (_, daemon_restart) = crate::exit_evidence::from_log(tail.as_deref());
466 let terminal_oom = !daemon_restart
467 && facts.oom_killed == "true"
468 && crate::exit_evidence::recent_oom_delta(&facts.cgroup_memory, &facts.finished_at);
469 let memory_spec = option_str(&record, "onKillResumeMemory").map(str::to_string);
470 let recovery_limits = if terminal_oom {
471 memory_spec.as_ref().map(|spec| {
472 crate::docker_resource_options::resolve(
473 &json!({"memory":spec}),
474 &resource_limits,
475 runner,
476 crate::docker_resource_options::random_fraction,
477 )
478 })
479 } else {
480 None
481 };
482 let resolved = match recovery_limits {
483 Some(Ok((limits, values))) => {
484 log(&format!(
485 "Recovery memory limit: {} -> {} ({})\n",
486 resource_limits
487 .iter()
488 .find(|s| s.starts_with("--memory="))
489 .map(String::as_str)
490 .unwrap_or("unlimited"),
491 values["memory"],
492 memory_spec.as_deref().unwrap_or("")
493 ));
494 resource_limits = limits;
495 Some(values)
496 }
497 Some(Err(error)) => return give_up(format!("recovery limit failed: {}", error)),
498 None => None,
499 };
500 if let Some(line) = build_resource_limits_status_line(&resource_limits) {
501 log(&format!("{}\n", line));
502 }
503
504 if recovery_command.is_some() {
505 let copied = if record
506 .options
507 .get("commandHandoff")
508 .and_then(Value::as_bool)
509 == Some(true)
510 {
511 crate::docker_command_handoff::write_command_handoff(
512 &container_name,
513 &format!(
514 "export {}={}; {}",
515 RECOVERY_ATTEMPT_ENV,
516 attempt,
517 recovery_command.as_deref().unwrap()
518 ),
519 option_str(&record, "shell").unwrap_or("auto"),
520 record.options.get("keepAlive").and_then(Value::as_bool) == Some(true),
521 runner,
522 )
523 .unwrap_or_else(|error| CommandRunOutput {
524 error: Some(error),
525 ..Default::default()
526 })
527 } else {
528 write_recovery_marker(&container_name, attempt, runner)
529 };
530 if !copied.success {
531 return give_up(format!(
532 "could not mark the container: {}",
533 failure_detail(&copied)
534 ));
535 }
536 }
537
538 let since = Utc::now().to_rfc3339_opts(SecondsFormat::Millis, true);
539 let mut next_attempt = record.attempt.as_ref().map(|_| {
540 crate::execution_attempt::create_attempt(&record, "automatic-recovery", &container_name)
541 });
542 if let Some(attempt) = next_attempt.as_mut() {
543 attempt.started_at = since.clone();
544 let mut lifecycle = record.clone();
545 lifecycle.attempt = Some(attempt.clone());
546 crate::execution_attempt::append_lifecycle(&lifecycle, "resume-started", json!({}));
547 }
548 let described = describe_exit_code_str(&facts.exit_code);
549 if let Some(attempt) = next_attempt.as_mut() {
550 record.status = ExecutionStatus::Executed;
551 record.exit_code = described.code;
552 record.end_time = normalize_docker_timestamp(Some(&facts.finished_at));
553 record.container_started_at = normalize_docker_timestamp(Some(&facts.started_at));
554 record.oom_killed = oom_killed;
555 record.cgroup_memory = parse_cgroup_memory_sample(&facts.cgroup_memory);
556 crate::execution_attempt::archive_attempt(&mut record);
557
558 record.attempt = Some(attempt.clone());
559 }
560 let mut history = record
561 .options
562 .get("recoveryHistory")
563 .and_then(Value::as_array)
564 .cloned()
565 .unwrap_or_default();
566 let delayed = if delay_range.is_some() {
567 format!(", delayMs={}", delay_ms)
568 } else {
569 String::new()
570 };
571 let counted = parse_cgroup_memory_sample(&facts.cgroup_memory)
573 .map(|memory| {
574 [
575 ("oomEvents", memory.oom_events),
576 ("oomKills", memory.oom_kills),
577 ]
578 .iter()
579 .filter_map(|(field, value)| value.map(|value| format!(", {}={}", field, value)))
580 .collect::<String>()
581 })
582 .unwrap_or_default();
583 history.push(json!(format!(
584 "{}: exit {}, oomKilled={}{}{}, resumed at {}",
585 attempt,
586 described
587 .code
588 .map(|code| code.to_string())
589 .unwrap_or_else(|| "unknown".to_string()),
590 oom_killed == Some(true),
591 counted,
592 delayed,
593 since
594 )));
595 let options = &mut record.options;
596 if let Some(values) = &resolved {
597 let mut combined = options
598 .get("resolvedLimits")
599 .filter(|v| v.is_object())
600 .cloned()
601 .unwrap_or_else(|| json!({}));
602 for (k, v) in values.as_object().unwrap() {
603 combined[k] = v.clone();
604 }
605 options.insert("resolvedLimits".into(), combined);
606 let mut specs = options
607 .get("resourceLimitSpecs")
608 .filter(|v| v.is_object())
609 .cloned()
610 .unwrap_or_else(|| json!({}));
611 specs["memory"] = json!(memory_spec);
612 options.insert("resourceLimitSpecs".into(), specs);
613 }
614 options.remove("exitEvidence");
615 options.insert("recoveryAttempts".to_string(), json!(attempt));
616 options.insert("recoveryHistory".to_string(), Value::Array(history));
617 options.insert("lastRecoveryAt".to_string(), json!(since));
618 if delay_range.is_some() {
619 options.insert("lastRecoveryDelayMs".to_string(), json!(delay_ms));
620 }
621 if !resource_limits.is_empty() {
622 options.insert("resourceLimits".to_string(), json!(&resource_limits));
623 }
624 record.status = ExecutionStatus::Executing;
625 record.exit_code = None;
626 record.end_time = None;
627 record.exit_reason = None;
628 record.oom_killed = None;
629 record.cgroup_memory = None;
630 record.memory_exhausted = None;
631 record.memory_exhausted_reason = None;
632 record.end_time_source = None;
633 record.observed_at = None;
634 record.stale_detected_at = None;
635 record.container_started_at = None;
636 let previous = store.get(execution_id).unwrap_or_else(|| record.clone());
637 crate::launch_owner::mark_launch(&mut record);
638 if let Err(error) = store.reserve_launch(&record, &previous) {
639 return give_up(format!("launch reservation failed: {}", error));
640 }
641 if resolved.is_some() || record.options.contains_key("cpuPenaltyConfig") {
642 let mut args = vec!["update".into()];
643 args.extend(
644 resource_limits
645 .iter()
646 .filter(|s| {
647 [
648 "--memory=",
649 "--memory-swap=",
650 "--cpus=",
651 "--cpu-quota=",
652 "--cpu-period=",
653 ]
654 .iter()
655 .any(|f| s.starts_with(f))
656 })
657 .cloned(),
658 );
659 args.push(container_name.clone());
660 let updated = runner.run(&docker_command().to_string_lossy(), &args);
661 if !updated.success {
662 let _ = store.save(&previous);
663 return give_up(format!(
664 "docker update failed: {}",
665 failure_detail(&updated)
666 ));
667 }
668 }
669 let started = runner.run(
670 &docker_command().to_string_lossy(),
671 &["start".to_string(), container_name.clone()],
672 );
673 if !started.success {
674 if let Some(attempt) = next_attempt.as_ref() {
675 let mut lifecycle = record.clone();
676 lifecycle.attempt = Some(attempt.clone());
677 crate::execution_attempt::append_lifecycle(
678 &lifecycle,
679 "launch-failed",
680 json!({"error": failure_detail(&started)}),
681 );
682 }
683 let _ = store.save(&previous);
684 return give_up(format!("docker start failed: {}", failure_detail(&started)));
685 }
686
687 if record.options.contains_key("cpuPenaltyConfig") {
688 let mut resolved = record
689 .options
690 .get("resolvedLimits")
691 .filter(|v| v.is_object())
692 .cloned()
693 .unwrap_or(json!({}));
694 resolved["cpus"] = json!(crate::docker_resource_limits::cpu_count(&resource_limits));
695 record.options.insert("resolvedLimits".into(), resolved);
696 }
697 record.options.insert("launchPending".into(), json!(false));
698 if let Some(attempt) = record.attempt.as_mut() {
699 attempt.launch_accepted_at = Some(Utc::now().to_rfc3339());
700 }
701 let persistence_error = store.save(&record).err();
702
703 if next_attempt.is_some() {
704 crate::execution_attempt::append_lifecycle(&record, "launch-accepted", json!({}));
705 }
706 start_watcher(
707 &container_name,
708 &record,
709 &DockerWatcherOptions {
710 since: Some(since),
711 recover_on_kill: true,
712 attempt_number: next_attempt.as_ref().map(|attempt| attempt.number),
713 },
714 );
715 if let Some(attempt) = next_attempt.filter(|_| persistence_error.is_none()) {
716 if let Ok(Some(current)) = store.patch_attempt(
717 &record.uuid,
718 attempt.number,
719 json!({"watcherAttachedAt": Utc::now().to_rfc3339()}),
720 ) {
721 crate::execution_attempt::append_lifecycle(¤t, "watcher-attached", json!({}));
722 }
723 }
724 if let Some(error) = persistence_error {
725 let stopped = runner.run(
726 &docker_command().to_string_lossy(),
727 &["stop".into(), container_name.clone()],
728 );
729 if stopped.success {
730 record.status = ExecutionStatus::Executed;
731 record.exit_code = Some(-1);
732 record.end_time = Some(Utc::now().to_rfc3339());
733 record.options.insert("launchPending".into(), json!(false));
734 let _ = store.save(&record);
735 }
736 let warning = json!({"code": "LAUNCH_PERSISTENCE_FAILED", "uuid": execution_id,
737 "containerName": container_name, "running": !stopped.success, "error": error})
738 .to_string();
739 log(&format!("[Recovery] {}\n", warning));
740 return RecoveryOutcome::not(&warning);
741 }
742 RecoveryOutcome {
743 recovered: true,
744 reason: "resumed".to_string(),
745 attempt: Some(attempt),
746 delay_ms: delay_range.map(|_| delay_ms),
747 }
748}
749
750pub fn start_system_watcher(
752 container_name: &str,
753 record: &ExecutionRecord,
754 watcher: &DockerWatcherOptions,
755) {
756 let log_path = (!record.log_path.is_empty()).then(|| PathBuf::from(&record.log_path));
757 let _ = start_detached_docker_completion_watcher_with(
758 container_name,
759 get_docker_container_cleanup_policy(&build_launch_options(record)),
760 log_path.as_ref(),
761 Some(record.uuid.as_str()),
762 watcher,
763 );
764}
765
766pub fn run_internal_recover(args: &[String]) -> i32 {
771 let execution_id = match args.first() {
772 Some(value) if !value.is_empty() => value.clone(),
773 _ => return 1,
774 };
775 if std::env::var("START_DISABLE_TRACKING").as_deref() == Ok("true") {
776 return 1;
777 }
778 let field = |index: usize| args.get(index).cloned().unwrap_or_default();
779 let store = ExecutionStore::with_options(ExecutionStoreOptions {
780 app_folder: std::env::var("START_APP_FOLDER").ok().map(PathBuf::from),
781 ..ExecutionStoreOptions::default()
782 });
783 let outcome = recover_killed_execution(
784 &store,
785 &execution_id,
786 &RecoveryFacts {
787 exit_code: field(1),
788 oom_killed: field(2),
789 started_at: field(3),
790 finished_at: field(4),
791 container_error: field(5),
792 cgroup_memory: field(6),
793 },
794 &SystemCommandRunner,
795 &start_system_watcher,
796 );
797 if outcome.recovered {
798 0
799 } else {
800 1
801 }
802}