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
//! Process manager implementation for lifecycle and resource management.
//!
//! This module provides the core `ProcessManager` struct that orchestrates all
//! process operations including starting, stopping, monitoring, and resource allocation.
//! It handles advanced features like clustering, port management, and persistent configuration.
//!
//! ## Key Features
//!
//! - **Process Lifecycle Management** - Start, stop, restart, reload, delete operations
//! - **Clustering Support** - Automatic load balancing with multiple instances
//! - **Advanced Port Management** - Single ports, ranges, and auto-assignment with conflict detection
//! - **Configuration Persistence** - Process configs saved and restored between sessions
//! - **Real-time Monitoring** - CPU, memory tracking with automatic health checks
//! - **Resource Limits** - Memory limit enforcement with automatic restart
//! - **Log Management** - Separate stdout/stderr files with automatic rotation
//!
//! ## Examples
//!
//! ### Basic Process Management
//!
//! ```rust,no_run
//! use pmdaemon::{ProcessManager, ProcessConfig};
//!
//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
//! let mut manager = ProcessManager::new().await?;
//!
//! let config = ProcessConfig::builder()
//! .name("web-server")
//! .script("node")
//! .args(vec!["server.js"])
//! .build()?;
//!
//! // Start the process
//! let process_id = manager.start(config).await?;
//!
//! // List all processes
//! let processes = manager.list().await?;
//! for process in processes {
//! println!("Process: {} ({})", process.name, process.state);
//! }
//!
//! // Stop the process
//! manager.stop("web-server").await?;
//! # Ok(())
//! # }
//! ```
//!
//! ### Clustering with Port Management
//!
//! ```rust,no_run
//! use pmdaemon::{ProcessManager, ProcessConfig, config::PortConfig};
//!
//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
//! let mut manager = ProcessManager::new().await?;
//!
//! let config = ProcessConfig::builder()
//! .name("web-cluster")
//! .script("node")
//! .args(vec!["app.js"])
//! .instances(4)
//! .port(PortConfig::Range(3000, 3003)) // Ports 3000-3003
//! .build()?;
//!
//! // Start 4 instances with automatic port distribution
//! manager.start(config).await?;
//! # Ok(())
//! # }
//! ```
use crate::config::{PortConfig, ProcessConfig};
use crate::error::{Error, Result};
use crate::monitoring::Monitor;
use crate::process::{Process, ProcessId, ProcessStatus};
use comfy_table::{presets::UTF8_FULL, Attribute, Cell, Color, ContentArrangement, Table};
use std::collections::{HashMap, HashSet};
use std::path::PathBuf;
use std::time::Duration;
use tokio::fs;
use tokio::sync::RwLock;
use tokio::time::interval;
use tracing::{debug, error, info, warn};
use uuid::Uuid;
/// Main process manager for orchestrating process lifecycle and resources.
///
/// The `ProcessManager` is the central component that handles all process operations
/// including starting, stopping, monitoring, and resource allocation. It provides
/// advanced features like clustering, port management, and persistent configuration
/// that go beyond standard PM2 capabilities.
///
/// ## Architecture
///
/// - **Process Storage** - Thread-safe storage for all managed processes
/// - **Port Allocation** - Conflict-free port assignment with ranges and auto-detection
/// - **Configuration Persistence** - Automatic save/restore of process configurations
/// - **Monitoring Integration** - Real-time CPU/memory tracking with health checks
/// - **Log Management** - Automatic log file creation and management
///
/// ## Thread Safety
///
/// All operations are thread-safe using `RwLock` for concurrent access.
/// Multiple threads can safely read process information while write operations
/// are properly synchronized.
///
/// # Examples
///
/// ```rust,no_run
/// use pmdaemon::{ProcessManager, ProcessConfig};
///
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// // Create a new process manager
/// let mut manager = ProcessManager::new().await?;
///
/// // Start monitoring loop in background
/// tokio::spawn(async move {
/// if let Err(e) = manager.start_monitoring().await {
/// eprintln!("Monitoring error: {}", e);
/// }
/// });
/// # Ok(())
/// # }
/// ```
pub struct ProcessManager {
/// Map of process ID to process
processes: RwLock<HashMap<ProcessId, Process>>,
/// Map of process name to process ID for quick lookup
name_to_id: RwLock<HashMap<String, ProcessId>>,
/// System monitor for collecting metrics
monitor: RwLock<Monitor>,
/// Configuration directory path
config_dir: PathBuf,
/// Set of allocated ports
allocated_ports: RwLock<HashSet<u16>>,
}
impl ProcessManager {
/// Create a new process manager
pub async fn new() -> Result<Self> {
let config_dir = Self::get_config_dir()?;
// Ensure config directory exists
if !config_dir.exists() {
fs::create_dir_all(&config_dir)
.await
.map_err(|e| Error::config(format!("Failed to create config directory: {}", e)))?;
}
let mut manager = Self {
processes: RwLock::new(HashMap::new()),
name_to_id: RwLock::new(HashMap::new()),
monitor: RwLock::new(Monitor::new()),
config_dir,
allocated_ports: RwLock::new(HashSet::new()),
};
// Load existing processes from configuration
manager.load_processes().await?;
Ok(manager)
}
/// Get the configuration directory path
///
/// Checks for PMDAEMON_HOME environment variable first, which allows overriding
/// the default configuration directory. This is particularly useful for testing
/// and when running multiple isolated PMDaemon instances.
fn get_config_dir() -> Result<PathBuf> {
// Check for PMDAEMON_HOME environment variable first
if let Ok(pmdaemon_home) = std::env::var("PMDAEMON_HOME") {
return Ok(PathBuf::from(pmdaemon_home));
}
let home_dir =
dirs::home_dir().ok_or_else(|| Error::config("Could not determine home directory"))?;
Ok(home_dir.join(crate::CONFIG_DIR))
}
/// Get the API key file path
pub fn get_api_key_path() -> Result<PathBuf> {
Ok(Self::get_config_dir()?.join("api-key"))
}
/// Get the PID directory path
fn get_pid_dir(&self) -> PathBuf {
self.config_dir.join(crate::PID_DIR)
}
/// Get the logs directory path
fn get_logs_dir(&self) -> PathBuf {
self.config_dir.join(crate::LOG_DIR)
}
/// Get log file paths for a process
fn get_log_paths(&self, process_name: &str) -> (PathBuf, PathBuf, PathBuf) {
let logs_dir = self.get_logs_dir();
let out_file = logs_dir.join(format!("{}-out.log", process_name));
let err_file = logs_dir.join(format!("{}-error.log", process_name));
let combined_file = logs_dir.join(format!("{}.log", process_name));
(out_file, err_file, combined_file)
}
/// Ensure logs directory exists
async fn ensure_logs_dir(&self) -> Result<()> {
let logs_dir = self.get_logs_dir();
if !logs_dir.exists() {
fs::create_dir_all(&logs_dir)
.await
.map_err(|e| Error::config(format!("Failed to create logs directory: {}", e)))?;
}
Ok(())
}
/// Save PID file for a process
async fn save_pid_file(&self, process_name: &str, pid: u32) -> Result<()> {
let pid_dir = self.get_pid_dir();
if !pid_dir.exists() {
fs::create_dir_all(&pid_dir)
.await
.map_err(|e| Error::config(format!("Failed to create PID directory: {}", e)))?;
}
let pid_file = pid_dir.join(format!("{}.pid", process_name));
fs::write(&pid_file, pid.to_string())
.await
.map_err(|e| Error::config(format!("Failed to write PID file: {}", e)))?;
debug!("Saved PID file for process {}: {}", process_name, pid);
Ok(())
}
/// Remove PID file for a process
async fn remove_pid_file(&self, process_name: &str) -> Result<()> {
let pid_file = self.get_pid_dir().join(format!("{}.pid", process_name));
if pid_file.exists() {
fs::remove_file(&pid_file)
.await
.map_err(|e| Error::config(format!("Failed to remove PID file: {}", e)))?;
debug!("Removed PID file for process: {}", process_name);
}
Ok(())
}
/// Read PID from PID file
async fn read_pid_file(&self, process_name: &str) -> Result<Option<u32>> {
let pid_file = self.get_pid_dir().join(format!("{}.pid", process_name));
if !pid_file.exists() {
return Ok(None);
}
let pid_content = fs::read_to_string(&pid_file)
.await
.map_err(|e| Error::config(format!("Failed to read PID file: {}", e)))?;
let pid = pid_content
.trim()
.parse::<u32>()
.map_err(|e| Error::config(format!("Invalid PID in file: {}", e)))?;
Ok(Some(pid))
}
/// Start a new process (or multiple instances for clustering)
pub async fn start(&mut self, config: ProcessConfig) -> Result<ProcessId> {
// Validate configuration
config.validate()?;
if config.instances == 1 {
// Single instance
self.start_single_instance(config).await
} else {
// Multiple instances (clustering)
self.start_cluster(config).await
}
}
/// Start a single process instance
async fn start_single_instance(&mut self, config: ProcessConfig) -> Result<ProcessId> {
// Check if process with same name already exists
let name_map = self.name_to_id.read().await;
if name_map.contains_key(&config.name) {
return Err(Error::process_already_exists(&config.name));
}
drop(name_map);
// Create new process
let mut process = Process::new(config.clone());
let process_id = process.id;
// Allocate port if specified
if let Some(port_config) = &process.config.port {
let assigned_port = self
.allocate_port(port_config, &process.config.name)
.await?;
process.assigned_port = Some(assigned_port);
// Add PORT environment variable
process
.config
.env
.insert("PORT".to_string(), assigned_port.to_string());
}
// Ensure logs directory exists
self.ensure_logs_dir().await?;
// Get log file paths
let (out_log, err_log, _combined_log) = self.get_log_paths(&process.config.name);
// Start the process with log redirection
process
.start_with_logs(Some(out_log), Some(err_log))
.await?;
// Save PID file if process started successfully
if let Some(pid) = process.pid() {
self.save_pid_file(&process.config.name, pid).await?;
// Also store the PID in the process for later retrieval
process.set_stored_pid(Some(pid));
}
// Save configuration to disk
self.save_process_config(&process).await?;
// Save runtime metadata (assigned port, etc.)
self.save_process_metadata(&process).await?;
// Store process
let mut processes = self.processes.write().await;
let mut name_map = self.name_to_id.write().await;
processes.insert(process_id, process);
name_map.insert(config.name, process_id);
Ok(process_id)
}
/// Start multiple process instances (clustering)
async fn start_cluster(&mut self, config: ProcessConfig) -> Result<ProcessId> {
// Check if any instance with the base name already exists
let name_map = self.name_to_id.read().await;
for i in 0..config.instances {
let instance_name = format!("{}-{}", config.name, i);
if name_map.contains_key(&instance_name) {
return Err(Error::process_already_exists(&instance_name));
}
}
drop(name_map);
let mut first_process_id = None;
let mut started_instances = Vec::new();
// Start each instance
for i in 0..config.instances {
let instance_name = format!("{}-{}", config.name, i);
let mut instance_config = config.clone();
instance_config.name = instance_name.clone();
instance_config.instances = 1; // Each instance is a single process
// Add instance-specific environment variable
instance_config
.env
.insert("PM2_INSTANCE_ID".to_string(), i.to_string());
instance_config
.env
.insert("NODE_APP_INSTANCE".to_string(), i.to_string());
// Handle port allocation for cluster instances
if let Some(port_config) = &config.port {
match port_config {
PortConfig::Auto(start, end) => {
// Each instance gets auto-assigned port from the range
instance_config.port = Some(PortConfig::Auto(*start, *end));
}
PortConfig::Range(start, end) => {
// Each instance gets a specific port from the range
if i < (end - start + 1) as u32 {
let instance_port = start + i as u16;
instance_config.port = Some(PortConfig::Single(instance_port));
} else {
return Err(Error::config(format!(
"Not enough ports in range {}-{} for {} instances",
start, end, config.instances
)));
}
}
PortConfig::Single(port) => {
// For single port, only the first instance gets it
if i == 0 {
instance_config.port = Some(PortConfig::Single(*port));
} else {
instance_config.port = None; // Other instances get no port
}
}
}
}
match self.start_single_instance(instance_config).await {
Ok(process_id) => {
if first_process_id.is_none() {
first_process_id = Some(process_id);
}
started_instances.push((i, process_id));
info!("Started cluster instance {}: {}", i, instance_name);
}
Err(e) => {
error!("Failed to start cluster instance {}: {}", i, e);
// Clean up already started instances
for (_, pid) in started_instances {
if let Err(cleanup_err) = self.stop_by_id(pid).await {
warn!("Failed to cleanup instance {}: {}", pid, cleanup_err);
}
}
return Err(e);
}
}
}
info!(
"Started cluster '{}' with {} instances",
config.name, config.instances
);
Ok(first_process_id.unwrap()) // We know this is Some because instances > 1
}
/// Stop a process by ProcessId
async fn stop_by_id(&mut self, process_id: ProcessId) -> Result<()> {
let mut processes = self.processes.write().await;
if let Some(process) = processes.get_mut(&process_id) {
let process_name = process.config.name.clone();
process.stop().await?;
// Remove PID file
drop(processes); // Release lock before async operation
self.remove_pid_file(&process_name).await?;
}
Ok(())
}
/// Stop a process
pub async fn stop(&mut self, identifier: &str) -> Result<()> {
let process_id = self.resolve_identifier(identifier).await?;
let mut processes = self.processes.write().await;
if let Some(process) = processes.get_mut(&process_id) {
let process_name = process.config.name.clone();
process.stop().await?;
// Remove PID file
drop(processes); // Release lock before async operation
self.remove_pid_file(&process_name).await?;
}
Ok(())
}
/// Restart a process
pub async fn restart(&mut self, identifier: &str) -> Result<()> {
self.restart_with_port(identifier, None).await
}
/// Restart a process with optional port override
pub async fn restart_with_port(
&mut self,
identifier: &str,
port_override: Option<PortConfig>,
) -> Result<()> {
let process_id = self.resolve_identifier(identifier).await?;
let mut processes = self.processes.write().await;
if let Some(process) = processes.get_mut(&process_id) {
// Handle port deallocation and reallocation if there's an override
if let Some(new_port_config) = port_override {
// Deallocate current port if any
if let Some(current_port_config) = &process.config.port {
self.deallocate_ports(current_port_config, process.assigned_port)
.await;
}
// Allocate new port
let assigned_port = self
.allocate_port(&new_port_config, &process.config.name)
.await?;
process.assigned_port = Some(assigned_port);
// Update environment variable
process
.config
.env
.insert("PORT".to_string(), assigned_port.to_string());
info!(
"Restarting {} with new port: {}",
process.config.name, assigned_port
);
}
process.restart().await?;
}
Ok(())
}
/// Reload a process (graceful restart)
pub async fn reload(&mut self, identifier: &str) -> Result<()> {
self.reload_with_port(identifier, None).await
}
/// Reload a process with optional port override
pub async fn reload_with_port(
&mut self,
identifier: &str,
port_override: Option<PortConfig>,
) -> Result<()> {
// For now, reload is the same as restart with port override
self.restart_with_port(identifier, port_override).await
}
/// Delete a process
pub async fn delete(&mut self, identifier: &str) -> Result<()> {
let process_id = self.resolve_identifier(identifier).await?;
// First, stop the process if it's running
let (process_name, port_config, assigned_port, was_running) = {
let mut processes = self.processes.write().await;
if let Some(mut process) = processes.remove(&process_id) {
let process_name = process.config.name.clone();
let port_config = process.config.port.clone();
let assigned_port = process.assigned_port;
let was_running = process.is_running();
// Stop the process if it's running
if was_running {
info!("Stopping process '{}' before deletion", process_name);
if let Err(e) = process.stop().await {
warn!(
"Failed to stop process '{}' during deletion: {}",
process_name, e
);
// Continue with deletion even if stop fails
}
}
// Remove from name map
let mut name_map = self.name_to_id.write().await;
name_map.remove(&process_name);
drop(name_map);
(process_name, port_config, assigned_port, was_running)
} else {
return Ok(()); // Process not found, nothing to delete
}
};
// Deallocate ports
if let Some(port_config) = port_config {
self.deallocate_ports(&port_config, assigned_port).await;
}
// Clean up files
self.remove_process_config(&process_name).await?;
self.remove_pid_file(&process_name).await?;
self.remove_log_files(&process_name).await?;
if was_running {
info!(
"Process '{}' stopped and deleted successfully",
process_name
);
} else {
info!("Process '{}' deleted successfully", process_name);
}
Ok(())
}
/// Delete all processes
pub async fn delete_all(&mut self) -> Result<usize> {
let process_ids: Vec<ProcessId>;
// Get all process IDs
{
let processes = self.processes.read().await;
process_ids = processes.keys().cloned().collect();
}
let mut deleted_count = 0;
let mut stopped_count = 0;
for process_id in process_ids {
// Stop and remove the process
let (process_name, port_config, assigned_port, _was_running) = {
let mut processes = self.processes.write().await;
if let Some(mut process) = processes.remove(&process_id) {
let process_name = process.config.name.clone();
let port_config = process.config.port.clone();
let assigned_port = process.assigned_port;
let was_running = process.is_running();
// Stop the process if it's running
if was_running {
if let Err(e) = process.stop().await {
warn!(
"Failed to stop process '{}' during bulk deletion: {}",
process_name, e
);
// Continue with deletion even if stop fails
} else {
stopped_count += 1;
}
}
// Remove from name map
let mut name_map = self.name_to_id.write().await;
name_map.remove(&process_name);
drop(name_map);
deleted_count += 1;
(process_name, port_config, assigned_port, was_running)
} else {
continue; // Process already deleted
}
};
// Deallocate ports
if let Some(port_config) = port_config {
self.deallocate_ports(&port_config, assigned_port).await;
}
// Clean up files
if let Err(e) = self.remove_process_config(&process_name).await {
warn!("Failed to remove config for {}: {}", process_name, e);
}
if let Err(e) = self.remove_pid_file(&process_name).await {
warn!("Failed to remove PID file for {}: {}", process_name, e);
}
if let Err(e) = self.remove_log_files(&process_name).await {
warn!("Failed to remove log files for {}: {}", process_name, e);
}
}
if stopped_count > 0 {
info!(
"Stopped {} running processes and deleted {} total processes",
stopped_count, deleted_count
);
} else {
info!("Deleted {} processes", deleted_count);
}
Ok(deleted_count)
}
/// Delete processes by status
pub async fn delete_by_status(&mut self, status_str: &str) -> Result<usize> {
use crate::process::ProcessState;
// Parse the status string
let target_state = match status_str.to_lowercase().as_str() {
"starting" => ProcessState::Starting,
"online" => ProcessState::Online,
"stopping" => ProcessState::Stopping,
"stopped" => ProcessState::Stopped,
"errored" => ProcessState::Errored,
"restarting" => ProcessState::Restarting,
_ => return Err(crate::error::Error::config(format!(
"Invalid status '{}'. Valid statuses are: starting, online, stopping, stopped, errored, restarting",
status_str
))),
};
let process_ids_to_delete: Vec<ProcessId>;
// Find processes with matching status
{
let processes = self.processes.read().await;
process_ids_to_delete = processes
.iter()
.filter(|(_, process)| process.state == target_state)
.map(|(id, _)| *id)
.collect();
}
let mut deleted_count = 0;
let mut stopped_count = 0;
for process_id in process_ids_to_delete {
// Stop and remove the process
let (process_name, port_config, assigned_port, _was_running) = {
let mut processes = self.processes.write().await;
if let Some(mut process) = processes.remove(&process_id) {
let process_name = process.config.name.clone();
let port_config = process.config.port.clone();
let assigned_port = process.assigned_port;
let was_running = process.is_running();
// Stop the process if it's running
if was_running {
if let Err(e) = process.stop().await {
warn!(
"Failed to stop process '{}' during status-based deletion: {}",
process_name, e
);
// Continue with deletion even if stop fails
} else {
stopped_count += 1;
}
}
// Remove from name map
let mut name_map = self.name_to_id.write().await;
name_map.remove(&process_name);
drop(name_map);
deleted_count += 1;
(process_name, port_config, assigned_port, was_running)
} else {
continue; // Process already deleted
}
};
// Deallocate ports
if let Some(port_config) = port_config {
self.deallocate_ports(&port_config, assigned_port).await;
}
// Clean up files
let _ = self.remove_process_config(&process_name).await;
let _ = self.remove_pid_file(&process_name).await;
let _ = self.remove_log_files(&process_name).await;
}
if stopped_count > 0 {
info!(
"Stopped {} running processes and deleted {} total processes with status '{}'",
stopped_count, deleted_count, status_str
);
} else {
info!(
"Deleted {} processes with status '{}'",
deleted_count, status_str
);
}
Ok(deleted_count)
}
/// List all processes
pub async fn list(&self) -> Result<Vec<ProcessStatus>> {
let processes = self.processes.read().await;
Ok(processes.values().map(|p| p.status()).collect())
}
/// Monitor processes in real-time.
///
/// Displays a comprehensive real-time dashboard of all managed processes using beautifully
/// formatted tables with color-coded status indicators. Uses the default update interval
/// of 2 seconds.
///
/// For custom update intervals, use [`monitor_with_interval`](Self::monitor_with_interval).
///
/// ## Dashboard Components
///
/// - **System Overview** - CPU usage, memory consumption, load average, and uptime
/// - **Process Table** - Detailed process information with the following columns:
/// - **Name** - Process name
/// - **ID** - Process UUID (first 8 characters)
/// - **Status** - Color-coded process state (Online=Green, Stopped=Red, etc.)
/// - **PID** - System process ID (blue highlighting)
/// - **CPU%** - Real-time CPU usage percentage
/// - **Memory** - Memory consumption in MB
/// - **Restarts** - Total number of restarts
/// - **Port** - Assigned port number (cyan highlighting)
/// - **Uptime** - Process uptime in human-readable format
///
/// ## Visual Features
///
/// - Professional table formatting using `comfy-table` with UTF8 borders
/// - Color-coded status indicators for quick visual assessment
/// - Clear screen refresh for smooth real-time updates
/// - Update counter and timestamp for monitoring freshness
///
/// # Returns
///
/// Returns `Ok(())` when monitoring is stopped (e.g., by Ctrl+C), or an error
/// if the monitoring setup fails.
///
/// # Examples
///
/// ```rust,no_run
/// use pmdaemon::ProcessManager;
///
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let manager = ProcessManager::new().await?;
///
/// // Start real-time monitoring dashboard with default 2-second updates
/// manager.monitor().await?;
/// # Ok(())
/// # }
/// ```
///
/// # Note
///
/// This method runs an infinite loop and will block the current thread until
/// interrupted (typically with Ctrl+C). It's designed for interactive use
/// and provides the same comprehensive monitoring as the CLI `pmdaemon monit` command.
pub async fn monitor(&self) -> Result<()> {
self.monitor_with_interval(Duration::from_secs(2)).await
}
/// Monitor processes in real-time with a configurable update interval.
///
/// Displays a comprehensive real-time dashboard of all managed processes using beautifully
/// formatted tables with color-coded status indicators. Updates at the specified interval
/// with the latest system and process metrics.
///
/// # Arguments
///
/// * `update_interval` - How frequently to refresh the display. Common values:
/// - `Duration::from_secs(1)` - Fast updates for debugging (higher CPU usage)
/// - `Duration::from_secs(2)` - Default balanced updates
/// - `Duration::from_secs(5)` - Slower updates for reduced system load
/// - `Duration::from_millis(500)` - Very fast updates for development
///
/// ## Dashboard Components
///
/// - **System Overview** - CPU usage, memory consumption, load average, and uptime
/// - **Process Table** - Detailed process information with the following columns:
/// - **Name** - Process name
/// - **ID** - Process UUID (first 8 characters)
/// - **Status** - Color-coded process state (Online=Green, Stopped=Red, etc.)
/// - **PID** - System process ID (blue highlighting)
/// - **CPU%** - Real-time CPU usage percentage
/// - **Memory** - Memory consumption in MB
/// - **Restarts** - Total number of restarts
/// - **Port** - Assigned port number (cyan highlighting)
/// - **Uptime** - Process uptime in human-readable format
///
/// ## Visual Features
///
/// - Professional table formatting using `comfy-table` with UTF8 borders
/// - Color-coded status indicators for quick visual assessment
/// - Clear screen refresh for smooth real-time updates
/// - Update counter and timestamp for monitoring freshness
///
/// # Returns
///
/// Returns `Ok(())` when monitoring is stopped (e.g., by Ctrl+C), or an error
/// if the monitoring setup fails.
///
/// # Examples
///
/// ```rust,no_run
/// use pmdaemon::ProcessManager;
/// use std::time::Duration;
///
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let manager = ProcessManager::new().await?;
///
/// // Fast updates for debugging
/// manager.monitor_with_interval(Duration::from_secs(1)).await?;
///
/// // Slower updates to reduce system load
/// manager.monitor_with_interval(Duration::from_secs(5)).await?;
///
/// // Very fast updates for development
/// manager.monitor_with_interval(Duration::from_millis(500)).await?;
/// # Ok(())
/// # }
/// ```
///
/// # Performance Considerations
///
/// - **Faster intervals** (< 1 second) provide more responsive monitoring but use more CPU
/// - **Slower intervals** (> 3 seconds) reduce system load but may miss short-lived events
/// - **Default interval** (2 seconds) provides a good balance for most use cases
///
/// # Note
///
/// This method runs an infinite loop and will block the current thread until
/// interrupted (typically with Ctrl+C). It's designed for interactive use.
pub async fn monitor_with_interval(&self, update_interval: Duration) -> Result<()> {
info!(
"Starting real-time process monitoring dashboard with {:?} update interval",
update_interval
);
let mut interval = interval(update_interval);
let mut iteration = 0u64;
loop {
interval.tick().await;
iteration += 1;
// Clear screen and move cursor to top
#[cfg(windows)]
{
// For Windows, try to use the cls command or fall back to ANSI
if std::process::Command::new("cmd")
.args(&["/C", "cls"])
.status()
.is_err()
{
print!("\x1B[2J\x1B[H");
}
}
#[cfg(not(windows))]
{
// For Unix-like systems, use ANSI escape sequences
print!("\x1B[2J\x1B[H");
}
// Create header table
let mut header_table = Table::new();
header_table
.load_preset(UTF8_FULL)
.set_content_arrangement(ContentArrangement::Dynamic)
.set_header(vec![
Cell::new("PMDaemon Process Monitor")
.add_attribute(Attribute::Bold)
.fg(Color::Cyan),
Cell::new(format!("Update #{}", iteration))
.add_attribute(Attribute::Bold)
.fg(Color::Yellow),
]);
println!("{}", header_table);
println!("Press Ctrl+C to exit\n");
// Get system metrics and create system overview table
match self.get_system_info().await {
Ok(system_metrics) => {
let mut system_table = Table::new();
system_table
.load_preset(UTF8_FULL)
.set_content_arrangement(ContentArrangement::Dynamic)
.set_header(vec![Cell::new("System Overview")
.add_attribute(Attribute::Bold)
.fg(Color::Green)]);
system_table
.add_row(vec![format!("CPU Usage: {:.1}%", system_metrics.cpu_usage)]);
system_table.add_row(vec![format!(
"Memory: {:.1}% ({:.1} GB / {:.1} GB)",
system_metrics.memory_percent,
system_metrics.memory_used as f64 / 1024.0 / 1024.0 / 1024.0,
system_metrics.memory_total as f64 / 1024.0 / 1024.0 / 1024.0
)]);
system_table.add_row(vec![format!(
"Load Average: [{:.2}, {:.2}, {:.2}]",
system_metrics.load_average[0],
system_metrics.load_average[1],
system_metrics.load_average[2]
)]);
system_table
.add_row(vec![format!("Uptime: {} seconds", system_metrics.uptime)]);
println!("{}", system_table);
}
Err(e) => {
let mut error_table = Table::new();
error_table
.load_preset(UTF8_FULL)
.set_header(vec![Cell::new("System Overview")
.add_attribute(Attribute::Bold)
.fg(Color::Red)]);
error_table.add_row(vec![format!("Error retrieving metrics: {}", e)]);
println!("{}", error_table);
}
}
// Get process list
match self.list().await {
Ok(processes) => {
if processes.is_empty() {
let mut no_processes_table = Table::new();
no_processes_table
.load_preset(UTF8_FULL)
.set_header(vec![Cell::new("Processes")
.add_attribute(Attribute::Bold)
.fg(Color::Blue)]);
no_processes_table.add_row(vec!["No processes currently managed."]);
println!("{}", no_processes_table);
} else {
// Create process table
let mut process_table = Table::new();
process_table
.load_preset(UTF8_FULL)
.set_content_arrangement(ContentArrangement::Dynamic)
.set_header(vec![
Cell::new("Name").add_attribute(Attribute::Bold),
Cell::new("ID").add_attribute(Attribute::Bold),
Cell::new("Status").add_attribute(Attribute::Bold),
Cell::new("PID").add_attribute(Attribute::Bold),
Cell::new("CPU%").add_attribute(Attribute::Bold),
Cell::new("Memory").add_attribute(Attribute::Bold),
Cell::new("Restarts").add_attribute(Attribute::Bold),
Cell::new("Port").add_attribute(Attribute::Bold),
Cell::new("Uptime").add_attribute(Attribute::Bold),
]);
// Get monitoring data for all processes
let processes_guard = self.processes.read().await;
let mut monitor = self.monitor.write().await;
let pids: Vec<u32> =
processes_guard.values().filter_map(|p| p.pid()).collect();
let monitoring_data = if !pids.is_empty() {
monitor.update_process_metrics(&pids).await
} else {
std::collections::HashMap::new()
};
drop(monitor);
drop(processes_guard);
// Add each process to the table
for process_status in processes {
let cpu_usage = if let Some(pid) = process_status.pid {
monitoring_data
.get(&pid)
.map(|m| format!("{:.1}%", m.cpu_usage))
.unwrap_or_else(|| "N/A".to_string())
} else {
"N/A".to_string()
};
let memory_usage = if let Some(pid) = process_status.pid {
monitoring_data
.get(&pid)
.map(|m| {
format!("{:.1}MB", m.memory_usage as f64 / 1024.0 / 1024.0)
})
.unwrap_or_else(|| "N/A".to_string())
} else {
"N/A".to_string()
};
let uptime = if let Some(uptime_start) = process_status.uptime {
let duration = chrono::Utc::now() - uptime_start;
let seconds = duration.num_seconds();
if seconds < 60 {
format!("{}s", seconds)
} else if seconds < 3600 {
format!("{}m", seconds / 60)
} else {
format!("{}h", seconds / 3600)
}
} else {
"N/A".to_string()
};
// Color code the status
let status_cell = match process_status.state {
crate::process::ProcessState::Online => {
Cell::new("Online").fg(Color::Green)
}
crate::process::ProcessState::Stopped => {
Cell::new("Stopped").fg(Color::Red)
}
crate::process::ProcessState::Errored => Cell::new("Errored")
.fg(Color::Red)
.add_attribute(Attribute::Bold),
crate::process::ProcessState::Starting => {
Cell::new("Starting").fg(Color::Yellow)
}
crate::process::ProcessState::Stopping => {
Cell::new("Stopping").fg(Color::Yellow)
}
crate::process::ProcessState::Restarting => {
Cell::new("Restarting").fg(Color::Blue)
}
};
// Format port assignment
let port_assignment = if let Some(port) = process_status.assigned_port {
Cell::new(port.to_string()).fg(Color::Cyan)
} else {
Cell::new("N/A").fg(Color::DarkGrey)
};
// Format PID
let pid_cell = if let Some(pid) = process_status.pid {
Cell::new(pid.to_string()).fg(Color::Blue)
} else {
Cell::new("-").fg(Color::DarkGrey)
};
process_table.add_row(vec![
Cell::new(&process_status.name),
Cell::new(
process_status
.id
.to_string()
.chars()
.take(8)
.collect::<String>(),
),
status_cell,
pid_cell,
Cell::new(cpu_usage),
Cell::new(memory_usage),
Cell::new(process_status.restarts.to_string()),
port_assignment,
Cell::new(uptime),
]);
}
println!("{}", process_table);
}
}
Err(e) => {
let mut error_table = Table::new();
error_table
.load_preset(UTF8_FULL)
.set_header(vec![Cell::new("Error")
.add_attribute(Attribute::Bold)
.fg(Color::Red)]);
error_table.add_row(vec![format!("Error retrieving process list: {}", e)]);
println!("{}", error_table);
}
}
// Add timestamp footer
let mut footer_table = Table::new();
footer_table
.load_preset(UTF8_FULL)
.set_content_arrangement(ContentArrangement::Dynamic);
footer_table.add_row(vec![Cell::new(format!(
"Last updated: {}",
chrono::Utc::now().format("%Y-%m-%d %H:%M:%S UTC")
))
.add_attribute(Attribute::Dim)]);
println!("{}", footer_table);
}
}
/// Get process logs.
///
/// Retrieves the last N lines from both stdout and stderr log files for the specified process.
/// Returns a formatted string containing both log streams with clear separation.
///
/// # Arguments
///
/// * `identifier` - Process name or UUID to get logs for
/// * `lines` - Number of lines to retrieve from the end of each log file
///
/// # Returns
///
/// Returns a formatted string containing the log content, or an error if the process
/// doesn't exist or log files cannot be read.
///
/// # Examples
///
/// ```rust,no_run
/// use pmdaemon::ProcessManager;
///
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let manager = ProcessManager::new().await?;
///
/// // Get last 50 lines of logs for a process
/// let logs = manager.get_logs("my-app", 50).await?;
/// println!("{}", logs);
/// # Ok(())
/// # }
/// ```
pub async fn get_logs(&self, identifier: &str, lines: usize) -> Result<String> {
let process_id = self.resolve_identifier(identifier).await?;
// Get the process name for log file paths
let process_name = {
let processes = self.processes.read().await;
if let Some(process) = processes.get(&process_id) {
process.config.name.clone()
} else {
return Err(Error::process_not_found(identifier));
}
};
let (out_log, err_log, _combined_log) = self.get_log_paths(&process_name);
let mut result = String::new();
// Debug: Log the paths being used
debug!(
"Looking for logs at: stdout={:?}, stderr={:?}",
out_log, err_log
);
// Read stdout log
if out_log.exists() {
result.push_str(&format!("==> {} stdout <==\n", process_name));
match fs::read_to_string(&out_log).await {
Ok(content) => {
debug!("Read {} bytes from stdout log", content.len());
if content.is_empty() {
result.push_str("(stdout log file is empty)\n");
} else {
let log_lines: Vec<&str> = content.lines().collect();
let start = if log_lines.len() > lines {
log_lines.len() - lines
} else {
0
};
debug!(
"Showing {} lines from stdout (total: {})",
log_lines.len() - start,
log_lines.len()
);
for line in &log_lines[start..] {
result.push_str(line);
result.push('\n');
}
}
}
Err(e) => {
result.push_str(&format!("Error reading stdout log: {}\n", e));
}
}
result.push('\n');
} else {
result.push_str(&format!("==> {} stdout <==\n", process_name));
result.push_str(&format!("No stdout log file found at: {:?}\n\n", out_log));
}
// Read stderr log
if err_log.exists() {
result.push_str(&format!("==> {} stderr <==\n", process_name));
match fs::read_to_string(&err_log).await {
Ok(content) => {
debug!("Read {} bytes from stderr log", content.len());
if content.is_empty() {
result.push_str("(stderr log file is empty)\n");
} else {
let log_lines: Vec<&str> = content.lines().collect();
let start = if log_lines.len() > lines {
log_lines.len() - lines
} else {
0
};
debug!(
"Showing {} lines from stderr (total: {})",
log_lines.len() - start,
log_lines.len()
);
for line in &log_lines[start..] {
result.push_str(line);
result.push('\n');
}
}
}
Err(e) => {
result.push_str(&format!("Error reading stderr log: {}\n", e));
}
}
} else {
result.push_str(&format!("==> {} stderr <==\n", process_name));
result.push_str(&format!("No stderr log file found at: {:?}\n", err_log));
}
Ok(result)
}
/// Follow process logs in real-time.
///
/// Continuously monitors and displays new log entries from both stdout and stderr
/// log files for the specified process. Similar to `tail -f` functionality.
/// This method blocks until interrupted (e.g., by Ctrl+C).
///
/// # Arguments
///
/// * `identifier` - Process name or UUID to follow logs for
///
/// # Returns
///
/// Returns `Ok(())` when log following is stopped, or an error if the process
/// doesn't exist or log files cannot be accessed.
///
/// # Examples
///
/// ```rust,no_run
/// use pmdaemon::ProcessManager;
///
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let manager = ProcessManager::new().await?;
///
/// // Follow logs for a process (blocks until Ctrl+C)
/// manager.follow_logs("my-app").await?;
/// # Ok(())
/// # }
/// ```
pub async fn follow_logs(&self, identifier: &str) -> Result<()> {
let process_id = self.resolve_identifier(identifier).await?;
// Get the process name for log file paths
let process_name = {
let processes = self.processes.read().await;
if let Some(process) = processes.get(&process_id) {
process.config.name.clone()
} else {
return Err(Error::process_not_found(identifier));
}
};
let (out_log, err_log, _combined_log) = self.get_log_paths(&process_name);
info!("Following logs for process: {}", process_name);
println!("==> Following logs for {} <==", process_name);
println!("Press Ctrl+C to stop following");
println!();
// Track file positions for both stdout and stderr
let mut out_position = if out_log.exists() {
fs::metadata(&out_log).await.map(|m| m.len()).unwrap_or(0)
} else {
0
};
let mut err_position = if err_log.exists() {
fs::metadata(&err_log).await.map(|m| m.len()).unwrap_or(0)
} else {
0
};
let mut interval = interval(Duration::from_millis(500)); // Check every 500ms
loop {
interval.tick().await;
// Check stdout log for new content
if out_log.exists() {
if let Ok(metadata) = fs::metadata(&out_log).await {
let current_size = metadata.len();
if current_size > out_position {
// Read only new content from stdout log
use tokio::fs::File;
use tokio::io::{AsyncReadExt, AsyncSeekExt};
if let Ok(mut file) = File::open(&out_log).await {
if file
.seek(tokio::io::SeekFrom::Start(out_position))
.await
.is_ok()
{
let mut buffer = Vec::new();
if file.read_to_end(&mut buffer).await.is_ok() {
if let Ok(new_content) = String::from_utf8(buffer) {
if !new_content.trim().is_empty() {
for line in new_content.lines() {
println!("[stdout] {}", line);
}
}
}
}
}
}
out_position = current_size;
}
}
}
// Check stderr log for new content
if err_log.exists() {
if let Ok(metadata) = fs::metadata(&err_log).await {
let current_size = metadata.len();
if current_size > err_position {
// Read only new content from stderr log
use tokio::fs::File;
use tokio::io::{AsyncReadExt, AsyncSeekExt};
if let Ok(mut file) = File::open(&err_log).await {
if file
.seek(tokio::io::SeekFrom::Start(err_position))
.await
.is_ok()
{
let mut buffer = Vec::new();
if file.read_to_end(&mut buffer).await.is_ok() {
if let Ok(new_content) = String::from_utf8(buffer) {
if !new_content.trim().is_empty() {
for line in new_content.lines() {
println!("[stderr] {}", line);
}
}
}
}
}
}
err_position = current_size;
}
}
}
// Check if process still exists
let processes = self.processes.read().await;
if !processes.contains_key(&process_id) {
println!(
"\nProcess {} no longer exists, stopping log following",
process_name
);
break;
}
drop(processes);
}
Ok(())
}
/// Get process information
pub async fn get_process_info(&self, identifier: &str) -> Result<ProcessStatus> {
let process_id = self.resolve_identifier(identifier).await?;
let processes = self.processes.read().await;
if let Some(process) = processes.get(&process_id) {
Ok(process.status())
} else {
Err(Error::process_not_found(identifier))
}
}
/// Start web monitoring server
pub async fn start_web_server(&self, host: &str, port: u16) -> Result<()> {
self.start_web_server_with_api_key(host, port, None).await
}
/// Start web monitoring server with API key authentication
pub async fn start_web_server_with_api_key(
&self,
host: &str,
port: u16,
api_key: Option<String>,
) -> Result<()> {
use crate::web::WebServer;
use std::sync::Arc;
use tokio::sync::RwLock;
info!("Starting web monitoring server on {}:{}", host, port);
if api_key.is_some() {
info!("API key authentication enabled");
}
// Create a new process manager instance for the web server
// This is a temporary solution - in a real implementation, we'd want to share the same instance
let manager_arc = Arc::new(RwLock::new(ProcessManager::new().await?));
let web_server = WebServer::new_with_api_key(manager_arc, api_key).await?;
web_server.start(host, port).await
}
/// Start the process monitoring loop
pub async fn start_monitoring(&self) -> Result<()> {
info!("Starting process monitoring loop");
let mut interval = interval(Duration::from_secs(5)); // Check every 5 seconds
loop {
interval.tick().await;
// Check process status and handle auto-restart
if let Err(e) = self.check_all_processes().await {
error!("Error during process monitoring: {}", e);
}
// Update monitoring data
if let Err(e) = self.update_monitoring_data().await {
error!("Error updating monitoring data: {}", e);
}
}
}
/// Check all processes and handle auto-restart
pub async fn check_all_processes(&self) -> Result<()> {
let mut processes = self.processes.write().await;
let mut monitor = self.monitor.write().await;
let mut to_restart = Vec::new();
// Collect PIDs for monitoring data update
let pids: Vec<(ProcessId, u32, String)> = processes
.iter()
.filter_map(|(id, p)| p.pid().map(|pid| (*id, pid, p.config.name.clone())))
.collect();
// Update monitoring data for all running processes
if !pids.is_empty() {
let pid_list: Vec<u32> = pids.iter().map(|(_, pid, _)| *pid).collect();
let monitoring_data = monitor.update_process_metrics(&pid_list).await;
// Check memory limits for each process
for (process_id, pid, process_name) in pids {
if let Some(process) = processes.get(&process_id) {
if let Some(max_memory) = process.config.max_memory_restart {
if let Some(metrics) = monitoring_data.get(&pid) {
let memory_mb = metrics.memory_usage / 1024 / 1024; // Convert to MB
let limit_mb = max_memory / 1024 / 1024;
if memory_mb > limit_mb {
warn!("Process {} exceeded memory limit: {}MB > {}MB, scheduling restart",
process_name, memory_mb, limit_mb);
to_restart.push(process_id);
} else {
debug!(
"Process {} memory usage: {}MB / {}MB",
process_name, memory_mb, limit_mb
);
}
}
}
}
}
}
drop(monitor); // Release monitor lock before process operations
// Check process status and handle crashes
for (process_id, process) in processes.iter_mut() {
match process.check_status().await {
Ok(is_running) => {
if !is_running && process.config.autorestart {
// Process has died and should be restarted
warn!(
"Process {} has died, scheduling restart",
process.config.name
);
to_restart.push(*process_id);
}
}
Err(e) => {
error!(
"Error checking process {} status: {}",
process.config.name, e
);
}
}
}
// Restart processes that need it (memory limit exceeded or crashed)
for process_id in to_restart {
if let Some(process) = processes.get_mut(&process_id) {
let restart_reason = if process.is_running() {
"memory limit exceeded"
} else {
"process crashed"
};
info!(
"Auto-restarting process {} ({})",
process.config.name, restart_reason
);
if let Err(e) = process.restart().await {
error!(
"Failed to auto-restart process {}: {}",
process.config.name, e
);
} else {
// Update PID file and metadata for restarted process
if let Some(new_pid) = process.pid() {
process.set_stored_pid(Some(new_pid));
let process_name = process.config.name.clone();
drop(processes); // Release lock before async operation
if let Err(e) = self.save_pid_file(&process_name, new_pid).await {
warn!("Failed to update PID file after restart: {}", e);
}
// Re-acquire lock to save metadata
let processes = self.processes.read().await;
if let Some(process) = processes.get(&process_id) {
if let Err(e) = self.save_process_metadata(process).await {
warn!("Failed to update metadata after restart: {}", e);
}
}
break; // Re-acquire lock in next iteration
}
}
}
}
Ok(())
}
/// Update process monitoring data
pub async fn update_monitoring_data(&self) -> Result<()> {
let processes = self.processes.read().await;
let mut monitor = self.monitor.write().await;
// Collect PIDs of running processes
let pids: Vec<u32> = processes.values().filter_map(|p| p.pid()).collect();
if !pids.is_empty() {
let monitoring_data = monitor.update_process_metrics(&pids).await;
debug!(
"Updated monitoring data for {} processes",
monitoring_data.len()
);
// Drop the read lock before acquiring write lock
drop(processes);
// Apply monitoring data back to processes
let mut processes = self.processes.write().await;
for (pid, data) in monitoring_data {
// Find the process with this PID and update its monitoring data
for process in processes.values_mut() {
if process.pid() == Some(pid) {
process.update_monitoring(data.cpu_usage, data.memory_usage);
break;
}
}
}
}
Ok(())
}
/// Get system metrics
pub async fn get_system_info(&self) -> Result<crate::monitoring::SystemMetrics> {
let mut monitor = self.monitor.write().await;
Ok(monitor.get_system_metrics().await)
}
/// Save process configuration to disk
async fn save_process_config(&self, process: &Process) -> Result<()> {
let config_file = self
.config_dir
.join(format!("{}.json", process.config.name));
let config_json = serde_json::to_string_pretty(&process.config)
.map_err(|e| Error::config(format!("Failed to serialize config: {}", e)))?;
fs::write(&config_file, config_json)
.await
.map_err(|e| Error::config(format!("Failed to write config file: {}", e)))?;
debug!("Saved configuration for process: {}", process.config.name);
Ok(())
}
/// Save process runtime metadata (assigned port, etc.) to disk
async fn save_process_metadata(&self, process: &Process) -> Result<()> {
use serde_json::json;
let metadata_file = self
.config_dir
.join(format!("{}.meta.json", process.config.name));
let metadata = json!({
"id": process.id,
"assigned_port": process.assigned_port,
"instance": process.instance,
"stored_pid": process.stored_pid
});
let metadata_json = serde_json::to_string_pretty(&metadata)
.map_err(|e| Error::config(format!("Failed to serialize metadata: {}", e)))?;
fs::write(&metadata_file, metadata_json)
.await
.map_err(|e| Error::config(format!("Failed to write metadata file: {}", e)))?;
debug!("Saved metadata for process: {}", process.config.name);
Ok(())
}
/// Load process runtime metadata from disk
async fn load_process_metadata(&self, process: &mut Process) -> Result<()> {
let metadata_file = self
.config_dir
.join(format!("{}.meta.json", process.config.name));
if !metadata_file.exists() {
// No metadata file, that's okay
return Ok(());
}
let metadata_content = fs::read_to_string(&metadata_file)
.await
.map_err(|e| Error::config(format!("Failed to read metadata file: {}", e)))?;
let metadata: serde_json::Value = serde_json::from_str(&metadata_content)
.map_err(|e| Error::config(format!("Failed to parse metadata file: {}", e)))?;
// Restore process ID
if let Some(id_str) = metadata.get("id").and_then(|v| v.as_str()) {
if let Ok(id) = uuid::Uuid::parse_str(id_str) {
process.set_id(id);
}
}
// Restore assigned port
if let Some(port) = metadata.get("assigned_port").and_then(|v| v.as_u64()) {
process.assigned_port = Some(port as u16);
}
// Restore instance number
if let Some(instance) = metadata.get("instance").and_then(|v| v.as_u64()) {
process.instance = Some(instance as u32);
}
// Restore stored PID
if let Some(pid) = metadata.get("stored_pid").and_then(|v| v.as_u64()) {
process.stored_pid = Some(pid as u32);
}
debug!("Loaded metadata for process: {}", process.config.name);
Ok(())
}
/// Attempt to detect port from process logs
async fn detect_port_from_logs(&self, process_name: &str) -> Option<u16> {
let (out_log, _err_log, _combined_log) = self.get_log_paths(process_name);
if !out_log.exists() {
return None;
}
match fs::read_to_string(&out_log).await {
Ok(content) => {
// Common patterns for port detection
let patterns = [
r"(?i)server.*(?:listening|bound|running).*(?:on|at).*:(\d+)",
r"(?i)listening.*(?:on|at).*:(\d+)",
r"(?i)bound.*(?:to|on).*:(\d+)",
r"(?i)port\s*:?\s*(\d+)",
r"(?i)running.*(?:on|at).*:(\d+)",
];
for pattern in &patterns {
if let Ok(re) = regex::Regex::new(pattern) {
for line in content.lines().rev().take(50) {
// Check last 50 lines
if let Some(captures) = re.captures(line) {
if let Some(port_match) = captures.get(1) {
if let Ok(port) = port_match.as_str().parse::<u16>() {
debug!("Detected port {} from log line: {}", port, line);
return Some(port);
}
}
}
}
}
}
None
}
Err(_) => None,
}
}
/// Load all process configurations from disk
async fn load_processes(&mut self) -> Result<()> {
let mut entries = fs::read_dir(&self.config_dir)
.await
.map_err(|e| Error::config(format!("Failed to read config directory: {}", e)))?;
while let Some(entry) = entries
.next_entry()
.await
.map_err(|e| Error::config(format!("Failed to read directory entry: {}", e)))?
{
let path = entry.path();
if let Some(file_name) = path.file_name().and_then(|n| n.to_str()) {
// Only load process config files, not metadata files
if file_name.ends_with(".json") && !file_name.ends_with(".meta.json") {
if let Err(e) = self.load_process_config(&path).await {
warn!("Failed to load process config from {:?}: {}", path, e);
}
}
}
}
info!(
"Loaded {} process configurations",
self.processes.read().await.len()
);
Ok(())
}
/// Load a single process configuration from disk
async fn load_process_config(&mut self, config_path: &PathBuf) -> Result<()> {
let config_content = fs::read_to_string(config_path)
.await
.map_err(|e| Error::config(format!("Failed to read config file: {}", e)))?;
let config: ProcessConfig = serde_json::from_str(&config_content)
.map_err(|e| Error::config(format!("Failed to parse config file: {}", e)))?;
// Create process but don't start it automatically
let mut process = Process::new(config.clone());
let process_id = process.id;
// Load runtime metadata if it exists
self.load_process_metadata(&mut process).await?;
// Check if the process is still running by checking PID files
if let Ok(Some(pid)) = self.read_pid_file(&config.name).await {
// Check if the process is actually running
let mut monitor = self.monitor.write().await;
if monitor.is_process_running(pid).await {
// Process is still running, update the process state
process.set_state(crate::process::ProcessState::Online);
// Restore port allocation if the process has a port configuration
if let Some(port_config) = &config.port {
match port_config {
PortConfig::Single(port) => {
process.assigned_port = Some(*port);
let mut allocated_ports = self.allocated_ports.write().await;
allocated_ports.insert(*port);
debug!(
"Restored port allocation {} for running process {}",
port, config.name
);
}
PortConfig::Range(start, _end) => {
// For ranges, we assume the first port was assigned
process.assigned_port = Some(*start);
let mut allocated_ports = self.allocated_ports.write().await;
allocated_ports.insert(*start);
debug!(
"Restored port allocation {} for running process {}",
start, config.name
);
}
PortConfig::Auto(_, _) => {
// For auto ports, we can't easily restore the exact port
// This is a limitation - in a real implementation, we'd save the assigned port
debug!(
"Cannot restore auto-assigned port for process {}",
config.name
);
}
}
}
// Note: We can't restore the actual Child handle, but we can track the PID
process.set_stored_pid(Some(pid));
// Try to detect port from logs if not already assigned
if process.assigned_port.is_none() {
if let Some(detected_port) = self.detect_port_from_logs(&config.name).await {
process.assigned_port = Some(detected_port);
debug!(
"Detected port {} for process {} from logs",
detected_port, config.name
);
}
}
debug!("Found running process {} with PID {}", config.name, pid);
} else {
// PID file exists but process is not running, clean up
process.set_state(crate::process::ProcessState::Stopped);
if let Err(e) = self.remove_pid_file(&config.name).await {
warn!("Failed to remove stale PID file for {}: {}", config.name, e);
}
}
} else {
// No PID file, process is stopped
process.set_state(crate::process::ProcessState::Stopped);
}
let process_name = config.name.clone();
let mut processes = self.processes.write().await;
let mut name_map = self.name_to_id.write().await;
processes.insert(process_id, process);
name_map.insert(config.name, process_id);
debug!("Loaded process configuration: {}", process_name);
Ok(())
}
/// Remove process configuration from disk
async fn remove_process_config(&self, process_name: &str) -> Result<()> {
let config_file = self.config_dir.join(format!("{}.json", process_name));
if config_file.exists() {
fs::remove_file(&config_file)
.await
.map_err(|e| Error::config(format!("Failed to remove config file: {}", e)))?;
debug!("Removed configuration file for process: {}", process_name);
}
// Also remove metadata file
let metadata_file = self.config_dir.join(format!("{}.meta.json", process_name));
if metadata_file.exists() {
fs::remove_file(&metadata_file)
.await
.map_err(|e| Error::config(format!("Failed to remove metadata file: {}", e)))?;
debug!("Removed metadata file for process: {}", process_name);
}
Ok(())
}
/// Read log files for a process
pub async fn read_logs(
&self,
process_name: &str,
lines: Option<usize>,
follow: bool,
) -> Result<()> {
let (out_log, err_log, _combined_log) = self.get_log_paths(process_name);
if follow {
// Use the dedicated follow_logs method for real-time following
return self.follow_logs(process_name).await;
}
let lines_to_read = lines.unwrap_or(15);
// Read stdout log
if out_log.exists() {
println!("==> {} stdout <==", process_name);
if let Ok(content) = fs::read_to_string(&out_log).await {
let lines: Vec<&str> = content.lines().collect();
let start = if lines.len() > lines_to_read {
lines.len() - lines_to_read
} else {
0
};
for line in &lines[start..] {
println!("{}", line);
}
}
println!();
}
// Read stderr log
if err_log.exists() {
println!("==> {} stderr <==", process_name);
if let Ok(content) = fs::read_to_string(&err_log).await {
let lines: Vec<&str> = content.lines().collect();
let start = if lines.len() > lines_to_read {
lines.len() - lines_to_read
} else {
0
};
for line in &lines[start..] {
println!("{}", line);
}
}
}
Ok(())
}
/// Clear log files for a process
pub async fn clear_logs(&self, process_name: &str) -> Result<()> {
let (out_log, err_log, _combined_log) = self.get_log_paths(process_name);
if out_log.exists() {
fs::write(&out_log, "")
.await
.map_err(|e| Error::config(format!("Failed to clear stdout log: {}", e)))?;
}
if err_log.exists() {
fs::write(&err_log, "")
.await
.map_err(|e| Error::config(format!("Failed to clear stderr log: {}", e)))?;
}
info!("Cleared logs for process: {}", process_name);
Ok(())
}
/// Remove log files for a process
async fn remove_log_files(&self, process_name: &str) -> Result<()> {
let (out_log, err_log, combined_log) = self.get_log_paths(process_name);
for log_file in [out_log, err_log, combined_log] {
if log_file.exists() {
if let Err(e) = fs::remove_file(&log_file).await {
warn!("Failed to remove log file {:?}: {}", log_file, e);
}
}
}
debug!("Removed log files for process: {}", process_name);
Ok(())
}
/// Allocate a port for a process
async fn allocate_port(&self, port_config: &PortConfig, process_name: &str) -> Result<u16> {
let mut allocated_ports = self.allocated_ports.write().await;
match port_config {
PortConfig::Single(port) => {
if allocated_ports.contains(port) {
return Err(Error::config(format!("Port {} is already in use", port)));
}
allocated_ports.insert(*port);
info!("Allocated port {} to process {}", port, process_name);
Ok(*port)
}
PortConfig::Range(start, end) => {
// For ranges, we need to allocate all ports in the range
let ports: Vec<u16> = (*start..=*end).collect();
for port in &ports {
if allocated_ports.contains(port) {
return Err(Error::config(format!(
"Port {} in range {}-{} is already in use",
port, start, end
)));
}
}
// Allocate all ports in the range
for port in &ports {
allocated_ports.insert(*port);
}
info!(
"Allocated port range {}-{} to process {}",
start, end, process_name
);
Ok(*start) // Return the first port in the range
}
PortConfig::Auto(start, end) => {
// Find the first available port in the range
for port in *start..=*end {
if !allocated_ports.contains(&port) {
allocated_ports.insert(port);
info!("Auto-allocated port {} to process {}", port, process_name);
return Ok(port);
}
}
Err(Error::config(format!(
"No available ports in range {}-{}",
start, end
)))
}
}
}
/// Deallocate ports for a port configuration
async fn deallocate_ports(&self, port_config: &PortConfig, assigned_port: Option<u16>) {
let mut allocated_ports = self.allocated_ports.write().await;
match port_config {
PortConfig::Single(port) => {
allocated_ports.remove(port);
debug!("Deallocated port {}", port);
}
PortConfig::Range(start, end) => {
for port in *start..=*end {
allocated_ports.remove(&port);
}
debug!("Deallocated port range {}-{}", start, end);
}
PortConfig::Auto(_, _) => {
if let Some(port) = assigned_port {
allocated_ports.remove(&port);
debug!("Deallocated auto-assigned port {}", port);
}
}
}
}
/// Check if a port is available
pub async fn is_port_available(&self, port: u16) -> bool {
let allocated_ports = self.allocated_ports.read().await;
!allocated_ports.contains(&port)
}
/// Get all allocated ports
pub async fn get_allocated_ports(&self) -> Vec<u16> {
let allocated_ports = self.allocated_ports.read().await;
let mut ports: Vec<u16> = allocated_ports.iter().copied().collect();
ports.sort();
ports
}
/// Resolve process identifier (name or UUID) to ProcessId
async fn resolve_identifier(&self, identifier: &str) -> Result<ProcessId> {
// Try to parse as UUID first
if let Ok(uuid) = Uuid::parse_str(identifier) {
let processes = self.processes.read().await;
if processes.contains_key(&uuid) {
return Ok(uuid);
}
}
// Try to resolve by name
let name_map = self.name_to_id.read().await;
if let Some(&process_id) = name_map.get(identifier) {
Ok(process_id)
} else {
Err(Error::process_not_found(identifier))
}
}
/// Get the number of processes
pub async fn process_count(&self) -> usize {
let processes = self.processes.read().await;
processes.len()
}
/// Check if a process exists by name
pub async fn process_exists(&self, name: &str) -> bool {
let name_map = self.name_to_id.read().await;
name_map.contains_key(name)
}
/// Get all process names
pub async fn get_process_names(&self) -> Vec<String> {
let name_map = self.name_to_id.read().await;
name_map.keys().cloned().collect()
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::config::{PortConfig, ProcessConfig};
use crate::process::{Process, ProcessState};
use pretty_assertions::assert_eq;
use std::time::Duration;
use tempfile::TempDir;
use tokio::fs;
async fn create_test_manager() -> (ProcessManager, TempDir) {
let temp_dir = TempDir::new().unwrap();
let config_dir = temp_dir.path().to_path_buf();
let manager = ProcessManager {
processes: RwLock::new(HashMap::new()),
name_to_id: RwLock::new(HashMap::new()),
monitor: RwLock::new(Monitor::new()),
config_dir,
allocated_ports: RwLock::new(HashSet::new()),
};
(manager, temp_dir)
}
fn create_test_config(name: &str) -> ProcessConfig {
ProcessConfig::builder()
.name(name)
.script("echo")
.args(vec!["hello", "world"])
.build()
.unwrap()
}
#[test]
fn test_get_config_dir() {
let result = ProcessManager::get_config_dir();
assert!(result.is_ok());
let path = result.unwrap();
assert!(path.to_string_lossy().contains(".pmdaemon"));
}
#[tokio::test]
async fn test_process_manager_new() {
let manager = ProcessManager::new().await;
assert!(manager.is_ok());
}
#[tokio::test]
async fn test_get_log_paths() {
let (manager, _temp_dir) = create_test_manager().await;
let (out_log, err_log, combined_log) = manager.get_log_paths("test-process");
assert!(out_log.to_string_lossy().contains("test-process-out.log"));
assert!(err_log.to_string_lossy().contains("test-process-error.log"));
assert!(combined_log.to_string_lossy().contains("test-process.log"));
}
#[tokio::test]
async fn test_ensure_logs_dir() {
let (manager, _temp_dir) = create_test_manager().await;
let result = manager.ensure_logs_dir().await;
assert!(result.is_ok());
let logs_dir = manager.get_logs_dir();
assert!(logs_dir.exists());
}
#[tokio::test]
async fn test_save_and_read_pid_file() {
let (manager, _temp_dir) = create_test_manager().await;
let process_name = "test-process";
let pid = 12345u32;
// Save PID file
let result = manager.save_pid_file(process_name, pid).await;
assert!(result.is_ok());
// Read PID file
let read_result = manager.read_pid_file(process_name).await;
assert!(read_result.is_ok());
assert_eq!(read_result.unwrap(), Some(pid));
// Test non-existent PID file
let missing_result = manager.read_pid_file("non-existent").await;
assert!(missing_result.is_ok());
assert_eq!(missing_result.unwrap(), None);
}
#[tokio::test]
async fn test_remove_pid_file() {
let (manager, _temp_dir) = create_test_manager().await;
let process_name = "test-process";
let pid = 12345u32;
// Save PID file first
manager.save_pid_file(process_name, pid).await.unwrap();
// Remove PID file
let result = manager.remove_pid_file(process_name).await;
assert!(result.is_ok());
// Verify it's gone
let read_result = manager.read_pid_file(process_name).await;
assert!(read_result.is_ok());
assert_eq!(read_result.unwrap(), None);
}
#[tokio::test]
async fn test_port_allocation_single() {
let (manager, _temp_dir) = create_test_manager().await;
let port_config = PortConfig::Single(8080);
// Allocate port
let result = manager.allocate_port(&port_config, "test-process").await;
assert!(result.is_ok());
assert_eq!(result.unwrap(), 8080);
// Try to allocate same port again
let result2 = manager.allocate_port(&port_config, "test-process2").await;
assert!(result2.is_err());
}
#[tokio::test]
async fn test_port_allocation_auto() {
let (manager, _temp_dir) = create_test_manager().await;
let port_config = PortConfig::Auto(8000, 8002);
// Allocate first port
let result1 = manager.allocate_port(&port_config, "test-process1").await;
assert!(result1.is_ok());
let port1 = result1.unwrap();
assert!((8000..=8002).contains(&port1));
// Allocate second port
let result2 = manager.allocate_port(&port_config, "test-process2").await;
assert!(result2.is_ok());
let port2 = result2.unwrap();
assert!((8000..=8002).contains(&port2));
assert_ne!(port1, port2);
}
#[tokio::test]
async fn test_port_allocation_range() {
let (manager, _temp_dir) = create_test_manager().await;
let port_config = PortConfig::Range(9000, 9002);
// Allocate port range
let result = manager.allocate_port(&port_config, "test-process").await;
assert!(result.is_ok());
assert_eq!(result.unwrap(), 9000); // Should return first port in range
// Try to allocate overlapping range
let port_config2 = PortConfig::Single(9001);
let result2 = manager.allocate_port(&port_config2, "test-process2").await;
assert!(result2.is_err()); // Should fail because 9001 is already allocated
}
#[tokio::test]
async fn test_port_deallocation() {
let (manager, _temp_dir) = create_test_manager().await;
let port_config = PortConfig::Single(8080);
// Allocate port
manager
.allocate_port(&port_config, "test-process")
.await
.unwrap();
assert!(!manager.is_port_available(8080).await);
// Deallocate port
manager.deallocate_ports(&port_config, Some(8080)).await;
assert!(manager.is_port_available(8080).await);
}
#[tokio::test]
async fn test_is_port_available() {
let (manager, _temp_dir) = create_test_manager().await;
// Port should be available initially
assert!(manager.is_port_available(8080).await);
// Allocate port
let port_config = PortConfig::Single(8080);
manager
.allocate_port(&port_config, "test-process")
.await
.unwrap();
// Port should not be available now
assert!(!manager.is_port_available(8080).await);
}
#[tokio::test]
async fn test_get_allocated_ports() {
let (manager, _temp_dir) = create_test_manager().await;
// Initially no ports allocated
let ports = manager.get_allocated_ports().await;
assert!(ports.is_empty());
// Allocate some ports
let port_config1 = PortConfig::Single(8080);
let port_config2 = PortConfig::Single(8081);
manager.allocate_port(&port_config1, "test1").await.unwrap();
manager.allocate_port(&port_config2, "test2").await.unwrap();
// Check allocated ports
let ports = manager.get_allocated_ports().await;
assert_eq!(ports.len(), 2);
assert!(ports.contains(&8080));
assert!(ports.contains(&8081));
}
#[tokio::test]
async fn test_get_logs_nonexistent_process() {
let (manager, _temp_dir) = create_test_manager().await;
// Try to get logs for a process that doesn't exist
let result = manager.get_logs("nonexistent", 10).await;
assert!(result.is_err());
assert!(result.unwrap_err().to_string().contains("not found"));
}
#[tokio::test]
async fn test_get_logs_with_mock_process() {
let (manager, _temp_dir) = create_test_manager().await;
let config = create_test_config("test-logs");
// Create a mock process entry
let process = Process::new(config.clone());
let process_id = process.id;
{
let mut processes = manager.processes.write().await;
let mut name_map = manager.name_to_id.write().await;
processes.insert(process_id, process);
name_map.insert(config.name.clone(), process_id);
}
// Create mock log files
let (out_log, err_log, _) = manager.get_log_paths(&config.name);
fs::create_dir_all(out_log.parent().unwrap()).await.unwrap();
fs::write(&out_log, "stdout line 1\nstdout line 2\nstdout line 3\n")
.await
.unwrap();
fs::write(&err_log, "stderr line 1\nstderr line 2\n")
.await
.unwrap();
// Test getting logs
let logs = manager.get_logs(&config.name, 2).await.unwrap();
// Should contain both stdout and stderr sections
assert!(logs.contains("==> test-logs stdout <=="));
assert!(logs.contains("==> test-logs stderr <=="));
assert!(logs.contains("stdout line 2"));
assert!(logs.contains("stdout line 3"));
assert!(logs.contains("stderr line 1"));
assert!(logs.contains("stderr line 2"));
// Should not contain the first stdout line (only last 2 lines)
assert!(!logs.contains("stdout line 1"));
}
#[tokio::test]
async fn test_get_logs_missing_files() {
let (manager, _temp_dir) = create_test_manager().await;
let config = create_test_config("test-missing-logs");
// Create a mock process entry
let process = Process::new(config.clone());
let process_id = process.id;
{
let mut processes = manager.processes.write().await;
let mut name_map = manager.name_to_id.write().await;
processes.insert(process_id, process);
name_map.insert(config.name.clone(), process_id);
}
// Don't create log files - test missing files
let logs = manager.get_logs(&config.name, 10).await.unwrap();
// Should contain sections indicating no files found
assert!(logs.contains("==> test-missing-logs stdout <=="));
assert!(logs.contains("==> test-missing-logs stderr <=="));
assert!(logs.contains("No stdout log file found"));
assert!(logs.contains("No stderr log file found"));
}
#[tokio::test]
async fn test_monitor_with_interval_validation() {
let (manager, _temp_dir) = create_test_manager().await;
// Test that monitor_with_interval accepts different durations
// We can't actually run the monitor loop in tests, but we can verify
// the method exists and accepts the right parameters
// This would normally run forever, so we'll just verify it compiles
// and the method signature is correct
let _future = manager.monitor_with_interval(Duration::from_millis(100));
let _future = manager.monitor_with_interval(Duration::from_secs(1));
let _future = manager.monitor_with_interval(Duration::from_secs(10));
// If we get here, the method signature is correct
// Test passed - process was successfully stopped
}
#[tokio::test]
async fn test_default_monitor_delegates_to_configurable() {
let (manager, _temp_dir) = create_test_manager().await;
// Test that the default monitor() method exists and compiles
// This verifies that monitor() properly delegates to monitor_with_interval()
let _future = manager.monitor();
// If we get here, the delegation is working
// Test passed - default monitor method exists and compiles
}
#[tokio::test]
async fn test_get_system_info() {
let (manager, _temp_dir) = create_test_manager().await;
// Test that we can get system information
let system_info = manager.get_system_info().await.unwrap();
// Verify system metrics have reasonable values
// CPU usage should now be normalized to >= 0.0 by the monitoring system
assert!(system_info.cpu_usage >= 0.0);
assert!(system_info.memory_usage > 0);
assert!(system_info.memory_total > 0);
assert!(system_info.memory_usage <= system_info.memory_total);
assert!(system_info.uptime > 0);
assert_eq!(system_info.load_average.len(), 3);
}
#[tokio::test]
async fn test_update_monitoring_data() {
let (manager, _temp_dir) = create_test_manager().await;
// Test that update_monitoring_data doesn't crash with no processes
let result = manager.update_monitoring_data().await;
assert!(result.is_ok());
// The method should handle empty process lists gracefully
}
#[tokio::test]
async fn test_process_count() {
let (manager, _temp_dir) = create_test_manager().await;
// Initially no processes
assert_eq!(manager.process_count().await, 0);
// Add a process manually for testing
let config = create_test_config("test-process");
let process = Process::new(config.clone());
let process_id = process.id;
{
let mut processes = manager.processes.write().await;
let mut name_map = manager.name_to_id.write().await;
processes.insert(process_id, process);
name_map.insert(config.name.clone(), process_id);
}
assert_eq!(manager.process_count().await, 1);
}
#[tokio::test]
async fn test_process_exists() {
let (manager, _temp_dir) = create_test_manager().await;
// Process should not exist initially
assert!(!manager.process_exists("test-process").await);
// Add a process manually for testing
let config = create_test_config("test-process");
let process = Process::new(config.clone());
let process_id = process.id;
{
let mut processes = manager.processes.write().await;
let mut name_map = manager.name_to_id.write().await;
processes.insert(process_id, process);
name_map.insert(config.name.clone(), process_id);
}
assert!(manager.process_exists("test-process").await);
assert!(!manager.process_exists("non-existent").await);
}
#[tokio::test]
async fn test_get_process_names() {
let (manager, _temp_dir) = create_test_manager().await;
// Initially no process names
let names = manager.get_process_names().await;
assert!(names.is_empty());
// Add processes manually for testing
let configs = vec![
create_test_config("process1"),
create_test_config("process2"),
];
{
let mut processes = manager.processes.write().await;
let mut name_map = manager.name_to_id.write().await;
for config in configs {
let process = Process::new(config.clone());
let process_id = process.id;
processes.insert(process_id, process);
name_map.insert(config.name.clone(), process_id);
}
}
let names = manager.get_process_names().await;
assert_eq!(names.len(), 2);
assert!(names.contains(&"process1".to_string()));
assert!(names.contains(&"process2".to_string()));
}
#[tokio::test]
async fn test_resolve_identifier_by_name() {
let (manager, _temp_dir) = create_test_manager().await;
// Add a process manually for testing
let config = create_test_config("test-process");
let process = Process::new(config.clone());
let process_id = process.id;
{
let mut processes = manager.processes.write().await;
let mut name_map = manager.name_to_id.write().await;
processes.insert(process_id, process);
name_map.insert(config.name.clone(), process_id);
}
// Resolve by name
let result = manager.resolve_identifier("test-process").await;
assert!(result.is_ok());
assert_eq!(result.unwrap(), process_id);
// Try non-existent process
let result = manager.resolve_identifier("non-existent").await;
assert!(result.is_err());
}
#[tokio::test]
async fn test_resolve_identifier_by_uuid() {
let (manager, _temp_dir) = create_test_manager().await;
// Add a process manually for testing
let config = create_test_config("test-process");
let process = Process::new(config.clone());
let process_id = process.id;
{
let mut processes = manager.processes.write().await;
let mut name_map = manager.name_to_id.write().await;
processes.insert(process_id, process);
name_map.insert(config.name.clone(), process_id);
}
// Resolve by UUID
let uuid_str = process_id.to_string();
let result = manager.resolve_identifier(&uuid_str).await;
assert!(result.is_ok());
assert_eq!(result.unwrap(), process_id);
}
#[tokio::test]
async fn test_list_empty() {
let (manager, _temp_dir) = create_test_manager().await;
let result = manager.list().await;
assert!(result.is_ok());
assert!(result.unwrap().is_empty());
}
#[tokio::test]
async fn test_save_and_remove_process_config() {
let (manager, _temp_dir) = create_test_manager().await;
let config = create_test_config("test-process");
let process = Process::new(config.clone());
// Save config
let result = manager.save_process_config(&process).await;
assert!(result.is_ok());
// Check file exists
let config_file = manager.config_dir.join("test-process.json");
assert!(config_file.exists());
// Remove config
let result = manager.remove_process_config("test-process").await;
assert!(result.is_ok());
// Check file is gone
assert!(!config_file.exists());
}
#[tokio::test]
async fn test_clear_logs() {
let (manager, _temp_dir) = create_test_manager().await;
let process_name = "test-process";
// Create logs directory and files
manager.ensure_logs_dir().await.unwrap();
let (out_log, err_log, _) = manager.get_log_paths(process_name);
// Write some content to log files
fs::write(&out_log, "stdout content").await.unwrap();
fs::write(&err_log, "stderr content").await.unwrap();
// Clear logs
let result = manager.clear_logs(process_name).await;
assert!(result.is_ok());
// Check files are empty
let out_content = fs::read_to_string(&out_log).await.unwrap();
let err_content = fs::read_to_string(&err_log).await.unwrap();
assert!(out_content.is_empty());
assert!(err_content.is_empty());
}
#[tokio::test]
async fn test_remove_log_files() {
let (manager, _temp_dir) = create_test_manager().await;
let process_name = "test-process";
// Create logs directory and files
manager.ensure_logs_dir().await.unwrap();
let (out_log, err_log, combined_log) = manager.get_log_paths(process_name);
// Create log files
fs::write(&out_log, "stdout content").await.unwrap();
fs::write(&err_log, "stderr content").await.unwrap();
fs::write(&combined_log, "combined content").await.unwrap();
// Remove log files
manager.remove_log_files(process_name).await.unwrap();
// Check files are gone
assert!(!out_log.exists());
assert!(!err_log.exists());
assert!(!combined_log.exists());
}
#[tokio::test]
async fn test_delete_all() {
let (mut manager, _temp_dir) = create_test_manager().await;
// Create some test processes
let config1 = create_test_config("test-process-1");
let config2 = create_test_config("test-process-2");
// Add processes directly to the manager for testing
let process1 = Process::new(config1);
let process2 = Process::new(config2);
let id1 = process1.id;
let id2 = process2.id;
{
let mut processes = manager.processes.write().await;
let mut name_map = manager.name_to_id.write().await;
processes.insert(id1, process1);
processes.insert(id2, process2);
name_map.insert("test-process-1".to_string(), id1);
name_map.insert("test-process-2".to_string(), id2);
}
// Verify processes exist
assert_eq!(manager.processes.read().await.len(), 2);
// Delete all processes
let deleted_count = manager.delete_all().await.unwrap();
assert_eq!(deleted_count, 2);
// Verify all processes are deleted
assert_eq!(manager.processes.read().await.len(), 0);
assert_eq!(manager.name_to_id.read().await.len(), 0);
}
#[tokio::test]
async fn test_delete_by_status() {
let (mut manager, _temp_dir) = create_test_manager().await;
// Create test processes with different states
let config1 = create_test_config("stopped-process");
let config2 = create_test_config("online-process");
let mut process1 = Process::new(config1);
let mut process2 = Process::new(config2);
// Set different states
process1.state = ProcessState::Stopped;
process2.state = ProcessState::Online;
let id1 = process1.id;
let id2 = process2.id;
{
let mut processes = manager.processes.write().await;
let mut name_map = manager.name_to_id.write().await;
processes.insert(id1, process1);
processes.insert(id2, process2);
name_map.insert("stopped-process".to_string(), id1);
name_map.insert("online-process".to_string(), id2);
}
// Verify processes exist
assert_eq!(manager.processes.read().await.len(), 2);
// Delete only stopped processes
let deleted_count = manager.delete_by_status("stopped").await.unwrap();
assert_eq!(deleted_count, 1);
// Verify only the stopped process was deleted
assert_eq!(manager.processes.read().await.len(), 1);
assert!(manager
.name_to_id
.read()
.await
.contains_key("online-process"));
assert!(!manager
.name_to_id
.read()
.await
.contains_key("stopped-process"));
}
#[tokio::test]
async fn test_delete_by_invalid_status() {
let (mut manager, _temp_dir) = create_test_manager().await;
// Try to delete by invalid status
let result = manager.delete_by_status("invalid-status").await;
assert!(result.is_err());
let error_msg = result.unwrap_err().to_string();
assert!(error_msg.contains("Invalid status"));
assert!(error_msg.contains("invalid-status"));
}
}