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
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
//! Controlling the entire operation.
use crate::common::file_io::TheFileIo;
use crate::roto_runtime::types::FilterName;
use crate::roto_runtime::types::CompiledRoto;
use crate::roto_runtime::create_runtime;
use crate::comms::{
DirectLink, Gate, GateAgent, GraphStatus, Link, DEF_UPDATE_QUEUE_LEN,
};
use crate::config::{Config, ConfigFile, Marked};
use crate::log::Terminate;
use crate::targets::Target;
use crate::tracing::{MsgRelation, Trace, Tracer};
use crate::units::Unit;
use crate::{http, ingress, metrics};
use arc_swap::ArcSwap;
use futures::future::{join_all, select, Either};
use log::{debug, error, info, log_enabled, trace, warn};
use non_empty_vec::NonEmpty;
use reqwest::Client as HttpClient;
use serde::Deserialize;
use std::collections::HashSet;
use std::ops::Deref;
use std::sync::{Arc, Mutex, RwLock, Weak};
use std::time::{Duration, Instant};
use std::{cell::RefCell, fmt::Display};
use std::{collections::HashMap, mem::Discriminant};
use tokio::sync::mpsc::{self, Receiver, Sender};
use tokio::sync::Barrier;
use uuid::Uuid;
use {
crate::http::{PercentDecodedPath, ProcessRequest},
hyper::{Body, Method, Request, Response},
};
//------------ Component -----------------------------------------------------
/// Facilities available to all components.
///
/// Upon being started, every component receives one of these. It provides
/// access to information and services available to all components.
pub struct Component {
/// The component’s name.
name: Arc<str>,
/// The component's type name.
type_name: &'static str,
/// An HTTP client.
http_client: Option<HttpClient>,
/// A reference to the metrics collection.
metrics: Option<metrics::Collection>,
/// A reference to the HTTP resources collection.
http_resources: http::Resources,
/// A reference to the compiled Roto script.
roto_compiled: Option<Arc<CompiledRoto>>,
/// A reference to the Tracer
tracer: Arc<Tracer>,
/// A reference to the ingress sources.
ingresses: Arc<ingress::Register>,
}
#[cfg(test)]
impl Default for Component {
fn default() -> Self {
Self {
name: "MOCK".into(),
type_name: "MOCK",
http_client: Default::default(),
metrics: Default::default(),
http_resources: Default::default(),
roto_compiled: Default::default(),
tracer: Default::default(),
ingresses: Default::default(),
}
}
}
impl Component {
/// Creates a new component from its, well, components.
fn new(
name: String,
type_name: &'static str,
http_client: HttpClient,
metrics: metrics::Collection,
http_resources: http::Resources,
roto_compiled: Option<Arc<CompiledRoto>>,
tracer: Arc<Tracer>,
ingresses: Arc<ingress::Register>,
) -> Self {
Component {
name: name.into(),
type_name,
http_client: Some(http_client),
metrics: Some(metrics),
http_resources,
roto_compiled,
tracer,
ingresses,
}
}
/// Returns the name of the component.
pub fn name(&self) -> &Arc<str> {
&self.name
}
/// Returns the type name of the component.
pub fn type_name(&self) -> &'static str {
self.type_name
}
/// Returns a reference to an HTTP Client.
pub fn http_client(&self) -> &HttpClient {
self.http_client.as_ref().unwrap()
}
pub fn http_resources(&self) -> &http::Resources {
&self.http_resources
}
pub fn roto_compiled(
&self,
) -> &Option<Arc<CompiledRoto>> {
&self.roto_compiled
}
pub fn tracer(&self) -> &Arc<Tracer> {
&self.tracer
}
/// Register a metrics source.
pub fn register_metrics(&mut self, source: Arc<dyn metrics::Source>) {
if let Some(metrics) = &self.metrics {
metrics.register(self.name.clone(), Arc::downgrade(&source));
}
}
/// Register an HTTP resource.
pub fn register_http_resource(
&mut self,
process: Arc<dyn http::ProcessRequest>,
rel_base_url: &str,
) {
debug!("registering resource {:?}", &rel_base_url);
self.http_resources.register(
Arc::downgrade(&process),
self.name.clone(),
self.type_name,
rel_base_url,
false,
)
}
/// Register a sub HTTP resource.
pub fn register_sub_http_resource(
&mut self,
process: Arc<dyn http::ProcessRequest>,
rel_base_url: &str,
) {
debug!("registering resource {:?}", &rel_base_url);
self.http_resources.register(
Arc::downgrade(&process),
self.name.clone(),
self.type_name,
rel_base_url,
true,
)
}
pub fn register_ingress(&self) -> ingress::IngressId {
self.ingresses.register()
}
pub fn ingresses(&self) -> Arc<ingress::Register> {
self.ingresses.clone()
}
}
//------------ Manager -------------------------------------------------------
#[derive(Clone, Copy, Debug)]
pub enum LinkType {
Queued,
Direct,
}
#[allow(dead_code)]
#[derive(Clone, Copy, Debug)]
pub struct LinkInfo {
link_type: LinkType,
id: Uuid,
gate_id: Uuid,
connected_gate_slot: Option<Uuid>,
}
impl From<&Link> for LinkInfo {
fn from(link: &Link) -> Self {
Self {
link_type: LinkType::Queued,
id: link.id(),
gate_id: link.gate_id(),
connected_gate_slot: link.connected_gate_slot(),
}
}
}
impl From<&DirectLink> for LinkInfo {
fn from(link: &DirectLink) -> Self {
Self {
link_type: LinkType::Direct,
id: link.id(),
gate_id: link.gate_id(),
connected_gate_slot: link.connected_gate_slot(),
}
}
}
#[derive(Debug, Default)]
pub struct LinkReport {
gates: HashMap<String, Uuid>,
links: HashMap<String, UpstreamLinkReport>,
}
impl LinkReport {
fn new() -> Self {
Default::default()
}
fn add_gate(&mut self, name: String, id: Uuid) {
self.gates.insert(name, id);
}
fn add_link(&mut self, name: String, report: UpstreamLinkReport) {
self.links.insert(name, report);
}
fn ready(&self) -> Result<(), usize> {
let remaining = self
.links
.iter()
.filter(|(_name, report)| !report.ready())
.count();
if remaining > 0 {
Err(remaining)
} else {
Ok(())
}
}
fn get_gate_id(&self, name: &str) -> Option<Uuid> {
self.gates.get(name).copied()
}
fn get_svg(&self, tracer: Arc<Tracer>, trace_id: Option<u8>) -> String {
use chrono::Utc;
use layout::backends::svg::SVGWriter;
use layout::core::base::Orientation;
use layout::core::color::Color;
use layout::core::format::RenderBackend;
use layout::core::geometry::Point;
use layout::core::style::*;
use layout::std_shapes::shapes::*;
use layout::topo::layout::VisualGraph;
let mut vg = VisualGraph::new(Orientation::LeftToRight);
let mut nodes = HashMap::new();
let trace =
trace_id.map_or_else(Trace::new, |id| tracer.get_trace(id));
// add nodes for each unit and target
for (unit_or_target_name, report) in &self.links {
let (shape_kind, style_attr) = match report
.graph_status()
.and_then(|weak_ref| weak_ref.upgrade())
{
Some(graph_status) if trace_id.is_none() => {
let shape_kind = ShapeKind::new_box(&format!(
"{}\n{}",
&unit_or_target_name,
graph_status.status_text()
));
let line_colour = match graph_status.okay() {
Some(false) => "red",
Some(true) => "green",
None => "black",
};
let style_attr = StyleAttr::new(
Color::fast(line_colour),
2,
None,
0,
15,
);
(shape_kind, style_attr)
}
_ if trace_id.is_some() => {
// TODO: Inefficient
let mut box_colour = "black";
let mut trace_txt = String::new();
if let Some(gate_id) =
self.get_gate_id(unit_or_target_name)
{
let msg_indices =
trace.msg_indices(gate_id, MsgRelation::ALL);
if !msg_indices.is_empty() {
box_colour = "blue";
trace_txt = extract_msg_indices(&trace, gate_id);
}
}
(
ShapeKind::new_box(&format!(
"{}\n{}",
&unit_or_target_name, trace_txt
)),
StyleAttr::new(
Color::fast(box_colour),
2,
None,
0,
15,
),
)
}
_ => (
ShapeKind::new_box(unit_or_target_name),
StyleAttr::new(Color::fast("black"), 2, None, 0, 15),
),
};
let node = Element::create(
shape_kind,
style_attr,
Orientation::LeftToRight,
Point::new(100., 100.),
);
let handle = vg.add_node(node);
nodes.insert(unit_or_target_name.clone(), handle);
}
// add graph edges
for (unit_or_target_name, report) in &self.links {
let links = report.into_vec();
for link in links {
let link_type = match link.link_type {
LinkType::Queued => "queued",
LinkType::Direct => "direct",
};
let gate_name = self
.gates
.iter()
.find(|(_, &id)| id == link.gate_id)
.map_or("unknown", |(name, _id)| name);
debug!("Gate: id={} name={gate_name}", link.gate_id);
let mut arrow = Arrow::simple(link_type);
if trace_id.is_some()
&& !trace
.msg_indices(link.gate_id, MsgRelation::GATE)
.is_empty()
{
arrow.look = StyleAttr::new(
Color::fast("blue"),
2,
Option::Some(Color::fast("blue")),
0,
15,
)
}
let to_node = nodes.get(unit_or_target_name).unwrap();
if let Some(from_node) = nodes.get(gate_name) {
vg.add_edge(arrow, *from_node, *to_node);
} else {
// This can happen if a unit or target didn't honor a new
// set of sources announced to it via a reconfigure
// message.
error!("Internal error: Component '{unit_or_target_name}' has broken link {} to non-existent gate {}", link.id, link.gate_id);
}
}
}
let mut svg = SVGWriter::new();
let last_updated = Utc::now();
vg.do_it(false, false, false, &mut svg);
svg.draw_text(
Point::new(200., 20.),
&format!("Last updated: {}", last_updated.to_rfc2822()),
&StyleAttr::simple(),
);
svg.finalize()
}
}
fn extract_msg_indices(trace: &Trace, gate_id: Uuid) -> String {
let (mut msg_indices, first, last) =
trace.msg_indices(gate_id, MsgRelation::ALL).iter().fold(
(String::new(), None::<usize>, None::<usize>),
|(mut out, mut first, mut last), idx| {
match (first, last) {
(None, None) => {
first = Some(*idx);
}
(None, Some(_l)) => unreachable!(),
(Some(f), None) => {
match *idx {
idx if idx == f + 1 => {
last = Some(idx);
}
idx if idx > f + 1 => {
if !out.is_empty() {
out.push_str(", ");
}
out.push_str(&format!("{}", f));
first = Some(idx);
}
_ => unreachable!(),
};
}
(Some(f), Some(l)) => {
match *idx {
idx if idx == l + 1 => {
last = Some(idx);
}
idx if idx > l + 1 => {
if !out.is_empty() {
out.push_str(", ");
}
out.push_str(&format!("{}-{}", f, l));
first = Some(idx);
last = None;
}
_ => {}
};
}
}
(out, first, last)
},
);
match (first, last) {
(None, None) => {}
(None, Some(_l)) => unreachable!(),
(Some(f), None) => {
if !msg_indices.is_empty() {
msg_indices.push_str(", ");
}
msg_indices.push_str(&format!("{}", f));
}
(Some(f), Some(l)) => {
if !msg_indices.is_empty() {
msg_indices.push_str(", ");
}
msg_indices.push_str(&format!("{}-{}", f, l));
}
}
format!("[{msg_indices}]")
}
#[derive(Clone, Default)]
pub struct UpstreamLinkReport {
links: Arc<Mutex<Option<Vec<LinkInfo>>>>,
// this is actually about downstream sending, not about upstream links ...
graph_status: Arc<Mutex<Option<Weak<dyn GraphStatus>>>>,
}
impl std::fmt::Debug for UpstreamLinkReport {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self.links.lock().unwrap().deref() {
Some(links) => {
let graph_status = self.graph_status.lock().unwrap();
f.debug_struct("UpstreamLinkReport")
.field("links", links)
.field("graph_status", &graph_status.is_some())
.finish()
}
_ => f.debug_struct("UpstreamLinkReport").finish(),
}
}
}
impl UpstreamLinkReport {
pub fn new() -> Self {
Default::default()
}
pub fn ready(&self) -> bool {
self.links.lock().unwrap().is_some()
}
pub fn set_sources<T>(&self, links: &NonEmpty<T>)
where
// this strange for<'a> &'a construct is a Higher-Rank Trait Bound and
// is needed here in order to express that a reference to T can be
// made into a LinkInfo, i.e. to match impl From<&Link> for LinkInfo {
// .. }.
for<'a> &'a T: Into<LinkInfo>,
{
let mut lock = self.links.lock().unwrap();
let typed_links = links.iter().map(|link| link.into()).collect();
lock.replace(typed_links);
}
pub fn set_source<T>(&self, link: &T)
where
// this strange for<'a> &'a construct is a Higher-Rank Trait Bound and
// is needed here in order to express that a reference to T can be
// made into a LinkInfo, i.e. to match impl From<&Link> for LinkInfo {
// .. }.
for<'a> &'a T: Into<LinkInfo>,
{
let mut lock = self.links.lock().unwrap();
lock.replace(vec![link.into()]);
}
/// Units that are themselves the source do not have upstream sources and
/// so should
/// notify via declare_source() that they have no sources.
pub fn declare_source(&self) {
let mut lock = self.links.lock().unwrap();
lock.replace(vec![]);
}
pub fn set_graph_status(&self, graph_status: Arc<dyn GraphStatus>) {
*self.graph_status.lock().unwrap() =
Some(Arc::downgrade(&graph_status));
}
pub fn graph_status(&self) -> Option<Weak<dyn GraphStatus>> {
self.graph_status.lock().unwrap().clone()
}
pub fn into_vec(&self) -> Vec<LinkInfo> {
if let Some(v) = self.links.lock().unwrap().as_ref() {
v.clone()
} else {
vec![]
}
}
}
#[allow(clippy::large_enum_variant)]
pub enum TargetCommand {
Reconfigure { new_config: Target },
ReportLinks { report: UpstreamLinkReport },
Terminate,
}
impl Display for TargetCommand {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
TargetCommand::Reconfigure { .. } => f.write_str("Reconfigure"),
TargetCommand::ReportLinks { .. } => f.write_str("ReportLinks"),
TargetCommand::Terminate => f.write_str("Terminate"),
}
}
}
/// A manager for components and auxiliary services.
///
/// Requires a running Tokio reactor that has been "entered" (see Tokio
/// `Handle::enter()`).
pub struct Manager {
/// The currently active units represented by agents to their gates.
running_units: HashMap<String, (Discriminant<Unit>, GateAgent)>,
/// The currently active targets represented by their command senders.
running_targets:
HashMap<String, (Discriminant<Target>, mpsc::Sender<TargetCommand>)>,
/// Gates for newly loaded, not yet spawned units.
pending_gates: HashMap<String, (Gate, GateAgent)>,
/// An HTTP client.
http_client: HttpClient,
/// The metrics collection maintained by this manager.
metrics: metrics::Collection,
/// The HTTP resources collection maintained by this manager.
http_resources: http::Resources,
/// A reference to the compiled Roto script.
roto_compiled: Option<Arc<CompiledRoto>>,
graph_svg_processor: Arc<dyn ProcessRequest>,
graph_svg_data: Arc<ArcSwap<(Instant, LinkReport)>>,
file_io: TheFileIo,
tracer: Arc<Tracer>,
tracer_processor: Arc<dyn ProcessRequest>,
ingresses: Arc<ingress::Register>,
}
impl Default for Manager {
fn default() -> Self {
Self::new()
}
}
impl Manager {
/// Creates a new manager.
pub fn new() -> Self {
let graph_svg_data = Arc::new(ArcSwap::from_pointee((
Instant::now(),
LinkReport::new(),
)));
let tracer = Arc::new(Tracer::new());
let ingresses = Arc::new(ingress::Register::new());
let (graph_svg_processor, graph_svg_rel_base_url) =
Self::mk_svg_http_processor(
graph_svg_data.clone(),
tracer.clone(),
);
let (tracer_processor, tracer_rel_base_url) =
Self::mk_tracer_http_processor(tracer.clone());
#[allow(
clippy::let_and_return,
clippy::default_constructed_unit_structs
)]
let manager = Manager {
running_units: Default::default(),
running_targets: Default::default(),
pending_gates: Default::default(),
http_client: Default::default(),
metrics: Default::default(),
http_resources: Default::default(),
roto_compiled: Default::default(),
graph_svg_processor,
graph_svg_data,
file_io: TheFileIo::default(),
tracer,
tracer_processor,
ingresses,
};
// Register the /status/graph endpoint.
manager.http_resources.register(
Arc::downgrade(&manager.graph_svg_processor),
"status_graph".into(),
"status_graph",
graph_svg_rel_base_url,
true,
);
manager.http_resources.register(
Arc::downgrade(&manager.tracer_processor),
"tracer".into(),
"tracer",
tracer_rel_base_url,
true,
);
manager
}
#[cfg(test)]
pub fn set_file_io(&mut self, file_io: TheFileIo) {
self.file_io = file_io;
}
/// Loads the given config file.
///
/// Parses the given file as a TOML config file. All links to units
/// referenced in the configuration are pre-connected.
///
/// If there are any errors in the config file, they are logged as errors
/// and a generic error is returned.
///
/// If the method succeeds, you need to call ['prepare'](Self::prepare)
/// followed by the [`spawn`](Self::spawn) method to spawn all units and
/// targets.
pub fn load(&mut self, file: &ConfigFile) -> Result<Config, Terminate> {
// Now load the config file, e.g. something like this:
//
// [units.a]
// type = "some-unit"
//
// [units.b]
// type = "other-unit"
// sources = ["a"]
//
// [targets.c]
// type = "some-target"
// upstream = "b"
//
// Results in something like this:
// unit unit target
// ┌───┐ ┌───┐ ┌───┐
// │ a │gate◀───link│ b │gate◀───link│ c │
// └───┘ └───┘ └───┘
//
// And where:
// link
// ▲
// │
// agent
// ▲
// │
// gate
// ▲
// │
// load
// unit
// ▲
// │
// load
// link
// ▲
// │
// unit◀───serde───▶target
// ▲
// │
// config
// file
// Where for Unit (and not shown here but similar for Target):
//
// #[derive(Debug, Deserialize)]
// #[serde(tag = "type")]
// pub enum Unit {
// #[serde(rename = "some-unit")] SomeUnit(SomeUnitConfig),
// #[serde(rename = "other-unit")] SomeUnit(OtherUnitConfig),
// ...
// }
//
// Deserializes into something like:
//
// #[derive(Deserialize)]
// pub struct Config {
// units: UnitSet { HashMap<String, Unit> }
// "a" --> Unit::SomeUnit{..}
// "b" --> Unit::OtherUnit{..}
//
// targets: TargetSet { HashMap<String, Target> }
// "c" --> Target::SomeTarget{..}
// }
//
// Where references to Link like: pub struct SomeUnit { sources:
// Vec<Link> } or: pub struct SomeTarget { upstream: Link }
//
// Are resolved via Serde like so:
//
// From<String> for Link via manager::load_link(name)
//
// Where manager::load_link(): - Creates a name -> LoadUnit entry in
// the static GATES map. - Each LoadUnit consists of a new Gate
// and GateAgent. - An MPSC channel is created, with: - The Gate
// getting the Receiver (RxGate) to receive commands. - The
// GateAgent getting the Sender (TxGate) for cloning to enable
// other parties to send commands to the Gate. - The GateAgent
// is used to create a Link, with: - The Link getting a clone
// of the Sender to send commands to the Gate.
//
// At this point **DISCONNECTED** Gates and Links have been created: -
// The Gates have not been given to Units yet so no data updates
// will be pushed (from Units) via the Gates. - The Gates have
// empty update Sender collections (Vec<TxUpdate>) so have no
// corresponding LinkConnection Receiver instances to send data
// updates to. - The Links have been given to Targets but not
// yet connected to Gates, i.e. have no LinkConnection Sender yet.
//
// To "wire up" these disconnected components: - Manager::spawn() will
// assign Gates to Units.
//
// - On first use Link::query() will invoke Link::connect() which
// will:
// - Construct a oneshot channel, keeping the Receiver
// (RxTemp) for itself, and passing the Sender (TxTemp) as
// the payload of a GateCommmand::Subscribe command to the
// Gate via the Links' cloned copy of TxGate.
// - The Gate will create a new MPSC channel and keep the
// Sender (TxUpdate) for itself and will pass the Receiver
// (RxUpdate) as the payload of a SubscribeResponse via
// TxTemp back to RxTemp.
// - TxTemp and RxTemp are discarded. The Gate now has a
// TxUpdate Sender which it can use to send data updates to
// to the RxUpdate Receiver which is now held by the Link
// (stored in a LinkConnection object).
Config::from_bytes(file.bytes(), file.dir()).map_err(|err| {
match file.path() {
Some(path) => error!("{}: {}", path.display(), err),
None => error!("{}", err),
}
Terminate::error()
})
}
/// Prepare for spawning.
///
/// Expects that the static GATES singleton has been populated with gates
/// (actually LoadUnit values mapped to the name of the unit they are for,
/// where a LoadUnit includes a Gate) for the units defined in the given
/// Config.
///
/// Primarily intended for testing purposes, allowing the prepare phase of
/// the load -> prepare -> spawn pipeline to be tested independently of
/// the other phases.
pub fn prepare(
&mut self,
config: &Config,
file: &ConfigFile,
) -> Result<(), Terminate> {
let roto_script =
config.roto_script.as_ref().and_then(|roto_script| {
file.path()
.and_then(|p| p.parent())
.map(|d| d.to_path_buf())
.map(|mut dir| {
dir.push(roto_script);
dir
})
});
if let Err(err) = self.compile_roto_script(&roto_script) {
let msg = format!("Unable to load main Roto script: {err}.");
error!("{msg}");
Err(Terminate::error())?
}
// Drain the singleton static GATES contents to a local variable.
let gates = GATES
.with(|gates| gates.replace(Some(Default::default())))
.unwrap();
// A Gate was created for each Link (e.g. for 'sources = ["a"]' and
// 'upstream = "b"') but does the config file define units with
// corresponding names ("a" and "b")? If not that means that the config
// file includes unresolvable links between components. For resolvable
// links the corresponding Gate will be moved to the pending
// collection to be handled later by spawn(). For unresolvable links
// the corresponding Gate will be dropped here.
for (name, load) in gates {
if let Some(mut gate) = load.gate {
gate.set_tracer(self.tracer.clone());
if !config.units.units.contains_key(&name) {
for mut link in load.links {
link.resolve_config(file);
error!(
"{}",
link.mark(format!(
"unresolved link to unit '{}'",
name
))
);
}
return Err(Terminate::error());
} else {
self.pending_gates
.insert(name.clone(), (gate, load.agent));
}
}
}
// At this point self.pending contains the newly created but
// disconnected Gates, and GateAgents for sending commands to them,
// and the Config object contains the newly created but not yet
// started Units and Targets. The caller should invoke spawn() to run
// each Unit and Target and assign Gates to Units by name.
Ok(())
}
pub fn compile_roto_script(
&mut self,
roto_scripts_path: &Option<std::path::PathBuf>,
) -> Result<(), String> {
let path = if let Some(p) = roto_scripts_path {
p
} else {
info!("no roto scripts path to load filters from");
return Ok(());
};
let i = roto::FileTree::read(path);
// .map_err(|e| e.to_string())?;
let c = i
.compile(create_runtime().unwrap())
.map_err(|e| e.to_string())?;
self.roto_compiled = Some(Arc::new(Mutex::new(c)));
Ok(())
}
/// Spawns all units and targets in the config into the given runtime.
///
/// # Panics
///
/// The method panics if the config hasn’t been successfully prepared via
/// the same manager earlier.
///
/// # Hot reloading
///
/// Running units and targets that do not exist in the config by the same
/// name, or exist by the same name but have a different type, will be
/// terminated.
///
/// Running units and targets with the same name and type as in the config
/// will be signalled to reconfigure themselves per the new config (even
/// if unchanged, it is the responsibility of the unit/target to decide
/// how to react to the "new" config).
///
/// Units receive the reconfigure signal via their gate. The gate will
/// automatically update itself and its clones to use the new set of
/// Senders that correspond to changes in the set of downstream units and
/// targets that link to the unit.
///
/// Units and targets receive changes to their set of links (if any) as
/// part of the "new" config payload of the reconfigure signal. It is the
/// responsibility of the unit/target to switch from the old links to the
/// new links and, if desired, to drain old link queues before ceasing to
/// query them further.
pub fn spawn(&mut self, config: &mut Config) {
self.spawn_internal(
config,
Self::spawn_unit,
Self::spawn_target,
Self::reconfigure_unit,
Self::reconfigure_target,
Self::terminate_unit,
Self::terminate_target,
)
}
/// Separated out from [spawn](Self::spawn) for testing purposes.
///
/// Pass the new unit to the existing unit to reconfigure itself. If the
/// set of downstream units and targets that refer to the unit being
/// reconfigured have changed, we need to ensure that the gates and links
/// in use correspond to the newly configured topology. For example:
///
/// Before:
///
/// ```text
/// unit target
/// ┌───┐ ┌───┐
/// │ a │gate◀─────────────────────────link│ c │
/// └───┘ └───┘
/// ```
/// After:
///
/// ```text
/// running:
/// --------
/// unit target
/// ┌───┐ ┌───┐
/// │ a │gate◀─────────────────────────link│ c │
/// └───┘ └───┘
///
/// pending:
/// --------
/// unit unit target
/// ┌───┐ ┌───┐ ┌───┐
/// │ a'│gate'◀───link'│ b'│gate'◀───link'│ c'│
/// └───┘ └───┘ └───┘
/// ```
/// In this example unit a and target c still exist in the config file,
/// possibly with changed settings, and new unit b has been added. The
/// pending gates and links for new units that correspond to existing
/// units are NOT the same links and gates, hence they have been marked in
/// the diagram with ' to distinguish them.
///
/// At this point we haven't started unit b' yet so what we actually have
/// is:
///
/// ```text
/// current:
/// --------
/// unit target
/// ┌───┐ ┌───┐
/// │ a │gate◀─────────────────────────link│ c │
/// └───┘ └───┘
///
/// unit unit target
/// ┌───┐ ┌───┐ ┌───┐
/// │ a'│gate◀╴╴╴╴link'│ b'│gate'◀╴╴╴link'│ c'│
/// └───┘ └───┘ └───┘
/// ```
/// Versus:
///
/// ```text
/// desired:
/// --------
/// unit unit target
/// ┌───┐ ┌───┐ ┌───┐
/// │ a │gate◀────link'│ b'│gate'◀───link'│ c │
/// └───┘ └───┘ └───┘
/// ```
/// If we blindly replace unit a with a' and target c with c' we risk
/// breaking existing connections or discarding state unnecessarily. So
/// instead we want the existing units and targets to decide for
/// themselves what needs to be done to adjust to the configuration
/// changes.
///
/// If we weren't reconfiguring unit a we wouldn't have a problem, the new
/// a' would correctly establish a link with the new b'. So it's unit a
/// that we have to fix.
///
/// Unit a has a gate with a data update Sender that corresponds with the
/// Receiver of the link held by target c. The gate of unit a may actually
/// have been cloned and thus there may be multiple Senders corresponding
/// to target c. The gate of unit a may also be linked to other links held
/// by other units and targets than in our simple example. We need to drop
/// the wrong data update Senders and replace them with new ones referring
/// to unit b' (well, at this point we don't know that it's unit b' we're
/// talking about, just that we want gate a to have the same update
/// Senders as gate a' (as all of the newly created gates and links have
/// the desired topological setup).
///
/// Note that the only way we have of influencing the data update senders
/// of clones to match changes we make to the update sender of the
/// original gate that was cloned is to send commands to the cloned gates.
///
/// So, to reconfigure units we send their gate a Reconfigure command
/// containing the new configuration. Note that this includes any newly
/// constructed Links so the unit can .close() its current link(s) to
/// prevent new incoming messages, process any messages still queued in
/// the link, then when Link::query() returns UnitStatus::Gone because the
/// queue is empty and the receiver is closed, we can at that point switch
/// to using the new links. This is done inside each unit.
///
/// The Reconfiguring GateStatus update will be propagated by the gate to
/// its clones, if any. This allows spawned tasks each handling a client
/// connection, e.g. from different routers, to each handle any
/// reconfiguration required in the best way.
///
/// For Targets we do something similar but as they don't have a Gate we
/// pass a new MPSC Channel receiver to them and hold the corresponding
/// sender here.
///
/// Finally, unit and/or target configurations that have been commented
/// out but for which a unit/target was already running, require that we
/// detect the missing config and send a Terminate command to the orphaned
/// unit/target.
#[allow(clippy::too_many_arguments)]
fn spawn_internal<
SpawnUnit,
SpawnTarget,
ReconfUnit,
ReconfTarget,
TermUnit,
TermTarget,
>(
&mut self,
config: &mut Config,
spawn_unit: SpawnUnit,
spawn_target: SpawnTarget,
reconfigure_unit: ReconfUnit,
reconfigure_target: ReconfTarget,
terminate_unit: TermUnit,
terminate_target: TermTarget,
) where
SpawnUnit: Fn(Component, Unit, Gate, WaitPoint),
SpawnTarget:
Fn(Component, Target, Receiver<TargetCommand>, WaitPoint),
ReconfUnit: Fn(&str, GateAgent, Unit, Gate),
ReconfTarget: Fn(&str, Sender<TargetCommand>, Target),
TermUnit: Fn(&str, Arc<GateAgent>),
TermTarget: Fn(&str, Arc<Sender<TargetCommand>>),
{
// We checked in load() for unresolvable links from units and targets
// to upstreams. Here we do the opposite, we check for created Units
// that are not referenced by any downstream units or targets. Any
// so-called "unused" unit will either be discarded, or if already
// running (due to a previous invocation of spawn()) will be commanded
// to terminate.
let mut new_running_units = HashMap::new();
let mut new_running_targets = HashMap::new();
let num_targets = config.targets.targets.len();
let num_units = config.units.units.len();
let coordinator = Coordinator::new(num_targets + num_units);
// Spawn, reconfigure and terminate targets according to the config
for (name, new_target) in config.targets.targets.drain() {
if let Some(running_target) = self.running_targets.remove(&name) {
let (running_target_type, running_target_sender) =
running_target;
let new_target_type = std::mem::discriminant(&new_target);
if new_target_type != running_target_type {
// Terminate the current target. The new one replacing it
// will be spawned below.
terminate_target(&name, running_target_sender.into());
} else {
reconfigure_target(
&name,
running_target_sender.clone(),
new_target,
);
new_running_targets.insert(
name,
(running_target_type, running_target_sender),
);
// Skip spawning a new target.
continue;
}
}
// Spawn the new target
let component = Component::new(
name.clone(),
new_target.type_name(),
self.http_client.clone(),
self.metrics.clone(),
self.http_resources.clone(),
self.roto_compiled.clone(),
self.tracer.clone(),
self.ingresses.clone(),
);
let target_type = std::mem::discriminant(&new_target);
let (cmd_tx, cmd_rx) = mpsc::channel(100);
spawn_target(
component,
new_target,
cmd_rx,
coordinator.clone().track(name.clone()),
);
new_running_targets.insert(name, (target_type, cmd_tx));
}
// Spawn, reconfigure and terminate units according to the config
for (name, new_unit) in config.units.units.drain() {
let (mut new_gate, new_agent) =
match self.pending_gates.remove(&name) {
Some((gate, agent)) => (gate, agent),
None => {
if let Some(running_unit) =
self.running_units.remove(&name)
{
warn!(
"Unit '{}' is unused and will be stopped.",
name
);
let running_unit_agent = running_unit.1;
terminate_unit(&name, running_unit_agent.into());
} else {
error!(
"Unit '{}' is unused and will not be started.",
name
);
}
continue;
}
};
new_gate.set_name(&name);
// For the Unit that was created for configuration file section
// [units.<name>], see if we already have a GateAgent for a Unit
// by that name, i.e. a Unit by that name is already running.
if let Some(running_unit) = self.running_units.remove(&name) {
// Yes, a Unit by that name is already running. Is it the same
// type? If so, command it to reconfigure itself to match the
// new Unit settings (if changed). Otherwise, command it to
// terminate as it will be replaced by a unit of the same name
// but different type.
let (running_unit_type, running_unit_agent) = running_unit;
let new_unit_type = std::mem::discriminant(&new_unit);
if new_unit_type != running_unit_type {
// Terminate the current unit. The new one replacing it
// will be launched below.
terminate_unit(&name, running_unit_agent.into());
} else {
reconfigure_unit(
&name,
running_unit_agent,
new_unit,
new_gate,
);
new_running_units
.insert(name, (new_unit_type, new_agent));
continue;
}
}
// Spawn the new unit
let component = Component::new(
name.clone(),
new_unit.type_name(),
self.http_client.clone(),
self.metrics.clone(),
self.http_resources.clone(),
self.roto_compiled.clone(),
self.tracer.clone(),
self.ingresses.clone(),
);
let unit_type = std::mem::discriminant(&new_unit);
spawn_unit(
component,
new_unit,
new_gate,
coordinator.clone().track(name.clone()),
);
new_running_units.insert(name, (unit_type, new_agent));
}
// Terminate running units whose corresponding configuration file
// block was removed or commented out and thus not encountered above.
for (name, (_, agent)) in self.running_units.drain() {
terminate_unit(&name, agent.into());
}
// Terminate running targets whose corresponding configuration file
// block was removed or commented out and thus not encountered above.
for (name, (_, cmd_tx)) in self.running_targets.drain() {
terminate_target(&name, cmd_tx.into());
}
self.running_units = new_running_units;
self.running_targets = new_running_targets;
self.coordinate_and_track_startup(coordinator);
}
fn coordinate_and_track_startup(
&mut self,
coordinator: Arc<Coordinator>,
) {
let mut reports = LinkReport::new();
let mut agent_cmd_futures = vec![];
let mut target_cmd_futures = vec![];
// Generate report-link commands to send to all running units.
for (name, (_unit_type, gate_agent)) in &self.running_units {
let report = UpstreamLinkReport::new();
reports.add_gate(name.clone(), gate_agent.id());
reports.add_link(name.clone(), report.clone());
let agent = gate_agent.clone();
let name = name.clone();
agent_cmd_futures.push(async move {
if let Err(err) = agent.report_links(report).await {
error!(
"Internal error: Report links command could not be sent to gate of unit '{}': {}",
name, err
);
}
});
}
// Generate report-link commands to send to all running targets.
for (name, (_target_type, cmd_sender)) in &self.running_targets {
let report = UpstreamLinkReport::new();
reports.add_link(name.clone(), report.clone());
let sender = cmd_sender.clone();
let name = name.clone();
target_cmd_futures.push(async move {
if let Err(err) = sender.send(TargetCommand::ReportLinks { report }).await {
error!(
"Internal error: Report links command could not be sent to target '{}': {}",
name, err
);
}
});
}
let graph_svg_data = self.graph_svg_data.clone();
crate::tokio::spawn("coordinator", async move {
// Wait for all running units and targets to become ready and to
// finish supplying responses to report-link commands, then log a
// link report at debug level, and generate an SVG representation
// of the link report for display at /status/graph.
debug!("Waiting for coodinator");
coordinator
.wait(|pending_component_names, status| {
warn!(
"Components {} are taking a long time to become {}.",
pending_component_names.join(", "),
status
);
})
.await;
// Now it's safe to send the report link commands. Before this
// point they might have been ignored because one or more units
// were not ready to process them yet.
for future in agent_cmd_futures {
future.await;
}
for future in target_cmd_futures {
future.await;
}
loop {
match reports.ready() {
Ok(()) => break,
Err(remaining) => {
trace!(
"Waiting for {} upstream link reports to become available.",
remaining
);
tokio::time::sleep(Duration::from_secs(1)).await;
}
}
}
if log_enabled!(log::Level::Debug) {
debug!(
"Dumping gate/link/unit/target relationships:\n{:#?}",
&reports
);
}
graph_svg_data.swap(Arc::new((Instant::now(), reports)));
});
}
pub fn link_report_updated_at(&self) -> Instant {
self.graph_svg_data.load().0
}
pub fn terminate(&mut self) {
for (name, (_, agent)) in self.running_units.drain() {
let agent = Arc::new(agent);
Self::terminate_unit(&name, agent.clone());
while !agent.is_terminated() {
std::thread::sleep(Duration::from_millis(10));
}
}
for (name, (_, cmd_tx)) in self.running_targets.drain() {
let cmd_tx = Arc::new(cmd_tx);
Self::terminate_target(&name, cmd_tx.clone());
while !cmd_tx.is_closed() {
std::thread::sleep(Duration::from_millis(10));
}
}
}
fn spawn_unit(
component: Component,
new_unit: Unit,
new_gate: Gate,
waitpoint: WaitPoint,
) {
info!("Starting unit '{}'", component.name);
crate::tokio::spawn(
&format!("unit[{}]", component.name),
new_unit.run(component, new_gate, waitpoint),
);
}
fn spawn_target(
component: Component,
new_target: Target,
cmd_rx: Receiver<TargetCommand>,
waitpoint: WaitPoint,
) {
info!("Starting target '{}'", component.name);
crate::tokio::spawn(
&format!("target[{}]", component.name),
new_target.run(component, cmd_rx, waitpoint),
);
}
fn reconfigure_unit(
name: &str,
agent: GateAgent,
new_config: Unit,
new_gate: Gate,
) {
info!("Reconfiguring unit '{}'", name);
let name = name.to_owned();
crate::tokio::spawn("unit-reconfigurer", async move {
if let Err(err) = agent.reconfigure(new_config, new_gate).await {
error!(
"Internal error: reconfigure command could not be sent to unit '{}': {}",
name, err
);
}
});
}
fn reconfigure_target(
name: &str,
sender: Sender<TargetCommand>,
new_config: Target,
) {
info!("Reconfiguring target '{}'", name);
let name = name.to_owned();
crate::tokio::spawn("target-reconfigurer", async move {
if let Err(err) =
sender.send(TargetCommand::Reconfigure { new_config }).await
{
error!(
"Internal error: reconfigure command could not be sent to target '{}': {}",
name, err
);
}
});
}
fn terminate_unit(name: &str, agent: Arc<GateAgent>) {
info!("Stopping unit '{}'", name);
crate::tokio::spawn("unit-terminator", async move {
agent.terminate().await;
});
}
fn terminate_target(name: &str, sender: Arc<Sender<TargetCommand>>) {
info!("Stopping target '{}'", name);
crate::tokio::spawn("target-terminator", async move {
let _ = sender.send(TargetCommand::Terminate).await;
});
}
/// Returns a new reference to the manager’s metrics collection.
pub fn metrics(&self) -> metrics::Collection {
self.metrics.clone()
}
/// Returns a new reference the the HTTP resources collection.
pub fn http_resources(&self) -> http::Resources {
self.http_resources.clone()
}
// Create a HTTP processor that renders the SVG unit/target configuration graph.
fn mk_svg_http_processor(
graph_svg_data: Arc<arc_swap::ArcSwapAny<Arc<(Instant, LinkReport)>>>,
tracer: Arc<Tracer>,
) -> (Arc<dyn ProcessRequest>, &'static str) {
const REL_BASE_URL: &str = "/status/graph";
let processor = Arc::new(move |request: &Request<_>| {
let req_path = request.uri().decoded_path();
if request.method() == Method::GET
&& req_path.starts_with(REL_BASE_URL)
{
let (_base_path, restant) =
req_path.split_at(REL_BASE_URL.len());
let trace_id = if restant.contains("/traces/") {
restant.split_at("/traces/".len()).1.parse::<u8>().ok()
} else {
None
};
let svg =
graph_svg_data.load().1.get_svg(tracer.clone(), trace_id);
let traces = if let Some(trace_id) = trace_id {
let trace = tracer.get_trace(trace_id);
let mut traces_html = format!(
r###"
<p>Showing pipeline route and processing details of trace {trace_id}:</p>
<table>
<tr>
<th>#</th>
<th>When</th>
<th>What</th>
</tr>
"###
);
for (idx, msg) in trace.msgs().iter().enumerate() {
traces_html.push_str(&format!(
r###"
<tr>
<td>{idx}</td>
<td>{}</td>
<td><pre>{}</pre></td>
</tr>
"###,
msg.timestamp, msg.msg
));
}
traces_html.push_str("</table>\n");
traces_html
} else {
String::new()
};
let html = format!(
r###"
<html lang="en">
<head>
<meta charset="UTF-8">
<style>
table {{
border-collapse: collapse;
}}
th, td {{
border: 1px solid black;
padding: 2px 20px 2px 20px;
}}
</style>
</head>
<body>
<svg xmlns="http://www.w3.org/2000/svg" style="width: 100%; height: 300px;">
{svg}
</svg>
{traces}
</body>
</html>
"###
);
let body = Body::from(html);
let response = Response::builder()
.status(hyper::StatusCode::OK)
.header("Content-Type", "text/html")
.body(body)
.unwrap();
Some(response)
} else {
None
}
});
(processor, REL_BASE_URL)
}
fn mk_tracer_http_processor(
tracer: Arc<Tracer>,
) -> (Arc<dyn ProcessRequest>, &'static str) {
const REL_BASE_URL: &str = "/status/traces";
let processor = Arc::new(move |request: &Request<_>| {
let req_path = request.uri().decoded_path();
if request.method() == Method::GET && req_path == REL_BASE_URL {
let response = Response::builder()
.status(hyper::StatusCode::OK)
.header("Content-Type", "text/plain")
.body(Body::from(format!("{tracer:#?}")))
.unwrap();
Some(response)
} else {
None
}
});
(processor, REL_BASE_URL)
}
}
//------------ Checkpoint ----------------------------------------------------
pub struct WaitPoint {
coordinator: Arc<Coordinator>,
name: String,
ready: bool,
}
impl WaitPoint {
pub fn new(coordinator: Arc<Coordinator>, name: String) -> Self {
Self {
coordinator,
name,
ready: false,
}
}
pub async fn ready(&mut self) {
self.coordinator.clone().ready(&self.name).await;
self.ready = true;
}
pub async fn running(mut self) {
// Targets don't need to signal ready & running separately so they
// just invoke this fn, but we still need to make sure that the
// barrier is reached twice otherwise the client of the Coordinator
// will be left waiting forever.
if !self.ready {
self.ready().await;
}
self.coordinator.ready(&self.name).await
}
}
pub struct Coordinator {
barrier: Barrier,
max_components: usize,
pending: Arc<RwLock<HashSet<String>>>,
}
impl Coordinator {
pub const SLOW_COMPONENT_ALARM_DURATION: Duration =
Duration::from_secs(60);
pub fn new(max_components: usize) -> Arc<Self> {
let barrier = Barrier::new(max_components + 1);
let pending = Arc::new(RwLock::new(HashSet::new()));
Arc::new(Self {
barrier,
max_components,
pending,
})
}
pub fn track(self: Arc<Self>, name: String) -> WaitPoint {
if self.pending.write().unwrap().insert(name.clone()) {
if self.pending.read().unwrap().len() > self.max_components {
panic!(
"Coordinator::track() called more times than expected"
);
}
WaitPoint::new(self, name)
} else {
unreachable!();
}
}
// Note: should be invoked twice:
// - The first time the the units and targets reach the barrier when all
// are ready. The barrier is then automatically reset and ready for
// use again.
// - The second time the units and targets reach the barrier when all
// are running.
pub async fn ready(self: Arc<Self>, name: &str) {
if self
.pending
.read()
.unwrap()
.get(&name.to_string())
.is_some()
{
self.barrier.wait().await;
} else {
unreachable!();
}
}
pub async fn wait<T>(self: Arc<Self>, mut alarm: T)
where
T: FnMut(Vec<String>, &str),
{
// Units and targets need to reach the barrier twice: once to signal
// that they are ready to run but are not yet actually running, and
// once when they are running.
self.clone().wait_internal(&mut alarm, "ready").await;
self.wait_internal(&mut alarm, "running").await;
}
pub async fn wait_internal<T>(
self: Arc<Self>,
alarm: &mut T,
status: &str,
) where
T: FnMut(Vec<String>, &str),
{
debug!("Waiting for all components to become {}...", status);
let num_unused_barriers =
self.max_components - self.pending.read().unwrap().len() + 1;
let unused_barriers: Vec<_> = (0..num_unused_barriers)
.map(|_| self.barrier.wait())
.collect();
let slow_startup_alarm =
Box::pin(tokio::time::sleep(Self::SLOW_COMPONENT_ALARM_DURATION));
match select(join_all(unused_barriers), slow_startup_alarm).await {
Either::Left(_) => {}
Either::Right((_, incomplete_join_all)) => {
// Raise the alarm about the slow components
let pending_component_names = self
.pending
.read()
.unwrap()
.iter()
.cloned()
.collect::<Vec<String>>();
alarm(pending_component_names, status);
// Previous wait was interrupted, keep waiting
incomplete_join_all.await;
}
}
info!("All components are {}.", status);
}
}
//------------ UnitSet -------------------------------------------------------
/// A set of units to be started.
#[derive(Deserialize)]
#[serde(transparent)]
pub struct UnitSet {
units: HashMap<String, Unit>,
}
impl UnitSet {
pub fn units(&self) -> &HashMap<String, Unit> {
&self.units
}
}
impl From<HashMap<String, Unit>> for UnitSet {
fn from(v: HashMap<String, Unit>) -> Self {
Self { units: v }
}
}
//------------ TargetSet -----------------------------------------------------
/// A set of targets to be started.
#[derive(Default, Deserialize)]
#[serde(transparent)]
pub struct TargetSet {
targets: HashMap<String, Target>,
}
impl TargetSet {
pub fn new() -> Self {
Default::default()
}
pub fn targets(&self) -> &HashMap<String, Target> {
&self.targets
}
}
impl From<HashMap<String, Target>> for TargetSet {
fn from(v: HashMap<String, Target>) -> Self {
Self { targets: v }
}
}
//------------ LoadUnit ------------------------------------------------------
/// A unit referenced during loading.
struct LoadUnit {
/// The gate of the unit.
///
/// This is some only if the unit is newly created and has not yet been
/// spawned onto a runtime.
gate: Option<Gate>,
/// A gate agent for the unit.
agent: GateAgent,
/// A list of location of links in the config.
///
/// This is only used for generating errors if non-existing units are
/// referenced in the config file.
links: Vec<Marked<()>>,
}
impl LoadUnit {
fn new(queue_size: usize) -> Self {
let (gate, agent) = Gate::new(queue_size);
LoadUnit {
gate: Some(gate),
agent,
links: Vec::new(),
}
}
}
impl From<GateAgent> for LoadUnit {
fn from(agent: GateAgent) -> Self {
LoadUnit {
gate: None,
agent,
links: Vec::new(),
}
}
}
//------------ Loading Links -------------------------------------------------
thread_local!(
static GATES: RefCell<Option<HashMap<String, LoadUnit>>> =
RefCell::new(Some(Default::default()))
);
/// Loads a link with the given name.
///
/// # Panics
///
/// This function panics if it is called outside of a run of
/// [`Manager::load`].
pub fn load_link(link_id: Marked<String>) -> Link {
GATES.with(|gates| {
let mut gates = gates.borrow_mut();
let gates = gates.as_mut().unwrap();
let mark = link_id.mark(());
let link_id = link_id.into_inner();
let (name, queue_size) = get_queue_size_for_link(link_id);
let unit = gates
.entry(name)
.or_insert_with(|| LoadUnit::new(queue_size));
unit.links.push(mark);
unit.agent.create_link()
})
}
/// Support link names of the form <name>:<queue_size> where queue_size is an
/// unsigned integer value.
///
/// TODO: Don't overload the meaning of the link name, instead support a
/// richer more meaningful configuration syntax for configuring the queue
/// size.
fn get_queue_size_for_link(link_id: String) -> (String, usize) {
let (name, queue_size) =
if let Some((name, options)) = link_id.split_once(':') {
let queue_len = options.parse::<usize>().unwrap_or_else(|err| {
warn!(
"Invalid queue length '{}' for '{}', falling back to the \
default ({}): {}",
options, name, DEF_UPDATE_QUEUE_LEN, err
);
DEF_UPDATE_QUEUE_LEN
});
(name.to_string(), queue_len)
} else {
(link_id, DEF_UPDATE_QUEUE_LEN)
};
(name, queue_size)
}
//------------ Loading FilterName --------------------------------------------
thread_local!(
static ROTO_FILTER_NAMES: RefCell<Option<HashSet<FilterName>>> =
RefCell::new(Some(Default::default()))
);
/// Loads a filter name with the given name.
///
/// # Panics
///
/// This function panics if it is called outside of a run of
/// [`Manager::load`].
pub fn load_filter_name(filter_name: FilterName) -> FilterName {
ROTO_FILTER_NAMES.with(|filter_names| {
let mut filter_names = filter_names.borrow_mut();
let filter_names = filter_names.as_mut().unwrap();
filter_names.insert(filter_name.clone());
filter_name
})
}
//------------ Tests ---------------------------------------------------------
#[cfg(test)]
mod tests {
use std::{
fmt::Display,
ops::{Deref, DerefMut},
sync::atomic::{AtomicU8, Ordering::SeqCst},
};
use super::*;
use crate::config::Source;
static SOME_COMPONENT: &str = "some-component";
static OTHER_COMPONENT: &str = "other-component";
// #[test]
// fn gates_singleton_is_correctly_initialized() {
// let gates = GATES.with(|gates| gates.take());
// assert!(gates.is_some());
// assert!(gates.unwrap().is_empty());
// }
// #[test]
// fn new_manager_is_correctly_initialized() {
// let manager = init_manager();
// assert!(manager.running_units.is_empty());
// assert!(manager.running_targets.is_empty());
// assert!(manager.pending_gates.is_empty());
// }
// #[test]
// fn config_without_target_should_fail() {
// // given a config without any targets
// let toml = r#"
// http_listen = []
// "#;
// let config_file = mk_config_from_toml(toml);
// // when loaded into the manager
// let mut manager = init_manager();
// let res = Config::from_config_file(config_file, &mut manager);
// // then it should fail
// assert!(res.is_err());
// }
// #[test]
// fn config_with_unresolvable_links_should_fail() {
// // given a config with only a single target with a link to a
// // missing unit
// let toml = r#"
// http_listen = []
// [targets.null]
// type = "null-out"
// source = "missing-unit"
// "#;
// let config_file = mk_config_from_toml(toml);
// // when loaded into the manager
// let mut manager = init_manager();
// let res = Config::from_config_file(config_file, &mut manager);
// // then it should fail
// assert!(res.is_err());
// }
// #[test]
// fn config_with_unresolvable_filter_names_should_fail() {
// // given a config with only unit that takes a filter_name
// // referring to a roto filter that has not been loaded
// let toml = r#"
// http_listen = []
// [units.filter]
// type = "filter"
// filter_name = "i-dont-exist"
// [targets.null]
// type = "null-out"
// source = "missing-unit"
// "#;
// let config_file = mk_config_from_toml(toml);
// // when loaded into the manager
// let mut manager = init_manager();
// let res = Config::from_config_file(config_file, &mut manager);
// // then it should fail
// assert!(res.is_err());
// }
// #[test]
// fn fully_resolvable_config_should_load() {
// let toml = r#"
// http_listen = []
// [units.some-unit]
// type = "bmp-tcp-in"
// listen = ""
// [targets.null]
// type = "null-out"
// source = "some-unit"
// "#;
// let config_file = mk_config_from_toml(toml);
// // when loaded into the manager
// let mut manager = init_manager();
// let res = Config::from_config_file(config_file, &mut manager);
// // then it should pass
// assert!(res.is_ok());
// }
// #[tokio::test(flavor = "multi_thread")]
// async fn fully_resolvable_config_should_spawn() -> Result<(), Terminate> {
// // given a config with only a single target with a link to a missing unit
// let toml = r#"
// http_listen = []
// [units.some-unit]
// type = "bmp-tcp-in"
// listen = ""
// [targets.null]
// type = "null-out"
// source = "some-unit"
// "#;
// let config_file = mk_config_from_toml(toml);
// // when loaded into the manager and spawned
// let mut manager = init_manager();
// let (_source, config) = Config::from_config_file(config_file, &mut manager)?;
// spawn(&mut manager, config);
// // then it should spawn the unit and target
// let log = SPAWN_LOG.with(|log| log.take());
// assert_eq!(log.len(), 2);
// assert_log_contains(&log, "some-unit", SpawnAction::SpawnUnit);
// assert_log_contains(&log, "null", SpawnAction::SpawnTarget);
// Ok(())
// }
// #[tokio::test(flavor = "multi_thread")]
// async fn config_reload_should_trigger_reconfigure() -> Result<(), Terminate> {
// // given a config with only a single target with a link to a missing unit
// let toml = r#"
// http_listen = []
// [units.some-unit]
// type = "bmp-tcp-in"
// listen = ""
// [targets.null]
// type = "null-out"
// source = "some-unit"
// "#;
// let config_file = mk_config_from_toml(toml);
// // when loaded into the manager and spawned
// let mut manager = init_manager();
// let (_source, config) = Config::from_config_file(config_file.clone(), &mut manager)?;
// spawn(&mut manager, config);
// // then it should spawn the unit and target
// let log = SPAWN_LOG.with(|log| log.take());
// assert_eq!(log.len(), 2);
// assert_log_contains(&log, "some-unit", SpawnAction::SpawnUnit);
// assert_log_contains(&log, "null", SpawnAction::SpawnTarget);
// // and when re-loaded
// let (_source, config) = Config::from_config_file(config_file, &mut manager)?;
// spawn(&mut manager, config);
// // it should cause reconfiguration
// let log = SPAWN_LOG.with(|log| log.take());
// assert_eq!(log.len(), 2);
// assert_log_contains(&log, "some-unit", SpawnAction::ReconfigureUnit);
// assert_log_contains(&log, "null", SpawnAction::ReconfigureTarget);
// Ok(())
// }
// #[tokio::test(flavor = "multi_thread")]
// async fn unused_unit_should_not_be_spawned() -> Result<(), Terminate> {
// // given a config with only a single target with a link to a missing unit
// let toml = r#"
// http_listen = []
// [units.unused-unit]
// type = "bmp-tcp-in"
// listen = ""
// [units.some-unit]
// type = "bmp-tcp-in"
// listen = ""
// [targets.null]
// type = "null-out"
// source = "some-unit"
// "#;
// let config_file = mk_config_from_toml(toml);
// // when loaded into the manager and spawned
// let mut manager = init_manager();
// let (_source, config) = Config::from_config_file(config_file, &mut manager)?;
// spawn(&mut manager, config);
// // then it should spawn the unit and target
// let log = SPAWN_LOG.with(|log| log.take());
// assert_eq!(log.len(), 2);
// assert_log_contains(&log, "some-unit", SpawnAction::SpawnUnit);
// assert_log_contains(&log, "null", SpawnAction::SpawnTarget);
// Ok(())
// }
// #[tokio::test(flavor = "multi_thread")]
// async fn added_target_should_be_spawned() -> Result<(), Terminate> {
// // given a config with only a single target with a link to a single unit
// let toml = r#"
// http_listen = []
// [units.some-unit]
// type = "bmp-tcp-in"
// listen = ""
// [targets.null]
// type = "null-out"
// source = "some-unit"
// "#;
// let config_file = mk_config_from_toml(toml);
// // when loaded into the manager and spawned
// let mut manager = init_manager();
// let (_source, config) = Config::from_config_file(config_file, &mut manager)?;
// spawn(&mut manager, config);
// // then it should spawn the unit and target
// let log = SPAWN_LOG.with(|log| log.take());
// assert_eq!(log.len(), 2);
// assert_log_contains(&log, "some-unit", SpawnAction::SpawnUnit);
// assert_log_contains(&log, "null", SpawnAction::SpawnTarget);
// // when the config is modified to include a new target
// let toml = r#"
// http_listen = []
// [units.some-unit]
// type = "bmp-tcp-in"
// listen = ""
// [targets.null]
// type = "null-out"
// source = "some-unit"
// [targets.null2]
// type = "null-out"
// source = "some-unit"
// "#;
// let config_file = mk_config_from_toml(toml);
// // when loaded into the manager and spawned
// let (_source, config) = Config::from_config_file(config_file, &mut manager)?;
// spawn(&mut manager, config);
// // then it should spawn the added target
// let log = SPAWN_LOG.with(|log| log.take());
// assert_eq!(log.len(), 3);
// assert_log_contains(&log, "some-unit", SpawnAction::ReconfigureUnit);
// assert_log_contains(&log, "null", SpawnAction::ReconfigureTarget);
// assert_log_contains(&log, "null2", SpawnAction::SpawnTarget);
// Ok(())
// }
// #[tokio::test(flavor = "multi_thread")]
// async fn removed_target_should_be_terminated() -> Result<(), Terminate> {
// // given a config with only a single target with a link to a missing unit
// let toml = r#"
// http_listen = []
// [units.some-unit]
// type = "bmp-tcp-in"
// listen = ""
// [targets.null]
// type = "null-out"
// source = "some-unit"
// [targets.null2]
// type = "null-out"
// source = "some-unit"
// "#;
// let config_file = mk_config_from_toml(toml);
// // when loaded into the manager and spawned
// let mut manager = init_manager();
// let (_source, config) = Config::from_config_file(config_file, &mut manager)?;
// spawn(&mut manager, config);
// // then it should spawn the unit and target
// let log = SPAWN_LOG.with(|log| log.take());
// assert_eq!(log.len(), 3);
// assert_log_contains(&log, "some-unit", SpawnAction::SpawnUnit);
// assert_log_contains(&log, "null", SpawnAction::SpawnTarget);
// assert_log_contains(&log, "null2", SpawnAction::SpawnTarget);
// // when the config is modified to remove a target
// let toml = r#"
// http_listen = []
// [units.some-unit]
// type = "bmp-tcp-in"
// listen = ""
// #[targets.null]
// #type = "null-out"
// #source = "some-unit"
// [targets.null2]
// type = "null-out"
// source = "some-unit"
// "#;
// let config_file = mk_config_from_toml(toml);
// // when loaded into the manager and spawned
// let (_source, config) = Config::from_config_file(config_file, &mut manager)?;
// spawn(&mut manager, config);
// // then it should terminate the removed target
// let log = SPAWN_LOG.with(|log| log.take());
// assert_eq!(log.len(), 3);
// assert_log_contains(&log, "some-unit", SpawnAction::ReconfigureUnit);
// assert_log_contains(&log, "null", SpawnAction::TerminateTarget);
// assert_log_contains(&log, "null2", SpawnAction::ReconfigureTarget);
// // Note: we don't check that the gate of some-unit has been updated to
// // remove the Sender for the Link to target null because that is logic
// // within the Gate itself and should be tested in the Gate unit tests.
// Ok(())
// }
// #[tokio::test(flavor = "multi_thread")]
// async fn modified_settings_are_correctly_announced() -> Result<(), Terminate> {
// // given a config with only a single target with a link to a missing unit
// let toml = r#"
// http_listen = []
// [units.some-unit]
// type = "bmp-tcp-in"
// listen = ""
// [targets.null]
// type = "null-out"
// source = "some-unit"
// "#;
// let config_file = mk_config_from_toml(toml);
// // when loaded into the manager and spawned
// let mut manager = init_manager();
// let (_source, config) = Config::from_config_file(config_file, &mut manager)?;
// spawn(&mut manager, config);
// // then it should spawn the unit and target
// let log = SPAWN_LOG.with(|log| log.take());
// assert_eq!(log.len(), 2);
// assert_log_contains(&log, "some-unit", SpawnAction::SpawnUnit);
// assert_log_contains(&log, "null", SpawnAction::SpawnTarget);
// // when the config is modified
// let toml = r#"
// http_listen = []
// [units.some-unit]
// type = "bmp-tcp-in"
// listen = "changed"
// [targets.null]
// type = "null-out"
// source = "some-unit"
// "#;
// let config_file = mk_config_from_toml(toml);
// // when loaded into the manager and spawned
// let (_source, config) = Config::from_config_file(config_file, &mut manager)?;
// spawn(&mut manager, config);
// // then it should terminate the removed target
// let log = SPAWN_LOG.with(|log| log.take());
// assert_eq!(log.len(), 2);
// assert_log_contains(&log, "some-unit", SpawnAction::ReconfigureUnit);
// assert_log_contains(&log, "null", SpawnAction::ReconfigureTarget);
// let item = get_log_item(&log, "some-unit", SpawnAction::ReconfigureUnit);
// if let UnitOrTargetConfig::UnitConfig(Unit::BmpTcpIn(config)) = &item.config {
// assert_eq!(config.listen, "changed");
// } else {
// unreachable!();
// }
// Ok(())
// }
// #[tokio::test]
// async fn coordinator_with_no_components_should_finish_immediately() {
// let coordinator = Coordinator::new(0);
// let mut alarm_fired = false;
// coordinator.wait(|_, _| alarm_fired = true).await;
// assert!(!alarm_fired);
// }
// #[tokio::test]
// #[should_panic]
// async fn coordinator_track_too_many_components_causes_panic() {
// let coordinator = Coordinator::new(0);
// coordinator.track(SOME_COMPONENT.to_string());
// }
// #[tokio::test]
// #[should_panic]
// async fn coordinator_track_component_twice_causes_panic() {
// let coordinator = Coordinator::new(0);
// coordinator.clone().track(SOME_COMPONENT.to_string());
// coordinator.track(SOME_COMPONENT.to_string());
// }
// #[tokio::test]
// #[should_panic]
// async fn coordinator_unknown_ready_component_twice_causes_panic() {
// let coordinator = Coordinator::new(0);
// coordinator.ready(SOME_COMPONENT).await;
// }
// #[tokio::test(start_paused = true)]
// async fn coordinator_with_one_ready_component_should_not_raise_alarm() {
// let coordinator = Coordinator::new(1);
// let mut alarm_fired = false;
// let wait_point = coordinator.clone().track(SOME_COMPONENT.to_string());
// let join_handle = tokio::task::spawn(wait_point.running());
// assert!(!join_handle.is_finished());
// coordinator.wait(|_, _| alarm_fired = true).await;
// join_handle.await.unwrap();
// assert!(!alarm_fired);
// }
// #[tokio::test(start_paused = true)]
// async fn coordinator_with_two_ready_components_should_not_raise_alarm() {
// let coordinator = Coordinator::new(2);
// let mut alarm_fired = false;
// let wait_point1 = coordinator.clone().track(SOME_COMPONENT.to_string());
// let wait_point2 = coordinator.clone().track(OTHER_COMPONENT.to_string());
// let join_handle1 = tokio::task::spawn(wait_point1.running());
// let join_handle2 = tokio::task::spawn(wait_point2.running());
// assert!(!join_handle1.is_finished());
// assert!(!join_handle2.is_finished());
// coordinator.wait(|_, _| alarm_fired = true).await;
// join_handle1.await.unwrap();
// join_handle2.await.unwrap();
// assert!(!alarm_fired);
// }
// #[tokio::test(start_paused = true)]
// async fn coordinator_with_component_with_slow_ready_phase_should_raise_alarm() {
// let coordinator = Coordinator::new(1);
// let alarm_fired_count = Arc::new(AtomicU8::new(0));
// let wait_point = coordinator.clone().track(SOME_COMPONENT.to_string());
// // Deliberately don't call wait_point.ready() or wait_point.running()
// let join_handle = {
// let alarm_fired_count = alarm_fired_count.clone();
// tokio::task::spawn(coordinator.wait(move |_, _| {
// alarm_fired_count.fetch_add(1, Ordering::Relaxed);
// }))
// };
// // Advance time beyond the maximum time allowed for the 'ready' state to be reached
// let advance_time_by = Coordinator::SLOW_COMPONENT_ALARM_DURATION;
// let advance_time_by = advance_time_by.checked_add(Duration::from_secs(1)).unwrap();
// tokio::time::sleep(advance_time_by).await;
// // Check that the alarm fired once
// assert_eq!(alarm_fired_count.load(Ordering::Relaxed), 1);
// // Set the component state to the final state 'running'
// wait_point.running().await;
// // Which should unblock the coordinator wait
// join_handle.await.unwrap();
// }
// #[tokio::test(start_paused = true)]
// async fn coordinator_with_component_with_slow_running_phase_should_raise_alarm() {
// let coordinator = Coordinator::new(1);
// let alarm_fired_count = Arc::new(AtomicU8::new(0));
// let mut wait_point = coordinator.clone().track(SOME_COMPONENT.to_string());
// // Deliberately don't call wait_point.ready() or wait_point.running()
// let join_handle = {
// let alarm_fired_count = alarm_fired_count.clone();
// tokio::task::spawn(coordinator.wait(move |_, _| {
// alarm_fired_count.fetch_add(1, Ordering::Relaxed);
// }))
// };
// // Advance time beyond the maximum time allowed for the 'ready' state to be reached
// let advance_time_by = Coordinator::SLOW_COMPONENT_ALARM_DURATION;
// let advance_time_by = advance_time_by.checked_add(Duration::from_secs(1)).unwrap();
// tokio::time::sleep(advance_time_by).await;
// // Check that the alarm fired once
// assert_eq!(alarm_fired_count.load(Ordering::Relaxed), 1);
// // Achieve the 'ready' state in the component under test, but not yet the 'running' state
// wait_point.ready().await;
// // Advance time beyond the maximum time allowed for the 'running' state to be reached
// let advance_time_by = Coordinator::SLOW_COMPONENT_ALARM_DURATION;
// let advance_time_by = advance_time_by.checked_add(Duration::from_secs(1)).unwrap();
// tokio::time::sleep(advance_time_by).await;
// // Check that the alarm fired again
// assert_eq!(alarm_fired_count.load(Ordering::Relaxed), 2);
// // Set the component state to the final state 'running'
// wait_point.running().await;
// // Which should unblock the coordinator wait
// join_handle.await.unwrap();
// }
use uuid::Uuid;
use crate::{
manager::extract_msg_indices,
tracing::{MsgRelation, Trace},
};
#[test]
fn test_empty_extract_msg_indices() {
let empty_trace = Trace::new();
let gate_id = Uuid::new_v4();
let trace_txt = extract_msg_indices(&empty_trace, gate_id);
assert_eq!("[]", trace_txt);
}
#[test]
fn test_single_extract_msg_indices() {
let mut empty_trace = Trace::new();
let gate_id = Uuid::new_v4();
empty_trace.append_msg(gate_id, "blah".to_owned(), MsgRelation::GATE);
let trace_txt = extract_msg_indices(&empty_trace, gate_id);
assert_eq!("[0]", trace_txt);
}
#[test]
fn test_long_range_extract_msg_indices() {
let mut empty_trace = Trace::new();
let gate_id = Uuid::new_v4();
empty_trace.append_msg(gate_id, "blah".to_owned(), MsgRelation::GATE);
empty_trace.append_msg(gate_id, "blah".to_owned(), MsgRelation::GATE);
empty_trace.append_msg(gate_id, "blah".to_owned(), MsgRelation::GATE);
let trace_txt = extract_msg_indices(&empty_trace, gate_id);
assert_eq!("[0-2]", trace_txt);
}
#[test]
fn test_single_range_extract_msg_indices() {
let mut empty_trace = Trace::new();
let gate_id = Uuid::new_v4();
empty_trace.append_msg(gate_id, "blah".to_owned(), MsgRelation::GATE);
empty_trace.append_msg(gate_id, "blah".to_owned(), MsgRelation::GATE);
let trace_txt = extract_msg_indices(&empty_trace, gate_id);
assert_eq!("[0-1]", trace_txt);
}
#[test]
fn test_single_then_range_extract_msg_indices() {
let mut empty_trace = Trace::new();
let gate_id1 = Uuid::new_v4();
let gate_id2 = Uuid::new_v4();
empty_trace.append_msg(
gate_id2,
"blah".to_owned(),
MsgRelation::GATE,
);
empty_trace.append_msg(
gate_id1,
"blah".to_owned(),
MsgRelation::GATE,
);
empty_trace.append_msg(
gate_id2,
"blah".to_owned(),
MsgRelation::GATE,
);
empty_trace.append_msg(
gate_id2,
"blah".to_owned(),
MsgRelation::GATE,
);
let trace_txt = extract_msg_indices(&empty_trace, gate_id2);
assert_eq!("[0, 2-3]", trace_txt);
}
#[test]
fn test_single_range_single_extract_msg_indices() {
let mut empty_trace = Trace::new();
let gate_id1 = Uuid::new_v4();
let gate_id2 = Uuid::new_v4();
empty_trace.append_msg(
gate_id2,
"blah".to_owned(),
MsgRelation::GATE,
);
empty_trace.append_msg(
gate_id1,
"blah".to_owned(),
MsgRelation::GATE,
);
empty_trace.append_msg(
gate_id2,
"blah".to_owned(),
MsgRelation::GATE,
);
empty_trace.append_msg(
gate_id2,
"blah".to_owned(),
MsgRelation::GATE,
);
empty_trace.append_msg(
gate_id1,
"blah".to_owned(),
MsgRelation::GATE,
);
empty_trace.append_msg(
gate_id2,
"blah".to_owned(),
MsgRelation::GATE,
);
let trace_txt = extract_msg_indices(&empty_trace, gate_id2);
assert_eq!("[0, 2-3, 5]", trace_txt);
}
#[test]
fn test_single_range_single_long_range_extract_msg_indices() {
let mut empty_trace = Trace::new();
let gate_id1 = Uuid::new_v4();
let gate_id2 = Uuid::new_v4();
empty_trace.append_msg(
gate_id2,
"blah".to_owned(),
MsgRelation::GATE,
);
empty_trace.append_msg(
gate_id1,
"blah".to_owned(),
MsgRelation::GATE,
);
empty_trace.append_msg(
gate_id2,
"blah".to_owned(),
MsgRelation::GATE,
);
empty_trace.append_msg(
gate_id2,
"blah".to_owned(),
MsgRelation::GATE,
);
empty_trace.append_msg(
gate_id1,
"blah".to_owned(),
MsgRelation::GATE,
);
empty_trace.append_msg(
gate_id2,
"blah".to_owned(),
MsgRelation::GATE,
);
empty_trace.append_msg(
gate_id1,
"blah".to_owned(),
MsgRelation::GATE,
);
empty_trace.append_msg(
gate_id2,
"blah".to_owned(),
MsgRelation::GATE,
);
empty_trace.append_msg(
gate_id2,
"blah".to_owned(),
MsgRelation::GATE,
);
empty_trace.append_msg(
gate_id2,
"blah".to_owned(),
MsgRelation::GATE,
);
let trace_txt = extract_msg_indices(&empty_trace, gate_id2);
assert_eq!("[0, 2-3, 5, 7-9]", trace_txt);
}
#[test]
fn test_range_then_single_extract_msg_indices() {
let mut empty_trace = Trace::new();
let gate_id1 = Uuid::new_v4();
let gate_id2 = Uuid::new_v4();
empty_trace.append_msg(
gate_id2,
"blah".to_owned(),
MsgRelation::GATE,
);
empty_trace.append_msg(
gate_id2,
"blah".to_owned(),
MsgRelation::GATE,
);
empty_trace.append_msg(
gate_id1,
"blah".to_owned(),
MsgRelation::GATE,
);
empty_trace.append_msg(
gate_id2,
"blah".to_owned(),
MsgRelation::GATE,
);
let trace_txt = extract_msg_indices(&empty_trace, gate_id2);
assert_eq!("[0-1, 3]", trace_txt);
}
#[tokio::test(flavor = "multi_thread")]
async fn unused_unit_should_not_be_spawned() -> Result<(), Terminate> {
// given a config with only a single target with a link to a missing unit
let toml = r#"
http_listen = []
[units.unused-unit]
type = "bmp-tcp-in"
listen = "1.2.3.4:12345"
[units.some-unit]
type = "bmp-tcp-in"
listen = "1.2.3.4:12345"
[targets.null]
type = "null-out"
source = "some-unit"
"#;
let config_file = mk_config_from_toml(toml);
// when loaded into the manager and spawned
let mut manager = init_manager();
let (_source, config) =
Config::from_config_file(config_file, &mut manager)?;
spawn(&mut manager, config);
// then it should spawn the unit and target
let log = SPAWN_LOG.with(|log| log.take());
assert_eq!(log.len(), 2);
assert_log_contains(&log, "some-unit", SpawnAction::SpawnUnit);
assert_log_contains(&log, "null", SpawnAction::SpawnTarget);
Ok(())
}
#[tokio::test(flavor = "multi_thread")]
async fn added_target_should_be_spawned() -> Result<(), Terminate> {
// given a config with only a single target with a link to a single unit
let toml = r#"
http_listen = []
[units.some-unit]
type = "bmp-tcp-in"
listen = "1.2.3.4:12345"
[targets.null]
type = "null-out"
source = "some-unit"
"#;
let config_file = mk_config_from_toml(toml);
// when loaded into the manager and spawned
let mut manager = init_manager();
let (_source, config) =
Config::from_config_file(config_file, &mut manager)?;
spawn(&mut manager, config);
// then it should spawn the unit and target
let log = SPAWN_LOG.with(|log| log.take());
assert_eq!(log.len(), 2);
assert_log_contains(&log, "some-unit", SpawnAction::SpawnUnit);
assert_log_contains(&log, "null", SpawnAction::SpawnTarget);
// when the config is modified to include a new target
let toml = r#"
http_listen = []
[units.some-unit]
type = "bmp-tcp-in"
listen = "1.2.3.4:12345"
[targets.null]
type = "null-out"
source = "some-unit"
[targets.null2]
type = "null-out"
source = "some-unit"
"#;
let config_file = mk_config_from_toml(toml);
// when loaded into the manager and spawned
let (_source, config) =
Config::from_config_file(config_file, &mut manager)?;
spawn(&mut manager, config);
// then it should spawn the added target
let log = SPAWN_LOG.with(|log| log.take());
assert_eq!(log.len(), 3);
assert_log_contains(&log, "some-unit", SpawnAction::ReconfigureUnit);
assert_log_contains(&log, "null", SpawnAction::ReconfigureTarget);
assert_log_contains(&log, "null2", SpawnAction::SpawnTarget);
Ok(())
}
#[tokio::test(flavor = "multi_thread")]
async fn removed_target_should_be_terminated() -> Result<(), Terminate> {
// given a config with only a single target with a link to a missing unit
let toml = r#"
http_listen = []
[units.some-unit]
type = "bmp-tcp-in"
listen = "1.2.3.4:12345"
[targets.null]
type = "null-out"
source = "some-unit"
[targets.null2]
type = "null-out"
source = "some-unit"
"#;
let config_file = mk_config_from_toml(toml);
// when loaded into the manager and spawned
let mut manager = init_manager();
let (_source, config) =
Config::from_config_file(config_file, &mut manager)?;
spawn(&mut manager, config);
// then it should spawn the unit and target
let log = SPAWN_LOG.with(|log| log.take());
assert_eq!(log.len(), 3);
assert_log_contains(&log, "some-unit", SpawnAction::SpawnUnit);
assert_log_contains(&log, "null", SpawnAction::SpawnTarget);
assert_log_contains(&log, "null2", SpawnAction::SpawnTarget);
// when the config is modified to remove a target
let toml = r#"
http_listen = []
[units.some-unit]
type = "bmp-tcp-in"
listen = "1.2.3.4:12345"
#[targets.null]
#type = "null-out"
#source = "some-unit"
[targets.null2]
type = "null-out"
source = "some-unit"
"#;
let config_file = mk_config_from_toml(toml);
// when loaded into the manager and spawned
let (_source, config) =
Config::from_config_file(config_file, &mut manager)?;
spawn(&mut manager, config);
// then it should terminate the removed target
let log = SPAWN_LOG.with(|log| log.take());
assert_eq!(log.len(), 3);
assert_log_contains(&log, "some-unit", SpawnAction::ReconfigureUnit);
assert_log_contains(&log, "null", SpawnAction::TerminateTarget);
assert_log_contains(&log, "null2", SpawnAction::ReconfigureTarget);
// Note: we don't check that the gate of some-unit has been updated to
// remove the Sender for the Link to target null because that is logic
// within the Gate itself and should be tested in the Gate unit tests.
Ok(())
}
#[tokio::test(flavor = "multi_thread")]
async fn modified_settings_are_correctly_announced(
) -> Result<(), Terminate> {
// given a config with only a single target with a link to a missing unit
let toml = r#"
http_listen = []
[units.some-unit]
type = "bmp-tcp-in"
listen = "1.2.3.4:12345"
[targets.null]
type = "null-out"
source = "some-unit"
"#;
let config_file = mk_config_from_toml(toml);
// when loaded into the manager and spawned
let mut manager = init_manager();
let (_source, config) =
Config::from_config_file(config_file, &mut manager)?;
spawn(&mut manager, config);
// then it should spawn the unit and target
let log = SPAWN_LOG.with(|log| log.take());
assert_eq!(log.len(), 2);
assert_log_contains(&log, "some-unit", SpawnAction::SpawnUnit);
assert_log_contains(&log, "null", SpawnAction::SpawnTarget);
// when the config is modified
let toml = r#"
http_listen = []
[units.some-unit]
type = "bmp-tcp-in"
listen = "5.6.7.8:1818"
[targets.null]
type = "null-out"
source = "some-unit"
"#;
let config_file = mk_config_from_toml(toml);
// when loaded into the manager and spawned
let (_source, config) =
Config::from_config_file(config_file, &mut manager)?;
spawn(&mut manager, config);
// then it should terminate the removed target
let log = SPAWN_LOG.with(|log| log.take());
assert_eq!(log.len(), 2);
assert_log_contains(&log, "some-unit", SpawnAction::ReconfigureUnit);
assert_log_contains(&log, "null", SpawnAction::ReconfigureTarget);
let item =
get_log_item(&log, "some-unit", SpawnAction::ReconfigureUnit);
if let UnitOrTargetConfig::UnitConfig(Unit::BmpTcpIn(config)) =
&item.config
{
assert_eq!(config.listen.to_string(), "5.6.7.8:1818");
} else {
unreachable!();
}
Ok(())
}
#[tokio::test]
async fn coordinator_with_no_components_should_finish_immediately() {
let coordinator = Coordinator::new(0);
let mut alarm_fired = false;
coordinator.wait(|_, _| alarm_fired = true).await;
assert!(!alarm_fired);
}
#[tokio::test]
#[should_panic]
async fn coordinator_track_too_many_components_causes_panic() {
let coordinator = Coordinator::new(0);
coordinator.track(SOME_COMPONENT.to_string());
}
#[tokio::test]
#[should_panic]
async fn coordinator_track_component_twice_causes_panic() {
let coordinator = Coordinator::new(0);
coordinator.clone().track(SOME_COMPONENT.to_string());
coordinator.track(SOME_COMPONENT.to_string());
}
#[tokio::test]
#[should_panic]
async fn coordinator_unknown_ready_component_twice_causes_panic() {
let coordinator = Coordinator::new(0);
coordinator.ready(SOME_COMPONENT).await;
}
#[tokio::test(start_paused = true)]
async fn coordinator_with_one_ready_component_should_not_raise_alarm() {
let coordinator = Coordinator::new(1);
let mut alarm_fired = false;
let wait_point =
coordinator.clone().track(SOME_COMPONENT.to_string());
let join_handle = tokio::task::spawn(wait_point.running());
assert!(!join_handle.is_finished());
coordinator.wait(|_, _| alarm_fired = true).await;
join_handle.await.unwrap();
assert!(!alarm_fired);
}
#[tokio::test(start_paused = true)]
async fn coordinator_with_two_ready_components_should_not_raise_alarm() {
let coordinator = Coordinator::new(2);
let mut alarm_fired = false;
let wait_point1 =
coordinator.clone().track(SOME_COMPONENT.to_string());
let wait_point2 =
coordinator.clone().track(OTHER_COMPONENT.to_string());
let join_handle1 = tokio::task::spawn(wait_point1.running());
let join_handle2 = tokio::task::spawn(wait_point2.running());
assert!(!join_handle1.is_finished());
assert!(!join_handle2.is_finished());
coordinator.wait(|_, _| alarm_fired = true).await;
join_handle1.await.unwrap();
join_handle2.await.unwrap();
assert!(!alarm_fired);
}
#[tokio::test(start_paused = true)]
async fn coordinator_with_component_with_slow_ready_phase_should_raise_alarm(
) {
let coordinator = Coordinator::new(1);
let alarm_fired_count = Arc::new(AtomicU8::new(0));
let wait_point =
coordinator.clone().track(SOME_COMPONENT.to_string());
// Deliberately don't call wait_point.ready() or wait_point.running()
let join_handle = {
let alarm_fired_count = alarm_fired_count.clone();
tokio::task::spawn(coordinator.wait(move |_, _| {
alarm_fired_count.fetch_add(1, SeqCst);
}))
};
// Advance time beyond the maximum time allowed for the 'ready' state to be reached
let advance_time_by = Coordinator::SLOW_COMPONENT_ALARM_DURATION;
let advance_time_by =
advance_time_by.checked_add(Duration::from_secs(1)).unwrap();
tokio::time::sleep(advance_time_by).await;
// Check that the alarm fired once
assert_eq!(alarm_fired_count.load(SeqCst), 1);
// Set the component state to the final state 'running'
wait_point.running().await;
// Which should unblock the coordinator wait
join_handle.await.unwrap();
}
#[tokio::test(start_paused = true)]
async fn coordinator_with_component_with_slow_running_phase_should_raise_alarm(
) {
let coordinator = Coordinator::new(1);
let alarm_fired_count = Arc::new(AtomicU8::new(0));
let mut wait_point =
coordinator.clone().track(SOME_COMPONENT.to_string());
// Deliberately don't call wait_point.ready() or wait_point.running()
let join_handle = {
let alarm_fired_count = alarm_fired_count.clone();
tokio::task::spawn(coordinator.wait(move |_, _| {
alarm_fired_count.fetch_add(1, SeqCst);
}))
};
// Advance time beyond the maximum time allowed for the 'ready' state to be reached
let advance_time_by = Coordinator::SLOW_COMPONENT_ALARM_DURATION;
let advance_time_by =
advance_time_by.checked_add(Duration::from_secs(1)).unwrap();
tokio::time::sleep(advance_time_by).await;
// Check that the alarm fired once
assert_eq!(alarm_fired_count.load(SeqCst), 1);
// Achieve the 'ready' state in the component under test, but not yet the 'running' state
wait_point.ready().await;
// Advance time beyond the maximum time allowed for the 'running' state to be reached
let advance_time_by = Coordinator::SLOW_COMPONENT_ALARM_DURATION;
let advance_time_by =
advance_time_by.checked_add(Duration::from_secs(1)).unwrap();
tokio::time::sleep(advance_time_by).await;
// Check that the alarm fired again
assert_eq!(alarm_fired_count.load(SeqCst), 2);
// Set the component state to the final state 'running'
wait_point.running().await;
// Which should unblock the coordinator wait
join_handle.await.unwrap();
}
// --- Test helpers ------------------------------------------------------
fn mk_config_from_toml(toml: &str) -> ConfigFile {
ConfigFile::new(toml.as_bytes().to_vec(), Source::default()).unwrap()
}
type UnitOrTargetName = String;
#[derive(Debug, Eq, PartialEq)]
enum SpawnAction {
SpawnUnit,
SpawnTarget,
ReconfigureUnit,
ReconfigureTarget,
TerminateUnit,
TerminateTarget,
}
impl Display for SpawnAction {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
SpawnAction::SpawnUnit => f.write_str("SpawnUnit"),
SpawnAction::SpawnTarget => f.write_str("SpawnTarget"),
SpawnAction::ReconfigureUnit => {
f.write_str("ReconfigureUnit")
}
SpawnAction::ReconfigureTarget => {
f.write_str("ReconfigureTarget")
}
SpawnAction::TerminateUnit => f.write_str("TerminateUnit"),
SpawnAction::TerminateTarget => {
f.write_str("TerminateTarget")
}
}
}
}
#[derive(Debug)]
enum UnitOrTargetConfig {
None,
UnitConfig(Unit),
TargetConfig(Target),
}
#[derive(Debug)]
struct SpawnLogItem {
pub name: UnitOrTargetName,
pub action: SpawnAction,
pub config: UnitOrTargetConfig,
}
impl SpawnLogItem {
fn new(
name: UnitOrTargetName,
action: SpawnAction,
_config: UnitOrTargetConfig,
) -> Self {
Self {
name,
action,
config: _config,
}
}
}
impl Display for SpawnLogItem {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "'{}' for unit/target '{}'", self.action, self.name)
}
}
#[derive(Debug, Default)]
struct SpawnLog(pub Vec<SpawnLogItem>);
impl SpawnLog {
pub fn new() -> Self {
Self(vec![])
}
}
impl Display for SpawnLog {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
writeln!(f, "[")?;
for item in &self.0 {
writeln!(f, " {}", item)?;
}
writeln!(f, "]")
}
}
impl Deref for SpawnLog {
type Target = Vec<SpawnLogItem>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl DerefMut for SpawnLog {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
thread_local!(
static SPAWN_LOG: RefCell<SpawnLog> = RefCell::new(SpawnLog::new())
);
fn assert_log_contains(log: &SpawnLog, name: &str, action: SpawnAction) {
assert!(
log.iter()
.any(|item| item.name == name && item.action == action),
"No '{}' action for unit/target '{}' found in spawn log: {}",
action,
name,
log
);
}
fn get_log_item<'a>(
log: &'a SpawnLog,
name: &str,
action: SpawnAction,
) -> &'a SpawnLogItem {
let found = log
.iter()
.find(|item| item.name == name && item.action == action);
assert!(found.is_some());
found.unwrap()
}
fn spawn_unit(c: Component, u: Unit, _: Gate, _: WaitPoint) {
log_spawn_action(
c.name.to_string(),
SpawnAction::SpawnUnit,
UnitOrTargetConfig::UnitConfig(u),
);
}
fn spawn_target(
c: Component,
t: Target,
_: Receiver<TargetCommand>,
_: WaitPoint,
) {
log_spawn_action(
c.name.to_string(),
SpawnAction::SpawnTarget,
UnitOrTargetConfig::TargetConfig(t),
);
}
fn reconfigure_unit(name: &str, _: GateAgent, u: Unit, _: Gate) {
log_spawn_action(
name.to_string(),
SpawnAction::ReconfigureUnit,
UnitOrTargetConfig::UnitConfig(u),
);
}
fn reconfigure_target(name: &str, _: Sender<TargetCommand>, t: Target) {
log_spawn_action(
name.to_string(),
SpawnAction::ReconfigureTarget,
UnitOrTargetConfig::TargetConfig(t),
);
}
fn terminate_unit(name: &str, _: Arc<GateAgent>) {
log_spawn_action(
name.to_string(),
SpawnAction::TerminateUnit,
UnitOrTargetConfig::None,
);
}
fn terminate_target(name: &str, _: Arc<Sender<TargetCommand>>) {
log_spawn_action(
name.to_string(),
SpawnAction::TerminateTarget,
UnitOrTargetConfig::None,
);
}
fn clear_spawn_action_log() {
SPAWN_LOG.with(|log| log.borrow_mut().clear());
}
fn log_spawn_action(
name: String,
action: SpawnAction,
cfg: UnitOrTargetConfig,
) {
SPAWN_LOG.with(|log| {
log.borrow_mut().push(SpawnLogItem::new(name, action, cfg))
});
}
fn spawn(manager: &mut Manager, mut config: Config) {
clear_spawn_action_log();
manager.spawn_internal(
&mut config,
spawn_unit,
spawn_target,
reconfigure_unit,
reconfigure_target,
terminate_unit,
terminate_target,
);
}
fn init_manager() -> Manager {
GATES.with(|gates| gates.replace(Some(Default::default())));
ROTO_FILTER_NAMES.with(|filter_names| {
filter_names.replace(Some(Default::default()))
});
Manager::new()
}
}