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
//! The run loop, and what a `Start` does.
//!
//! `run` drains the mailbox until a shutdown resolves, and `handle_command`
//! is the one dispatch point every command passes through. `do_start` is
//! here too, because starting a sheep is the path the rest of the actor is
//! shaped around.
use super::*;
impl<R: ProcessRunner> Actor<R> {
/// Runs the actor to completion: every mailbox message until a `Shutdown`
/// fully resolves. Dropping `rx` then closes the mailbox, so later
/// [`SupervisorHandle`] calls see [`SupervisorError::EngineStopped`].
pub(super) async fn run(mut self, mut rx: mpsc::Receiver<Msg>) {
// Both spawn paths install their flock before this runs, so seeding
// here is what keeps a handover from announcing a carried table.
let mut announced = self.dog_index();
while let Some(msg) = rx.recv().await {
let should_break = match msg {
// Synchronous: nothing in the command path awaits, so the
// actor cannot park on a busy sheep task.
Msg::Command(cmd) => self.handle_command(cmd),
Msg::Exited { id, outcome } => self.handle_exited(id, outcome),
Msg::RestartDue { id, epoch } => {
self.handle_restart_due(id, epoch);
false
}
Msg::Ready { id } => {
self.handle_ready_signal(id);
false
}
Msg::LambLabel {
root_pid,
pid,
label,
} => {
if let Some(extras) = self.extras.as_ref() {
let now = tokio::time::Instant::now();
extras.stats.label_lamb(root_pid, pid, &label, now);
}
false
}
Msg::ReloadDeadline { name, stamp } => {
self.handle_reload_deadline(&name, stamp);
false
}
Msg::ReloadVerified {
name,
new_id,
readiness,
} => {
self.handle_reload_verified(&name, new_id, readiness);
false
}
Msg::ActionReply {
id,
action,
body,
stamp,
} => {
self.handle_action_reply(id, &action, body, stamp);
false
}
Msg::ActionResult { id, stamp, outcome } => {
self.handle_action_result(id, stamp, outcome);
false
}
Msg::ReadyResult {
id,
epoch,
manually,
readiness,
} => {
self.handle_ready_result(id, epoch, manually, readiness);
false
}
};
// After every message rather than in each handler, so no path
// that registers, deletes or edits a sheep can forget it.
self.announce_dog_tables(&mut announced);
self.prune_disabled();
if should_break {
break;
}
}
}
pub(super) fn handle_command(&mut self, cmd: Command) -> bool {
match cmd {
// Rejected once shutdown has begun: it would spawn a child the
// shutdown aggregation, fixed when it ran, cannot know to kill.
Command::Start {
apps,
policy,
gate,
reply,
} => {
let result = if self.shutting_down {
Err(SupervisorError::EngineStopped)
} else {
self.do_start(apps, None, policy, &gate)
};
let _ = reply.send(result);
false
}
Command::RegisterAtRest {
apps,
disabled,
reply,
} => {
self.mark_disabled(&apps, disabled);
let registered = apps.iter().map(|app| self.register_at_rest(app)).collect();
let _ = reply.send(Ok(registered));
false
}
Command::RegisterDogsAtRest {
dogs,
disabled,
reply,
} => {
let registered = dogs
.into_iter()
.map(|(app, source)| self.register_dog_at_rest(&app, source, &disabled))
.collect();
let _ = reply.send(Ok(registered));
false
}
Command::ConfigDrift { apps, reply } => {
let _ = reply.send(Ok(self.config_drift(&apps)));
false
}
// Rejected while shutting down: a dog spawns. The check is inside
// `do_start_dog`.
Command::StartDog { app, source, reply } => {
let result = self.do_start_dog(*app, source);
let _ = reply.send(result);
false
}
Command::Scale { name, count, reply } => {
self.handle_scale(&name, count, reply);
false
}
// Answered during a shutdown: `handle_apply_config` declines to
// route the instance count while `shutting_down`.
Command::ApplyConfig { apps, reset, reply } => {
let report = self.handle_apply_config(apps, reset);
let _ = reply.send(Ok(report));
false
}
// All three are answered during a shutdown: one reads memory,
// and the others park a config for a spawn a shutdown will not
// reach.
Command::SheepConfig { name, reply } => {
let _ = reply.send(self.handle_sheep_config(&name));
false
}
Command::SetSheepEnv {
name,
key,
value,
reply,
} => {
let _ = reply.send(self.handle_set_sheep_env(
&name,
&key,
value.as_ref().map(EnvValue::as_str),
));
false
}
Command::SetSheepEnvBatch {
name,
entries,
force,
dry_run,
reply,
} => {
let entries: BTreeMap<String, String> = entries
.into_iter()
.map(|(key, value)| (key, value.as_str().to_string()))
.collect();
let _ =
reply.send(self.handle_set_sheep_env_batch(&name, &entries, force, dry_run));
false
}
Command::SetSheepField {
name,
key,
value,
reply,
} => {
let _ = reply.send(self.handle_set_sheep_field(&name, &key, &value));
false
}
// Both answered during a shutdown, as the pane's doors above are.
Command::DogSheepSettings { dog, reply } => {
let _ = reply.send(self.handle_dog_sheep_settings(&dog));
false
}
Command::SetSheepDogSettings {
name,
dog,
table,
reply,
} => {
let _ = reply.send(self.handle_set_sheep_dog_settings(&name, &dog, table));
false
}
Command::SetSmit {
conn,
sheep,
smit,
reply,
} => {
let _ = reply.send(self.handle_set_smit(conn, &sheep, smit));
false
}
Command::ForgetSmits { conn, reply } => {
self.smits.retain(|_, (painter, _)| *painter != conn);
let _ = reply.send(());
false
}
Command::List { reply } => {
let _ = reply.send(self.snapshot_all());
false
}
Command::Reopen { selector, reply } => {
self.handle_reopen(&selector, reply);
false
}
Command::Flush { selector, reply } => {
self.handle_flush(&selector, reply);
false
}
#[cfg(unix)]
Command::HandoverSnapshot { fds, reply } => {
self.handle_handover_snapshot(fds, reply);
false
}
#[cfg(unix)]
Command::HandoverFitness { reply } => {
self.handle_handover_fitness(reply);
false
}
Command::Trigger {
selector,
action,
params,
reply,
} => {
self.begin_action(&selector, action, params, reply);
false
}
Command::Signal {
selector,
sig,
reply,
} => {
self.begin_signal(&selector, sig, reply);
false
}
Command::SendLine {
selector,
line,
reply,
} => {
self.begin_send_line(&selector, line, reply);
false
}
Command::Stop { selector, reply } => {
self.begin_manual(
selector,
ManualKind::Stop,
CommandOrigin::Operator,
ReplyKind::Info(reply),
);
false
}
Command::Restart {
selector,
origin,
reply,
} => {
if self.shutting_down {
send_reply(ReplyKind::Info(reply), Err(SupervisorError::EngineStopped));
} else {
self.restart_unless_disabled(&selector, origin, ReplyKind::Info(reply));
}
false
}
Command::Disable { selector, reply } => {
self.handle_disable(&selector, reply);
false
}
Command::DisableDog { name, reply } => {
self.handle_disable_dog(&name, reply);
false
}
Command::Enable { selector, reply } => {
self.handle_enable(&selector, reply);
false
}
Command::ExtraRestart {
id,
pid,
epoch,
observed,
} => {
self.handle_extra_restart(id, pid, epoch, observed);
false
}
Command::Reload { selector, reply } => {
if self.shutting_down {
let _ = reply.send(Err(SupervisorError::EngineStopped));
} else {
self.handle_reload(&selector, reply);
}
false
}
Command::Delete { selector, reply } => {
self.begin_manual(
selector,
ManualKind::Delete,
CommandOrigin::Operator,
ReplyKind::Ids(reply),
);
false
}
Command::Shutdown { reply } => self.begin_shutdown(reply),
}
}
/// Registers + spawns one dog, or reports the one already running under
/// that name.
///
/// The name lookup reads names rather than markers: what it rules out is
/// two live processes under one name, dog or not. A dog entry at rest is
/// the exception, since no process stands behind it: it spawns in place
/// from `app` and `source`, which win over what it was registered with.
/// A dog that ran and stopped is not at rest, so a boot that names it
/// again leaves it stopped.
pub(super) fn do_start_dog(
&mut self,
app: ResolvedApp,
source: DogSource,
) -> Result<ProcessInfo, SupervisorError> {
if self.shutting_down {
return Err(SupervisorError::EngineStopped);
}
let name = app.config().name.clone();
let held = self
.sheep
.iter()
.find(|(_, slot)| slot.entry.spec.config().name == name)
.map(|(id, slot)| {
(
*id,
is_at_rest(&slot.entry) || self.is_parked_dog(&slot.entry),
to_info(&slot.entry, &self.smits),
)
});
let at_rest = match held {
Some((id, true, _)) => Some(id),
Some((_, false, info)) => {
// A disable still stopping this dog is the operator's earlier
// word, and the enable is the later one.
self.cancel_dog_disable(&name);
return Ok(info);
}
None => None,
};
// Cleared whether or not the spawn lands: the operator's word is
// `enable`, and a spawn that fails is `Errored` rather than disabled.
self.disabled.remove(&name);
// The at-rest entry is dropped and the spawn takes its id, so a dog
// keeps its place in the listing across an enable. `spawn_fresh` hands
// out `next_id`, and a dog is one instance, which is one id.
let resume = at_rest.map(|id| {
self.sheep.remove(&id);
std::mem::replace(&mut self.next_id, id)
});
// `PerApp`: a dog that cannot start must land in the dogs table as
// `Errored`, which `dogs::spawn_dog_watch` subscribes to.
let started = self.do_start(
vec![app],
Some(source),
BatchPolicy::PerApp,
&BTreeSet::new(),
);
if let Some(next_id) = resume {
debug_assert_eq!(self.next_id, at_rest.map_or(0, |id| id + 1));
self.next_id = next_id;
}
started?
.into_iter()
.next()
.ok_or_else(|| SupervisorError::SpawnFailed("the dog registered no instance".into()))
}
/// Expands each app through `instance_slots` + `assemble`, spawning one
/// instance per slot, after checking every app in the batch.
///
/// Under [`BatchPolicy::AllOrNothing`] nothing is registered if any app
/// fails that check, and the error names every one that did. A spawn that
/// fails anyway still leaves the batch part-registered: only exec knows
/// for certain.
///
/// `dog` is written onto every entry this registers, and is `None` for
/// every caller but [`Self::do_start_dog`]; see [`ProcessEntry::dog`].
pub(super) fn do_start(
&mut self,
apps: Vec<ResolvedApp>,
dog: Option<DogSource>,
policy: BatchPolicy,
gate: &BTreeSet<String>,
) -> Result<Vec<ProcessInfo>, SupervisorError> {
// Before any app is registered, so a refused one costs the batch
// nothing but the refusal. A dog is never marked, and a dog's name
// is not a sheep's to take.
if dog.is_none() {
self.refuse_dog_names(apps.iter().map(|app| app.config().name.as_str()))?;
self.refuse_disabled(apps.iter().map(|app| app.config().name.as_str()))?;
}
// One sequence rather than two: a zip against `apps` misaligns the
// moment a failure is skipped.
let mut ready: Vec<(ResolvedApp, Option<Credentials>)> = Vec::with_capacity(apps.len());
// `AllOrNothing` only: a non-empty `refusals` returns before anything
// is registered.
let mut refusals = Vec::new();
// `PerApp` only, joined into one error at the end.
let mut failures = Vec::new();
let total = apps.len();
for app in apps {
let name = app.config().name.clone();
// Once per app: every instance shares one identity, and it is
// ahead of the registering loop so a lookup failing on the fourth
// app leaves none of the first three registered.
let credentials = match privilege::resolve(app.config()) {
Ok(resolved) => resolved,
Err(err) => {
// One refusal per app, not one per failed check: the
// summary below counts apps.
match policy {
// No row: one `Errored` row alone is the half-state
// this policy prevents.
BatchPolicy::AllOrNothing => refusals.push(format!("{name}: {err}")),
// A row, since the rest of the batch goes on. Safe
// only because it carries `SpawnIdentity::Unresolved`,
// so a later restart resolves through
// `credentials_for_spawn` and meets this same refusal.
BatchPolicy::PerApp => {
failures.push(format!("{name}: {err}"));
// `Fresh` only: the emit announces a transition,
// and a repeat restore transitions nothing.
if let Registration::Fresh(info) = self.register_without_spawning(
&app,
ProcStatus::Errored,
dog.clone(),
) {
self.emit(ProcessEventKind::Errored, info, true);
}
}
}
continue;
}
};
// Instance 0 and no credentials: neither changes which file exec
// names, which is all `preflight` reads.
let view = self.secret_view(&app);
let described = match assemble(&app, 0, &self.paths, None, &view) {
Ok(spec) => spec,
// A reference nobody has set is as knowable here as a missing
// binary is, and here is the last point at which refusing
// costs nothing: no app in the batch is registered yet.
Err(err) if !err.is_retriable() => match policy {
BatchPolicy::AllOrNothing => {
refusals.push(format!("{name}: {err}"));
continue;
}
// Reported, never refused: the spawn below meets the same
// error and leaves an `Errored` row an operator can read.
BatchPolicy::PerApp => {
tracing::warn!(sheep = %name, "{err}");
describe(&app, 0, &self.paths, None, &view)
}
},
// Decided nowhere but at the spawn: a provider dog that is
// merely late is what `spawn_fresh` routes to the ordinary
// backoff, per instance.
Err(_) => describe(&app, 0, &self.paths, None, &view),
};
match self.runner.preflight(&described) {
Preflight::Unknown => {}
Preflight::Impossible(reason) if policy == BatchPolicy::AllOrNothing => {
refusals.push(format!("{name}: {reason}"));
continue;
}
// Reported, never refused: the spawn fails on its own and
// names the same program.
Preflight::Impossible(reason) | Preflight::Doubtful(reason) => {
tracing::warn!(sheep = %name, "{reason}");
}
}
ready.push((app, credentials));
}
if !refusals.is_empty() {
return Err(SupervisorError::CannotStart(format!(
"nothing in this batch was registered; {} of {} apps cannot start: {}",
refusals.len(),
total,
refusals.join("; "),
)));
}
let mut results = Vec::new();
'apps: for (app, credentials) in ready {
let name = app.config().name.clone();
let mut existing: Vec<u32> = self
.sheep
.values()
.filter(|slot| slot.entry.spec.config().name == name)
.map(|slot| slot.entry.instance)
.collect();
existing.sort_unstable();
let slots = instance_slots(&existing, app.config().instances);
for instance in slots {
match self.spawn_fresh(&app, instance, credentials, dog.clone(), gate) {
Ok(info) => results.push(info),
Err(message) => {
let failure = format!("{name}: {message}");
match policy {
BatchPolicy::AllOrNothing => {
return Err(SupervisorError::SpawnFailed(failure));
}
// Every remaining app still gets its turn.
// `spawn_fresh` registered this one `Errored`.
BatchPolicy::PerApp => {
failures.push(failure);
// The rest of this app's instances share its
// binary and cwd, and would fail the same.
continue 'apps;
}
}
}
}
}
}
// An `Err` rather than a partial `Ok`, so `snapshot::muster`'s log and
// `do_start_dog`'s refusal still fire.
if !failures.is_empty() {
return Err(SupervisorError::SpawnFailed(failures.join("; ")));
}
// Built so far in the caller's order, which is the Flockfile's rather
// than the one every other listing takes.
sort_flock(&mut results);
Ok(results)
}
/// Refuses the first of `names` that a registered dog already holds.
///
/// A sheep started under a dog's name would join the dog's entries as one
/// more instance of it, leaving a name that answers to both.
///
/// # Errors
///
/// [`SupervisorError::IsADog`] naming that dog.
fn refuse_dog_names<'a>(
&self,
names: impl IntoIterator<Item = &'a str>,
) -> Result<(), SupervisorError> {
let held = |name: &str| {
self.sheep
.values()
.any(|slot| slot.entry.dog.is_some() && slot.entry.spec.config().name == name)
};
match names.into_iter().find(|name| held(name)) {
Some(name) => Err(SupervisorError::IsADog(format!(
"{name} is a dog, so a sheep cannot take its name; rename the sheep"
))),
None => Ok(()),
}
}
}
/// Whether `entry` is a dog that has never had a process: registered, not
/// started.
///
/// Every process exit writes `last_exit`, an operator's `stop` included, so a
/// dog that ran and stopped is not at rest and is not respawned by a boot
/// that names it again. `last_exit` rides a handover, so the answer holds
/// across one.
fn is_at_rest(entry: &ProcessEntry) -> bool {
entry.dog.is_some() && entry.status == ProcStatus::Stopped && entry.last_exit.is_none()
}