aither-sandbox 0.16.0

Terminal-first command execution with heel sandboxing
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
//! Container exec implementation backed by bollard.

use async_channel::{Receiver, Sender};
use bollard::Docker;
use bollard::container::LogOutput;
use bollard::exec::CreateExecOptions;
use futures_lite::{Stream, StreamExt};
use std::future::Future;
use std::pin::Pin;
use std::process::{ExitStatus, Output};
use std::sync::Arc;

use crate::process_tree::JobProcess;
use crate::shell_session::{ContainerExec, ContainerExecOutcome, ExecLifetime};
use crate::stdin_watch::{
    CONTAINER_EXEC_WRAPPER, CONTAINER_JOB_SCRIPT, CONTAINER_STDIN_WATCH_INTERVAL, EpisodeDetector,
    Probe, StdinWatchSignal, parse_container_probe,
};

/// Executes commands in a running container via Docker exec.
#[derive(Debug, Clone)]
pub struct BollardContainerExec {
    client: Arc<Docker>,
}

impl BollardContainerExec {
    /// Create a new exec adapter from a shared Docker client.
    #[must_use]
    pub const fn new(client: Arc<Docker>) -> Self {
        Self { client }
    }
}

/// Exit code of [`CONTAINER_JOB_SCRIPT`]'s `kill` when no pid is recorded.
const KILL_NO_PID: i64 = 3;

/// What a helper script run inside the container printed and returned.
struct ScriptRun {
    stdout: String,
    stderr: String,
    exit_code: Option<i64>,
}

impl ScriptRun {
    /// The output when the script exited 0.
    fn success(self, what: &str) -> Result<String, String> {
        if self.exit_code == Some(0) {
            return Ok(self.stdout);
        }
        Err(format!(
            "{what} exited with {:?}: {}{}",
            self.exit_code,
            self.stdout.trim(),
            self.stderr.trim()
        ))
    }
}

/// Runs `sh -c script sh args…` in the container and collects its output and
/// exit code.
async fn run_script_in_container(
    client: &Docker,
    container_id: &str,
    script: &str,
    args: &[&str],
    what: &str,
) -> Result<ScriptRun, String> {
    let mut cmd = vec!["sh", "-c", script, "sh"];
    cmd.extend_from_slice(args);
    let exec = client
        .create_exec(
            container_id,
            CreateExecOptions {
                cmd: Some(cmd),
                attach_stdout: Some(true),
                attach_stderr: Some(true),
                ..Default::default()
            },
        )
        .await
        .map_err(|e| format!("failed to create {what} exec: {e}"))?;

    let started = client
        .start_exec(&exec.id, None)
        .await
        .map_err(|e| format!("failed to start {what} exec: {e}"))?;

    let mut run = ScriptRun {
        stdout: String::new(),
        stderr: String::new(),
        exit_code: None,
    };
    match started {
        bollard::exec::StartExecResults::Attached { mut output, .. } => {
            while let Some(chunk) = output.next().await {
                match chunk {
                    Ok(LogOutput::StdOut { message } | LogOutput::Console { message }) => {
                        run.stdout.push_str(&String::from_utf8_lossy(&message));
                    }
                    Ok(LogOutput::StdErr { message }) => {
                        run.stderr.push_str(&String::from_utf8_lossy(&message));
                    }
                    Ok(LogOutput::StdIn { .. }) => {}
                    Err(e) => return Err(format!("{what} stream error: {e}")),
                }
            }
        }
        bollard::exec::StartExecResults::Detached => {
            return Err(format!("{what} exec detached unexpectedly"));
        }
    }
    run.exit_code = client
        .inspect_exec(&exec.id)
        .await
        .map_err(|e| format!("failed to inspect {what} exec: {e}"))?
        .exit_code;
    Ok(run)
}

/// Runs the stdin probe script inside the container for the exec whose root
/// recorded its own in-container pid in `pid_file`.
async fn probe_stdin_inside_container(
    client: &Docker,
    container_id: &str,
    pid_file: &str,
) -> Result<Probe, String> {
    let output = run_script_in_container(
        client,
        container_id,
        CONTAINER_JOB_SCRIPT,
        &["probe", pid_file],
        "stdin probe",
    )
    .await?
    .success("stdin probe")?;
    parse_container_probe(&output)
}

/// Whether the exec is still running.
async fn exec_running(client: &Docker, exec_id: &str) -> Result<bool, String> {
    Ok(client
        .inspect_exec(exec_id)
        .await
        .map_err(|e| format!("failed to inspect exec for kill: {e}"))?
        .running
        .unwrap_or(false))
}

