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
use nix::sys::signal::{self, Signal};
use nix::sys::wait::{self, WaitPidFlag, WaitStatus};
use nix::unistd::Pid;
use serde::{Deserialize, Serialize};
use std::io::prelude::*;
use std::io::{PipeReader, PipeWriter};
use std::thread;
use std::{fmt, str};
use tempfile::TempDir;
use crate::{Command, ProcPidSmapsRollup, ProcPidStatus, Rusage, error::*};
/// Result of a process after it has terminated.
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct ExitStatus {
/// The exit code of the child process.
pub code: i32,
/// The detailed message of the [code][ExitStatus::code].
pub reason: String,
/// The exit code of the internal process.
pub exit_code: Option<i32>,
/// Information about resource usage of the internal process.
pub rusage: Option<Rusage>,
/// Accumulated smaps stats for all mappings of the internal process.
pub proc_pid_smaps_rollup: Option<ProcPidSmapsRollup>,
/// Memory usage and status information of the internal process.
pub proc_pid_status: Option<ProcPidStatus>,
}
impl ExitStatus {
pub(crate) const SUCCESS: i32 = 0;
pub(crate) const FAILURE: i32 = 125; // If the Container itself fails.
/// Constructs a new ExitStatus with FAILURE code.
pub(crate) fn new_failure(reason: &str) -> Self {
Self {
code: Self::FAILURE,
reason: reason.to_string(),
exit_code: None,
rusage: None,
proc_pid_smaps_rollup: None,
proc_pid_status: None,
}
}
/// Constructs a new ExitStatus from nix::sys::wait::WaitStatus.
pub(crate) fn from_wait_status(ws: &WaitStatus, command: &Command) -> Self {
let program = command.get_program();
match *ws {
WaitStatus::Exited(_, status) => Self {
code: status,
reason: format!("process({program}) exited with code {status}"),
exit_code: Some(status),
rusage: None,
proc_pid_smaps_rollup: None,
proc_pid_status: None,
},
WaitStatus::Signaled(_, signal, _) => Self {
code: 128 + signal as i32,
reason: format!("process({program}) received signal {signal}"),
exit_code: None,
rusage: None,
proc_pid_smaps_rollup: None,
proc_pid_status: None,
},
_ => {
unreachable!("ExitStatus::from_wait_status");
}
}
}
/// Was termination successful? Signal termination is not considered a
/// success, and success is defined as a zero exit status of internal process.
pub fn success(&self) -> bool {
self.code == Self::SUCCESS
}
}
/// The output of a finished process.
pub struct Output {
/// The status of the child process.
pub status: ExitStatus,
/// The data that the internal process wrote to stdout.
pub stdout: Vec<u8>,
/// The data that the internal process wrote to stderr.
pub stderr: Vec<u8>,
}
impl fmt::Debug for Output {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
let stdout_utf8 = str::from_utf8(&self.stdout);
let stdout_debug: &dyn fmt::Debug = match stdout_utf8 {
Ok(ref str) => str,
Err(_) => &self.stdout,
};
let stderr_utf8 = str::from_utf8(&self.stderr);
let stderr_debug: &dyn fmt::Debug = match stderr_utf8 {
Ok(ref str) => str,
Err(_) => &self.stderr,
};
fmt.debug_struct("Output")
.field("status", &self.status)
.field("stdout", stdout_debug)
.field("stderr", stderr_debug)
.finish()
}
}
/// Representation of a running or exited child process.
///
/// A child process is created via the [Command::spawn]. This struct is similar
/// to [std::process::Child].
///
/// [Command::spawn]: crate::Command::spawn
/// [std::process::Child]: https://doc.rust-lang.org/std/process/struct.Child.html
pub struct Child {
pid: Pid,
status: Option<ExitStatus>,
status_reader: Option<PipeReader>,
status_reader_noleading: bool,
tmpdir: Option<TempDir>,
/// Only initialized when using [Stdio::piped()](crate::Stdio::piped()).
pub stdin: Option<PipeWriter>,
/// Only initialized when using [Stdio::piped()](crate::Stdio::piped()).
pub stdout: Option<PipeReader>,
/// Only initialized when using [Stdio::piped()](crate::Stdio::piped()).
pub stderr: Option<PipeReader>,
/// .
#[cfg(feature = "cgroups")]
cgroup: Option<crate::cgroups::Manager>,
/// Only initialized when using [crate::RustSlirp].
#[cfg(feature = "rustslirp")]
pub rustslirp_tapfd: Option<std::os::fd::RawFd>,
}
impl Child {
/// Constructor.
#[allow(clippy::too_many_arguments)]
pub(crate) fn new(
pid: Pid,
stdin: Option<PipeWriter>,
stdout: Option<PipeReader>,
stderr: Option<PipeReader>,
status_reader: PipeReader,
status_reader_noleading: bool,
status: Option<ExitStatus>,
tmpdir: Option<TempDir>,
#[cfg(feature = "cgroups")] cgroup: Option<crate::cgroups::Manager>,
#[cfg(feature = "rustslirp")] rustslirp_tapfd: Option<std::os::fd::RawFd>,
) -> Self {
Self {
pid,
stdin,
stdout,
stderr,
status_reader: Some(status_reader),
status_reader_noleading,
status,
tmpdir,
#[cfg(feature = "cgroups")]
cgroup,
#[cfg(feature = "rustslirp")]
rustslirp_tapfd,
}
}
/// Returns the OS-assigned process identifier associated with this child.
pub fn id(&self) -> u32 {
self.pid.as_raw() as u32
}
/// Forces the child process to exit.
pub fn kill(&mut self) -> Result<()> {
// If we've already waited on this process then the pid can be recycled
// and used for another process, and we probably shouldn't be killing
// random processes, so return Ok because the process has exited already.
if self.status.is_some() {
return Ok(());
}
_ = signal::kill(self.pid, Signal::SIGKILL);
Ok(())
}
/// Attempts to collect the exit status of the child if it has already exited.
///
/// This function will not block the calling thread and will only check to see
/// if the child process has exited or not. If the child has exited then on Unix
/// the process ID is reaped. This function is guaranteed to repeatedly return
/// a successful exit status so long as the child has already exited.
///
/// If the child has exited, then Ok(Some(status)) is returned. If the exit
/// status is not available at this time then Ok(None) is returned. If an error
/// occurs, then that error is returned.
///
/// Note that unlike wait, this function will not attempt to drop stdin.
pub fn try_wait(&mut self) -> Result<Option<ExitStatus>> {
if let Some(status) = &self.status {
return Ok(Some(status.clone()));
}
let flags = Some(WaitPidFlag::WNOHANG);
let ws = wait::waitpid(self.pid, flags).map_err(ProcessErrorKind::NixError)?;
if let WaitStatus::StillAlive = ws {
Ok(None)
} else {
Ok(Some(self.retrieve_exit_status(ws)?))
}
}
/// Waits for the child to exit completely, returning the status that it
/// exited with.
///
/// The stdin handle to the child process, if any, will be closed before
/// waiting. This helps avoid deadlock: it ensures that the child does not
/// block waiting for input from the parent, while the parent waits for
/// the child to exit.
pub fn wait(&mut self) -> Result<ExitStatus> {
drop(self.stdin.take());
if let Some(status) = &self.status {
return Ok(status.clone());
}
let flags = None;
let ws = wait::waitpid(self.pid, flags).map_err(ProcessErrorKind::NixError)?;
self.retrieve_exit_status(ws)
}
/// Retrieve exit status.
fn retrieve_exit_status(&mut self, ws: WaitStatus) -> Result<ExitStatus> {
if let WaitStatus::Signaled(_, Signal::SIGKILL, _) = ws {
let reason = "container received signal SIGKILL";
self.status = Some(ExitStatus::new_failure(reason));
}
if self.status.is_none() {
self.retrieve_exit_status_internal_process()?;
}
self.logging();
drop(self.tmpdir.take());
#[cfg(feature = "cgroups")]
drop(self.cgroup.take());
let s = self.status.clone();
s.ok_or(Error::ProcessError(ProcessErrorKind::ChildExitStatusGone))
}
/// Retrieve the exit status of the internal process from a pipe whose
/// write end has been closed.
fn retrieve_exit_status_internal_process(&mut self) -> Result<()> {
if let Some(mut reader) = self.status_reader.take() {
if !self.status_reader_noleading {
let mut request = [0];
reader
.read_exact(&mut request)
.map_err(ProcessErrorKind::StdIoError)?;
}
let mut encoded = vec![];
reader
.read_to_end(&mut encoded)
.map_err(ProcessErrorKind::StdIoError)?;
drop(reader);
let status =
postcard::from_bytes(&encoded[..]).map_err(ProcessErrorKind::PostcardError)?;
self.status = Some(status);
}
Ok(())
}
/// Logging.
fn logging(&self) {
if !log::log_enabled!(log::Level::Debug) {
return;
}
if let Some(status) = &self.status {
log::debug!("================================");
log::debug!("Exited: {}", status.reason);
if let Some(r) = &status.rusage {
let (rt, ut, st) = (r.real_time, r.user_time, r.system_time);
log::debug!("Metric: RealTime: {:>12} sec", rt.as_secs_f64());
log::debug!("Metric: UserTime: {:>12} sec", ut.as_secs_f64());
log::debug!("Metric: SysTime: {:>12} sec", st.as_secs_f64());
}
if let Some(r) = &status.proc_pid_smaps_rollup {
log::debug!("Metric: Rss: {:>12} kB", r.rss);
log::debug!("Metric: Shared_Dirty: {:>12} kB", r.shared_dirty);
log::debug!("Metric: Shared_Clean: {:>12} kB", r.shared_clean);
log::debug!("Metric: Private_Dirty: {:>12} kB", r.private_dirty);
log::debug!("Metric: Private_Clean: {:>12} kB", r.private_clean);
log::debug!("Metric: Pss: {:>12} kB", r.pss);
log::debug!("Metric: Pss_Dirty: {:>12} kB", r.pss_dirty);
log::debug!("Metric: Pss_Anon: {:>12} kB", r.pss_anon);
log::debug!("Metric: Pss_File: {:>12} kB", r.pss_file);
log::debug!("Metric: Pss_Shmem: {:>12} kB", r.pss_shmem);
}
if let Some(r) = &status.proc_pid_status {
log::debug!("Metric: VmPeak: {:>12} kB", r.vmpeak);
log::debug!("Metric: VmSize: {:>12} kB", r.vmsize);
log::debug!("Metric: VmHWM: {:>12} kB", r.vmhwm);
log::debug!("Metric: VmRSS: {:>12} kB", r.vmrss);
log::debug!("Metric: VmData: {:>12} kB", r.vmdata);
log::debug!("Metric: VmStk: {:>12} kB", r.vmstk);
log::debug!("Metric: VmExe: {:>12} kB", r.vmexe);
log::debug!("Metric: VmLib: {:>12} kB", r.vmlib);
log::debug!("Metric: VmPTE: {:>12} kB", r.vmpte);
log::debug!("Metric: VmSwap: {:>12} kB", r.vmswap);
log::debug!("Metric: RssAnon: {:>12} kB", r.rssanon);
log::debug!("Metric: RssFile: {:>12} kB", r.rssfile);
log::debug!("Metric: RssShmem: {:>12} kB", r.rssshmem);
}
} else {
log::debug!("================================");
log::debug!("Exited: NULL");
}
}
/// Simultaneously waits for the child to exit and collect all remaining
/// output on the stdout/stderr handles, returning an `Output` instance.
///
/// The stdin handle to the child process, if any, will be closed before
/// waiting. This helps avoid deadlock: it ensures that the child does not
/// block waiting for input from the parent, while the parent waits for
/// the child to exit.
///
/// If the child was configured with standard output or error wired to
/// a file descriptor or inherited from the process, then no output will be
/// returned.
pub fn wait_with_output(&mut self) -> Result<Output> {
drop(self.stdin.take());
let (mut stdout, mut stderr) = (vec![], vec![]);
match (self.stdout.take(), self.stderr.take()) {
(None, None) => {}
(Some(mut out), None) => {
out.read_to_end(&mut stdout)
.map(drop)
.map_err(ProcessErrorKind::StdIoError)?;
}
(None, Some(mut err)) => {
err.read_to_end(&mut stderr)
.map(drop)
.map_err(ProcessErrorKind::StdIoError)?;
}
(Some(mut out), Some(mut err)) => {
self.read2(&mut out, &mut stdout, &mut err, &mut stderr)?;
}
}
let status = self.wait()?;
Ok(Output {
status,
stdout,
stderr,
})
}
fn read2(
&mut self,
out: &mut PipeReader,
stdout: &mut Vec<u8>,
err: &mut PipeReader,
stderr: &mut Vec<u8>,
) -> Result<()> {
thread::scope(|s| {
let throut = s.spawn(move || out.read_to_end(stdout).map(drop));
let threrr = s.spawn(move || err.read_to_end(stderr).map(drop));
let r = throut.join();
match r {
Err(_) => return Err(ProcessErrorKind::StdThreadJoinError),
Ok(Err(e)) => return Err(ProcessErrorKind::StdIoError(e)),
Ok(Ok(_)) => {}
}
let r = threrr.join();
match r {
Err(_) => Err(ProcessErrorKind::StdThreadJoinError),
Ok(r) => r.map_err(ProcessErrorKind::StdIoError),
}
})?;
Ok(())
}
}