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 if let Some(line) = format_cgroup_memory_log_line(&facts.cgroup_memory) {
407 log(&format!("{}\n", line));
408 }
409 let recovery_command = option_str(&record, "recoveryCommand").map(str::to_string);
410 log(&format_recovery_separator(&RecoverySeparator {
411 attempt,
412 max_attempts,
413 exit_code: &facts.exit_code,
414 oom_killed: &facts.oom_killed,
415 container_name: &container_name,
416 command: recovery_command.as_deref(),
417 delay_ms,
418 }));
419
420 if delay_ms > 0
425 && wait_for_recovery_delay(delay_ms, delay.sleep, &|| {
426 is_stop_requested(store, execution_id)
427 })
428 {
429 log(&format!(
430 "[Recovery {}/{}] Not resuming: the session was stopped on request during the delay.\n",
431 attempt, max_attempts
432 ));
433 return RecoveryOutcome {
434 recovered: false,
435 reason: "stop-requested".to_string(),
436 attempt: Some(attempt),
437 delay_ms: Some(delay_ms),
438 };
439 }
440
441 let resource_limits = read_docker_resource_limits(&container_name, runner).unwrap_or_default();
445 if let Some(line) = build_resource_limits_status_line(&resource_limits) {
446 log(&format!("{}\n", line));
447 }
448
449 if recovery_command.is_some() {
450 let copied = write_recovery_marker(&container_name, attempt, runner);
451 if !copied.success {
452 return give_up(format!(
453 "could not mark the container: {}",
454 failure_detail(&copied)
455 ));
456 }
457 }
458
459 let since = Utc::now().to_rfc3339_opts(SecondsFormat::Millis, true);
460 let mut next_attempt = record.attempt.as_ref().map(|_| {
461 crate::execution_attempt::create_attempt(&record, "automatic-recovery", &container_name)
462 });
463 if let Some(attempt) = next_attempt.as_mut() {
464 attempt.started_at = since.clone();
465 let mut lifecycle = record.clone();
466 lifecycle.attempt = Some(attempt.clone());
467 crate::execution_attempt::append_lifecycle(&lifecycle, "resume-started", json!({}));
468 }
469 let started = runner.run(
470 &docker_command().to_string_lossy(),
471 &["start".to_string(), container_name.clone()],
472 );
473 if !started.success {
474 if let Some(attempt) = next_attempt.as_ref() {
475 let mut lifecycle = record.clone();
476 lifecycle.attempt = Some(attempt.clone());
477 crate::execution_attempt::append_lifecycle(
478 &lifecycle,
479 "launch-failed",
480 json!({"error": failure_detail(&started)}),
481 );
482 }
483 return give_up(format!("docker start failed: {}", failure_detail(&started)));
484 }
485
486 let described = describe_exit_code_str(&facts.exit_code);
487 if let Some(attempt) = next_attempt.as_mut() {
488 record.status = ExecutionStatus::Executed;
489 record.exit_code = described.code;
490 record.end_time = normalize_docker_timestamp(Some(&facts.finished_at));
491 record.container_started_at = normalize_docker_timestamp(Some(&facts.started_at));
492 record.oom_killed = oom_killed;
493 record.cgroup_memory = parse_cgroup_memory_sample(&facts.cgroup_memory);
494 crate::execution_attempt::archive_attempt(&mut record);
495 attempt.launch_accepted_at = Some(Utc::now().to_rfc3339());
496 record.attempt = Some(attempt.clone());
497 }
498 let mut history = record
499 .options
500 .get("recoveryHistory")
501 .and_then(Value::as_array)
502 .cloned()
503 .unwrap_or_default();
504 let delayed = if delay_range.is_some() {
505 format!(", delayMs={}", delay_ms)
506 } else {
507 String::new()
508 };
509 let counted = parse_cgroup_memory_sample(&facts.cgroup_memory)
511 .map(|memory| {
512 [
513 ("oomEvents", memory.oom_events),
514 ("oomKills", memory.oom_kills),
515 ]
516 .iter()
517 .filter_map(|(field, value)| value.map(|value| format!(", {}={}", field, value)))
518 .collect::<String>()
519 })
520 .unwrap_or_default();
521 history.push(json!(format!(
522 "{}: exit {}, oomKilled={}{}{}, resumed at {}",
523 attempt,
524 described
525 .code
526 .map(|code| code.to_string())
527 .unwrap_or_else(|| "unknown".to_string()),
528 oom_killed == Some(true),
529 counted,
530 delayed,
531 since
532 )));
533 let options = &mut record.options;
534 options.insert("recoveryAttempts".to_string(), json!(attempt));
535 options.insert("recoveryHistory".to_string(), Value::Array(history));
536 options.insert("lastRecoveryAt".to_string(), json!(since));
537 if delay_range.is_some() {
538 options.insert("lastRecoveryDelayMs".to_string(), json!(delay_ms));
539 }
540 if !resource_limits.is_empty() {
541 options.insert("resourceLimits".to_string(), json!(resource_limits));
542 }
543 record.status = ExecutionStatus::Executing;
544 record.exit_code = None;
545 record.end_time = None;
546 record.exit_reason = None;
547 record.oom_killed = None;
548 record.cgroup_memory = None;
549 record.memory_exhausted = None;
550 record.memory_exhausted_reason = None;
551 record.end_time_source = None;
552 record.observed_at = None;
553 record.stale_detected_at = None;
554 record.container_started_at = None;
555 let _ = store.save(&record);
558
559 if next_attempt.is_some() {
560 crate::execution_attempt::append_lifecycle(&record, "launch-accepted", json!({}));
561 }
562 start_watcher(
563 &container_name,
564 &record,
565 &DockerWatcherOptions {
566 since: Some(since),
567 recover_on_kill: true,
568 attempt_number: next_attempt.as_ref().map(|attempt| attempt.number),
569 },
570 );
571 if let Some(attempt) = next_attempt {
572 if let Ok(Some(current)) = store.patch_attempt(
573 &record.uuid,
574 attempt.number,
575 json!({"watcherAttachedAt": Utc::now().to_rfc3339()}),
576 ) {
577 crate::execution_attempt::append_lifecycle(¤t, "watcher-attached", json!({}));
578 }
579 }
580 RecoveryOutcome {
581 recovered: true,
582 reason: "resumed".to_string(),
583 attempt: Some(attempt),
584 delay_ms: delay_range.map(|_| delay_ms),
585 }
586}
587
588pub fn start_system_watcher(
590 container_name: &str,
591 record: &ExecutionRecord,
592 watcher: &DockerWatcherOptions,
593) {
594 let log_path = (!record.log_path.is_empty()).then(|| PathBuf::from(&record.log_path));
595 let _ = start_detached_docker_completion_watcher_with(
596 container_name,
597 get_docker_container_cleanup_policy(&build_launch_options(record)),
598 log_path.as_ref(),
599 Some(record.uuid.as_str()),
600 watcher,
601 );
602}
603
604pub fn run_internal_recover(args: &[String]) -> i32 {
609 let execution_id = match args.first() {
610 Some(value) if !value.is_empty() => value.clone(),
611 _ => return 1,
612 };
613 if std::env::var("START_DISABLE_TRACKING").as_deref() == Ok("true") {
614 return 1;
615 }
616 let field = |index: usize| args.get(index).cloned().unwrap_or_default();
617 let store = ExecutionStore::with_options(ExecutionStoreOptions {
618 app_folder: std::env::var("START_APP_FOLDER").ok().map(PathBuf::from),
619 ..ExecutionStoreOptions::default()
620 });
621 let outcome = recover_killed_execution(
622 &store,
623 &execution_id,
624 &RecoveryFacts {
625 exit_code: field(1),
626 oom_killed: field(2),
627 started_at: field(3),
628 finished_at: field(4),
629 container_error: field(5),
630 cgroup_memory: field(6),
631 },
632 &SystemCommandRunner,
633 &start_system_watcher,
634 );
635 if outcome.recovered {
636 0
637 } else {
638 1
639 }
640}