/// Kills the exec's whole process tree inside the container. Docker reports
/// exec pids in the host's namespace, so the kill goes through `pid_file`,
/// where the exec root recorded its own in-container pid. Succeeds only when
/// the exec is gone: a running exec that recorded no pid is an error.
async fn kill_exec_inside_container(
    client: &Docker,
    container_id: &str,
    exec_id: &str,
    pid_file: &str,
) -> Result<(), String> {
    if !exec_running(client, exec_id).await? {
        return Ok(());
    }
    let run = run_script_in_container(
        client,
        container_id,
        CONTAINER_JOB_SCRIPT,
        &["kill", pid_file],
        "in-container kill",
    )
    .await?;
    if run.exit_code == Some(KILL_NO_PID) {
        // The root removes its pid file when it exits, so a missing file is
        // an exec that ended meanwhile — or one that never recorded a pid.
        return if exec_running(client, exec_id).await? {
            Err("the exec is running but recorded no in-container pid".to_string())
        } else {
            Ok(())
        };
    }
    run.success("in-container kill").map(drop)
}

enum StreamEvent {
    Output(Option<Result<LogOutput, bollard::errors::Error>>),
    Stdin(Result<Vec<u8>, async_channel::RecvError>),
    WatchTick,
    Cancel,
}

/// How much of a streamed exec's stderr is kept for a message. The rest is
/// read and dropped, so the process is never held back and memory never grows
/// with what it prints.
const STREAMED_STDERR_KEPT: usize = 8 * 1024;

/// Appends `chunk` to `kept` up to `cap` bytes in all.
fn append_capped(kept: &mut Vec<u8>, chunk: &[u8], cap: usize) {
    let room = cap.saturating_sub(kept.len());
    kept.extend_from_slice(&chunk[..chunk.len().min(room)]);
}

/// Collects one chunk of output. The stderr kept is bounded when `streamed`,
/// for an exec whose stdout is streamed away and so never accumulates.
fn append_log_output(
    output: LogOutput,
    stdout: &mut Vec<u8>,
    stderr: &mut Vec<u8>,
    streamed: bool,
) {
    match output {
        LogOutput::StdOut { message } | LogOutput::Console { message } => {
            stdout.extend_from_slice(&message);
        }
        LogOutput::StdErr { message } if streamed => {
            append_capped(stderr, &message, STREAMED_STDERR_KEPT);
        }
        LogOutput::StdErr { message } => stderr.extend_from_slice(&message),
        LogOutput::StdIn { .. } => {}
    }
}

async fn write_container_stdin<W>(input: &mut W, bytes: &[u8]) -> Result<(), String>
where
    W: tokio::io::AsyncWrite + Unpin,
{
    use tokio::io::AsyncWriteExt;

    input
        .write_all(bytes)
        .await
        .map_err(|error| format!("container exec stdin write failed: {error}"))?;
    input
        .flush()
        .await
        .map_err(|error| format!("container exec stdin flush failed: {error}"))
}

async fn shutdown_container_stdin<W>(input: &mut W) -> Result<(), String>
where
    W: tokio::io::AsyncWrite + Unpin,
{
    use tokio::io::AsyncWriteExt;

    input
        .shutdown()
        .await
        .map_err(|error| format!("container exec stdin shutdown failed: {error}"))
}

/// Alerts for the stdin of one container exec.
struct StdinWatch {
    signal: Sender<StdinWatchSignal>,
    detector: EpisodeDetector,
    /// Writes fed to the exec's stdin so far.
    fed: u64,
}

impl StdinWatch {
    /// Reports a probe outcome through the alert channel.
    fn send(&self, signal: StdinWatchSignal) {
        let _ = self.signal.try_send(signal);
    }
}

struct WatchTick<'a, W> {
    client: &'a Docker,
    container_id: &'a str,
    exec_id: &'a str,
    pid_file: &'a str,
    input: &'a mut W,
    stdin_open: &'a mut bool,
    watch: &'a mut Option<StdinWatch>,
}

