Repository navigation
Expand file tree
/
Copy pathengine.c
More file actions
4771 lines (4466 loc) · 201 KB
/
Copy pathengine.c
File metadata and controls
4771 lines (4466 loc) · 201 KB
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
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#define FDCLOSE_DEFINE
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <signal.h>
#include <sys/wait.h>
#include <sys/mount.h>
#include <sys/reboot.h>
#include <termios.h>
#include <sys/stat.h>
#include <time.h>
#include <errno.h>
#include "ctl_gate.h"
#include "schema.h"
#include "engine.h"
#include "service.h"
#include "svc_serial.h"
#include "svc_dropins.h"
#include "reexec_state.h"
#include "dynuser.h"
#include "notify.h"
#include "fdstore.h"
#include "coredump.h"
#include <sys/resource.h>
#include "group.h"
#include "schema_shm.h"
#include "recorder.h"
#include <sys/mman.h>
#include <fcntl.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <stdarg.h>
#include <poll.h>
#include <sys/signalfd.h>
#include <glob.h>
#include <sys/ioctl.h>
#include <grp.h>
#include <sys/inotify.h>
#include <sys/random.h>
#include <linux/watchdog.h>
#include <dirent.h>
#include <mntent.h>
static void elog(FILE *f, const char *fmt, ...) {
va_list ap;
fprintf(f, "[%s] ", engine_paths.tag);
va_start(ap, fmt);
vfprintf(f, fmt, ap);
va_end(ap);
}
int engine_mkdir_p(const char *path, mode_t mode) {
char buf[PATH_MAX];
if (snprintf(buf, sizeof buf, "%s", path) >= (int)sizeof buf) { errno = ENAMETOOLONG; return -1; }
for (char *p = buf + 1; *p; p++) {
if (*p != '/') continue;
*p = '\0';
if (mkdir(buf, mode) < 0 && errno != EEXIST) return -1;
*p = '/';
}
if (mkdir(buf, mode) < 0 && errno != EEXIST) return -1;
return 0;
}
#define TICK_USEC 250000 /* 250ms main loop tick */
#define READY_POLL_MS 10 /* while a starting service's ready_path is awaited, */
#define READY_POLL_SECS 3 /* ...for this long after its spawn */
#define PID_FILE_WAIT_SECS 5
#define MAINPID_WAIT_SECS 10
service_t *services;
service_t *shadow_services;
int svc_count = 0;
static group_t groups_a[MAX_GROUPS];
static group_t groups_b[MAX_GROUPS];
static group_t *groups = groups_a;
group_t *shadow_groups = groups_b;
static int grp_count = 0;
#define EVICT_GRACE_SECS 3
/* a binder's own exit this close before its bound goes down was the bound's doing */
#define BIND_GRACE_MS 2000
#define EVICT_KILL_WAIT_SECS 5
#define EVICT_STUCK_RECHECK_SECS 60
eviction_t evictions[MAX_EVICTIONS];
int eviction_count = 0;
volatile int engine_running = 1;
volatile int engine_do_reboot = 0;
schema_shm_t *shm_ptr = NULL;
int ctl_fd = -1;
int notify_fd = -1;
static int sig_fd = -1;
int watchdog_fd = -1;
int64_t watchdog_pet_ms = 5000;
time_t notify_paused_since = 0; /* mono sec, 0 = notify reads flowing */
static int bus_reporter_seen = 0; /* a broker BUSNAME= report was accepted: ready_bus_name waits for its name */
int system_under_pressure = 0;
static int pass_changed = 1; /* first pass, or last pass moved a service: run at once */
#define PASS_RERUN_MAX 16 /* ...at most this many passes in a row */
int psi_fd = -1;
static int ino_fd = -1;
/* watch_path= has its own fd: a ready_path dir watch keeps its narrow mask
* instead of sharing a wd (and the widest mask) with a path watch */
static int path_fd = -1;
static int path_gc_due;
static int64_t ready_event_due = 0; /* CLOCK_MONOTONIC ms, 0 = none */
static int64_t ready_backstop_due = 0;
int64_t cpu_check_due = 0;
struct timespec init_start;
char booted_version[64] = SCHEMA_INIT_VERSION;
char booted_image[64] = "";
static void start_failsafe(service_t *svc);
static void active_kill_service(service_t *svc);
static void stop_main(service_t *svc);
static void svc_cgroup_kill_tree(service_t *svc);
static int svc_signal_all(service_t *svc, int sig);
static int handle_reload(int evict_mode, char *err, size_t errsz);
pid_t reexec_check_pid = 0;
int64_t reexec_check_due = 0;
int reexec_check_killed = 0;
/* Arm a calendar timer: set timer_next to the next CLOCK_REALTIME instant at
* which local wall-clock reaches one of its HH:MM slots on a day matching the
* timer's dow/dom constraints, strictly in the future. Walks forward
* day-by-day (mktime per step re-normalizes wday/mday and self-corrects
* DST/NTP each cycle). Daily timers (dow=dom=-1) match the first or second
* day and behave as before. */
/* randomized_delay_sec: 0..N whole seconds onto the deadline just armed, a
* fresh draw each arm. Never blocks: PID 1 can arm before the pool is ready. */
static void timer_jitter(service_t *svc) {
uint32_t r;
if (svc->timer_jitter_sec <= 0) return;
if (getrandom(&r, sizeof r, GRND_NONBLOCK) != (ssize_t)sizeof r) {
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
r = (uint32_t)ts.tv_nsec;
for (const char *p = svc->name; *p; p++) r = (r ^ (uint8_t)*p) * 16777619u;
}
svc->timer_next.tv_sec += (time_t)(r % ((uint32_t)svc->timer_jitter_sec + 1));
}
static void timer_arm_calendar(service_t *svc) {
svc->timer_next.tv_sec = calendar_next_after(svc->timer_cal, svc->timer_cal_n, time(NULL));
svc->timer_next.tv_nsec = 0;
timer_jitter(svc);
}
/* ── persistent calendar timers (persistent=1): catch up a fire missed while
* the machine was down. Last run is stamped under engine_paths.timer_stamp_dir. ── */
static void timer_stamp_path(const service_t *svc, char *buf, size_t n) {
snprintf(buf, n, "%s/%s.stamp", engine_paths.timer_stamp_dir, svc->name);
}
static time_t timer_stamp_read(const service_t *svc) {
char path[256]; timer_stamp_path(svc, path, sizeof path);
FILE *f = fopen(path, "r");
if (!f) return 0;
long long v = 0;
if (fscanf(f, "%lld", &v) != 1) v = 0;
fclose(f);
return (time_t)v;
}
static void timer_stamp_write(const service_t *svc, time_t t) {
engine_mkdir_p(engine_paths.timer_stamp_dir, 0755);
char path[256]; timer_stamp_path(svc, path, sizeof path);
FILE *f = fopen(path, "w");
if (!f) return;
fprintf(f, "%lld\n", (long long)t);
fclose(f);
}
/* most recent past (or current) occurrence of any of the timer's HH:MM slots
* on a day matching its dow/dom constraints, <= now. Walks backward
* day-by-day; returns 0 if none in the last ~400 days (constraint never
* satisfiable). */
static time_t calendar_recent_occurrence(const service_t *svc, time_t now) {
return calendar_recent_at_or_before(svc->timer_cal, svc->timer_cal_n, now);
}
/* If a scheduled fire passed while we were down, fire now; otherwise arm
* normally. A never-stamped timer is seeded (no replay of history on first
* deploy). */
static void timer_catchup_check(service_t *svc) {
time_t now = time(NULL);
time_t stamp = timer_stamp_read(svc);
if (stamp == 0) {
timer_stamp_write(svc, now);
timer_arm_calendar(svc);
return;
}
if (calendar_recent_occurrence(svc, now) > stamp) {
svc->timer_next.tv_sec = now; /* CLOCK_REALTIME: fires on the next tick */
svc->timer_next.tv_nsec = 0;
timer_jitter(svc);
service_log(svc, "timer-catchup");
} else {
timer_arm_calendar(svc);
}
}
/* A separate /var is mounted by mount-fstab, after the timers are armed: a
* stamp read before then comes from the empty shadow /var, reads as "never
* stamped" and the catch-up is lost. So a persistent timer arms on the
* calendar and reads its stamp once mount-fstab has made one attempt (a
* failing one never mounts /var, and must not hold timers forever); with no
* mount-fstab, on the next pass. */
static void timer_arm_persistent(service_t *svc) {
svc->timer_catchup_wait = 1;
timer_arm_calendar(svc);
}
/* born "already ran": PERFECT, first fire at the calendar or boot + on_boot_sec */
static void timer_arm(service_t *svc) {
svc->inst.state = STATE_PERFECT;
if (svc->flags & SVC_TIMER_CALENDAR) {
if (svc->flags & SVC_TIMER_PERSIST) timer_arm_persistent(svc);
else timer_arm_calendar(svc);
return;
}
clock_gettime(CLOCK_MONOTONIC, &svc->timer_next);
svc->timer_next.tv_sec += svc->timer_boot_sec;
timer_jitter(svc);
}
static void timer_catchup_tick(void) {
int i, any = 0;
for (i = 0; i < svc_count && !any; i++)
any = services[i].timer_catchup_wait;
if (!any) return;
for (i = 0; i < svc_count; i++) {
if (strcmp(services[i].name, "mount-fstab") != 0) continue;
uint8_t st = services[i].inst.state;
if (st != STATE_PERFECT && st != STATE_EXCISED &&
st != STATE_DORMANT && st != STATE_RECOVERY)
return;
}
for (i = 0; i < svc_count; i++) {
if (!services[i].timer_catchup_wait) continue;
services[i].timer_catchup_wait = 0;
/* not PERFECT: it is firing on the calendar right now, that is the run */
if (services[i].inst.state == STATE_PERFECT)
timer_catchup_check(&services[i]);
}
}
time_t mono_sec(void) {
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
return ts.tv_sec;
}
/* cgroup.events "populated 0" once every process in the subtree is gone,
* and a cgroup that no longer exists holds nothing. Otherwise unreadable
* counts as populated so the kill is still attempted. */
static int cgroup_populated(const char *cg) {
char path[320], line[64];
FILE *f;
int pop = 1;
snprintf(path, sizeof path, "%s/cgroup.events", cg);
if (!(f = fopen(path, "r"))) return errno != ENOENT;
while (fgets(line, sizeof line, f))
if (sscanf(line, "populated %d", &pop) == 1) break;
fclose(f);
return pop;
}
static void eviction_add_as(pid_t pid, const char *cgroup, int reaped, int killed, int grace) {
if (eviction_count >= MAX_EVICTIONS) return;
evictions[eviction_count].pid = pid;
evictions[eviction_count].deadline = mono_sec() + grace;
evictions[eviction_count].reaped = reaped;
evictions[eviction_count].killed = killed;
snprintf(evictions[eviction_count].cgroup, sizeof evictions[eviction_count].cgroup, "%s", cgroup);
eviction_count++;
}
static void eviction_add(pid_t pid, const char *cgroup) {
eviction_add_as(pid, cgroup, 0, 0, EVICT_GRACE_SECS);
}
/* A service spawning into CG owns it again: a leftover-tree entry for it
* would judge the new instance */
static void eviction_forget(const char *cg) {
for (int i = 0; i < eviction_count; )
if (evictions[i].pid == 0 && !strcmp(evictions[i].cgroup, cg))
evictions[i] = evictions[--eviction_count];
else
i++;
}
/* A killed tree can't be rmdir'ed until its processes are gone, and
* cgroup.kill is asynchronous: leave the leftover to the eviction sweep,
* which rmdirs it once it is empty (or at the 1 s backstop). */
static void svc_cgroup_kill_tree(service_t *svc) {
char cg[sizeof svc->cgroup_path];
snprintf(cg, sizeof cg, "%s", svc->cgroup_path);
service_cgroup_kill(svc);
if (cg[0] && access(cg, F_OK) == 0) {
eviction_forget(cg);
/* pid 0: nothing to signal, only the tree to rmdir once empty */
eviction_add_as(0, cg, 1, 1, 1);
}
}
static void eviction_drop(int i) {
if (evictions[i].cgroup[0]) cgroup_rmdir_tree(evictions[i].cgroup);
evictions[i] = evictions[--eviction_count];
}
/* An evicted child that exits on SIGTERM must not leave a live pid in the
* table: by the deadline it may be reused, and the log would claim a kill
* that never happened. While its cgroup still holds descendants that
* ignored SIGTERM the entry stays, marked reaped, to cgroup.kill them at the
* deadline. The pid itself is kept so an older image after a re-exec, which
* ignores reaped=, behaves as it always did instead of seeing pid 0.
*
* Leftovers are reparented to PID 1, so each one lands here too: the entry
* whose cgroup has just emptied is dropped and its directory removed, with
* no polling. The service is gone from the config, so nothing else would
* ever rmdir it. */
static void eviction_reaped(pid_t pid) {
int i;
for (i = 0; i < eviction_count; i++) {
if (evictions[i].pid != pid || evictions[i].reaped) continue;
if (evictions[i].cgroup[0]) evictions[i].reaped = 1;
else eviction_drop(i);
break;
}
for (i = 0; i < eviction_count; ) {
if (evictions[i].cgroup[0] && (evictions[i].reaped || evictions[i].killed) &&
!cgroup_populated(evictions[i].cgroup))
eviction_drop(i);
else
i++;
}
}
/* A reload or re-exec that brings an evicted service's name back would spawn
* the new instance into the old cgroup (cgroup v2 cannot rename it aside),
* and the deadline kill would take it down with the leftovers. Kill the
* leftovers now, before the new one starts. A running service is skipped: it
* was re-added by an older image, which kept the entry, and is in there. */
void eviction_readded(void) {
for (int i = 0; i < eviction_count; ) {
int s;
for (s = 0; s < svc_count; s++)
if (services[s].child_pid == 0 && evictions[i].cgroup[0] &&
strcmp(evictions[i].cgroup, service_cgroup_path_for(&services[s])) == 0)
break;
if (s == svc_count) { i++; continue; }
if (cgroup_populated(evictions[i].cgroup)) {
cgroup_kill_path(evictions[i].cgroup);
elog(stdout, "'%s' is back in the configuration: force-killed what its evicted instance left in %s\n",
services[s].name, evictions[i].cgroup);
}
eviction_drop(i);
}
}
static void eviction_tick(void) {
time_t now = mono_sec();
int i = 0;
while (i < eviction_count) {
if (now < evictions[i].deadline) { i++; continue; }
int live = evictions[i].cgroup[0] ? cgroup_populated(evictions[i].cgroup) : 1;
if (evictions[i].killed) {
if (!live) { eviction_drop(i); continue; }
/* a task stuck in D state outlives SIGKILL; dropping the entry
* would leak the cgroup once it finally dies, so keep checking */
if (evictions[i].killed == 1)
elog(stdout, "eviction: %s still populated %d s after SIGKILL\n",
evictions[i].cgroup, EVICT_KILL_WAIT_SECS);
evictions[i].killed = 2;
evictions[i].deadline = now + EVICT_STUCK_RECHECK_SECS;
i++;
continue;
}
if (!live) { eviction_drop(i); continue; }
int killed = evictions[i].cgroup[0] && cgroup_kill_path(evictions[i].cgroup);
/* no cgroup, or neither cgroup.kill nor cgroup.procs usable: fall back
* to a direct SIGKILL. previously this whole branch was gated on
* cgroup[0], so an orphan with no cgroup that ignored SIGTERM survived
* eviction entirely. an unreaped pid is still our child, so it cannot
* have been reused (bar an entry adopted from an older image, which
* may have reaped it before the re-exec). */
if (!killed && !evictions[i].reaped && evictions[i].pid > 0) {
/* a stop runner leads its own group: take what it started too */
kill(-evictions[i].pid, SIGKILL);
kill(evictions[i].pid, SIGKILL);
killed = 1;
}
if (killed && !evictions[i].reaped)
elog(stdout, "eviction grace expired: force-killed pid=%d\n",
(int)evictions[i].pid);
else if (killed)
elog(stdout, "eviction grace expired: force-killed leftovers in %s\n",
evictions[i].cgroup);
if (killed && evictions[i].cgroup[0]) {
/* SIGKILL lands asynchronously; eviction_reaped() removes the
* cgroup once the dead are reaped, this deadline is the backstop */
evictions[i].killed = 1;
evictions[i].deadline = now + EVICT_KILL_WAIT_SECS;
i++;
continue;
}
eviction_drop(i);
}
}
/* runtime_dir=: removed once the service is stopped for good, kept across
* respawns and backoff; waits for exec_stop_post, which may still use it */
static void runtime_dir_tick(void) {
for (int i = 0; i < svc_count; i++) {
service_t *s = &services[i];
if (!s->rt_made || s->child_pid > 0 || s->stop_pid > 0 || s->inst.state != STATE_EXCISED) continue;
service_runtime_dirs_remove(s);
s->rt_made = 0;
}
}
static void service_watchdog_tick(void) {
struct timespec now;
clock_gettime(CLOCK_MONOTONIC, &now);
int64_t now_ms = ts_ms_ceil(&now);
for (int i = 0; i < svc_count; i++) {
service_t *svc = &services[i];
if (svc->wd_armed_sec <= 0 || svc->child_pid <= 0 || !svc->notify_ready || svc->ctl_killed)
continue;
if (svc->is_frozen || notify_paused_since) {
svc->last_pet = now;
if (svc->wd_abort_at.tv_sec || svc->wd_abort_at.tv_nsec)
svc->wd_abort_at = now;
continue;
}
if (now_ms < svc_wd_due(&svc->last_pet, &svc->wd_abort_at, svc->wd_armed_sec)) continue;
if (svc->wd_abort_at.tv_sec || svc->wd_abort_at.tv_nsec) {
service_log(svc, "watchdog-kill");
kill(svc->child_pid, SIGKILL);
svc->wd_abort_at = (struct timespec){0, 0};
svc->last_pet = now;
} else {
elog(stdout, "watchdog: '%s' sent no WATCHDOG=1 for %ds — SIGABRT\n",
svc->name, svc->wd_armed_sec);
service_log(svc, "watchdog-abort");
svc->wd_fired = 1;
kill(svc->child_pid, SIGABRT);
svc->wd_abort_at = now;
}
}
}
static void load_env_file(void) {
char envp[160];
const char *path = envp;
snprintf(envp, sizeof envp, "%s/env", engine_paths.run_dir);
int fd = service_open_trusted(path);
if (fd < 0 && errno != EPERM && engine_paths.env_fallback)
fd = service_open_trusted(path = engine_paths.env_fallback);
if (fd < 0) {
if (errno == EPERM)
elog(stderr, "REFUSED %s: not a regular file owned by root and "
"writable only by its owner — not loaded\n", path);
return;
}
FILE *f = fdopen(fd, "r");
if (!f) { close(fd); return; }
char line[512];
int r;
while ((r = svc_read_line(f, line, sizeof(line))) != 0) {
char *start = line;
if (r < 0) {
elog(stderr, "%s: line longer than %zu bytes — ignored\n",
path, sizeof(line) - 1);
continue;
}
while (*start == ' ' || *start == '\t') start++;
char *end = start + strlen(start) - 1;
while (end >= start && (*end == '\n' || *end == '\r' || *end == ' ' || *end == '\t')) {
*end = '\0';
end--;
}
if (*start == '\0' || *start == '#') continue;
char *eq = strchr(start, '=');
if (!eq) continue;
*eq = '\0';
char *key = start;
char *val = eq + 1;
char *key_end = key + strlen(key) - 1;
while (key_end >= key && (*key_end == ' ' || *key_end == '\t')) {
*key_end = '\0';
key_end--;
}
while (*val == ' ' || *val == '\t') val++;
setenv(key, val, 1);
}
fclose(f);
}
/* ── zombie reaper ──────────────────────────────────────────────────── */
static void restart_budget_refresh(service_t *svc) {
struct timespec now;
clock_gettime(CLOCK_MONOTONIC, &now);
if (now.tv_sec - svc->spawn_time_mono.tv_sec >= RESTART_RESET_SECS) {
svc->restart_count = 0;
svc->card_next = 0;
svc->fallback_live = 0;
}
}
static void breaker_clear(service_t *svc) {
/* a cleared breaker restarts the backoff too, or the first FRICTION re-trips it */
if (svc->circuit_broken) svc->dormant_count = 0;
svc->circuit_broken = 0;
}
static void fallback_up(service_t *fb) {
fb->standby_up = 1;
fb->flags &= ~SVC_NO_RESTART;
if (fb->child_pid <= 0 && (fb->inst.state == STATE_EXCISED || fb->inst.state == STATE_PERFECT)) {
fb->inst.state = STATE_NEW_PROCESS;
fb->restart_count = 0;
breaker_clear(fb);
}
service_log(fb, "fallback-up");
}
static void fallback_down(service_t *fb) {
if (!fb->standby_up) return;
fb->standby_up = 0;
fb->flags |= SVC_NO_RESTART;
if (fb->child_pid > 0) {
fb->ctl_killed = 1;
stop_main(fb);
} else {
fb->inst.state = STATE_EXCISED;
}
service_log(fb, "fallback-down");
}
static void park(service_t *svc) {
struct timespec now;
time_t delay;
svc->dormant_count++;
delay = 300L << (svc->dormant_count - 1);
if (delay > 3600) delay = 3600;
clock_gettime(CLOCK_MONOTONIC, &now);
svc->dormant_until.tv_sec = now.tv_sec + delay;
svc->dormant_until.tv_nsec = now.tv_nsec;
svc->inst.state = STATE_DORMANT;
service_log(svc, "dormant");
}
const char *excise_reason_name(uint8_t r) {
static const char *const n[] = {
[EXC_NONE] = "none", [EXC_BREAKER] = "breaker", [EXC_START_TIMEOUT] = "start-timeout",
[EXC_MAIN_PID_TIMEOUT] = "main-pid-timeout", [EXC_EXIT_CODE] = "exit-code",
[EXC_SIGNAL] = "signal", [EXC_CORE_DUMP] = "core-dump",
[EXC_READINESS_LOST] = "readiness-lost", [EXC_NO_CGROUP] = "no-cgroup",
[EXC_LISTEN_FAIL] = "listen-fail", [EXC_FUSE] = "fuse", [EXC_PROBE] = "probe-failed",
[EXC_BIND] = "bind", [EXC_TRIGGER_LIMIT] = "trigger-limit-hit",
};
return r < sizeof n / sizeof n[0] ? n[r] : "unknown";
}
/* A death nobody asked for, from the last wait status; a clean exit 0 is none. */
uint8_t excise_reason_from_exit(const service_t *svc) {
if (svc->ctl_killed) return EXC_NONE;
if (svc->term_signal) return svc->core_dumped ? EXC_CORE_DUMP : EXC_SIGNAL;
return svc->has_exited && svc->exit_status != 0 ? EXC_EXIT_CODE : EXC_NONE;
}
/* FRICTION gave up on the service: park it with backoff, or after the fifth
* time trip the crash-loop breaker. Only this path sets circuit_broken; a
* start-timeout or fallback-down excise is not a crash loop. */
void engine_friction_verdict(service_t *svc) {
if (!(svc->flags & SVC_CRITICAL) && !svc->no_excise && svc->dormant_count >= 4) {
svc->dormant_count++;
svc->circuit_broken = 1;
svc->excise_reason = EXC_BREAKER;
service_log(svc, "breaker-tripped"); /* not also 76-excised: one loss, one record */
} else {
park(svc);
}
}
static int held_now(const service_t *svc) {
struct timespec now;
clock_gettime(CLOCK_MONOTONIC, &now);
return svc_retry_held(svc, &now);
}
/* start/restart/reset lift a stop's hold, not the .svc's own no_restart=1:
* clearing the shared flag made a no_restart service auto-restart from then on */
static void restart_policy_restore(service_t *svc) {
svc->path_stop = 0;
if (svc->no_restart_cfg) svc->flags |= SVC_NO_RESTART;
else svc->flags &= ~SVC_NO_RESTART;
}
static void ctl_rearm(service_t *svc, int start) {
svc->card_next = 0;
breaker_clear(svc);
svc->excise_reason = EXC_NONE;
svc->bind_held = 0;
svc->restart_at.tv_sec = svc->restart_at.tv_nsec = 0;
svc->trigger_count = 0;
svc->trigger_window = (struct timespec){0, 0};
if (start) svc->standby_up |= service_is_standby(svc, services, svc_count);
if (svc->fallback_live) {
service_t *fb = service_fallback(svc, services, svc_count);
if (fb) fallback_down(fb);
}
}
static void play_card(service_t *svc) {
char ev[32];
if (svc->card_pid > 0 || svc->card_next >= svc->card_count) return;
snprintf(ev, sizeof ev, "card-%d/%d", svc->card_next + 1, svc->card_count);
if (strncmp(svc->card[svc->card_next], "fallback:", 9) == 0) {
service_t *fb = service_fallback(svc, services, svc_count);
svc->card_next++;
service_log(svc, ev);
if (!fb) {
service_log(svc, "card-no-fallback");
return;
}
svc->fallback_live = 1;
fallback_up(fb);
park(svc);
return;
}
pid_t pid = service_card_spawn(svc, svc->card_next);
svc->card_next++;
svc->card_killed = 0;
if (pid < 0) {
service_log(svc, "card-fork-fail");
return;
}
svc->card_pid = pid;
clock_gettime(CLOCK_MONOTONIC, &svc->card_start);
service_log(svc, ev);
}
static void card_done(service_t *svc, int status) {
int killed = svc->card_killed;
svc->card_pid = 0;
svc->card_killed = 0;
if (killed) return; /* card-timeout was logged at the kill */
service_log(svc, WIFEXITED(status) && WEXITSTATUS(status) == 0 ? "card-done" : "card-failed");
}
static void kill_group(pid_t p) {
kill(-p, SIGKILL);
kill(p, SIGKILL);
}
static uint64_t stop_grace_ms(const service_t *svc) {
return svc->stop_timeout_sec ? (uint64_t)svc->stop_timeout_sec * 1000 : SHUT_GRACE_MS;
}
/* exec_stop / exec_stop_post: one runner child, reaped by reap() and bounded
* by stop_timeout_sec in monitor_failsafes(); PID 1 never waits on it.
* stop_phase: 1 exec_stop, 2 exec_stop_post, | STOP_TIMED_OUT once killed. */
#define STOP_TIMED_OUT 4
static int stop_cmds_begin(service_t *svc, int phase) {
int n = (phase & 1 ? svc->exec_stop_count : 0) + (phase & 2 ? svc->exec_stop_post_count : 0);
if (!n || svc->stop_pid > 0) return 0;
pid_t pid = service_stop_spawn(svc, phase);
if (pid < 0) {
service_log(svc, "stop-cmd-fork-fail");
return 0;
}
svc->stop_pid = pid;
svc->stop_phase = phase;
clock_gettime(CLOCK_MONOTONIC, &svc->stop_start);
service_log(svc, phase == 2 ? "stop-post" : "stop-cmd");
return 1;
}
/* ── bind= (docs/superpowers/specs/2026-11-03-bind-key-design.md) ──────
* The binder follows its bound: stopped when the bound goes down (held),
* started again when it comes back, unless it was stopped on purpose or
* failed on its own. bind=X is also a dep=X, so dep_idx resolves it. */
static int svc_is_up(const service_t *s) {
if (s->inst.state == STATE_FUNDAMENTAL || s->inst.state == STATE_SETTLED ||
s->inst.state == STATE_PERFECT) return 1;
/* a socket service PID 1 listens for stays up across its idle exit and
* the on-demand start after it: its binders mustn't churn per connection */
return s->listen_open && (s->inst.state == STATE_NEW_PROCESS || s->inst.state == STATE_FULL_TRUST);
}
/* The bound's index; -1 when it isn't in the config, or is a timer/oneshot
* (their PERFECT means "ran", not "up") */
static int bind_bound(const service_t *s) {
if (!s->bind_name[0]) return -1;
for (int k = 0; k < MAX_DEPS && s->dep_name[k][0]; k++) {
if (strcmp(s->dep_name[k], s->bind_name) != 0) continue;
int b = s->dep_idx[k];
if (b < 0 || b >= svc_count || (services[b].flags & (SVC_TIMER | SVC_ONESHOT))) return -1;
return b;
}
return -1;
}
static void stop_main(service_t *svc);
static int ts_after(struct timespec a, struct timespec b) {
return a.tv_sec > b.tv_sec || (a.tv_sec == b.tv_sec && a.tv_nsec > b.tv_nsec);
}
/* The hold remembers the bound's run that was last seen up: "back" is a newer
* run up. Not the time of the hold, which can come after the bound already
* respawned (a down edge noticed late, a binder reaped after) */
static void bind_hold(service_t *b, const char *ev) {
if (!b->bind_held) {
int t = bind_bound(b);
b->bind_held_since = t >= 0 ? services[t].bind_seen_spawn : (struct timespec){0, 0};
}
b->bind_held = 1;
b->bind_died_at.tv_sec = b->bind_died_at.tv_nsec = 0;
service_log(b, ev);
}
/* Stop a running binder the way schema-ctl stop would, but held: its exit is
* the bound's doing (reap() takes it to EXCISED/EXC_BIND, no recovery) */
static void bind_stop(service_t *b, const char *ev) {
if (b->bind_held || b->child_pid <= 0) return;
/* being stopped on purpose already: its bound's return must not start it */
if (b->ctl_killed && (b->flags & SVC_NO_RESTART)) return;
bind_hold(b, ev);
b->restart_at.tv_sec = b->restart_at.tv_nsec = 0;
stop_main(b);
}
/* A stop was asked of SVC: its running binders go first, held, so their exit
* during its exec_stop (podman pod stop ends the containers) isn't theirs */
static void bind_stop_binders(const service_t *svc) {
int idx = (int)(svc - services);
if (idx < 0 || idx >= svc_count) return;
for (int j = 0; j < svc_count; j++)
if (j != idx && bind_bound(&services[j]) == idx)
bind_stop(&services[j], "bind-stop");
}
static void bind_start(service_t *b) {
b->bind_held = 0;
b->excise_reason = EXC_NONE;
b->inst.state = STATE_NEW_PROCESS;
service_log(b, "bind-start");
}
/* Once per tick pass, before the services tick: act on each bound's edge
* since the last pass's tail (inst.prev_state isn't maintained by the
* engine, so the edge is our own bind_was_up snapshot) */
static void bind_tick(void) {
struct timespec now;
clock_gettime(CLOCK_MONOTONIC, &now);
for (int j = 0; j < svc_count; j++) {
service_t *b = &services[j];
if (!b->bind_name[0]) {
/* bind= removed on a reload while held: nothing to wait for now */
if (b->bind_held) {
b->bind_held = 0;
if (b->inst.state == STATE_EXCISED && b->excise_reason == EXC_BIND && b->child_pid <= 0)
bind_start(b);
}
continue;
}
int t = bind_bound(b);
if (t < 0) {
/* no bound to follow: never runs without it */
if (!b->bind_held) {
if (b->child_pid > 0) bind_stop(b, "bind-target-missing");
else {
bind_hold(b, "bind-target-missing");
if (b->inst.state != STATE_EXCISED) {
b->inst.state = STATE_EXCISED;
b->excise_reason = EXC_BIND;
}
}
}
continue;
}
service_t *bd = &services[t];
int up = svc_is_up(bd);
/* gone since the last pass, or back already with a new process */
int went_down = bd->bind_was_up &&
(!up || (!bd->listen_open && (bd->spawn_time_mono.tv_sec != bd->bind_seen_spawn.tv_sec ||
bd->spawn_time_mono.tv_nsec != bd->bind_seen_spawn.tv_nsec)));
if (went_down) {
if (b->child_pid > 0) {
bind_stop(b, "bind-stop");
} else if (!b->bind_held && !b->circuit_broken &&
(b->bind_died_at.tv_sec || b->bind_died_at.tv_nsec)) {
int64_t ago = (int64_t)(now.tv_sec - b->bind_died_at.tv_sec) * 1000 +
(now.tv_nsec - b->bind_died_at.tv_nsec) / 1000000;
if (ago >= 0 && ago < BIND_GRACE_MS) {
/* it went first in the bound's own going: not its failure */
b->restart_count = b->bind_saved_restarts;
b->dormant_count = b->bind_saved_dormant;
b->restart_at.tv_sec = b->restart_at.tv_nsec = 0;
b->inst.state = STATE_EXCISED;
b->excise_reason = EXC_BIND;
bind_hold(b, "bind-reclassified");
}
}
}
/* back: up, not stopping, and a run of it newer than our hold. Up
* alone isn't enough -- a pod asked to stop is still FUNDAMENTAL
* while its exec_stop ends our process */
int back = up && bd->stop_pid <= 0 && !bd->ctl_killed &&
ts_after(bd->spawn_time_mono, b->bind_held_since);
/* and not before its own old process and stop runner are gone */
if (b->bind_held && back && b->child_pid <= 0 && b->stop_pid <= 0)
bind_start(b);
/* strict start: dep= lets a non-critical excised dep through; bind= never */
if (!b->bind_held && b->child_pid <= 0 && b->inst.state == STATE_NEW_PROCESS &&
(bd->inst.state == STATE_EXCISED || bd->inst.state == STATE_DORMANT)) {
b->inst.state = STATE_EXCISED;
b->excise_reason = EXC_BIND;
bind_hold(b, "bind-wait");
}
}
}
static void bind_snapshot_up(void) {
for (int j = 0; j < svc_count; j++) {
services[j].bind_was_up = (uint8_t)svc_is_up(&services[j]);
if (services[j].bind_was_up) services[j].bind_seen_spawn = services[j].spawn_time_mono;
}
}
/* SIGTERM, or "signal 37" for one with no short name */
static void sig_text(int sig, char *buf, size_t n) {
const char *ab = sig_abbrev(sig);
if (ab) snprintf(buf, n, "SIG%s", ab);
else snprintf(buf, n, "signal %d", sig);
}
static int kill_sig(const service_t *s) { return s->kill_signal ? s->kill_signal : SIGTERM; }
static int final_sig(const service_t *s) { return s->final_kill_signal ? s->final_kill_signal : SIGKILL; }
/* a runtime stop that never ends: final_kill_signal after stop_timeout_sec,
* else systemd's TimeoutStopSec default (shutdown keeps its own 3 s grace) */
#define RUNTIME_STOP_GRACE_MS 90000
static uint64_t runtime_stop_grace_ms(const service_t *svc) {
return svc->stop_timeout_sec ? (uint64_t)svc->stop_timeout_sec * 1000 : RUNTIME_STOP_GRACE_MS;
}
static int kill_sent_set(const service_t *svc) {
return svc->kill_sent.tv_sec || svc->kill_sent.tv_nsec;
}
/* kill_signal= to the whole cgroup under control-group, else the main
* process. The escalation deadline runs from the first signal: a repeated
* stop doesn't push it back. */
static void stop_signal(service_t *svc) {
if (svc->child_pid <= 0) return;
if (svc->kill_mode == KILL_MODE_CGROUP) svc_signal_all(svc, kill_sig(svc));
else kill(svc->child_pid, kill_sig(svc));
if (!kill_sent_set(svc)) clock_gettime(CLOCK_MONOTONIC, &svc->kill_sent);
}
/* final_kill_signal=: the main process under process, else everything */
static void final_signal(service_t *svc) {
int sig = final_sig(svc);
if (svc->kill_mode == KILL_MODE_PROCESS) {
if (svc->child_pid > 0) kill(svc->child_pid, sig);
} else if (sig == SIGKILL) {
svc_cgroup_kill_tree(svc);
if (svc->child_pid > 0) kill(svc->child_pid, SIGKILL);
} else {
svc_signal_all(svc, sig);
}
}
/* What the main process left when it went, by kill_mode: unset sweeps it
* (SIGKILL), mixed sends final_kill_signal, process leaves it, and
* control-group leaves a stop's TERMed rest its grace (kill_sent stays set:
* the escalation check sends final_kill_signal at the deadline, and a
* respawn waits for the cgroup to drain). 1 = still draining. */
static int sweep_rest(service_t *svc) {
switch (svc->kill_mode) {
case KILL_MODE_PROCESS:
return 0;
case KILL_MODE_MIXED:
final_signal(svc);
return 0;
case KILL_MODE_CGROUP:
if (kill_sent_set(svc) && svc_signal_all(svc, 0) > 0) return 1;
svc_cgroup_kill_tree(svc);
return 0;
default:
svc_cgroup_kill_tree(svc);
return 0;
}
}
/* Stop signal to the main process, after its exec_stop commands when it has any */
static void stop_main(service_t *svc) {
if (svc->child_pid <= 0) return;
bind_stop_binders(svc);
if (svc->stop_pid > 0 && svc->stop_phase == 1) return;
if (!stop_cmds_begin(svc, 1)) stop_signal(svc);
}
static void stop_cmds_done(service_t *svc, int status) {
int phase = svc->stop_phase;
svc->stop_pid = 0;
svc->stop_phase = 0;
service_log(svc, WIFEXITED(status) && WEXITSTATUS(status) == 0 ? "stop-cmd-done" : "stop-cmd-failed");
if ((phase & 3) != 1) return;
if (svc->child_pid > 0) {
if (!(phase & STOP_TIMED_OUT)) stop_signal(svc);
} else {
/* main went first (exec_stop killed it): its post was held for us */
stop_cmds_begin(svc, 2);
}
}
/* exec_reload runner gone: the service itself is untouched either way */
static void reload_cmds_done(service_t *svc, int status) {
svc->reload_pid = 0;
service_log(svc, WIFEXITED(status) && WEXITSTATUS(status) == 0 ? "reload-done" : "reload-fail");
}
static void mark_boot_ready(service_t *svc, int how) {
if (svc->boot_ready.tv_sec || svc->boot_ready.tv_nsec) return;
svc->boot_ready = svc->stable_time;
svc->boot_how = how;
}
/* Record why a run ended (wait status) and log a signal death to the rail. */
static void note_exit(service_t *svc, int status) {
svc->exit_status = WIFEXITED(status) ? WEXITSTATUS(status) : -1;
svc->term_signal = WIFSIGNALED(status) ? WTERMSIG(status) : 0;
svc->core_dumped = WIFSIGNALED(status) && WCOREDUMP(status);
svc->has_exited = 1;
if (svc->term_signal) {
char ev[48];
const char *ab = sig_abbrev(svc->term_signal);
snprintf(ev, sizeof ev, "killed-SIG%s%s", ab ? ab : "?", svc->core_dumped ? "-core" : "");
service_log(svc, ev);
}
}
/* A forking daemon's main PID, from its pid_file: alive and inside the
* service's cgroup, so a stale or planted file cannot hand PID 1 some other
* process to supervise and kill. 0 if not (yet) valid. */
static pid_t pid_file_read(const service_t *svc) {
char buf[32];
struct stat st;
long p = 0;
int fd, found = 0;
ssize_t n;
fd = open(svc->pid_file, O_RDONLY | O_NOFOLLOW | O_CLOEXEC | O_NONBLOCK);
if (fd < 0) return 0;
if (fstat(fd, &st) != 0 || !S_ISREG(st.st_mode)) { close(fd); return 0; }
n = read(fd, buf, sizeof buf - 1);
close(fd);
if (n <= 0) return 0;
buf[n] = '\0';
if (sscanf(buf, "%ld", &p) != 1) return 0;
if (p <= 1 || p > INT_MAX || kill((pid_t)p, 0) != 0) return 0;
if (!svc->cgroup_path[0]) return 0;
/* in the cgroup or below it: a daemon may move itself into a child */
char text[NOTIFY_CGROUP_TEXT_MAX];
found = notify_read_cgroup((pid_t)p, text, sizeof text) &&
notify_cgroup_text_matches(text, svc->cgroup_path);
return found ? (pid_t)p : 0;
}
/* The launcher of a pid_file service exited 0: adopt the daemon it left, or
* wait up to PID_FILE_WAIT_SECS for a pid_file written after the exit. */
static void fork_adopt(service_t *svc) {
pid_t p = pid_file_read(svc);
if (p) {
char ev[48];
svc->child_pid = p;
svc->fork_state = 1;