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
#[macro_use]
extern crate log;
use std::io;
use std::io::prelude::*;
use std::io::{BufReader};
use std::fs::File;
use std::process::{ChildStdout, Command, Stdio, ExitStatus};
use std::sync::Mutex;
use std::ops::DerefMut;
use std::os::unix::io::FromRawFd;
use std::os::unix::io::AsRawFd;
use std::sync::mpsc;
pub enum Output {
Parent,
Ignore,
ToFd(File),
}
pub struct DealWithOutput { stderr: Output, stdout: Output }
pub fn output() -> DealWithOutput {
DealWithOutput { stdout: Output::Parent, stderr: Output::Parent }
}
impl DealWithOutput {
pub fn stderr(&mut self, stderr: Output) -> &mut Self {
self.stderr = stderr;
self
}
pub fn stdout(&mut self, stdout: Output) -> &mut Self {
self.stdout = stdout;
self
}
}
pub fn process_read_consumer<R: Read>(
deal_with: &mut DealWithOutput,
mut input: R,
cmd_args: (String, Vec<String>))
-> io::Result<ExitStatus>
{
let mut cmd = build_command(cmd_args);
cmd.stdin(Stdio::piped());
setup_stderr(&deal_with.stderr, &mut cmd)?;
setup_stdout(&deal_with.stdout, &mut cmd)?;
let mut process = cmd.spawn()?;
{
let mut stdin = process.stdin.take().expect("impossible! no stdin");
io::copy(&mut input, &mut stdin)?;
}
let status = process.wait()?;
Ok(status)
}
pub fn process_as_reader<R>(
stdin_opt: Option<R>,
stderr: Output,
cmd_args: (String, Vec<String>)) -> io::Result<ChildStream>
where R: Read + Send + 'static,
{
let mut cmd = build_command(cmd_args);
cmd.stdout(Stdio::piped());
if let Some(_) = stdin_opt {
cmd.stdin(Stdio::piped());
}
setup_stderr(&stderr, &mut cmd)?;
let mut process = cmd.spawn()?;
let stdout = process.stdout.take().expect("impossible! no stdout");
let (send_result, receiver) = mpsc::channel();
if let Some(input) = stdin_opt {
let mut stdin = process.stdin.take().expect("impossible! no stdin");
let input_mutex = Mutex::new(input);
let sender = send_result.clone();
let done_stdin = move |result| {
match result {
Err(err) => {
send_or_log_result(sender, Err(ProcessAsyncError::StdinError(err)))
}
Ok(Err(err)) => {
send_or_log_result(sender, Err(ProcessAsyncError::StdinError(err)))
}
Ok(Ok(_)) => {}
}
};
concurrent::spawn_catch_panic(done_stdin, move || {
let mut inp = input_mutex.lock().expect("error locking stdin");
let _ = io::copy(inp.deref_mut(), &mut stdin)?;
Ok(())
});
}
let sender = send_result.clone();
let done_wait = move |result| {
match result {
Err(err) => {
send_or_log_result(sender,
Err(ProcessAsyncError::WaitError(err)))
}
Ok(Err(err)) => {
send_or_log_result(sender,
Err(ProcessAsyncError::WaitError(err)))
}
Ok(Ok(status)) => {
send_or_log_result(sender, Ok(status));
}
}
};
concurrent::spawn_catch_panic(done_wait, move || {
let status = process.wait()?;
Ok(status)
});
Ok(ChildStream {
stdout: BufReader::new(stdout),
wait_result: FutureExitResult::new(receiver)
})
}
#[derive(Debug)]
pub enum ProcessAsyncError {
RecvError(mpsc::RecvError),
WaitError(io::Error),
StdinError(io::Error),
ExitStatusError(Option<i32>),
AlreadyResolvedError,
}
type ProecessAsyncResult = Result<ExitStatus, ProcessAsyncError>;
pub struct FutureExitResult {
recv: mpsc::Receiver<ProecessAsyncResult>,
already: bool,
}
impl FutureExitResult {
fn new(receiver: mpsc::Receiver<ProecessAsyncResult>) -> Self {
FutureExitResult { recv: receiver, already: false }
}
fn exit_status(&mut self) -> ProecessAsyncResult {
if self.already { return Err(ProcessAsyncError::AlreadyResolvedError) }
self.already = true;
match self.recv.recv() {
Err(err) => {
Err(ProcessAsyncError::RecvError(err))
}
Ok(stream_status) => {
stream_status
}
}
}
pub fn wait(&mut self) -> Result<Option<i32>, ProcessAsyncError> {
let status = self.exit_status()?;
if status.success() {
Ok(status.code())
} else {
Err(ProcessAsyncError::ExitStatusError(status.code()))
}
}
}
pub struct ChildStream {
pub stdout: BufReader<ChildStdout>,
pub wait_result: FutureExitResult
}
impl ChildStream {
pub fn wait(&mut self) -> Result<Option<i32>, ProcessAsyncError> {
self.wait_result.wait()
}
}
fn send_or_log_result<T>(sender: mpsc::Sender<Result<T, ProcessAsyncError>>, result: Result<T, ProcessAsyncError>){
match sender.send(result) {
Ok(_) => {}
Err(err) => error!("error sending done message: {}", err),
}
}
fn setup_stderr(deal_with_stderr: &Output, cmd: &mut Command) -> io::Result<()> {
match deal_with_stderr {
&Output::Parent => {}
&Output::Ignore => {
cmd.stderr(Stdio::null());
}
&Output::ToFd(ref file) => {
unsafe {
cmd.stderr(Stdio::from_raw_fd(file.as_raw_fd()));
}
}
}
Ok(())
}
fn setup_stdout(deal_with_stdout: &Output, cmd: &mut Command) -> io::Result<()> {
match deal_with_stdout {
&Output::Parent => {}
&Output::Ignore => {
cmd.stdout(Stdio::null());
}
&Output::ToFd(ref file) => {
unsafe {
cmd.stdout(Stdio::from_raw_fd(file.as_raw_fd()));
}
}
}
Ok(())
}
fn build_command(cmd_args: (String, Vec<String>)) -> Command {
let (exe, args) = cmd_args;
let mut cmd = Command::new(exe);
for arg in args { cmd.arg(arg); }
return cmd
}
mod concurrent {
use std::io;
use std::io::{Error, ErrorKind};
use std::panic;
use std::thread;
use std::thread::JoinHandle;
use std::any::Any;
pub fn caught_panic_to_io_error(err: Box<Any + Send + 'static>) -> io::Error {
let msg = match err.downcast_ref::<&'static str>() {
Some(s) => *s,
None => {
match err.downcast_ref::<String>() {
Some(s) => &s[..],
None => "Box<Any>",
}
}
};
Error::new(ErrorKind::Other, msg)
}
pub fn spawn_catch_panic<Function, Returned, Finished>(done: Finished, f: Function) -> JoinHandle<()>
where Function: FnOnce() -> Returned,
Function: Send + 'static,
Function: panic::UnwindSafe,
Finished: FnOnce(io::Result<Returned>) -> (),
Finished: Send + 'static,
{
thread::spawn(move || {
let result = panic::catch_unwind(move || { f() });
match result {
Err(err) => { done(Err(caught_panic_to_io_error(err))) }
Ok(ok) => { done(Ok(ok)) }
}
})
}
}