/// One watch tick. A probe-side failure — a Docker API error or the script
/// reporting it cannot read the job — is surfaced to the job's alerts and
/// ends detection for this exec; it must never fail the exec itself.
async fn handle_container_watch_tick<W>(tick: WatchTick<'_, W>)
where
    W: tokio::io::AsyncWrite + Unpin,
{
    let Some(watch) = tick.watch.as_mut() else {
        return;
    };
    match tick.client.inspect_exec(tick.exec_id).await {
        Err(error) => {
            watch.send(StdinWatchSignal::Failed(format!(
                "failed to inspect running exec for stdin watch: {error}"
            )));
            *tick.watch = None;
        }
        Ok(inspect) if !inspect.running.unwrap_or(false) => {
            if *tick.stdin_open {
                let _ = shutdown_container_stdin(tick.input).await;
                *tick.stdin_open = false;
            }
            *tick.watch = None;
        }
        Ok(_) => {
            match probe_stdin_inside_container(tick.client, tick.container_id, tick.pid_file).await
            {
                Ok(probe) => {
                    if watch.detector.observe(watch.fed, probe) {
                        watch.send(StdinWatchSignal::Blocked);
                    }
                }
                Err(error) => {
                    watch.send(StdinWatchSignal::Failed(error));
                    *tick.watch = None;
                }
            }
        }
    }
}

async fn inspect_exec_exit_status(client: &Docker, exec_id: &str) -> Result<ExitStatus, String> {
    let inspect = client
        .inspect_exec(exec_id)
        .await
        .map_err(|e| format!("failed to inspect exec: {e}"))?;
    let exit_code = i32::try_from(inspect.exit_code.unwrap_or(-1))
        .map_err(|_| "container exec exit code is outside i32 range".to_string())?;
    Ok(ExitStatusExt::from_raw(exit_code))
}

/// The output stream of an attached container exec.
type ExecOutput = Pin<Box<dyn Stream<Item = Result<LogOutput, bollard::errors::Error>> + Send>>;

/// The writable stdin of an attached container exec.
type ExecInput = Pin<Box<dyn tokio::io::AsyncWrite + Send>>;

/// The wrapper's argument naming what becomes of the processes the script
/// leaves running.
const fn lifetime_argument(lifetime: &ExecLifetime) -> &'static str {
    match lifetime {
        ExecLifetime::Foreground => "foreground",
        ExecLifetime::Background { .. } => "background",
    }
}

/// Takes the lines the exec wrapper wrote about the processes it killed out of
/// the exec's stderr. Each starts with `pid_file`, a path nothing else knows:
/// `<pid_file> killed <pid> <name>` names one process, `<pid_file> error
/// <message>` reports a kill that failed.
fn split_killed(stderr: &[u8], pid_file: &str) -> Result<(Vec<u8>, Vec<JobProcess>), String> {
    let killed_prefix = format!("{pid_file} killed ");
    let error_prefix = format!("{pid_file} error ");
    let mut kept = Vec::with_capacity(stderr.len());
    let mut killed = Vec::new();
    for line in stderr.split_inclusive(|byte| *byte == b'\n') {
        let text = String::from_utf8_lossy(line);
        let text = text.trim_end_matches('\n');
        if let Some(process) = text.strip_prefix(&killed_prefix) {
            let (pid, name) = process
                .split_once(' ')
                .ok_or_else(|| format!("malformed process report from the exec wrapper: {text}"))?;
            let pid = pid
                .parse()
                .map_err(|_| format!("malformed process report from the exec wrapper: {text}"))?;
            killed.push(JobProcess {
                pid,
                name: name.to_string(),
            });
        } else if let Some(message) = text.strip_prefix(&error_prefix) {
            return Err(format!(
                "could not end the processes the command left running: {message}"
            ));
        } else {
            kept.extend_from_slice(line);
        }
    }
    Ok((kept, killed))
}

/// Creates the exec running `script` in `working_dir` under
/// [`CONTAINER_EXEC_WRAPPER`],
/// which records its pid in `pid_file`, and starts it with its output stream
/// and stdin attached.
async fn start_attached_exec(
    client: &Docker,
    container_id: &str,
    script: &str,
    pid_file: &str,
    working_dir: &str,
    lifetime: &ExecLifetime,
) -> Result<(String, ExecOutput, ExecInput), String> {
    let config = CreateExecOptions {
        cmd: Some(vec![
            "sh",
            "-c",
            CONTAINER_EXEC_WRAPPER,
            "sh",
            pid_file,
            script,
            lifetime_argument(lifetime),
            CONTAINER_JOB_SCRIPT,
        ]),
        attach_stdin: Some(true),
        attach_stdout: Some(true),
        attach_stderr: Some(true),
        working_dir: Some(working_dir),
        ..Default::default()
    };

    let exec_id = client
        .create_exec(container_id, config)
        .await
        .map_err(|e| format!("failed to create exec: {e}"))?
        .id;

    match client
        .start_exec(&exec_id, None)
        .await
        .map_err(|e| format!("failed to start exec: {e}"))?
    {
        bollard::exec::StartExecResults::Attached { output, input } => Ok((exec_id, output, input)),
        bollard::exec::StartExecResults::Detached => {
            Err("exec started in detached mode unexpectedly".to_string())
        }
    }
}

