tobogganSe connecter

louise

Clone avec HTTPS, un jeton personnel en mot de passe, ou avec SSH, une clé ajoutée dans vos paramètres.

188 lignes · 6586 octetsBrut · Historique
1//! Running a program for compiled programs (`std/command`, ADR 0085).
2//!
3//! The driver is `louise_rt_prims::command`, shared with the interpreter.
4//! Here the calling actor parks on the child's descriptors (its pipes,
5//! its pidfd and a timerfd for the next deadline), all registered with the
6//! scheduler's reactor under one token, as a socket is (`net.rs`): the
7//! scheduler thread is never blocked on the child. A kill wakes the actor,
8//! which unwinds; dropping the child then kills its process group and
9//! reaps it.
10//!
11//! Arguments come as plain values (texts, lists, `Bytes`, `Int`s) and the
12//! result as tuples of `Int`s and `Bytes`: `std/command` builds its own
13//! types from them, so nothing here depends on their layout.
14
15use std::os::fd::RawFd;
16use std::path::PathBuf;
17use std::time::Duration;
18
19use louise_rt_prims::command::{
20 Child, Collected, Dir, Failure, Interest, Outcome, Spec, Step, spawn,
21};
22use mio::Token;
23use mio::unix::SourceFd;
24
25use crate::abi::{Ctx, UNIT, Value, int};
26use crate::int::saturating;
27use crate::net::{io_events, wait_for};
28use crate::prims::boolean;
29use crate::sched::this;
30use crate::values::{bytes_from, bytes_of, cell, list, list_items, string, text};
31
32/// A running child and its registrations, undone when it is dropped
33/// (done, or its actor was killed).
34struct Running {
35 ctx: *mut Ctx,
36 child: Child,
37}
38
39impl Running {
40 /// Register the child's descriptors under `token`, edge-triggered.
41 fn register(&self, token: Token) -> std::io::Result<()> {
42 // SAFETY: `ctx` is the running actor's context.
43 let (_, sched) = unsafe { this(self.ctx) };
44 sched.with_registry(|registry| {
45 self.child.fds().into_iter().try_for_each(|(fd, interest)| {
46 let interest = match interest {
47 Interest::Read => mio::Interest::READABLE,
48 Interest::Write => mio::Interest::WRITABLE,
49 };
50 registry.register(&mut SourceFd(&fd), token, interest)
51 })
52 })
53 }
54}
55
56impl Drop for Running {
57 fn drop(&mut self) {
58 // SAFETY: `ctx` is the actor's context, alive while it unwinds.
59 let (_, sched) = unsafe { this(self.ctx) };
60 let fds: Vec<RawFd> = self.child.fds().into_iter().map(|(fd, _)| fd).collect();
61 sched.with_registry(|registry| {
62 for fd in &fds {
63 // Closed descriptors left epoll by themselves.
64 let _ = registry.deregister(&mut SourceFd(fd));
65 }
66 });
67 }
68}
69
70/// `run_raw`: run a program to its end (see `std/command`). Returns
71/// `Ok((exit kind, exit value, stdout, stderr, stdout cut, stderr cut,
72/// files))`, each file `(kind, size, data)` in the order of `out_names`,
73/// or `Error((code, message))`.
74///
75/// # Safety
76/// `ctx` must be the running actor's context; the other arguments live
77/// values of the types `std/command` declares.
78#[unsafe(no_mangle)]
79#[allow(clippy::too_many_arguments, reason = "one extern, all plain values")]
80pub unsafe extern "C" fn tl_command_run(
81 ctx: *mut Ctx,
82 program: Value,
83 args: Value,
84 env_names: Value,
85 env_values: Value,
86 dir_kind: Value,
87 dir: Value,
88 in_names: Value,
89 in_data: Value,
90 out_names: Value,
91 max_file: Value,
92 stdin: Value,
93 max_stdout: Value,
94 max_stderr: Value,
95 timeout_ms: Value,
96 grace_ms: Value,
97) -> Value {
98 // SAFETY: caller guarantees live values of the declared types.
99 let spec = unsafe {
100 let texts = |l: Value| {
101 list_items(l)
102 .map(|v| text(v).to_owned())
103 .collect::<Vec<_>>()
104 };
105 let count = |v: Value| usize::try_from(saturating(v)).unwrap_or(0);
106 let ms = |v: Value| Duration::from_millis(u64::try_from(saturating(v)).unwrap_or(0));
107 let dir = match saturating(dir_kind) {
108 0 => Dir::Inherit,
109 1 => Dir::In(PathBuf::from(text(dir))),
110 _ => Dir::Scratch {
111 inputs: texts(in_names)
112 .into_iter()
113 .zip(list_items(in_data).map(|v| bytes_of(v).to_vec()))
114 .collect(),
115 outputs: texts(out_names),
116 max_file: count(max_file),
117 },
118 };
119 Spec {
120 program: text(program).to_owned(),
121 args: texts(args),
122 env: texts(env_names)
123 .into_iter()
124 .zip(texts(env_values))
125 .collect(),
126 dir,
127 stdin: bytes_of(stdin).to_vec(),
128 max_stdout: count(max_stdout),
129 max_stderr: count(max_stderr),
130 timeout: ms(timeout_ms),
131 grace: ms(grace_ms),
132 }
133 };
134 let running = match spawn(spec) {
135 Ok(child) => Running { ctx, child },
136 Err(f) => return failure(ctx, &f),
137 };
138 // SAFETY: `ctx` is the running actor's context.
139 let token = unsafe { this(ctx).1.io_token() };
140 if let Err(e) = running.register(token) {
141 return failure(ctx, &Failure::Failed(format!("reactor: {e}")));
142 }
143 let mut running = running;
144 loop {
145 // SAFETY: `ctx` is the running actor's context.
146 let seen = unsafe { io_events(ctx) };
147 if let Step::Done(outcome) = running.child.step() {
148 drop(running);
149 return finished(ctx, outcome);
150 }
151 // SAFETY: as above; a kill returns false, and dropping `running`
152 // kills and reaps the child.
153 if !unsafe { wait_for(ctx, token, seen) } {
154 return UNIT;
155 }
156 }
157}
158
159fn finished(ctx: *mut Ctx, o: Outcome) -> Value {
160 let files: Vec<Value> = o
161 .files
162 .iter()
163 .map(|f| {
164 let (size, data) = match f {
165 Collected::Found(_, data) => (data.len() as i64, bytes_from(ctx, data)),
166 Collected::TooLarge(_, size) => (*size as i64, bytes_from(ctx, &[])),
167 Collected::Absent(_) => (0, bytes_from(ctx, &[])),
168 };
169 cell(ctx, 0, &[int(f.kind()), int(size), data])
170 })
171 .collect();
172 let fields = [
173 int(o.exit.kind()),
174 int(o.exit.value()),
175 bytes_from(ctx, &o.stdout),
176 bytes_from(ctx, &o.stderr),
177 boolean(o.stdout_cut),
178 boolean(o.stderr_cut),
179 list(ctx, files.into_iter()),
180 ];
181 let tuple = cell(ctx, 0, &fields);
182 cell(ctx, 0, &[tuple])
183}
184
185fn failure(ctx: *mut Ctx, f: &Failure) -> Value {
186 let pair = cell(ctx, 0, &[int(f.code()), string(ctx, f.message())]);
187 cell(ctx, 1, &[pair])
188}