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
use std::sync::Arc;
use async_priority_channel as priority;
use command_group::AsyncCommandGroup;
use tokio::{
select, spawn,
sync::{
mpsc::{self, Sender},
watch,
},
};
use tracing::{debug, debug_span, error, trace, Span};
use crate::{
action::{PostSpawn, PreSpawn},
command::Command,
error::RuntimeError,
event::{Event, Priority, Source, Tag},
handler::{rte, HandlerLock},
signal::process::SubSignal,
};
use super::Process;
#[derive(Clone, Copy, Debug)]
enum Intervention {
Kill,
Signal(SubSignal),
}
#[derive(Debug)]
pub struct Supervisor {
intervene: Sender<Intervention>,
ongoing: watch::Receiver<bool>,
}
impl Supervisor {
pub fn spawn(
errors: Sender<RuntimeError>,
events: priority::Sender<Event, Priority>,
mut commands: Vec<Command>,
grouped: bool,
actioned_events: Arc<[Event]>,
pre_spawn_handler: HandlerLock<PreSpawn>,
post_spawn_handler: HandlerLock<PostSpawn>,
) -> Result<Self, RuntimeError> {
commands.reverse();
let next = commands.pop().ok_or(RuntimeError::NoCommands)?;
let (notify, waiter) = watch::channel(true);
let (int_s, int_r) = mpsc::channel(8);
spawn(async move {
let span = debug_span!("supervisor");
let mut next = next;
let mut commands = commands;
let mut int = int_r;
loop {
let (mut process, pid) = match spawn_process(
span.clone(),
next,
grouped,
actioned_events.clone(),
pre_spawn_handler.clone(),
post_spawn_handler.clone(),
)
.await
{
Ok(pp) => pp,
Err(err) => {
let _enter = span.enter();
error!(%err, "while spawning process");
errors.send(err).await.ok();
trace!("marking process as done");
notify
.send(false)
.unwrap_or_else(|e| trace!(%e, "error sending process complete"));
trace!("closing supervisor task early");
return;
}
};
span.in_scope(|| debug!(?process, ?pid, "spawned process"));
loop {
select! {
p = process.wait() => {
match p {
Ok(_) => break, Err(err) => {
let _enter = span.enter();
error!(%err, "while waiting on process");
errors.try_send(err).ok();
trace!("marking process as done");
notify.send(false).unwrap_or_else(|e| trace!(%e, "error sending process complete"));
trace!("closing supervisor task early");
return;
}
}
},
Some(int) = int.recv() => {
match int {
Intervention::Kill => {
if let Err(err) = process.kill().await {
let _enter = span.enter();
error!(%err, "while killing process");
errors.try_send(err).ok();
trace!("continuing to watch command");
}
}
#[cfg(unix)]
Intervention::Signal(sig) => {
let _enter = span.enter();
if let Some(sig) = sig.to_nix() {
if let Err(err) = process.signal(sig) {
error!(%err, "while sending signal to process");
errors.try_send(err).ok();
trace!("continuing to watch command");
}
} else {
let err = RuntimeError::UnsupportedSignal(sig);
error!(%err, "while sending signal to process");
errors.try_send(err).ok();
trace!("continuing to watch command");
}
}
#[cfg(windows)]
Intervention::Signal(sig) => {
let _enter = span.enter();
let err = RuntimeError::UnsupportedSignal(sig);
error!(%err, "while sending signal to process");
errors.try_send(err).ok();
trace!("continuing to watch command");
}
}
}
else => break,
}
}
span.in_scope(|| trace!("got out of loop, waiting once more"));
match process.wait().await {
Err(err) => {
let _enter = span.enter();
error!(%err, "while waiting on process");
errors.try_send(err).ok();
}
Ok(status) => {
let event = span.in_scope(|| {
let event = Event {
tags: vec![
Tag::Source(Source::Internal),
Tag::ProcessCompletion(status.map(|s| s.into())),
],
metadata: Default::default(),
};
debug!(?event, "creating synthetic process completion event");
event
});
if let Err(err) = events.send(event, Priority::Low).await {
let _enter = span.enter();
error!(%err, "while sending process completion event");
errors
.try_send(RuntimeError::EventChannelSend {
ctx: "command supervisor",
err,
})
.ok();
}
}
}
let _enter = span.enter();
if let Some(cmd) = commands.pop() {
debug!(?cmd, "queuing up next command");
next = cmd;
} else {
debug!("no more commands to supervise");
break;
}
}
let _enter = span.enter();
trace!("marking process as done");
notify
.send(false)
.unwrap_or_else(|e| trace!(%e, "error sending process complete"));
trace!("closing supervisor task");
});
Ok(Self {
ongoing: waiter,
intervene: int_s,
})
}
pub async fn signal(&self, signal: SubSignal) {
if cfg!(windows) {
if let SubSignal::ForceStop = signal {
self.intervene.send(Intervention::Kill).await.ok();
}
} else {
trace!(?signal, "sending signal intervention");
self.intervene.send(Intervention::Signal(signal)).await.ok();
}
}
pub async fn kill(&self) {
trace!("sending kill intervention");
self.intervene.send(Intervention::Kill).await.ok();
}
pub fn is_running(&self) -> bool {
let ongoing = *self.ongoing.borrow();
trace!(?ongoing, "supervisor state");
ongoing
}
pub async fn wait(&self) -> Result<(), RuntimeError> {
if !*self.ongoing.borrow() {
trace!("supervisor already completed (pre)");
return Ok(());
}
debug!("waiting on supervisor completion");
let mut ongoing = self.ongoing.clone();
ongoing
.changed()
.await
.map_err(|err| RuntimeError::InternalSupervisor(err.to_string()))?;
debug!("supervisor completed");
Ok(())
}
}
async fn spawn_process(
span: Span,
command: Command,
grouped: bool,
actioned_events: Arc<[Event]>,
pre_spawn_handler: HandlerLock<PreSpawn>,
post_spawn_handler: HandlerLock<PostSpawn>,
) -> Result<(Process, u32), RuntimeError> {
let (pre_spawn, spawnable) = span.in_scope::<_, Result<_, RuntimeError>>(|| {
debug!(%grouped, ?command, "preparing command");
let mut spawnable = command.to_spawnable()?;
spawnable.kill_on_drop(true);
debug!("running pre-spawn handler");
Ok(PreSpawn::new(
command.clone(),
spawnable,
actioned_events.clone(),
))
})?;
pre_spawn_handler
.call(pre_spawn)
.await
.map_err(|e| rte("action pre-spawn", e))?;
let (proc, id, post_spawn) = span.in_scope::<_, Result<_, RuntimeError>>(|| {
let mut spawnable = Arc::try_unwrap(spawnable)
.map_err(|_| RuntimeError::HandlerLockHeld("pre-spawn"))?
.into_inner();
debug!(command=?spawnable, "spawning command");
let (proc, id) = if grouped {
let proc = spawnable
.group_spawn()
.map_err(|err| RuntimeError::IoError {
about: "spawning process group",
err,
})?;
let id = proc.id().ok_or(RuntimeError::ProcessDeadOnArrival)?;
debug!(pgid=%id, "process group spawned");
(Process::Grouped(proc), id)
} else {
let proc = spawnable.spawn().map_err(|err| RuntimeError::IoError {
about: "spawning process (ungrouped)",
err,
})?;
let id = proc.id().ok_or(RuntimeError::ProcessDeadOnArrival)?;
debug!(pid=%id, "process spawned");
(Process::Ungrouped(proc), id)
};
debug!("running post-spawn handler");
Ok((
proc,
id,
PostSpawn {
command: command.clone(),
events: actioned_events.clone(),
id,
grouped,
},
))
})?;
post_spawn_handler
.call(post_spawn)
.await
.map_err(|e| rte("action post-spawn", e))?;
Ok((proc, id))
}