/// What became of one output chunk handed to a streaming consumer.
enum Forwarded {
    /// The consumer took the chunk.
    Sent,
    /// The consumer is gone, so the exec has no reason to run on.
    ConsumerGone,
    /// The exec was told to stop while the consumer was not keeping up.
    Killed,
}

/// Hands `bytes` to `sink`, giving way to a kill while the sink is full.
async fn forward_stdout(
    sink: &Sender<Vec<u8>>,
    bytes: Vec<u8>,
    kill_rx: &Receiver<()>,
) -> Forwarded {
    tokio::select! {
        sent = sink.send(bytes) => if sent.is_ok() { Forwarded::Sent } else { Forwarded::ConsumerGone },
        () = async {
            let _ = kill_rx.recv().await;
        } => Forwarded::Killed,
    }
}

impl ContainerExec for BollardContainerExec {
    fn exec(
        &self,
        container_id: &str,
        script: &str,
        working_dir: &str,
        kill_rx: Receiver<()>,
        stdin_rx: Receiver<Vec<u8>>,
        lifetime: ExecLifetime,
    ) -> impl Future<Output = Result<ContainerExecOutcome, String>> + Send {
        exec_inner(
            self.client.clone(),
            container_id.to_string(),
            script.to_string(),
            working_dir.to_string(),
            kill_rx,
            stdin_rx,
            lifetime,
            None,
        )
    }

    fn exec_streamed(
        &self,
        container_id: &str,
        script: &str,
        working_dir: &str,
        kill_rx: Receiver<()>,
        stdin_rx: Receiver<Vec<u8>>,
        stdout: Sender<Vec<u8>>,
    ) -> impl Future<Output = Result<ContainerExecOutcome, String>> + Send {
        exec_inner(
            self.client.clone(),
            container_id.to_string(),
            script.to_string(),
            working_dir.to_string(),
            kill_rx,
            stdin_rx,
            ExecLifetime::Foreground,
            Some(stdout),
        )
    }
}

/// One container exec's whole run, shared by the buffered and the streamed
/// calls: `stdout_sink` carries stdout chunk by chunk instead of into the
/// outcome.
#[allow(clippy::too_many_arguments, clippy::too_many_lines)]
async fn exec_inner(
    client: std::sync::Arc<Docker>,
    container_id: String,
    script: String,
    working_dir: String,
    kill_rx: Receiver<()>,
    stdin_rx: Receiver<Vec<u8>>,
    lifetime: ExecLifetime,
    stdout_sink: Option<Sender<Vec<u8>>>,
) -> Result<ContainerExecOutcome, String> {
    // Docker reports the exec's pid in the host's namespace, which a
    // probe inside the container cannot use: the exec root records
    // its own in-container pid for the stdin probe and the kill path.
    let pid_file = format!(
        "/tmp/aither-exec-stdin-{}.pid",
        uuid::Uuid::new_v4().simple()
    );
    let (exec_id, mut output, mut input) = start_attached_exec(
        &client,
        &container_id,
        &script,
        &pid_file,
        &working_dir,
        &lifetime,
    )
    .await?;

    let mut stdout = Vec::new();
    let mut stderr = Vec::new();
    let stdin_blocked = match lifetime {
        ExecLifetime::Foreground => None,
        ExecLifetime::Background { stdin_blocked } => Some(stdin_blocked),
    };
    let mut watch = stdin_blocked.map(|signal| StdinWatch {
        signal,
        detector: EpisodeDetector::default(),
        fed: 0,
    });
    let mut ticker = async_io::Timer::interval(CONTAINER_STDIN_WATCH_INTERVAL);
    let mut stdin_open = true;

    loop {
        let event = tokio::select! {
            output = async { output.next().await } => StreamEvent::Output(output),
            () = async {
                let _ = kill_rx.recv().await;
            } => StreamEvent::Cancel,
            bytes = async { stdin_rx.recv().await }, if stdin_open => StreamEvent::Stdin(bytes),
            _ = async { ticker.next().await }, if watch.is_some() => StreamEvent::WatchTick,
        };

        match event {
            StreamEvent::Output(Some(Ok(output))) => match (&stdout_sink, output) {
                (Some(sink), LogOutput::StdOut { message } | LogOutput::Console { message }) => {
                    if !matches!(
                        forward_stdout(sink, message.to_vec(), &kill_rx).await,
                        Forwarded::Sent
                    ) {
                        if stdin_open {
                            let _ = shutdown_container_stdin(&mut input).await;
                        }
                        // A job the kill could not stop is still running,
                        // so it must not be reported killed.
                        kill_exec_inside_container(&client, &container_id, &exec_id, &pid_file)
                            .await
                            .map_err(|error| format!("failed to kill container exec: {error}"))?;
                        return Ok(ContainerExecOutcome::Killed);
                    }
                }
                (_, output) => {
                    append_log_output(output, &mut stdout, &mut stderr, stdout_sink.is_some());
                }
            },
            StreamEvent::Output(Some(Err(e))) => {
                return Err(format!("exec stream error: {e}"));
            }
            StreamEvent::Output(None) => {
                break;
            }
            StreamEvent::Stdin(Ok(bytes)) => {
                if let Some(watch) = watch.as_mut() {
                    watch.fed += 1;
                }
                write_container_stdin(&mut input, &bytes).await?;
            }
            StreamEvent::Stdin(Err(_)) => {
                shutdown_container_stdin(&mut input).await?;
                stdin_open = false;
            }
            StreamEvent::Cancel => {
                if stdin_open {
                    let _ = shutdown_container_stdin(&mut input).await;
                }
                // A job the kill could not stop is still running, so
                // it must not be reported killed.
                kill_exec_inside_container(&client, &container_id, &exec_id, &pid_file)
                    .await
                    .map_err(|error| format!("failed to kill container exec: {error}"))?;
                return Ok(ContainerExecOutcome::Killed);
            }
            StreamEvent::WatchTick => {
                handle_container_watch_tick(WatchTick {
                    client: &client,
                    container_id: &container_id,
                    exec_id: &exec_id,
                    pid_file: &pid_file,
                    input: &mut input,
                    stdin_open: &mut stdin_open,
                    watch: &mut watch,
                })
                .await;
            }
        }
    }

    let status = inspect_exec_exit_status(&client, &exec_id).await?;
    let (stderr, killed) = split_killed(&stderr, &pid_file)?;
    Ok(ContainerExecOutcome::Completed {
        output: Output {
            status,
            stdout,
            stderr,
        },
        killed,
    })
}

