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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
//! Daemon lifecycle management - start/stop operations
//!
//! Contains the core `run()`, `run_once()`, and `stop()` methods for daemon process management.
use super::hooks::{self, HookType, fire_hook};
use super::{SUPERVISOR, Supervisor};
use crate::daemon::RunOptions;
use crate::daemon_id::DaemonId;
use crate::daemon_status::DaemonStatus;
use crate::error::PortError;
use crate::ipc::IpcResponse;
use crate::log_store::LogStore;
use crate::log_store::sqlite::LOG_STORE;
use crate::pitchfork_toml::{ReadyCmd, ReadyHttp, ReadyOutput, ReadyPort};
use crate::procs::PROCS;
use crate::settings::settings;
use crate::shell::Shell;
use crate::supervisor::state::UpsertDaemonOpts;
use crate::{Result, env};
use indexmap::IndexMap;
use miette::IntoDiagnostic;
use once_cell::sync::Lazy;
use regex::Regex;
use std::collections::HashMap;
#[cfg(unix)]
use std::ffi::CString;
use std::sync::{Arc, atomic};
use std::time::Duration;
use tokio::io::AsyncBufReadExt;
use tokio::select;
use tokio::sync::oneshot;
use tokio::time;
/// Cache for compiled regex patterns to avoid recompilation on daemon restarts
static REGEX_CACHE: Lazy<std::sync::Mutex<HashMap<String, Regex>>> =
Lazy::new(|| std::sync::Mutex::new(HashMap::new()));
fn resolve_configured_ready_port(
configured_port: u16,
expected_ports: &[u16],
resolved_ports: &[u16],
) -> u16 {
let bump_offset = resolved_ports
.first()
.unwrap_or(&0)
.saturating_sub(*expected_ports.first().unwrap_or(&0));
if expected_ports.contains(&configured_port) && bump_offset > 0 {
configured_port
.checked_add(bump_offset)
.unwrap_or(configured_port)
} else {
configured_port
}
}
fn active_port_from_ready_port(ready_port: u16, resolved_ports: &[u16]) -> Option<u16> {
resolved_ports
.first()
.copied()
.filter(|&primary_port| primary_port == ready_port)
}
#[cfg(unix)]
#[derive(Clone, Debug, PartialEq, Eq)]
enum RunIdentity {
Inherit,
Switch {
uid: nix::unistd::Uid,
gid: nix::unistd::Gid,
username: Option<CString>,
},
}
/// Get or compile a regex pattern, caching the result for future use
pub(crate) fn get_or_compile_regex(pattern: &str) -> Option<Regex> {
let mut cache = REGEX_CACHE.lock().unwrap_or_else(|e| e.into_inner());
if let Some(re) = cache.get(pattern) {
return Some(re.clone());
}
match Regex::new(pattern) {
Ok(re) => {
cache.insert(pattern.to_string(), re.clone());
Some(re)
}
Err(e) => {
error!("invalid regex pattern '{pattern}': {e}");
None
}
}
}
/// Handle for an in-flight readiness command probe.
///
/// The spawned task owns the `tokio::process::Child` and waits for either the
/// process to exit or the cancel signal. Dropping the handle without cancelling
/// leaves the task running, but the child is started with `kill_on_drop(true)`
/// so it will still be terminated when the task ends.
pub(crate) struct CmdProbe {
pub(crate) cancel_tx: tokio::sync::oneshot::Sender<()>,
pub(crate) result_rx: tokio::sync::oneshot::Receiver<std::io::Result<std::process::ExitStatus>>,
}
/// Spawn a readiness command probe and return a handle that can be used to wait
/// for the exit status or cancel the probe.
///
/// The probe is started with `kill_on_drop(true)` as a cancellation fallback. The
/// spawned task waits for the process to exit; if cancellation is requested, it
/// kills the child and waits for it to reap before reporting the result.
fn apply_runtime_env(
command: &mut tokio::process::Command,
id: &DaemonId,
retry_count: u32,
daemon_env: Option<&IndexMap<String, String>>,
resolved_ports: &[u16],
) {
if let Some(ref path) = *env::ORIGINAL_PATH {
command.env("PATH", path);
}
if let Some(env_vars) = daemon_env {
command.envs(env_vars);
}
command
.env("PITCHFORK_DAEMON_ID", id.qualified())
.env("PITCHFORK_DAEMON_NAMESPACE", id.namespace())
.env("PITCHFORK_RETRY_COUNT", retry_count.to_string());
if let Some(port) = resolved_ports.first() {
command.env("PORT", port.to_string());
for (index, port) in resolved_ports.iter().enumerate() {
command.env(format!("PORT{index}"), port.to_string());
}
}
}
pub(crate) fn spawn_cmd_probe(
id: &DaemonId,
cmd: &str,
dir: &std::path::Path,
retry_count: u32,
daemon_env: Option<&IndexMap<String, String>>,
resolved_ports: &[u16],
) -> CmdProbe {
// Use the configured general.shell setting (same as daemon run and hooks)
// instead of default_for_platform(). On Windows, default_for_platform()
// returns Shell::Cmd which cannot parse Unix-style commands like
// "sleep 1; true". Falls back to default_for_platform() if the setting
// is empty or unparseable.
let shell_setting = settings().general.shell.clone();
let mut command = match shell_words::split(&shell_setting) {
Ok(parts) if !parts.is_empty() => {
let (program, args) = parts.split_first().unwrap();
let mut c = tokio::process::Command::new(program);
c.args(args);
c.arg(cmd);
c
}
_ => Shell::default_for_platform().command(cmd),
};
command
.current_dir(dir)
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.kill_on_drop(true);
apply_runtime_env(&mut command, id, retry_count, daemon_env, resolved_ports);
let mut child = match command.spawn() {
Ok(child) => child,
Err(e) => {
warn!("daemon {id}: failed to spawn command probe: {e}");
// Return a probe whose result channel is already closed. The caller will
// treat this the same as a probe that exited non-zero and respawn after
// the ready_check_interval, preserving the existing retry behaviour.
let (cancel_tx, _) = tokio::sync::oneshot::channel();
let (_, result_rx) = tokio::sync::oneshot::channel();
return CmdProbe {
cancel_tx,
result_rx,
};
}
};
let (cancel_tx, mut cancel_rx) = tokio::sync::oneshot::channel();
let (result_tx, result_rx) = tokio::sync::oneshot::channel();
tokio::spawn(async move {
let status = tokio::select! {
status = child.wait() => status,
_ = &mut cancel_rx => {
let mut child = child;
let _ = child.kill().await;
child.wait().await
}
};
let _ = result_tx.send(status);
});
CmdProbe {
cancel_tx,
result_rx,
}
}
/// Cancel an active command probe and clear its handle.
fn stop_cmd_probe_state(probe: &mut Option<CmdProbe>) {
if let Some(p) = probe.take() {
let _ = p.cancel_tx.send(());
}
}
/// Spawn a detached task that kills a daemon's process group after its
/// readiness checks are exhausted, logging a failed kill instead of
/// discarding it. The returned handle is awaited before the readiness
/// failure is reported so the process group is down by then.
fn spawn_ready_fail_kill(
id: DaemonId,
pid: u32,
stop_cfg: crate::config_types::StopConfig,
) -> tokio::task::JoinHandle<()> {
tokio::spawn(async move {
if let Err(e) = PROCS
.kill_process_group_async(pid, stop_cfg.signal.into(), stop_cfg.timeout)
.await
{
error!("daemon {id}: failed to kill pid {pid} after readiness failure: {e}");
}
})
}
/// Returns true if any configured readiness check can still succeed.
/// A check with no timeout is unbounded; a timed check can still succeed until its
/// deadline fires. `ready_delay` is only used as a fallback when no other check is
/// configured, so it is not counted here.
#[allow(clippy::too_many_arguments)]
fn any_ready_check_remaining(
ready_output: Option<&ReadyOutput>,
output_exhausted: bool,
ready_port: Option<&ReadyPort>,
port_exhausted: bool,
ready_http: Option<&ReadyHttp>,
http_exhausted: bool,
ready_cmd: Option<&ReadyCmd>,
cmd_exhausted: bool,
) -> bool {
ready_output.is_some_and(|o| o.timeout.is_none() || !output_exhausted)
|| ready_port.is_some_and(|p| p.timeout.is_none() || !port_exhausted)
|| ready_http.is_some_and(|h| h.timeout.is_none() || !http_exhausted)
|| ready_cmd.is_some_and(|c| c.timeout.is_none() || !cmd_exhausted)
}
fn delay_readiness_succeeded(
ready_notified: bool,
has_other_ready_check: bool,
process_exited: bool,
process_running: bool,
) -> bool {
!ready_notified && !has_other_ready_check && !process_exited && process_running
}
/// How long a failed start waits for the daemon's output to become queryable
/// before reporting. Typically satisfied in a few dozen milliseconds; a daemon
/// that failed without printing anything waits the whole of it, so keep it
/// short.
const SINK_OUTPUT_TIMEOUT: Duration = Duration::from_millis(400);
impl Supervisor {
/// Run a daemon, handling retries if configured
pub async fn run(&self, opts: RunOptions) -> Result<IpcResponse> {
let id = &opts.id;
let cmd = opts.cmd.clone();
// Clear any pending autostop for this daemon since it's being started
{
let mut pending = self.pending_autostops.lock().await;
if pending.remove(id).is_some() {
info!("cleared pending autostop for {id} (daemon starting)");
}
}
// Serialize against any in-flight stop of this daemon: a stop now
// waits for the whole process group to exit, so the Stopping window
// can last seconds instead of milliseconds. Starting through that
// window would collide with the dying instance (duplicate processes,
// port conflicts). Acquiring the stop lock waits the stop out; the
// state is re-read afterwards. The guard is owned and handed to
// run_once, which holds it until the new daemon's Running state and
// PID are persisted — releasing it before that point would let a
// concurrent run pass this same check (duplicate processes) or let a
// concurrent stop see no PID and return without stopping anything.
let mut stop_guard = Some(self.stop_lock(id).await.lock_owned().await);
let daemon = self.get_daemon(id).await;
if let Some(daemon) = daemon {
// Stopping state is treated as "not running" - the monitoring task will clean it up
// Only check for Running state with a valid PID
if !daemon.status.is_stopping()
&& !daemon.status.is_stopped()
&& let Some(pid) = daemon.pid
{
if opts.force {
self.stop_locked(id).await?;
info!("run: stop completed for daemon {id}");
} else {
warn!("daemon {id} already running with pid {pid}");
return Ok(IpcResponse::DaemonAlreadyRunning);
}
}
}
// If wait_ready is true and retry is configured, implement retry loop
if opts.wait_ready && opts.retry.count() > 0 {
// Use saturating_add to avoid overflow when retry = u32::MAX (infinite)
let max_attempts = opts.retry.count().saturating_add(1);
for attempt in 0..max_attempts {
let mut retry_opts = opts.clone();
retry_opts.retry_count = attempt;
retry_opts.cmd = cmd.clone();
// The first attempt starts under the guard held since the
// running check above; later attempts re-acquire it so stops
// are not locked out during the backoff sleeps.
let guard = match stop_guard.take() {
Some(guard) => guard,
None => self.stop_lock(id).await.lock_owned().await,
};
let result = self.run_once(retry_opts, guard).await?;
match result {
IpcResponse::DaemonReady { daemon } => {
return Ok(IpcResponse::DaemonReady { daemon });
}
IpcResponse::DaemonFailedWithCode {
exit_code,
resolved_ports,
} => {
if attempt < opts.retry.count() {
let backoff_secs = 2u64.saturating_pow(attempt).min(3600);
info!(
"daemon {id} failed (attempt {}/{}), retrying in {}s",
attempt + 1,
max_attempts,
backoff_secs
);
fire_hook(
HookType::OnRetry,
id.clone(),
opts.dir.0.clone(),
attempt + 1,
opts.env.clone(),
resolved_ports,
vec![],
)
.await;
time::sleep(Duration::from_secs(backoff_secs)).await;
continue;
} else {
info!("daemon {id} failed after {max_attempts} attempts");
return Ok(IpcResponse::DaemonFailedWithCode {
exit_code,
resolved_ports,
});
}
}
other => return Ok(other),
}
}
}
// No retry or wait_ready is false
let guard = match stop_guard.take() {
Some(guard) => guard,
None => self.stop_lock(id).await.lock_owned().await,
};
self.run_once(opts, guard).await
}
/// Run a daemon once (single attempt).
///
/// `stop_guard` is this daemon's stop lock, acquired by `run` before the
/// already-running check. It is held through spawning until the Running
/// state and PID are persisted (or an early failure returns), then dropped
/// before the potentially unbounded readiness wait.
pub(crate) async fn run_once(
&self,
opts: RunOptions,
stop_guard: tokio::sync::OwnedMutexGuard<()>,
) -> Result<IpcResponse> {
let id = &opts.id;
let original_cmd = opts.cmd.clone(); // Save original command for persistence
// Create channel for readiness notification if wait_ready is true
let (ready_tx, ready_rx) = if opts.wait_ready {
let (tx, rx) = oneshot::channel();
(Some(tx), Some(rx))
} else {
(None, None)
};
// Check port availability and apply auto-bump if configured
let expected_ports = opts
.port
.as_ref()
.map(|p| p.expect.clone())
.unwrap_or_default();
let (resolved_ports, effective_ready_port) = if !expected_ports.is_empty() {
let port_cfg = opts.port.as_ref().unwrap();
match check_ports_available(
&expected_ports,
port_cfg.auto_bump(),
port_cfg.max_bump_attempts(),
)
.await
{
Ok(resolved) => {
let ready_port = if let Some(configured_port) =
opts.ready_port.as_ref().and_then(|p| p.as_port())
{
Some(resolve_configured_ready_port(
configured_port,
&expected_ports,
&resolved,
))
} else if opts.ready_output.is_none()
&& opts.ready_http.is_none()
&& opts.ready_cmd.is_none()
&& opts.ready_delay.is_none()
{
// No other ready check configured — use the first expected port as a
// TCP port readiness check so the daemon is considered ready once it
// starts listening. Skip port 0 (ephemeral port request).
resolved.first().copied().filter(|&p| p != 0)
} else {
// Another ready check is configured (output/http/cmd/delay).
// Don't add an implicit TCP port check — it could race and fire
// before the daemon has produced any output.
None
};
info!("daemon {id}: ports {expected_ports:?} resolved to {resolved:?}");
(resolved, ready_port)
}
Err(e) => {
error!("daemon {id}: port check failed: {e}");
// Convert PortError to structured IPC response
if let Some(port_error) = e.downcast_ref::<PortError>() {
match port_error {
PortError::InUse { port, process, pid } => {
return Ok(IpcResponse::PortConflict {
port: *port,
process: process.clone(),
pid: *pid,
});
}
PortError::NoAvailablePort {
start_port,
attempts,
} => {
return Ok(IpcResponse::NoAvailablePort {
start_port: *start_port,
attempts: *attempts,
});
}
}
}
return Ok(IpcResponse::DaemonFailed {
error: e.to_string(),
});
}
}
} else {
// When ready_port is set without expected_port, check that the port
// is not already occupied. If another process is listening on it,
// the TCP readiness probe would immediately succeed and pitchfork
// would falsely consider the daemon ready — routing proxy traffic to
// the wrong process.
if let Some(port) = opts.ready_port.as_ref().and_then(|p| p.as_port())
&& port > 0
&& let Some((pid, process)) = detect_port_conflict(port).await
{
return Ok(IpcResponse::PortConflict { port, process, pid });
}
(
Vec::new(),
opts.ready_port.as_ref().and_then(|p| p.as_port()),
)
};
// Parse the configured shell (default "sh -c") into program + args.
// The run script is passed verbatim as the final argument, avoiding the
// lossy split->join round-trip that previously mangled $VAR/glob expansion.
let shell_setting = settings().general.shell.clone();
let shell_parts = match shell_words::split(&shell_setting) {
Ok(parts) if !parts.is_empty() => parts,
Ok(_) => {
return Ok(IpcResponse::DaemonFailed {
error: "general.shell setting is empty".to_string(),
});
}
Err(e) => {
return Ok(IpcResponse::DaemonFailed {
error: format!("failed to parse general.shell setting {shell_setting:?}: {e}"),
});
}
};
let (shell_program, shell_args) = shell_parts.split_first().unwrap();
// Use the original run string verbatim; fall back to joining cmd for
// ad-hoc commands (e.g. `pitchfork run -- cmd args`) that have no run string.
// We don't prepend `exec` because it breaks compound commands (e.g. `exec a && b`
// silently drops `b`). Users can add `exec` themselves in the run string.
let run_script = opts
.run
.clone()
.unwrap_or_else(|| shell_words::join(&original_cmd));
let (program, args) = if opts.mise.unwrap_or(settings().general.mise) {
match settings().resolve_mise_bin() {
Some(mise_bin) => {
let mise_bin_str = mise_bin.to_string_lossy().to_string();
info!("daemon {id}: wrapping command with mise ({mise_bin_str})");
let mut args = vec!["x".to_string(), "--".to_string()];
args.push(shell_program.clone());
args.extend(shell_args.iter().cloned());
args.push(run_script);
(mise_bin_str, args)
}
None => {
warn!("daemon {id}: mise=true but mise binary not found, running without mise");
let mut args: Vec<String> = shell_args.to_vec();
args.push(run_script);
(shell_program.clone(), args)
}
}
} else {
let mut args: Vec<String> = shell_args.to_vec();
args.push(run_script);
(shell_program.clone(), args)
};
#[cfg(unix)]
let run_identity = match resolve_effective_run_identity(opts.user.as_deref()) {
Ok(identity) => identity,
Err(e) => {
return Ok(IpcResponse::DaemonFailed {
error: e.to_string(),
});
}
};
info!("run: spawning daemon {id} with {program} {args:?}");
// Allocate PTY if configured
#[cfg(unix)]
let pty_pair = if opts.pty.unwrap_or(false) {
match super::pty::openpty() {
Ok(pair) => {
info!("daemon {id}: allocated PTY (pty = true)");
Some(pair)
}
Err(e) => {
warn!("daemon {id}: failed to allocate PTY, falling back to pipes: {e}");
None
}
}
} else {
None
};
// Output reaches the monitoring task either from readers this process
// owns or, when a sink owns the stream, relayed over IPC. The channel is
// created here rather than in that task so it exists before the sink
// starts: a daemon whose very first line matches its readiness pattern
// would otherwise have the match reported with nowhere to deliver it.
let (output_tx, output_rx) = tokio::sync::mpsc::channel::<super::OutputLine>(256);
let mut output_relay = None;
// Set up out-of-process capture before building the command, so the
// daemon can be handed the pipe's write end directly.
let mut sink_pipe = None;
let mut sink_writer = None;
let mut sink_child = None;
if super::log_sink::is_supported(&opts) {
let log_format = opts
.log_format
.clone()
.unwrap_or_else(|| settings().logs.log_format.clone());
let watch_for = super::log_sink::WatchFor::from_opts(id, &opts);
// The token ties this attempt's sink to this attempt's channel, so
// a sink still draining a previous attempt cannot report into it.
let relay_token = if watch_for.is_empty() {
0
} else {
let relay = super::log_sink::OutputRelay::register(id, output_tx.clone());
let token = relay.token();
output_relay = Some(relay);
token
};
match super::log_sink::SinkPipe::new(log_format, watch_for, relay_token) {
Ok((pipe, writer)) => match pipe.start(id) {
Ok(child) => {
sink_child = Some(super::log_sink::PendingSink::new(child));
sink_pipe = Some(pipe);
sink_writer = Some(writer);
}
Err(e) => {
warn!("could not start log sink for {id}, capturing in-process: {e}");
}
},
Err(e) => {
// Fall back to in-process capture rather than refusing to
// start the daemon.
warn!("could not create log pipe for {id}, capturing in-process: {e}");
}
}
}
let mut cmd = tokio::process::Command::new(&program);
#[cfg(unix)]
if let Some(ref pair) = pty_pair {
// PTY mode: connect both stdout and stderr to the slave PTY.
// The child uses the slave for stdin/stdout/stderr, and we read
// output from the master.
let slave_file = std::fs::File::from(
pair.slave
.try_clone()
.map_err(|e| miette::miette!("failed to dup slave PTY fd: {e}"))?,
);
cmd.stdin(std::process::Stdio::from(slave_file.try_clone().map_err(
|e| miette::miette!("failed to clone slave PTY fd for stdin: {e}"),
)?));
cmd.stdout(std::process::Stdio::from(slave_file.try_clone().map_err(
|e| miette::miette!("failed to clone slave PTY fd for stdout: {e}"),
)?));
cmd.stderr(std::process::Stdio::from(slave_file));
} else if let Some(writer) = sink_writer.take() {
// Capture belongs to a sibling sink process, so the daemon writes
// to a pipe this process does not read. See supervisor::log_sink.
let dup = writer
.try_clone()
.map_err(|e| miette::miette!("failed to dup log pipe for stderr: {e}"))?;
cmd.stdout(std::process::Stdio::from(writer))
.stderr(std::process::Stdio::from(dup));
} else {
cmd.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped());
}
#[cfg(not(unix))]
if let Some(writer) = sink_writer.take() {
let dup = writer
.try_clone()
.map_err(|e| miette::miette!("failed to dup log pipe for stderr: {e}"))?;
cmd.stdout(std::process::Stdio::from(writer))
.stderr(std::process::Stdio::from(dup));
} else {
cmd.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped());
}
cmd.args(&args).current_dir(&opts.dir);
#[cfg(unix)]
if pty_pair.is_none() {
cmd.stdin(std::process::Stdio::null());
}
#[cfg(not(unix))]
cmd.stdin(std::process::Stdio::null());
apply_runtime_env(
&mut cmd,
id,
opts.retry_count,
opts.env.as_ref(),
&resolved_ports,
);
// Inject proxy-related environment variables
inject_proxy_env(&mut cmd, &opts.slug);
#[cfg(unix)]
{
let run_identity = run_identity.clone();
let use_pty = pty_pair.is_some();
unsafe {
cmd.pre_exec(move || {
nix::unistd::setsid().map_err(nix_to_io_error)?;
// When using a PTY, set the slave as the controlling terminal.
// The slave FD has already been dup'd onto stdin/stdout/stderr
// by tokio, so we can use stdin (fd 0) for TIOCSCTTY.
if use_pty {
let ret = libc::ioctl(0, libc::TIOCSCTTY as libc::c_ulong, 0);
if ret < 0 {
// Non-fatal: the process can still run without
// a controlling terminal.
#[cfg(target_os = "linux")]
eprintln!(
"pitchfork: TIOCSCTTY failed: {}",
std::io::Error::last_os_error()
);
}
}
apply_run_identity(&run_identity)?;
Ok(())
});
}
}
// Timestamp the run so a failed start can wait for this attempt's output
// specifically, rather than seeing an earlier attempt's.
let spawn_time = chrono::Local::now();
// A sink is already running at this point. Both bail-outs below have to
// reap it explicitly: dropping the handle only reaps on a best-effort
// basis, and run_once runs once per retry attempt, so a daemon that
// consistently fails to spawn would otherwise accumulate sinks.
// A failed spawn returns here; the sink is terminated by PendingSink.
let mut child = cmd.spawn().into_diagnostic()?;
let pid = match child.id() {
Some(p) => p,
None => {
warn!("Daemon {id} exited before PID could be captured");
// Unlike a daemon that never started, this one ran and may have
// said why it gave up, and its output is the only diagnosis
// available. Its write end is already closed, so the sink is on
// its way to end of file: let it finish writing before reporting,
// then reap whatever is left of it.
if sink_child.is_some() {
super::log_sink::wait_for_output(id, spawn_time, SINK_OUTPUT_TIMEOUT).await;
}
return Ok(IpcResponse::DaemonFailed {
error: "Process exited immediately".to_string(),
});
}
};
info!("started daemon {id} with pid {pid}");
PROCS.refresh_pids(&[pid]);
// Register the daemon as monitored BEFORE persisting the Running
// state. The orphan reconciler treats any running, unmonitored PID
// as an orphan; if the state became visible first, a concurrent
// reconciliation pass could adopt — or under the kill policy,
// terminate — a daemon that was just legitimately started. The RAII
// guard unregisters on any early-error path below and is otherwise
// handed to the monitoring task.
let monitored_guard = super::adopt::MonitoredGuard::register(id.clone(), pid);
let monitor_token = monitored_guard.token();
// Hand the retained read end to a sink and keep one running for as long
// as this daemon is monitored.
let using_sink = sink_pipe.is_some();
// Take the sink out of the guard only once there is a pipe to supervise
// it with, so it is never left running unsupervised.
if let Some(pipe) = sink_pipe.take()
&& let Some(child) = sink_child.as_mut().and_then(|pending| pending.take())
{
pipe.supervise(id.clone(), monitor_token, child);
}
// The attempt's actual resolved ports, captured before the upsert
// moves them into state. Hooks, readiness probes, and the failure
// response must reflect this attempt: the state merge keeps the
// existing resolved_port when an update is empty, so a no-port
// attempt would otherwise inherit a previous run's stale ports
// through the upserted record.
let attempt_resolved_ports = resolved_ports.clone();
let daemon = self
.upsert_daemon(
UpsertDaemonOpts::from_run_options(&opts, DaemonStatus::Running)
.set(|o| {
o.pid = Some(pid);
o.cmd = Some(original_cmd);
o.ready_port = effective_ready_port.map(|p| ReadyPort {
port: Some(p),
template: None,
timeout: opts.ready_port.as_ref().and_then(|rp| rp.timeout),
});
o.port = crate::config_types::PortConfig::from_parts(
expected_ports,
opts.port.as_ref().map(|p| p.bump).unwrap_or_default(),
);
o.resolved_port = Some(resolved_ports);
})
.build(),
)
.await?;
// Running state and PID are now persisted: concurrent run/stop calls
// observe a running daemon and behave correctly, so release the stop
// lock rather than holding it through the readiness wait below, which
// can take arbitrarily long.
drop(stop_guard);
let id_clone = id.clone();
let ready_delay = opts.ready_delay;
let ready_output = opts.ready_output.clone();
let ready_http = opts.ready_http.clone();
let ready_port = effective_ready_port;
let implicit_ready_port = ready_port.map(|p| ReadyPort {
port: Some(p),
template: None,
timeout: None,
});
let ready_port_config = opts.ready_port.clone().or(implicit_ready_port);
let ready_cmd = opts.ready_cmd.clone();
let daemon_dir = opts.dir.0.clone();
let hook_retry_count = opts.retry_count;
let hook_retry = opts.retry;
let hook_daemon_env = opts.env.clone();
// Ports of THIS attempt, snapshotted before the monitor starts: a retry
// or restart may replace state.resolved_port before a hook task runs.
// Sourced from the attempt's local value, not the upserted record —
// the state merge inherits stale ports for a no-port attempt.
let hook_resolved_ports = attempt_resolved_ports.clone();
let readiness_daemon_env = opts.env.clone();
let readiness_resolved_ports = attempt_resolved_ports.clone();
let on_output_hook = opts.on_output_hook.clone();
// Whether this daemon has any port-related config — used to skip the
// active_port detection task for daemons that never bind a port (e.g. `sleep 60`).
// When the proxy is enabled, only detect active_port for daemons that are
// actually referenced by a registered slug, rather than blanket-polling every
// daemon (which wastes ~7.5 s of listeners::get_all() calls per port-less daemon).
let has_port_config = opts.port.as_ref().is_some_and(|p| !p.expect.is_empty())
|| (settings().proxy.enable && is_daemon_slug_target(id));
// When the ready_port check succeeds on the first resolved port we can
// set active_port directly instead
// of spawning detect_and_store_active_port (which relies on
// listeners::get_all() + process-tree traversal and is unreliable on
// Windows where Git Bash PID mapping can break descendant lookups).
let daemon_pid = pid;
// Prepare output readers before spawning the monitoring task.
// In PTY mode, we read from the PTY master FD.
// In pipe mode, we read from separate stdout/stderr pipes.
#[cfg(unix)]
let pty_reader = pty_pair.map(|p| {
tokio::io::BufReader::new(tokio::fs::File::from_std(std::fs::File::from(p.master)))
.lines()
});
#[cfg(not(unix))]
let pty_reader: Option<tokio::io::Lines<tokio::io::BufReader<tokio::fs::File>>> = None;
let stdout_reader = if pty_reader.is_none() {
child
.stdout
.take()
.map(|s| tokio::io::BufReader::new(s).lines())
} else {
None
};
let stderr_reader = if pty_reader.is_none() {
child
.stderr
.take()
.map(|s| tokio::io::BufReader::new(s).lines())
} else {
None
};
if !using_sink
&& pty_reader.is_none()
&& (stdout_reader.is_none() || stderr_reader.is_none())
{
error!("Failed to capture stdout/stderr for daemon {id}");
}
tokio::spawn(async move {
let id = id_clone;
// Registered before the Running upsert above; unregisters when
// this monitoring task ends.
let _monitored_guard = monitored_guard;
// Likewise for sink-relayed output: dropping this stops the
// supervisor delivering into a channel nobody is reading. Dropped
// explicitly once the daemon exits, before the drain below.
let output_relay = output_relay;
// Merge all output sources (PTY master OR stdout+stderr, or a
// sink's IPC reports) into a single channel.
let mut output_rx = output_rx;
if let Some(mut reader) = pty_reader {
// PTY mode: single merged stream from the master.
// output_tx is moved into the spawn; when the reader ends the
// channel closes automatically.
tokio::spawn(async move {
while let Ok(Some(mut line)) = reader.next_line().await {
// PTY slave uses ONLCR: \n → \r\n; strip the trailing \r.
if line.ends_with('\r') {
line.pop();
}
if output_tx
.send(super::OutputLine {
text: line,
source: super::OutputSource::Local,
})
.await
.is_err()
{
break;
}
}
});
} else {
// Pipe mode: stdout and stderr are merged into the same channel.
// Both `ready_output` and `on_output_hook` patterns match against
// lines from either stream, which is the expected behavior (a
// "server ready" message may appear on stderr in some tools).
if let Some(mut stdout) = stdout_reader {
let tx = output_tx.clone();
tokio::spawn(async move {
while let Ok(Some(line)) = stdout.next_line().await {
if tx
.send(super::OutputLine {
text: line,
source: super::OutputSource::Local,
})
.await
.is_err()
{
break;
}
}
});
}
if let Some(mut stderr) = stderr_reader {
let tx = output_tx.clone();
tokio::spawn(async move {
while let Ok(Some(line)) = stderr.next_line().await {
if tx
.send(super::OutputLine {
text: line,
source: super::OutputSource::Local,
})
.await
.is_err()
{
break;
}
}
});
}
// Drop the last sender so the channel closes when all readers
// finish. The relay holds its own clone, so a sink's reports
// still have somewhere to go after these end.
drop(output_tx);
}
let log_store = Arc::clone(&LOG_STORE);
let log_format = opts
.log_format
.clone()
.unwrap_or_else(|| crate::settings::settings().logs.log_format.clone());
let parse_line = move |line: &str| crate::log_parse::parse(line, &log_format);
const LOG_BATCH_SIZE: usize = 100;
const LOG_FLUSH_INTERVAL: Duration = Duration::from_millis(100);
let mut log_buffer: Vec<crate::log_parse::ParsedLog> =
Vec::with_capacity(LOG_BATCH_SIZE);
let mut log_flush_interval = tokio::time::interval(LOG_FLUSH_INTERVAL);
log_flush_interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
let flush_logs =
|buffer: &mut Vec<crate::log_parse::ParsedLog>| -> Option<tokio::task::JoinHandle<()>> {
if buffer.is_empty() {
return None;
}
let store = Arc::clone(&log_store);
let id = id.clone();
let batch = std::mem::take(buffer);
Some(tokio::task::spawn_blocking(move || {
if let Err(e) = store.append_structured_batch(&id, &batch) {
error!("Failed to write batch to log for daemon {id}: {e}");
}
}))
};
// SQLite WAL mode provides automatic durability; no explicit flush needed.
// Setup readiness checking
let mut ready_notified = false;
let mut ready_tx = ready_tx;
let ready_pattern = ready_output
.as_ref()
.and_then(|o| get_or_compile_regex(&o.pattern));
// Track whether we've already spawned the active_port detection task
let mut active_port_spawned = false;
// Validate on_output config early; discard the hook on any error so
// a bad regex does not silently fall through to the (None, None) => true
// match arm and fire on every line.
let on_output_hook = match on_output_hook {
Some(ref hook) => match hook.validate(id.name()) {
Ok(()) => on_output_hook,
Err(e) => {
error!("{e}");
None
}
},
None => None,
};
// Compile the regex pattern after validation so we only attempt this
// when the hook is known-good (validate() already checked the syntax).
let on_output_pattern: Option<regex::Regex> = on_output_hook
.as_ref()
.and_then(|h| h.regex.as_deref().and_then(get_or_compile_regex));
let on_output_debounce = on_output_hook
.as_ref()
.map(|h| h.debounce_duration())
.unwrap_or(Duration::from_millis(1000));
// Last time the on_output hook fired; None means it has never fired.
let mut on_output_last_fired: Option<std::time::Instant> = None;
let mut delay_timer =
ready_delay.map(|secs| Box::pin(time::sleep(Duration::from_secs(secs))));
// Track exhaustion of timed checks
let mut http_exhausted = false;
let mut cmd_exhausted = false;
let mut port_exhausted = false;
let mut output_exhausted = false;
// Get settings for intervals
let s = settings();
let ready_check_interval = s.supervisor_ready_check_interval();
let http_client_timeout = s.supervisor_http_client_timeout();
// Setup output readiness check deadline
let mut output_deadline = ready_output
.as_ref()
.and_then(|o| o.timeout)
.map(|d| Box::pin(time::sleep(d)));
// Setup HTTP readiness check interval and deadline
let mut http_check_interval = ready_http
.as_ref()
.map(|_| tokio::time::interval(ready_check_interval));
let mut http_deadline = ready_http
.as_ref()
.and_then(|h| h.timeout)
.map(|d| Box::pin(time::sleep(d)));
let http_client = ready_http.as_ref().map(|_| {
reqwest::Client::builder()
.timeout(http_client_timeout)
.build()
.unwrap_or_default()
});
// Setup TCP port readiness check interval and deadline
let mut port_check_interval =
ready_port.map(|_| tokio::time::interval(ready_check_interval));
let mut port_deadline = ready_port_config
.as_ref()
.and_then(|p| p.timeout)
.map(|d| Box::pin(time::sleep(d)));
// Setup command readiness check state. Probes are spawned one at a time;
// a non-zero result triggers a respawn delay, and a timeout stops the probe.
let mut cmd_probe: Option<CmdProbe> = None;
let mut cmd_respawn_delay: Option<_> = None;
let mut cmd_deadline = ready_cmd
.as_ref()
.and_then(|c| c.timeout)
.map(|d| Box::pin(time::sleep(d)));
if let Some(ref cmd) = ready_cmd {
cmd_probe = Some(spawn_cmd_probe(
&id,
&cmd.run,
daemon_dir.as_path(),
hook_retry_count,
readiness_daemon_env.as_ref(),
&readiness_resolved_ports,
));
}
// Use a channel to communicate process exit status
let (exit_tx, mut exit_rx) =
tokio::sync::mpsc::channel::<std::io::Result<std::process::ExitStatus>>(1);
// Spawn a task to wait for process exit
let child_pid = child.id().unwrap_or(0);
tokio::spawn(async move {
let result = child.wait().await;
// On non-Linux Unix (e.g. macOS) the zombie reaper may win the
// race and consume the exit status via waitpid(None, WNOHANG)
// before Tokio's child.wait() gets to it. When that happens,
// Tokio returns an ECHILD io::Error. We recover by checking
// REAPED_STATUSES for the stashed exit code.
//
// On Linux this is unnecessary because the reaper uses
// waitid(WNOWAIT) to peek before reaping, which avoids the
// race entirely.
#[cfg(all(unix, not(target_os = "linux")))]
let result = match &result {
Err(e) if e.raw_os_error() == Some(nix::libc::ECHILD) => {
if let Some(code) = super::REAPED_STATUSES.lock().await.remove(&child_pid) {
warn!(
"daemon pid {child_pid} wait() got ECHILD; \
recovered exit code {code} from zombie reaper"
);
// Synthesize an ExitStatus from the stashed code.
// On Unix we can use `ExitStatus::from_raw()` with
// a wait-style status word (code << 8 for normal
// exit, or raw signal number for signal death).
use std::os::unix::process::ExitStatusExt;
if code >= 0 {
Ok(std::process::ExitStatus::from_raw(code << 8))
} else {
// Negative code means killed by signal (-sig)
Ok(std::process::ExitStatus::from_raw((-code) & 0x7f))
}
} else {
warn!(
"daemon pid {child_pid} wait() got ECHILD but no \
stashed status found; reporting as error"
);
result
}
}
_ => result,
};
debug!("daemon pid {child_pid} wait() completed with result: {result:?}");
let _ = exit_tx.send(result).await;
});
#[allow(unused_assignments)]
// Initial None is a safety net; loop only exits via exit_rx.recv() which sets it
let mut exit_status = None;
// If there is no ready check of any kind and no delay, the daemon is
// considered immediately ready and the active_port detection task would
// never be triggered inside the select loop. Kick it off right away so
// that daemons without any readiness configuration still get their
// active_port populated (needed for proxy routing).
if has_port_config
&& ready_pattern.is_none()
&& ready_http.is_none()
&& ready_port.is_none()
&& ready_cmd.is_none()
&& delay_timer.is_none()
{
active_port_spawned = true;
detect_and_store_active_port(id.clone(), daemon_pid);
}
// Set when readiness checks exhaust. The group kill runs as a
// separate task so this loop can exit and the post-loop drain
// keeps consuming output — children logging during SIGTERM
// cleanup would otherwise block on a full pipe and never exit.
// The ready failure is only sent once the kill task completes,
// so the retry loop cannot respawn into the dying group.
let mut ready_fail_kill: Option<tokio::task::JoinHandle<()>> = None;
loop {
// biased: evaluate in exit → output → delay order so that
// process exit pre-empts both buffered output and the delay
// timer, preventing a dead daemon from being marked ready.
select! {
biased;
Some(result) = exit_rx.recv() => {
// Process exited - save exit status and notify if not ready yet
exit_status = Some(result);
debug!("daemon {id} process exited, exit_status: {exit_status:?}");
if !ready_notified {
if let Some(tx) = ready_tx.take() {
// Check if process exited successfully
let is_success = exit_status.as_ref()
.and_then(|r| r.as_ref().ok())
.map(|s| s.success())
.unwrap_or(false);
if is_success {
debug!("daemon {id} exited successfully before ready check, sending success notification");
let _ = tx.send(Ok(()));
} else {
let exit_code = exit_status.as_ref()
.and_then(|r| r.as_ref().ok())
.and_then(|s| s.code());
debug!("daemon {id} exited with failure before ready check, sending failure notification with exit_code: {exit_code:?}");
let _ = tx.send(Err(exit_code));
}
}
} else {
debug!("daemon {id} was already marked ready, not sending notification");
}
break;
},
Some(super::OutputLine { text: line, source }) = output_rx.recv() => {
// A line relayed by a sink is already in the store —
// the sink wrote and flushed it before reporting it —
// so it arrives here only to be acted on.
if matches!(source, super::OutputSource::Local) {
let parsed = parse_line(&line);
log_buffer.push(parsed);
if log_buffer.len() >= LOG_BATCH_SIZE {
let _ = flush_logs(&mut log_buffer);
}
}
trace!("output: {id} {line}");
// Strip ANSI for pattern matching so user-written patterns
// work regardless of whether the process emits color codes.
let line_clean = console::strip_ansi_codes(&line).to_string();
// Check if output matches ready pattern
if !ready_notified
&& !output_exhausted
&& let Some(ref pattern) = ready_pattern
&& pattern.is_match(&line_clean)
{
// Flush buffered logs synchronously before signalling
// readiness, so collect_startup_logs sees the line
// that triggered the match (and any co-buffered lines)
// in SQLite.
if let Some(handle) = flush_logs(&mut log_buffer) {
let _ = handle.await;
}
info!("daemon {id} ready: output matched pattern");
ready_notified = true;
if let Some(tx) = ready_tx.take() {
let _ = tx.send(Ok(()));
}
fire_hook(HookType::OnReady, id.clone(), daemon_dir.clone(), hook_retry_count, hook_daemon_env.clone(), hook_resolved_ports.clone(), vec![]).await;
stop_cmd_probe_state(&mut cmd_probe);
http_deadline = None;
cmd_deadline = None;
port_deadline = None;
output_deadline = None;
if !active_port_spawned && has_port_config {
active_port_spawned = true;
detect_and_store_active_port(id.clone(), daemon_pid);
}
}
// Check on_output hook. A sink has already applied the
// filter, and says so per line: a line reported only
// because it announced readiness must not fire a hook
// that filters for something else.
if let Some(ref hook) = on_output_hook {
let matched = match source {
super::OutputSource::Sink { fires_hook } => fires_hook,
super::OutputSource::Local => match (&hook.filter, &on_output_pattern) {
(Some(substr), _) => line_clean.contains(substr.as_str()),
(None, Some(re)) => re.is_match(&line_clean),
(None, None) => true,
},
};
if matched {
// The debounce is applied here as well as in the
// sink. A replacement sink starts with a fresh
// clock, and would otherwise let the hook fire
// twice inside one configured window.
let now = std::time::Instant::now();
let elapsed = on_output_last_fired.map(|t| now.duration_since(t));
if elapsed.is_none_or(|e| e >= on_output_debounce) {
on_output_last_fired = Some(now);
hooks::fire_output_hook(id.clone(), daemon_dir.clone(), hook_retry_count, hook_daemon_env.clone(), hook_resolved_ports.clone(), hook.run.clone(), line_clean.clone()).await;
}
}
}
// Yield briefly so that the output readiness deadline can be
// evaluated even when output is produced continuously.
tokio::task::yield_now().await;
}
_ = async {
if let Some(ref mut deadline) = http_deadline {
deadline.await;
} else {
std::future::pending::<()>().await;
}
}, if !ready_notified && ready_http.is_some() => {
http_exhausted = true;
http_deadline = None;
http_check_interval = None;
warn!("daemon {id}: HTTP readiness check timed out");
let any_remaining = any_ready_check_remaining(
ready_output.as_ref(),
output_exhausted,
ready_port_config.as_ref(),
port_exhausted,
ready_http.as_ref(),
http_exhausted,
ready_cmd.as_ref(),
cmd_exhausted,
);
if !any_remaining {
error!("daemon {id}: all readiness checks exhausted, failing");
stop_cmd_probe_state(&mut cmd_probe);
ready_fail_kill = Some(spawn_ready_fail_kill(
id.clone(),
daemon_pid,
opts.stop_signal.unwrap_or_default(),
));
break;
}
}
_ = async {
if let Some(ref mut deadline) = output_deadline {
deadline.await;
} else {
std::future::pending::<()>().await;
}
}, if !ready_notified && ready_output.is_some() => {
output_exhausted = true;
output_deadline = None;
warn!("daemon {id}: output readiness check timed out");
let any_remaining = any_ready_check_remaining(
ready_output.as_ref(),
output_exhausted,
ready_port_config.as_ref(),
port_exhausted,
ready_http.as_ref(),
http_exhausted,
ready_cmd.as_ref(),
cmd_exhausted,
);
if !any_remaining {
error!("daemon {id}: all readiness checks exhausted, failing");
stop_cmd_probe_state(&mut cmd_probe);
ready_fail_kill = Some(spawn_ready_fail_kill(
id.clone(),
daemon_pid,
opts.stop_signal.unwrap_or_default(),
));
break;
}
}
_ = async {
if let Some(ref mut interval) = http_check_interval {
interval.tick().await;
} else {
std::future::pending::<()>().await;
}
}, if !ready_notified && ready_http.is_some() && !http_exhausted => {
if let (Some(http), Some(client)) = (&ready_http, &http_client) {
match client.get(&http.url).send().await {
Ok(response) if http.accepts_status(response.status().as_u16()) => {
info!("daemon {id} ready: HTTP check passed (status {})", response.status());
ready_notified = true;
if let Some(tx) = ready_tx.take() {
let _ = tx.send(Ok(()));
}
fire_hook(HookType::OnReady, id.clone(), daemon_dir.clone(), hook_retry_count, hook_daemon_env.clone(), hook_resolved_ports.clone(), vec![]).await;
http_check_interval = None;
http_deadline = None;
stop_cmd_probe_state(&mut cmd_probe);
cmd_deadline = None;
port_deadline = None;
output_deadline = None;
if !active_port_spawned && has_port_config {
active_port_spawned = true;
detect_and_store_active_port(id.clone(), daemon_pid);
}
}
Ok(response) => {
trace!("daemon {id} HTTP check: status {} (not ready)", response.status());
}
Err(e) => {
trace!("daemon {id} HTTP check failed: {e}");
}
}
}
}
_ = async {
if let Some(ref mut deadline) = port_deadline {
deadline.await;
} else {
std::future::pending::<()>().await;
}
}, if !ready_notified && ready_port.is_some() => {
port_exhausted = true;
port_deadline = None;
port_check_interval = None;
warn!("daemon {id}: TCP port readiness check timed out");
let any_remaining = any_ready_check_remaining(
ready_output.as_ref(),
output_exhausted,
ready_port_config.as_ref(),
port_exhausted,
ready_http.as_ref(),
http_exhausted,
ready_cmd.as_ref(),
cmd_exhausted,
);
if !any_remaining {
error!("daemon {id}: all readiness checks exhausted, failing");
stop_cmd_probe_state(&mut cmd_probe);
ready_fail_kill = Some(spawn_ready_fail_kill(
id.clone(),
daemon_pid,
opts.stop_signal.unwrap_or_default(),
));
break;
}
}
_ = async {
if let Some(ref mut interval) = port_check_interval {
interval.tick().await;
} else {
std::future::pending::<()>().await;
}
}, if !ready_notified && ready_port.is_some() && !port_exhausted => {
if let Some(port) = ready_port {
match tokio::net::TcpStream::connect(("127.0.0.1", port)).await {
Ok(_) => {
info!("daemon {id} ready: TCP port {port} is listening");
ready_notified = true;
if let Some(tx) = ready_tx.take() {
let _ = tx.send(Ok(()));
}
fire_hook(HookType::OnReady, id.clone(), daemon_dir.clone(), hook_retry_count, hook_daemon_env.clone(), hook_resolved_ports.clone(), vec![]).await;
// Stop checking once ready
port_check_interval = None;
port_deadline = None;
stop_cmd_probe_state(&mut cmd_probe);
http_deadline = None;
cmd_deadline = None;
output_deadline = None;
if !active_port_spawned && has_port_config {
active_port_spawned = true;
// ready_port check just TCP-connected to this
// port, so it is definitely listening. If it
// matches the first resolved port, write
// active_port directly instead of spawning
// detect_and_store_active_port, which sleeps
// 500 ms then relies on listeners::get_all()
// + process-tree traversal — unreliable on
// Windows where Git Bash PID mapping can
// break descendant lookups.
if let Some(active_port) = active_port_from_ready_port(
port,
&readiness_resolved_ports,
) {
let mut state_file =
SUPERVISOR.state_file.lock().await;
if let Some(d) = state_file.daemons.get(&id)
&& d.pid == Some(daemon_pid)
{
state_file.set_active_port(&id, active_port);
}
} else {
detect_and_store_active_port(
id.clone(),
daemon_pid,
);
}
}
}
Err(_) => {
trace!("daemon {id} port check: port {port} not listening yet");
}
}
}
}
_ = async {
if let Some(ref mut delay) = cmd_respawn_delay {
delay.await;
} else {
std::future::pending::<()>().await;
}
}, if !ready_notified && ready_cmd.is_some() && !cmd_exhausted && cmd_probe.is_none() => {
if let Some(ref cmd) = ready_cmd {
cmd_probe = Some(spawn_cmd_probe(
&id,
&cmd.run,
daemon_dir.as_path(),
hook_retry_count,
readiness_daemon_env.as_ref(),
&readiness_resolved_ports,
));
}
cmd_respawn_delay = None;
}
result = async {
if let Some(probe) = cmd_probe.as_mut() {
std::pin::Pin::new(&mut probe.result_rx).await
} else {
std::future::pending::<Result<Result<std::process::ExitStatus, std::io::Error>, tokio::sync::oneshot::error::RecvError>>().await
}
}, if !ready_notified && ready_cmd.is_some() && !cmd_exhausted => {
// The probe task has finished; remove the handle so it is not
// cancelled or reused. This must happen only after this branch
// actually wins the select, not while constructing the future.
let _ = cmd_probe.take();
match result {
Ok(Ok(status)) if status.success() => {
info!("daemon {id} ready: readiness command succeeded");
ready_notified = true;
if let Some(tx) = ready_tx.take() {
let _ = tx.send(Ok(()));
}
fire_hook(HookType::OnReady, id.clone(), daemon_dir.clone(), hook_retry_count, hook_daemon_env.clone(), hook_resolved_ports.clone(), vec![]).await;
cmd_respawn_delay = None;
cmd_deadline = None;
http_deadline = None;
port_deadline = None;
output_deadline = None;
if !active_port_spawned && has_port_config {
active_port_spawned = true;
detect_and_store_active_port(id.clone(), daemon_pid);
}
}
Ok(Ok(_)) | Ok(Err(_)) | Err(_) => {
trace!("daemon {id} cmd check: command not ready, will respawn");
cmd_respawn_delay = Some(Box::pin(time::sleep(ready_check_interval)));
}
}
}
_ = async {
if let Some(ref mut deadline) = cmd_deadline {
deadline.await;
} else {
std::future::pending::<()>().await;
}
}, if !ready_notified && ready_cmd.is_some() => {
cmd_exhausted = true;
cmd_deadline = None;
stop_cmd_probe_state(&mut cmd_probe);
cmd_respawn_delay = None;
warn!("daemon {id}: command readiness check timed out");
let any_remaining = any_ready_check_remaining(
ready_output.as_ref(),
output_exhausted,
ready_port_config.as_ref(),
port_exhausted,
ready_http.as_ref(),
http_exhausted,
ready_cmd.as_ref(),
cmd_exhausted,
);
if !any_remaining {
error!("daemon {id}: all readiness checks exhausted, failing");
ready_fail_kill = Some(spawn_ready_fail_kill(
id.clone(),
daemon_pid,
opts.stop_signal.unwrap_or_default(),
));
break;
}
}
_ = async {
if let Some(ref mut timer) = delay_timer {
timer.await;
} else {
std::future::pending::<()>().await;
}
} => {
let has_other_ready_check = ready_pattern.is_some()
|| ready_http.is_some()
|| ready_port.is_some()
|| ready_cmd.is_some();
let delay_is_only_readiness = !ready_notified && !has_other_ready_check;
let process_exited = exit_status.is_some();
let process_running = if delay_is_only_readiness && !process_exited {
// Force-refresh sysinfo for this PID before checking.
// On Windows, the cached process list may be stale.
PROCS.refresh_pids(&[daemon_pid]);
PROCS.is_running(daemon_pid)
} else {
false
};
if delay_readiness_succeeded(
ready_notified,
has_other_ready_check,
process_exited,
process_running,
) {
info!("daemon {id} ready: delay elapsed");
ready_notified = true;
if let Some(tx) = ready_tx.take() {
let _ = tx.send(Ok(()));
}
fire_hook(HookType::OnReady, id.clone(), daemon_dir.clone(), hook_retry_count, hook_daemon_env.clone(), hook_resolved_ports.clone(), vec![]).await;
if !active_port_spawned && has_port_config {
active_port_spawned = true;
detect_and_store_active_port(id.clone(), daemon_pid);
}
} else if delay_is_only_readiness {
if process_exited {
debug!("daemon {id} exited during ready_delay, not marking as ready");
} else {
debug!("daemon {id} pid {daemon_pid} not running during ready_delay, deferring to exit handler");
}
}
if delay_is_only_readiness {
// Clear all deadlines — no other checks are configured
// when delay fires as readiness, but clear defensively.
output_deadline = None;
http_deadline = None;
cmd_deadline = None;
port_deadline = None;
stop_cmd_probe_state(&mut cmd_probe);
}
// Disable timer after it fires
delay_timer = None;
}
_ = log_flush_interval.tick() => {
let _ = flush_logs(&mut log_buffer);
}
}
}
// Snapshot the daemon state BEFORE draining output.
//
// The drain can take up to 5s (e.g. when child processes keep the
// stdout pipe open). During that time, a subsequent start() call
// (e.g. from `pitchfork restart`) can upsert the daemon with a new
// PID and Running status. If we only checked state AFTER the drain,
// the monitoring task would see d.pid != Some(old_pid) && !is_stopped()
// && !is_stopping() and return early without firing on_stop/on_exit
// hooks.
//
// By snapshotting is_stopping before the drain, we preserve the
// knowledge that stop() was called, so hooks fire correctly even
// if start() has since changed the state.
let pre_drain_daemon = SUPERVISOR.get_daemon(&id).await;
let pre_drain_is_stopping = pre_drain_daemon
.as_ref()
.is_some_and(|d| d.status.is_stopped() || d.status.is_stopping());
// Drain any in-flight output lines that were still in the mpsc
// channel or the OS pipe buffer when the child exited. Without
// this, trailing log lines from short-lived daemons get dropped.
// The reader tasks drop their senders on EOF, so recv() returns
// None when all data has been consumed. A total deadline of 5 s
// guards against a stuck reader (e.g. PTY master FD not closing)
// while ensuring drain doesn't block post-exit cleanup indefinitely.
//
// Stop accepting relayed output first: the relay holds a sender of
// its own, so leaving it registered would keep the channel open and
// make every drain wait out the whole deadline. Readiness is moot
// now anyway — the process has exited.
drop(output_relay);
let drain_deadline = tokio::time::Instant::now() + Duration::from_secs(5);
loop {
let now = tokio::time::Instant::now();
if now >= drain_deadline {
break;
}
let Ok(Some(line)) =
tokio::time::timeout(drain_deadline - now, output_rx.recv()).await
else {
break;
};
// Sink-relayed lines are already stored; see the select loop.
if matches!(line.source, super::OutputSource::Local) {
log_buffer.push(parse_line(&line.text));
}
}
// Flush any remaining log lines (including drained) before the process exits.
// Await the flush to guarantee all buffered logs are persisted before cleanup.
if let Some(handle) = flush_logs(&mut log_buffer) {
let _ = handle.await;
}
// Clear active_port since the process is no longer running
{
let mut state_file = SUPERVISOR.state_file.lock().await;
state_file.clear_active_port(&id);
}
// Get the final exit status
let exit_status = if let Some(status) = exit_status {
status
} else {
// Streams closed but process hasn't exited yet, wait for it
match exit_rx.recv().await {
Some(status) => status,
None => {
warn!("daemon {id} exit channel closed without receiving status");
Err(std::io::Error::other("exit channel closed"))
}
}
};
// If the loop exited via readiness exhaustion, wait for the group
// kill to finish before reporting the failure so the retry loop
// (or a waiting client) cannot start a replacement while the old
// process group is still terminating.
if let Some(kill) = ready_fail_kill {
let _ = kill.await;
if let Some(tx) = ready_tx.take() {
let _ = tx.send(Err(Some(124)));
}
}
let current_daemon = SUPERVISOR.get_daemon(&id).await;
// Signal that this monitoring task is processing its exit path.
// The RAII guard will decrement the counter and notify close()
// when the task finishes (including all fire_hook registrations),
// regardless of which return path is taken.
SUPERVISOR
.active_monitors
.fetch_add(1, atomic::Ordering::Release);
struct MonitorGuard;
impl Drop for MonitorGuard {
fn drop(&mut self) {
SUPERVISOR
.active_monitors
.fetch_sub(1, atomic::Ordering::Release);
SUPERVISOR.monitor_done.notify_waiters();
}
}
let _monitor_guard = MonitorGuard;
// Check if this monitoring task is for the current daemon process.
// If the daemon was intentionally stopped (pre_drain_is_stopping),
// skip this check — we must still fire on_stop/on_exit hooks even
// if start() has since changed the PID and status.
if !pre_drain_is_stopping
&& (current_daemon.is_none()
|| current_daemon.as_ref().is_some_and(|d| {
d.pid != Some(pid) && !d.status.is_stopped() && !d.status.is_stopping()
}))
{
// Another process has taken over, don't update status
return;
}
// Capture the intentional-stop flag. Combine pre-drain and
// post-drain state to handle both race orders:
// - stop() set Stopping before drain → pre_drain_is_stopping
// - stop() set Stopped during drain → current_daemon.is_stopped()
let already_stopped = current_daemon
.as_ref()
.is_some_and(|d| d.status.is_stopped());
let is_stopping = already_stopped
|| pre_drain_is_stopping
|| current_daemon
.as_ref()
.is_some_and(|d| d.status.is_stopping());
// --- Phase 1: Determine exit_code, exit_reason, and update daemon state ---
let (exit_code, exit_reason) = match (&exit_status, is_stopping) {
(Ok(status), true) => {
// Intentional stop (by pitchfork). status.code() returns None
// on Unix when killed by signal (e.g. SIGTERM); use -1 to
// distinguish from a clean exit code 0.
(status.code().unwrap_or(-1), "stop")
}
(Ok(status), false) if status.success() => (status.code().unwrap_or(-1), "exit"),
(Ok(status), false) => (status.code().unwrap_or(-1), "fail"),
(Err(_), true) => {
// child.wait() error while stopping (e.g. sysinfo reaped the process)
(-1, "stop")
}
(Err(_), false) => (-1, "fail"),
};
// Update daemon state unless stop() already did it (won the race),
// OR the daemon was intentionally stopped before the drain
// (pre_drain_is_stopping). In the latter case, start() may have
// upserted Running during the 5s drain, and we must NOT overwrite
// it with Stopped — that would undo the restart.
if !already_stopped && !pre_drain_is_stopping {
if let Ok(status) = &exit_status {
info!("daemon {id} exited with status {status}");
}
let (new_status, last_exit_success) = match exit_reason {
"stop" | "exit" => (
DaemonStatus::Stopped,
exit_status.as_ref().map(|s| s.success()).unwrap_or(true),
),
_ => (DaemonStatus::Errored(exit_code), false),
};
// Revalidate ownership inside the same state-lock section that
// performs the write. The snapshot above was taken without
// holding the lock, so a restart running on another thread can
// install a successor in between; overwriting its record would
// clear a live daemon's PID and undo the restart.
if !SUPERVISOR
.finalize_monitored_exit(
&id,
pid,
monitor_token,
new_status,
Some(last_exit_success),
)
.await
{
debug!("daemon {id} exit state was not written; a successor owns the record");
}
}
// --- Phase 2: Fire hooks ---
let hook_extra_env = vec![
("PITCHFORK_EXIT_CODE".to_string(), exit_code.to_string()),
("PITCHFORK_EXIT_REASON".to_string(), exit_reason.to_string()),
];
// Determine which hooks to fire based on exit reason
let hooks_to_fire: Vec<HookType> = match exit_reason {
"stop" => vec![HookType::OnStop, HookType::OnExit],
"exit" => vec![HookType::OnExit],
// "fail": fire on_fail + on_exit only when retries are exhausted
_ if hook_retry_count >= hook_retry.count() => {
vec![HookType::OnFail, HookType::OnExit]
}
_ => vec![],
};
for hook_type in hooks_to_fire {
fire_hook(
hook_type,
id.clone(),
daemon_dir.clone(),
hook_retry_count,
hook_daemon_env.clone(),
hook_resolved_ports.clone(),
hook_extra_env.clone(),
)
.await;
}
});
// If wait_ready is true, wait for readiness notification
if let Some(ready_rx) = ready_rx {
match ready_rx.await {
Ok(Ok(())) => {
info!("daemon {id} is ready");
Ok(IpcResponse::DaemonReady { daemon })
}
Ok(Err(exit_code)) => {
error!("daemon {id} failed before becoming ready");
// The caller reports this by querying the log store for
// what the daemon printed, so wait for the sink's final
// write first. The in-process path got this ordering by
// flushing synchronously before signalling.
//
// Only on the attempt that gives up: `run` retries inline,
// and waiting after every attempt would both delay the
// backoff and widen the window in which the daemon looks
// errored and idle — long enough for the background retry
// checker to start an attempt of its own alongside it.
let last_attempt = opts.retry_count >= opts.retry.count();
if using_sink && last_attempt {
super::log_sink::wait_for_output(id, spawn_time, SINK_OUTPUT_TIMEOUT).await;
}
Ok(IpcResponse::DaemonFailedWithCode {
exit_code,
resolved_ports: attempt_resolved_ports,
})
}
Err(_) => {
error!("readiness channel closed unexpectedly for daemon {id}");
Ok(IpcResponse::DaemonStart { daemon })
}
}
} else {
Ok(IpcResponse::DaemonStart { daemon })
}
}
/// Stop a running daemon
pub async fn stop(&self, id: &DaemonId) -> Result<IpcResponse> {
// Hold the daemon's stop lock for the whole stop (including the
// whole-group termination wait) so starts and concurrent stops of the
// same daemon serialize against it instead of racing the Stopping window.
let lock = self.stop_lock(id).await;
let _guard = lock.lock().await;
self.stop_locked(id).await
}
/// Stop implementation. Caller must hold the daemon's stop lock.
async fn stop_locked(&self, id: &DaemonId) -> Result<IpcResponse> {
let pitchfork_id = DaemonId::pitchfork();
if *id == pitchfork_id {
return Ok(IpcResponse::Error(
"Cannot stop supervisor via stop command".into(),
));
}
info!("stopping daemon: {id}");
if let Some(daemon) = self.get_daemon(id).await {
trace!("daemon to stop: {daemon}");
if let Some(pid) = daemon.pid {
trace!("killing pid: {pid}");
if PROCS.is_running(pid) {
// Something is alive on that PID, but the kill below signals
// the entire process group: if the PID was recycled while
// this record sat unsupervised, that group belongs to an
// unrelated process tree. The daemon itself is gone either
// way, so report it as not running and clear the record.
if !super::signalling_pid_is_authorized(
daemon.start_time,
PROCS.start_time(pid),
) {
warn!(
"pid {pid} recorded for daemon {id} belongs to another process now; not signalling it"
);
self.upsert_daemon(
UpsertDaemonOpts::builder(id.clone())
.set(|o| {
o.pid = None;
o.status = DaemonStatus::Stopped;
})
.build(),
)
.await?;
return Ok(IpcResponse::DaemonWasNotRunning);
}
// First set status to Stopping (preserve PID for monitoring task)
self.upsert_daemon(
UpsertDaemonOpts::builder(id.clone())
.set(|o| {
o.pid = Some(pid);
o.status = DaemonStatus::Stopping;
})
.build(),
)
.await?;
// Kill the entire process group atomically (daemon PID == PGID
// because we called setsid() at spawn time)
let stop_cfg = daemon.stop_signal.unwrap_or_default();
let stop_signal: i32 = stop_cfg.signal.into();
if let Err(e) = PROCS
.kill_process_group_async(pid, stop_signal, stop_cfg.timeout)
.await
{
debug!("failed to kill pid {pid}: {e}");
// Check if the process group is actually gone despite the
// error. Checking only the leader here would mark the daemon
// Stopped while surviving group members (e.g. one stuck in
// uninterruptible sleep) are still alive — letting a restart
// collide with them.
if PROCS.process_group_alive(pid) {
// Group still has live members - set back to Running
debug!(
"failed to stop pid {pid}: process group still alive after kill"
);
self.upsert_daemon(
UpsertDaemonOpts::builder(id.clone())
.set(|o| {
o.pid = Some(pid); // Preserve PID to avoid orphaning the process
o.status = DaemonStatus::Running;
})
.build(),
)
.await?;
return Ok(IpcResponse::DaemonStopFailed {
error: format!(
"process group of {pid} still alive after kill attempt: {e}"
),
});
}
}
// Process successfully stopped
// Note: kill_process_group_async waits for the ENTIRE process
// group to exit (stop signal -> stop_timeout -> SIGKILL, then a
// bounded verification), so a replacement daemon can be started
// without colliding with a still-terminating instance. The only
// exception is a member stuck in uninterruptible sleep, which is
// logged with a warning.
self.upsert_daemon(
UpsertDaemonOpts::builder(id.clone())
.set(|o| {
o.pid = None;
o.status = DaemonStatus::Stopped;
o.last_exit_success = Some(true);
})
.build(),
)
.await?;
} else {
debug!("pid {pid} not running, process may have exited unexpectedly");
// Process already dead — transition to Stopped so the
// retry checker sees a terminal state and stops
// scheduling new attempts. This is important for an
// explicit `pitchfork stop` on an Errored daemon: the
// user wants to abort retries.
self.upsert_daemon(
UpsertDaemonOpts::builder(id.clone())
.set(|o| {
o.pid = None;
o.status = DaemonStatus::Stopped;
})
.build(),
)
.await?;
return Ok(IpcResponse::DaemonWasNotRunning);
}
Ok(IpcResponse::Ok)
} else {
debug!("daemon {id} not running");
Ok(IpcResponse::DaemonNotRunning)
}
} else {
debug!("daemon {id} not found");
Ok(IpcResponse::DaemonNotFound)
}
}
}
#[cfg(unix)]
fn resolve_effective_run_identity(daemon_user: Option<&str>) -> Result<RunIdentity> {
let s = settings();
let settings_user = s.supervisor.user.trim();
let daemon_user = daemon_user.map(str::trim).filter(|user| !user.is_empty());
let settings_user = (!settings_user.is_empty()).then_some(settings_user);
let configured = daemon_user.or(settings_user);
let current_uid = nix::unistd::Uid::effective().as_raw();
let current_gid = nix::unistd::Gid::effective().as_raw();
resolve_run_identity(
configured,
current_uid,
current_gid,
std::env::var("SUDO_UID").ok().as_deref(),
std::env::var("SUDO_GID").ok().as_deref(),
)
}
#[cfg(unix)]
fn resolve_run_identity(
configured: Option<&str>,
current_uid: u32,
current_gid: u32,
sudo_uid: Option<&str>,
sudo_gid: Option<&str>,
) -> Result<RunIdentity> {
let current_uid = nix::unistd::Uid::from_raw(current_uid);
let current_gid = nix::unistd::Gid::from_raw(current_gid);
if let Some(user) = configured {
let identity = resolve_configured_user(user)?;
ensure_can_use_identity(user, &identity, current_uid, current_gid)?;
if identity.matches(current_uid, current_gid) {
return Ok(RunIdentity::Inherit);
}
return Ok(identity);
}
if current_uid.is_root()
&& let Some(identity) = resolve_sudo_identity(sudo_uid, sudo_gid)
{
return Ok(identity);
}
Ok(RunIdentity::Inherit)
}
#[cfg(unix)]
fn resolve_configured_user(user: &str) -> Result<RunIdentity> {
if user.chars().all(|c| c.is_ascii_digit()) {
let uid = user
.parse::<u32>()
.map_err(|e| miette::miette!("invalid run user UID '{}': {}", user, e))?;
let user_record = nix::unistd::User::from_uid(nix::unistd::Uid::from_raw(uid))
.into_diagnostic()?
.ok_or_else(|| miette::miette!("run user UID '{}' does not exist", user))?;
return run_identity_from_user_record(user_record);
}
let user_record = nix::unistd::User::from_name(user)
.into_diagnostic()?
.ok_or_else(|| miette::miette!("run user '{}' does not exist", user))?;
run_identity_from_user_record(user_record)
}
#[cfg(unix)]
fn run_identity_from_user_record(user: nix::unistd::User) -> Result<RunIdentity> {
let username = CString::new(user.name)
.map_err(|e| miette::miette!("run user name contains an interior nul byte: {}", e))?;
Ok(RunIdentity::Switch {
uid: user.uid,
gid: user.gid,
username: Some(username),
})
}
#[cfg(unix)]
fn run_identity_from_raw_ids(uid: u32, gid: u32, username: Option<CString>) -> RunIdentity {
RunIdentity::Switch {
uid: nix::unistd::Uid::from_raw(uid),
gid: nix::unistd::Gid::from_raw(gid),
username,
}
}
#[cfg(unix)]
fn resolve_sudo_identity(sudo_uid: Option<&str>, sudo_gid: Option<&str>) -> Option<RunIdentity> {
let uid = sudo_uid?.parse::<u32>().ok()?;
let gid = sudo_gid?.parse::<u32>().ok()?;
let username = nix::unistd::User::from_uid(nix::unistd::Uid::from_raw(uid))
.ok()
.flatten()
.and_then(|u| CString::new(u.name).ok());
Some(run_identity_from_raw_ids(uid, gid, username))
}
#[cfg(unix)]
fn ensure_can_use_identity(
configured_user: &str,
identity: &RunIdentity,
current_uid: nix::unistd::Uid,
current_gid: nix::unistd::Gid,
) -> Result<()> {
let RunIdentity::Switch { uid, gid, .. } = identity else {
return Ok(());
};
if *uid == current_uid && *gid == current_gid {
return Ok(());
}
if current_uid.is_root() {
return Ok(());
}
Err(miette::miette!(
"daemon is configured to run as '{}', but the supervisor is running as uid={} gid={}. Restart the supervisor with sudo to switch to uid={} gid={}, or choose a user matching the supervisor.",
configured_user,
current_uid.as_raw(),
current_gid.as_raw(),
uid.as_raw(),
gid.as_raw()
))
}
#[cfg(unix)]
fn apply_run_identity(identity: &RunIdentity) -> std::io::Result<()> {
let RunIdentity::Switch { uid, gid, username } = identity else {
return Ok(());
};
if let Some(username) = username {
initgroups_for_user(username, *gid)?;
} else {
setgroups_to_primary(*gid)?;
}
nix::unistd::setgid(*gid).map_err(nix_to_io_error)?;
nix::unistd::setuid(*uid).map_err(nix_to_io_error)?;
Ok(())
}
#[cfg(unix)]
impl RunIdentity {
fn matches(&self, uid: nix::unistd::Uid, gid: nix::unistd::Gid) -> bool {
matches!(self, RunIdentity::Switch { uid: u, gid: g, .. } if *u == uid && *g == gid)
}
}
#[cfg(unix)]
fn setgroups_to_primary(gid: nix::unistd::Gid) -> std::io::Result<()> {
let groups = [gid.as_raw() as libc::gid_t];
#[cfg(any(target_os = "linux", target_os = "android"))]
let group_count = groups.len();
#[cfg(not(any(target_os = "linux", target_os = "android")))]
let group_count = groups.len() as libc::c_int;
let rc = unsafe { libc::setgroups(group_count, groups.as_ptr()) };
if rc == -1 {
Err(std::io::Error::last_os_error())
} else {
Ok(())
}
}
#[cfg(unix)]
fn initgroups_for_user(username: &CString, gid: nix::unistd::Gid) -> std::io::Result<()> {
let gid = gid.as_raw();
#[cfg(any(
target_os = "macos",
target_os = "ios",
target_os = "tvos",
target_os = "watchos"
))]
let base_gid = i32::try_from(gid)
.map_err(|_| std::io::Error::other(format!("gid {gid} is out of range")))?;
#[cfg(not(any(
target_os = "macos",
target_os = "ios",
target_os = "tvos",
target_os = "watchos"
)))]
let base_gid = gid as libc::gid_t;
// SAFETY: `username` is a valid nul-terminated C string and `base_gid`
// is derived from a resolved system account or sudo-provided gid.
let rc = unsafe { libc::initgroups(username.as_ptr(), base_gid) };
if rc == -1 {
Err(std::io::Error::last_os_error())
} else {
Ok(())
}
}
#[cfg(unix)]
fn nix_to_io_error(err: nix::errno::Errno) -> std::io::Error {
std::io::Error::from_raw_os_error(err as i32)
}
/// Check if multiple ports are available and optionally auto-bump to find available ports.
///
/// All ports are bumped by the same offset to maintain relative port spacing.
/// Returns the resolved ports (either the original or bumped ones).
/// Returns an error if any port is in use and auto_bump is disabled,
/// or if no available ports can be found after max attempts.
async fn check_ports_available(
expected_ports: &[u16],
auto_bump: bool,
max_attempts: u32,
) -> Result<Vec<u16>> {
if expected_ports.is_empty() {
return Ok(Vec::new());
}
for bump_offset in 0..=max_attempts {
// Use wrapping_add to handle overflow correctly - ports wrap around at 65535
let candidate_ports: Vec<u16> = expected_ports
.iter()
.map(|&p| p.wrapping_add(bump_offset as u16))
.collect();
// Check if all ports in this set are available
let mut all_available = true;
let mut conflicting_port = None;
for &port in &candidate_ports {
// Port 0 is a special case - it requests an ephemeral port from the OS.
// Skip the availability check for port 0 since binding to it always succeeds.
if port == 0 {
continue;
}
// Use spawn_blocking to avoid blocking the async runtime during TCP bind checks.
//
// We check multiple addresses to avoid false-negatives caused by SO_REUSEADDR.
// On macOS/BSD, Rust's TcpListener::bind sets SO_REUSEADDR by default, which
// allows binding 0.0.0.0:port even when 127.0.0.1:port is already in use
// (because 0.0.0.0 is technically a different address). Most daemons bind
// to localhost, so checking 127.0.0.1 is essential to detect real conflicts.
// We also check [::1] to cover IPv6 loopback listeners.
//
// NOTE: This check has a time-of-check-to-time-of-use (TOCTOU) race condition.
// Another process could grab the port between our check and the daemon actually
// binding. This is inherent to the approach and acceptable for our use case
// since we're primarily detecting conflicts with already-running daemons.
if is_port_in_use(port).await {
all_available = false;
conflicting_port = Some(port);
break;
}
}
if all_available {
// Check for overflow (port wrapped around to 0 due to wrapping_add)
// If any candidate port is 0 but the original expected port wasn't 0,
// it means we've wrapped around and should stop
if candidate_ports.contains(&0) && !expected_ports.contains(&0) {
return Err(PortError::NoAvailablePort {
start_port: expected_ports[0],
attempts: bump_offset + 1,
}
.into());
}
if bump_offset > 0 {
info!("ports {expected_ports:?} bumped by {bump_offset} to {candidate_ports:?}");
}
return Ok(candidate_ports);
}
// Port is in use
if bump_offset == 0
&& !auto_bump
&& let Some(port) = conflicting_port
{
let (pid, process) = identify_port_owner(port).await;
return Err(PortError::InUse { port, process, pid }.into());
}
}
// No available ports found after max attempts
Err(PortError::NoAvailablePort {
start_port: expected_ports[0],
attempts: max_attempts + 1,
}
.into())
}
/// Check whether a port is currently in use by attempting to bind on multiple addresses.
///
/// Returns `true` when at least one bind attempt gets `AddrInUse`, meaning another
/// process is listening. Other errors (e.g. `AddrNotAvailable` on an address family
/// the OS doesn't support) are ignored so they don't produce false positives.
async fn is_port_in_use(port: u16) -> bool {
tokio::task::spawn_blocking(move || {
for &addr in &["0.0.0.0", "127.0.0.1", "::1"] {
match std::net::TcpListener::bind((addr, port)) {
Ok(listener) => drop(listener),
Err(e) if e.kind() == std::io::ErrorKind::AddrInUse => return true,
Err(_) => continue,
}
}
false
})
.await
.unwrap_or(false)
}
/// Best-effort lookup of the process occupying a port via `listeners::get_all()`.
///
/// Returns `(pid, process_name)`. Falls back to `(0, "unknown")` when the
/// system call fails (permission error, unsupported OS, etc.).
async fn identify_port_owner(port: u16) -> (u32, String) {
tokio::task::spawn_blocking(move || {
listeners::get_all()
.ok()
.and_then(|list| {
list.into_iter()
.find(|l| l.socket.port() == port)
.map(|l| (l.process.pid, l.process.name))
})
.unwrap_or((0, "unknown".to_string()))
})
.await
.unwrap_or((0, "unknown".to_string()))
}
/// Detect whether a port is in use, and if so, identify the owning process.
///
/// Combines `is_port_in_use` (reliable bind probe) with `identify_port_owner`
/// (best-effort process lookup). Returns `None` when the port is free.
async fn detect_port_conflict(port: u16) -> Option<(u32, String)> {
if !is_port_in_use(port).await {
return None;
}
Some(identify_port_owner(port).await)
}
#[derive(Debug, PartialEq, Eq)]
enum ActivePortSelection {
NoCandidates,
Selected(u16),
Ambiguous(Vec<u16>),
}
fn discovery_preferred_port(daemon: &crate::daemon::Daemon) -> Option<u16> {
daemon
.resolved_port
.first()
.copied()
.or_else(|| {
daemon
.port
.as_ref()
.and_then(|port| port.expect.first().copied())
})
.filter(|&port| port > 0)
}
fn select_active_port(
listeners: impl IntoIterator<Item = listeners::Listener>,
descendant_pids: &std::collections::HashSet<u32>,
preferred_port: Option<u16>,
) -> ActivePortSelection {
let process_ports: std::collections::BTreeSet<u16> = listeners
.into_iter()
.filter(|listener| {
listener.protocol == listeners::Protocol::TCP
&& listener.state == listeners::SocketState::Listen
&& descendant_pids.contains(&listener.process.pid)
})
.map(|listener| listener.socket.port())
.filter(|&port| port > 0)
.collect();
if let Some(port) = preferred_port
&& process_ports.contains(&port)
{
return ActivePortSelection::Selected(port);
}
match process_ports.len() {
0 => ActivePortSelection::NoCandidates,
1 => ActivePortSelection::Selected(*process_ports.first().unwrap()),
_ => ActivePortSelection::Ambiguous(process_ports.into_iter().collect()),
}
}
/// Spawn a background task that detects the daemon process's active listening port
/// and stores it in the state file as `active_port`.
///
/// This is called once when the daemon becomes ready. The port is cleared when the daemon stops.
///
/// Port selection strategy:
/// 1. Consider only TCP listening sockets owned by the daemon or its descendants.
/// 2. Prefer the first resolved port, falling back to the first expected port for
/// legacy state without resolved ports.
/// 3. Select a sole distinct candidate; leave `active_port` unset when ambiguous.
fn detect_and_store_active_port(id: DaemonId, pid: u32) {
tokio::spawn(async move {
// Retry with exponential backoff so that slow-starting daemons (JVM,
// Node.js, Python, etc.) that take more than 500 ms to bind their port
// are still detected. Total wait budget: 500+1000+2000+4000 = 7.5 s.
for delay_ms in [500u64, 1000, 2000, 4000] {
tokio::time::sleep(std::time::Duration::from_millis(delay_ms)).await;
// Read daemon state atomically: check if still alive and get the preferred port
// in a single lock acquisition to avoid TOCTOU and unnecessary lock overhead.
let preferred_port: Option<u16> = {
let state_file = SUPERVISOR.state_file.lock().await;
match state_file.daemons.get(&id) {
Some(d) if d.pid.is_none() => {
debug!("daemon {id}: aborting active_port detection — process exited");
return;
}
Some(d) => discovery_preferred_port(d),
None => None,
}
};
let selection = tokio::task::spawn_blocking(move || {
let listeners = listeners::get_all().ok()?;
// Refresh process tree so all_children sees current descendants.
PROCS.refresh_processes();
let descendant_pids: std::collections::HashSet<u32> = PROCS
.all_children(pid)
.into_iter()
.chain(std::iter::once(pid))
.collect();
Some(select_active_port(
listeners,
&descendant_pids,
preferred_port,
))
})
.await
.ok()
.flatten()
.unwrap_or(ActivePortSelection::NoCandidates);
let port = match selection {
ActivePortSelection::Selected(port) => port,
ActivePortSelection::Ambiguous(ports) => {
debug!(
"daemon {id}: ambiguous active_port candidates {ports:?} for pid {pid} \
and its descendants; leaving active_port unset (will retry)"
);
continue;
}
ActivePortSelection::NoCandidates => {
debug!(
"daemon {id}: no active port detected for pid {pid} or its descendants \
(will retry)"
);
continue;
}
};
debug!("daemon {id} active_port detected: {port}");
let mut state_file = SUPERVISOR.state_file.lock().await;
if let Some(d) = state_file.daemons.get(&id) {
// Guard against PID reuse: if the original process exited and the OS
// assigned the same PID to an unrelated process that happens to bind
// a port, we must not route proxy traffic to that unrelated service.
if d.pid == Some(pid) {
state_file.set_active_port(&id, port);
} else {
debug!(
"daemon {id}: skipping active_port write — PID mismatch \
(expected {pid}, current {:?})",
d.pid
);
}
}
return;
}
debug!(
"daemon {id}: active port detection exhausted all retries for pid {pid} and its descendants"
);
});
}
#[cfg(test)]
mod active_port_tests {
use super::*;
use crate::config_types::PortConfig;
use listeners::{Listener, Process, Protocol, SocketState};
use std::net::{IpAddr, Ipv4Addr, SocketAddr};
fn listener(pid: u32, port: u16, protocol: Protocol, state: SocketState) -> Listener {
Listener {
process: Process {
pid,
name: "test".to_string(),
path: "/test".to_string(),
},
socket: SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), port),
protocol,
state,
}
}
#[test]
fn active_port_candidates_exclude_outbound_tcp_and_udp_sockets() {
let daemon_pid = 100;
let child_pid = 101;
let descendant_pids = [daemon_pid, child_pid].into_iter().collect();
let listeners = vec![
listener(child_pid, 3004, Protocol::TCP, SocketState::Listen),
listener(daemon_pid, 47082, Protocol::TCP, SocketState::Established),
listener(daemon_pid, 5353, Protocol::UDP, SocketState::Unknown),
listener(999, 9000, Protocol::TCP, SocketState::Listen),
];
assert_eq!(
select_active_port(listeners, &descendant_pids, None),
ActivePortSelection::Selected(3004)
);
}
#[test]
fn bumped_cmd_readiness_prefers_resolved_primary_port() {
let daemon = crate::daemon::Daemon {
resolved_port: vec![3004],
port: Some(PortConfig {
expect: vec![3000],
..PortConfig::default()
}),
..crate::daemon::Daemon::default()
};
let descendant_pids = [100].into_iter().collect();
let listeners = vec![
listener(100, 9000, Protocol::TCP, SocketState::Listen),
listener(100, 3004, Protocol::TCP, SocketState::Listen),
];
assert_eq!(discovery_preferred_port(&daemon), Some(3004));
assert_eq!(
select_active_port(
listeners,
&descendant_pids,
discovery_preferred_port(&daemon),
),
ActivePortSelection::Selected(3004)
);
}
#[test]
fn legacy_state_uses_expected_primary_port_for_discovery() {
let daemon = crate::daemon::Daemon {
port: Some(PortConfig {
expect: vec![3000],
..PortConfig::default()
}),
..crate::daemon::Daemon::default()
};
assert_eq!(discovery_preferred_port(&daemon), Some(3000));
}
#[test]
fn ambiguous_candidates_leave_active_port_unset() {
let descendant_pids = [100].into_iter().collect();
let listeners = vec![
listener(100, 9000, Protocol::TCP, SocketState::Listen),
listener(100, 3000, Protocol::TCP, SocketState::Listen),
];
assert_eq!(
select_active_port(listeners, &descendant_pids, None),
ActivePortSelection::Ambiguous(vec![3000, 9000])
);
}
#[test]
fn bumped_ready_port_sets_only_the_resolved_primary_without_scanning() {
assert_eq!(active_port_from_ready_port(3004, &[3004]), Some(3004));
assert_eq!(active_port_from_ready_port(4003, &[3003, 4003]), None);
}
#[test]
fn delay_readiness_requires_delay_only_and_a_running_process() {
assert!(delay_readiness_succeeded(false, false, false, true));
assert!(!delay_readiness_succeeded(false, true, false, true));
assert!(!delay_readiness_succeeded(false, false, true, false));
assert!(!delay_readiness_succeeded(false, false, false, false));
assert!(!delay_readiness_succeeded(true, false, false, true));
}
}
/// Check whether a daemon (by its qualified ID) is the target of any registered
/// slug in the global config. This is used to decide whether to run the
/// `detect_and_store_active_port` polling task — only slug-targeted daemons need
/// it, avoiding wasted `listeners::get_all()` calls for port-less daemons.
///
/// Delegates to `proxy::server::is_slug_target()` which uses the same in-memory
/// slug cache as the proxy hot path, so this check is cheap.
fn is_daemon_slug_target(id: &DaemonId) -> bool {
// read_global_slugs is called once per daemon start — acceptable cost.
// We intentionally avoid making this async to keep has_port_config evaluation
// simple and synchronous in run_once().
let slugs = crate::pitchfork_toml::PitchforkToml::read_global_slugs();
slugs.iter().any(|(slug, entry)| {
let daemon_name = entry.daemon.as_deref().unwrap_or(slug);
id.name() == daemon_name
})
}
#[cfg(all(test, unix))]
mod tests {
use super::*;
#[test]
fn test_resolve_run_identity_empty_without_sudo() {
let identity = resolve_run_identity(None, 501, 20, None, None).unwrap();
assert_eq!(identity, RunIdentity::Inherit);
}
#[test]
fn test_resolve_run_identity_sudo_fallback() {
let identity = resolve_run_identity(None, 0, 0, Some("501"), Some("20")).unwrap();
let RunIdentity::Switch { uid, gid, .. } = identity else {
panic!("expected identity switch");
};
assert_eq!(uid.as_raw(), 501);
assert_eq!(gid.as_raw(), 20);
}
#[test]
fn test_resolve_run_identity_ignores_stale_sudo_when_not_root() {
let identity = resolve_run_identity(None, 501, 20, Some("0"), Some("0")).unwrap();
assert_eq!(identity, RunIdentity::Inherit);
}
#[test]
fn test_resolve_configured_user_root_name() {
let identity = resolve_configured_user("root").unwrap();
let RunIdentity::Switch { uid, username, .. } = identity else {
panic!("expected identity switch");
};
assert_eq!(uid.as_raw(), 0);
assert_eq!(
username.as_deref().and_then(|s| s.to_str().ok()),
Some("root")
);
}
#[test]
fn test_resolve_configured_user_root_uid() {
let identity = resolve_configured_user("0").unwrap();
let RunIdentity::Switch { uid, username, .. } = identity else {
panic!("expected identity switch");
};
assert_eq!(uid.as_raw(), 0);
assert_eq!(
username.as_deref().and_then(|s| s.to_str().ok()),
Some("root")
);
}
#[test]
fn test_resolve_configured_user_missing_user_fails() {
let err = resolve_configured_user("pitchfork-user-that-should-not-exist")
.unwrap_err()
.to_string();
assert!(err.contains("does not exist"));
}
#[test]
fn test_resolve_run_identity_requires_root_for_user_switch() {
let err = resolve_run_identity(Some("root"), 501, 20, None, None)
.unwrap_err()
.to_string();
assert!(err.contains("Restart the supervisor with sudo"));
}
#[test]
fn test_resolve_run_identity_same_user_is_noop() {
let identity = resolve_run_identity(Some("root"), 0, 0, Some("501"), Some("20")).unwrap();
assert_eq!(identity, RunIdentity::Inherit);
}
}
/// Inject proxy-related environment variables into a daemon's command.
///
/// Adds:
/// - `HOST` — the address the daemon should bind to (`127.0.0.1`, omitted in LAN mode)
/// - `PITCHFORK_URL` — the public proxy URL for this daemon (if it has a slug)
/// - `NODE_EXTRA_CA_CERTS` — path to the pitchfork CA cert (if HTTPS enabled)
/// - `__VITE_ADDITIONAL_SERVER_ALLOWED_HOSTS` — `.<tld>` for Vite host allowlisting
/// - `PITCHFORK_LAN` — set to `"1"` when LAN mode is active
fn inject_proxy_env(cmd: &mut tokio::process::Command, slug: &Option<String>) {
let s = crate::settings::settings();
let lan_enabled = s.proxy.lan || !s.proxy.lan_ip.is_empty();
if should_force_loopback_host(slug) && !lan_enabled {
// Only force loopback binding for daemons that are actually routed via a slug.
// In LAN mode, daemons need to bind to 0.0.0.0 to be reachable from the network.
cmd.env("HOST", "127.0.0.1");
}
// PITCHFORK_URL: the daemon's public proxy URL (only if it has a slug and proxy is enabled)
if let Some(url) = build_pitchfork_url(slug, &s) {
cmd.env("PITCHFORK_URL", &url);
}
// NODE_EXTRA_CA_CERTS: let Node.js backends trust the pitchfork CA
if s.proxy.enable && s.proxy.https {
let ca_path = if s.proxy.tls_cert.is_empty() {
crate::env::PITCHFORK_STATE_DIR.join("proxy").join("ca.pem")
} else {
std::path::PathBuf::from(&s.proxy.tls_cert)
};
if ca_path.exists() {
cmd.env("NODE_EXTRA_CA_CERTS", ca_path.to_string_lossy().to_string());
}
}
// __VITE_ADDITIONAL_SERVER_ALLOWED_HOSTS: Vite host allowlisting
if s.proxy.enable {
let tld = if lan_enabled { "local" } else { &s.proxy.tld };
cmd.env("__VITE_ADDITIONAL_SERVER_ALLOWED_HOSTS", format!(".{tld}"));
}
// PITCHFORK_LAN: signal to daemons that LAN mode is active
if lan_enabled {
cmd.env("PITCHFORK_LAN", "1");
}
}
fn should_force_loopback_host(slug: &Option<String>) -> bool {
let Some(slug) = slug.as_deref() else {
return false;
};
let s = crate::settings::settings();
if !s.proxy.enable {
return false;
}
let slugs = crate::pitchfork_toml::PitchforkToml::read_global_slugs();
slugs.contains_key(slug)
}
/// Compute the public proxy URL for a daemon.
///
/// Returns `None` if the daemon has no slug or the proxy is not enabled.
fn build_pitchfork_url(slug: &Option<String>, s: &crate::settings::Settings) -> Option<String> {
let slug = slug.as_ref()?;
if !s.proxy.enable {
return None;
}
let scheme = if s.proxy.https { "https" } else { "http" };
let port = u16::try_from(s.proxy.port).ok().filter(|&p| p > 0)?;
let port_suffix = if (scheme == "https" && port == 443) || (scheme == "http" && port == 80) {
String::new()
} else {
format!(":{port}")
};
let lan_enabled = s.proxy.lan || !s.proxy.lan_ip.is_empty();
let tld = if lan_enabled { "local" } else { &s.proxy.tld };
Some(format!("{scheme}://{slug}.{tld}{port_suffix}",))
}
#[cfg(test)]
mod ready_check_tests {
use super::*;
use std::time::Duration;
#[test]
fn any_ready_check_remaining_prefers_unbounded_checks() {
let http = ReadyHttp::new("http://localhost/health");
let cmd = ReadyCmd::new("true");
assert!(any_ready_check_remaining(
None,
false,
None,
false,
Some(&http),
false,
None,
false
));
assert!(any_ready_check_remaining(
None,
false,
None,
false,
None,
false,
Some(&cmd),
false
));
assert!(any_ready_check_remaining(
None,
false,
Some(&ReadyPort::new(8080)),
false,
Some(&http),
true,
Some(&cmd),
true
));
}
#[test]
fn any_ready_check_remaining_exhausted_timed_checks() {
let http = ReadyHttp {
url: "http://localhost/health".to_string(),
status: vec![],
timeout: Some(Duration::from_secs(5)),
};
let cmd = ReadyCmd {
run: "true".to_string(),
timeout: Some(Duration::from_secs(5)),
};
assert!(any_ready_check_remaining(
None,
false,
None,
false,
Some(&http),
false,
Some(&cmd),
false
));
assert!(!any_ready_check_remaining(
None,
false,
None,
false,
Some(&http),
true,
Some(&cmd),
true
));
}
#[tokio::test]
async fn spawn_cmd_probe_reports_success() {
let id = DaemonId::new("global", "probe-test");
let probe = spawn_cmd_probe(&id, "true", &std::env::temp_dir(), 0, None, &[]);
let status = probe.result_rx.await.unwrap().unwrap();
assert!(status.success());
}
#[tokio::test]
async fn spawn_cmd_probe_stops_on_request() {
let id = DaemonId::new("global", "probe-test");
let probe = spawn_cmd_probe(&id, "sleep 30", &std::env::temp_dir(), 0, None, &[]);
let CmdProbe {
cancel_tx,
result_rx,
} = probe;
let _ = cancel_tx.send(());
let status = result_rx.await.unwrap().unwrap();
assert!(!status.success());
}
#[tokio::test]
async fn spawn_cmd_probe_receives_daemon_and_resolved_port_environment() {
let id = DaemonId::new("worktree", "api");
let daemon_env = IndexMap::from([("CUSTOM_VALUE".to_string(), "yes".to_string())]);
let probe = spawn_cmd_probe(
&id,
r#"test "$CUSTOM_VALUE" = yes && test "$PORT" = 4100 && test "$PORT0" = 4100 && test "$PORT1" = 5100 && test "$PITCHFORK_DAEMON_ID" = worktree/api && test "$PITCHFORK_RETRY_COUNT" = 2"#,
&std::env::temp_dir(),
2,
Some(&daemon_env),
&[4100, 5100],
);
let status = probe.result_rx.await.unwrap().unwrap();
assert!(status.success());
}
#[test]
fn configured_ready_port_follows_expected_port_bump() {
assert_eq!(resolve_configured_ready_port(3000, &[3000], &[3004]), 3004);
assert_eq!(
resolve_configured_ready_port(4000, &[3000, 4000], &[3003, 4003]),
4003
);
assert_eq!(resolve_configured_ready_port(8080, &[3000], &[3004]), 8080);
}
}