#[cfg(unix)]
struct ExitStatusExt;

#[cfg(unix)]
impl ExitStatusExt {
    fn from_raw(code: i32) -> ExitStatus {
        use std::os::unix::process::ExitStatusExt as _;
        ExitStatus::from_raw(code << 8)
    }
}

#[cfg(not(unix))]
struct ExitStatusExt;

#[cfg(not(unix))]
impl ExitStatusExt {
    fn from_raw(code: i32) -> ExitStatus {
        use std::os::windows::process::ExitStatusExt as _;
        ExitStatus::from_raw(code as u32)
    }
}

/// The wrapper scripts run on the host here; the kill and the stdin probe
/// read `/proc` and are tested on Linux in `stdin_watch`.
#[cfg(all(test, unix))]
mod tests {
    use std::process::Command;

    use super::{CONTAINER_EXEC_WRAPPER, CONTAINER_JOB_SCRIPT};

    fn run_wrapper(
        pid_file: &std::path::Path,
        script: &str,
        dir: &std::path::Path,
    ) -> std::process::Output {
        run_wrapper_as(pid_file, script, "foreground", dir)
    }

    fn run_wrapper_as(
        pid_file: &std::path::Path,
        script: &str,
        lifetime: &str,
        dir: &std::path::Path,
    ) -> std::process::Output {
        run_wrapper_with_helper(pid_file, script, lifetime, CONTAINER_JOB_SCRIPT, dir)
    }

    /// Runs the wrapper with `helper` standing in for the job script.
    fn run_wrapper_with_helper(
        pid_file: &std::path::Path,
        script: &str,
        lifetime: &str,
        helper: &str,
        dir: &std::path::Path,
    ) -> std::process::Output {
        Command::new("sh")
            .args(["-c", CONTAINER_EXEC_WRAPPER, "sh"])
            .arg(pid_file)
            .arg(script)
            .arg(lifetime)
            .arg(helper)
            .current_dir(dir)
            .env("PID_FILE", pid_file)
            .output()
            .expect("run the exec wrapper")
    }

    /// The wrapper records its own pid — the parent of the shell running
    /// the script — keeps the script's exit status, and removes the file
    /// when it exits, also after a script that `exec`s.
    #[test]
    fn wrapper_records_its_pid_and_removes_the_file() {
        let dir = tempfile::tempdir().expect("temp dir");
        let pid_file = dir.path().join("exec.pid");
        let run = run_wrapper(
            &pid_file,
            "echo \"$PPID $(cat \"$PID_FILE\")\"; exit 3",
            dir.path(),
        );
        assert_eq!(run.status.code(), Some(3), "the script's status survives");
        let printed = String::from_utf8_lossy(&run.stdout);
        let mut pids = printed.split_whitespace();
        let parent = pids.next().expect("the script's parent pid");
        assert_eq!(
            pids.next(),
            Some(parent),
            "the file holds the wrapper's pid"
        );
        assert!(!pid_file.exists(), "the pid file is removed on exit");

        let run = run_wrapper(&pid_file, "exec true", dir.path());
        assert!(run.status.success());
        assert!(
            !pid_file.exists(),
            "a script that execs still gets cleaned up"
        );
    }

    /// The script sees none of the wrapper's arguments or variables, and a
    /// variable it sets cannot redirect the wrapper's cleanup.
    #[test]
    fn wrapper_hides_its_arguments_from_the_script() {
        let dir = tempfile::tempdir().expect("temp dir");
        let pid_file = dir.path().join("exec.pid");
        let run = run_wrapper(
            &pid_file,
            "echo \"$#[${1-}][${pid_file-}][${script-}]\"; pid_file=user.pid; : > \"$pid_file\"; trap - EXIT",
            dir.path(),
        );
        assert!(run.status.success());
        assert_eq!(String::from_utf8_lossy(&run.stdout), "0[][][]\n");
        assert!(
            dir.path().join("user.pid").exists(),
            "the script's own file stays"
        );
        assert!(!pid_file.exists(), "the wrapper removes its own file");
    }

    /// The wrapper's report of killed processes is taken out of stderr, which
    /// keeps everything else, in order.
    #[test]
    fn killed_processes_are_split_from_stderr() {
        let pid_file = "/tmp/aither-exec-stdin-abc.pid";
        let stderr = format!(
            "warning\n{pid_file} killed 41 sleep\n{pid_file} killed 42 my daemon\nlast words"
        );
        let (kept, killed) = super::split_killed(stderr.as_bytes(), pid_file).unwrap();
        assert_eq!(kept, b"warning\nlast words");
        assert_eq!(
            killed,
            [
                super::JobProcess {
                    pid: 41,
                    name: "sleep".to_string()
                },
                super::JobProcess {
                    pid: 42,
                    name: "my daemon".to_string()
                },
            ]
        );
        // Another exec's report, or the script's own line, is just output.
        let other = b"/tmp/other.pid killed 1 x\n".to_vec();
        let (kept, killed) = super::split_killed(&other, pid_file).unwrap();
        assert_eq!(kept, other);
        assert_eq!(killed, []);
    }

    /// A kill the wrapper could not complete fails the exec instead of passing
    /// as a clean one.
    #[test]
    fn a_failed_kill_report_is_an_error() {
        let pid_file = "/tmp/aither-exec-stdin-abc.pid";
        let stderr = format!("{pid_file} error cannot kill process 9 of the job\n");
        let error = super::split_killed(stderr.as_bytes(), pid_file).unwrap_err();
        assert!(error.contains("cannot kill process 9"), "{error}");
    }

    /// Whether `/proc/<pid>` is gone or the process is a zombie, within
    /// `wait`: the wrapper's SIGKILL is delivered and the process reaped
    /// asynchronously, so the kill is not visible the moment the wrapper exits.
    #[cfg(target_os = "linux")]
    fn dead_within(pid: &str, wait: std::time::Duration) -> bool {
        let deadline = std::time::Instant::now() + wait;
        loop {
            let dead = match std::fs::read_to_string(format!("/proc/{pid}/stat")) {
                Ok(stat) => stat
                    .rsplit_once(") ")
                    .is_some_and(|(_, rest)| rest.starts_with('Z') || rest.starts_with('X')),
                Err(error) if error.kind() == std::io::ErrorKind::NotFound => true,
                Err(error) => panic!("cannot read /proc/{pid}/stat: {error}"),
            };
            if dead {
                return true;
            }
            if std::time::Instant::now() >= deadline {
                return false;
            }
            std::thread::sleep(std::time::Duration::from_millis(10));
        }
    }

    /// A foreground wrapper kills what its script left running, including a
    /// process that left the process group, and reports each on stderr. Needs
    /// `/proc`, so it runs on Linux only.
    #[cfg(target_os = "linux")]
    #[test]
    fn foreground_wrapper_kills_and_reports_leftover_processes() {
        let dir = tempfile::tempdir().expect("temp dir");
        let pid_file = dir.path().join("exec.pid");
        for script in [
            "sleep 300 > /dev/null 2>&1 &",
            "setsid sleep 300 > /dev/null 2>&1 &",
        ] {
            let run = run_wrapper_as(&pid_file, script, "foreground", dir.path());
            assert!(run.status.success());
            let report = format!("{} killed ", pid_file.display());
            let stderr = String::from_utf8_lossy(&run.stderr);
            let line = stderr
                .lines()
                .find_map(|line| line.strip_prefix(&report))
                .unwrap_or_else(|| panic!("{script}: no kill report in {stderr}"));
            let (pid, name) = line.split_once(' ').expect("pid and name");
            assert_eq!(name, "sleep", "{script}");
            assert!(
                dead_within(pid, std::time::Duration::from_secs(5)),
                "{script}: process {pid} survived"
            );
        }
        let run = run_wrapper_as(&pid_file, "exit 4", "foreground", dir.path());
        assert_eq!(run.status.code(), Some(4));
        assert!(run.stderr.is_empty(), "nothing left, nothing reported");
    }

    /// A background wrapper stays until what its script left running exits,
    /// and kills nothing. Needs `/proc`, so it runs on Linux only.
    #[cfg(target_os = "linux")]
    #[test]
    fn background_wrapper_stays_until_leftover_processes_exit() {
        let dir = tempfile::tempdir().expect("temp dir");
        let pid_file = dir.path().join("exec.pid");
        let started = std::time::Instant::now();
        let run = run_wrapper_as(
            &pid_file,
            "setsid sleep 2 > /dev/null 2>&1 &",
            "background",
            dir.path(),
        );
        assert!(run.status.success());
        assert!(
            started.elapsed() >= std::time::Duration::from_secs(2),
            "the wrapper must outlive the leftover process"
        );
        assert!(
            run.stderr.is_empty(),
            "{}",
            String::from_utf8_lossy(&run.stderr)
        );
    }

    /// Leaves `$HOPPERS` processes running, each re-executing itself `$HOPS`
    /// times before it execs `$THEN`, with two thousand variables in its
    /// environment so that every exec spends long laying it out — the time
    /// during which `/proc` reads that environment as empty — and records
    /// their pids in `hoppers`.
    #[cfg(target_os = "linux")]
    const EXEC_HOPPERS: &str = r#"i=0; while [ $i -lt 2000 ]; do export "BULK_$i=$i"; i=$((i + 1)); done; hop='if [ "$1" -gt 0 ]; then exec sh -c "$0" "$0" $(($1 - 1)) "$2"; fi; exec $2'; : > hoppers; n=0; while [ $n -lt "$HOPPERS" ]; do sh -c "$hop" "$hop" "$HOPS" "$THEN" > /dev/null 2>&1 & echo $! >> hoppers; n=$((n + 1)); done"#;

    /// Runs the wrapper over [`EXEC_HOPPERS`] and returns its output and the
    /// hoppers' pids.
    #[cfg(target_os = "linux")]
    fn run_hoppers(
        lifetime: &str,
        hoppers: usize,
        hops: u32,
        then: &str,
        dir: &std::path::Path,
    ) -> (std::process::Output, Vec<String>) {
        let pid_file = dir.join("exec.pid");
        let run = Command::new("sh")
            .args(["-c", CONTAINER_EXEC_WRAPPER, "sh"])
            .arg(&pid_file)
            .arg(EXEC_HOPPERS)
            .arg(lifetime)
            .arg(CONTAINER_JOB_SCRIPT)
            .current_dir(dir)
            .env("HOPPERS", hoppers.to_string())
            .env("HOPS", hops.to_string())
            .env("THEN", then)
            .output()
            .expect("run the exec wrapper");
        let pids = std::fs::read_to_string(dir.join("hoppers")).expect("the hoppers' pids");
        let pids: Vec<String> = pids.lines().map(str::to_string).collect();
        assert_eq!(pids.len(), hoppers, "every hopper started");
        (run, pids)
    }

    /// Kills the processes of `pids` that are still alive and returns them.
    #[cfg(target_os = "linux")]
    fn kill_survivors(pids: &[String], wait: std::time::Duration) -> Vec<String> {
        let survivors: Vec<String> = pids
            .iter()
            .filter(|pid| !dead_within(pid, wait))
            .cloned()
            .collect();
        for pid in &survivors {
            Command::new("kill")
                .args(["-KILL", pid.as_str()])
                .status()
                .expect("kill a survivor");
        }
        survivors
    }

    /// The foreground kill finds every leftover process, also those that are
    /// in an exec while it looks: a process whose new image's environment is
    /// not laid out yet still belongs to the job.
    #[cfg(target_os = "linux")]
    #[test]
    fn foreground_wrapper_kills_leftover_processes_in_an_exec() {
        let dir = tempfile::tempdir().expect("temp dir");
        let (run, pids) = run_hoppers("foreground", 16, 2000, "sleep 300", dir.path());
        let survivors = kill_survivors(&pids, std::time::Duration::from_secs(5));
        let stderr = String::from_utf8_lossy(&run.stderr);
        assert!(
            survivors.is_empty(),
            "the wrapper missed {survivors:?}: {stderr}"
        );
        assert!(run.status.success(), "{stderr}");
        let report = format!("{} killed ", dir.path().join("exec.pid").display());
        for pid in &pids {
            assert!(
                stderr
                    .lines()
                    .filter_map(|line| line.strip_prefix(&report))
                    .any(|killed| killed
                        .split_once(' ')
                        .is_some_and(|(id, _)| id == pid.as_str())),
                "{pid} is not reported killed: {stderr}"
            );
        }
    }

    /// A background wrapper outlives a leftover process that execs again and
    /// again: no look at it during an exec ends the wait early.
    #[cfg(target_os = "linux")]
    #[test]
    fn background_wrapper_outlives_a_leftover_process_in_an_exec() {
        let dir = tempfile::tempdir().expect("temp dir");
        let (run, pids) = run_hoppers("background", 1, 1500, "true", dir.path());
        let survivors = kill_survivors(&pids, std::time::Duration::ZERO);
        let stderr = String::from_utf8_lossy(&run.stderr);
        assert!(
            survivors.is_empty(),
            "the wrapper ended before {survivors:?}: {stderr}"
        );
        assert!(run.status.success(), "{stderr}");
        assert!(run.stderr.is_empty(), "{stderr}");
    }

    /// A process that dropped the marker from its environment, or runs with
    /// none at all, escapes the job: the background wrapper does not wait for
    /// it, and reading an environment of any bytes is no error.
    #[cfg(target_os = "linux")]
    #[test]
    fn background_wrapper_ignores_a_process_without_the_marker() {
        let dir = tempfile::tempdir().expect("temp dir");
        let pid_file = dir.path().join("exec.pid");
        let started = std::time::Instant::now();
        let run = run_wrapper_as(
            &pid_file,
            r#"(unset AITHER_JOB; export ODD="$(printf '\303\251t\303\251\nx\001\177')"; exec sleep 30) > /dev/null 2>&1 & echo $! > escaped; env -i sleep 30 > /dev/null 2>&1 & echo $! >> escaped"#,
            "background",
            dir.path(),
        );
        let elapsed = started.elapsed();
        let pids: Vec<String> = std::fs::read_to_string(dir.path().join("escaped"))
            .expect("the escaped pids")
            .lines()
            .map(str::to_string)
            .collect();
        let survivors = kill_survivors(&pids, std::time::Duration::ZERO);
        assert_eq!(survivors.len(), 2, "both processes ran: {pids:?}");
        let stderr = String::from_utf8_lossy(&run.stderr);
        assert!(run.status.success(), "{stderr}");
        assert!(run.stderr.is_empty(), "{stderr}");
        assert!(
            elapsed < std::time::Duration::from_secs(10),
            "the wrapper waited for processes outside the job"
        );
    }

    /// A helper that fails ends the wait with an error line the exec turns
    /// into a failure, in the background wait and in the foreground kill: it
    /// is not read as "still alive". Runs anywhere `sh` does.
    #[test]
    fn a_failing_helper_ends_the_wait_with_an_error() {
        let dir = tempfile::tempdir().expect("temp dir");
        let pid_file = dir.path().join("exec.pid");
        let broken = "echo the job script needs tr; echo and more; exit 1";
        for lifetime in ["background", "foreground"] {
            let started = std::time::Instant::now();
            let run = run_wrapper_with_helper(&pid_file, "exit 0", lifetime, broken, dir.path());
            assert!(
                started.elapsed() < std::time::Duration::from_secs(5),
                "{lifetime}: the wrapper must not wait on a broken helper"
            );
            let stderr = String::from_utf8_lossy(&run.stderr);
            let error = super::split_killed(&run.stderr, &pid_file.display().to_string())
                .expect_err(&format!("{lifetime}: no error reported in {stderr}"));
            assert!(
                error.contains("the job script needs tr and more"),
                "{error}"
            );
        }
    }

    /// A wrapper that cannot record its pid fails before running the
    /// script, so the exec can never run without a pid to kill it by.
    #[test]
    fn wrapper_fails_fast_without_a_pid_file() {
        let dir = tempfile::tempdir().expect("temp dir");
        let pid_file = dir.path().join("missing").join("exec.pid");
        let run = run_wrapper(&pid_file, "echo ran", dir.path());
        assert_eq!(run.status.code(), Some(125));
        assert!(run.stdout.is_empty(), "the script must not run");
        assert!(
            String::from_utf8_lossy(&run.stderr).contains("cannot record the exec's pid"),
            "{}",
            String::from_utf8_lossy(&run.stderr)
        );
    }
}