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
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
|
%global _empty_manifest_terminate_build 0
Name: python-cloudreactor-procwrapper
Version: 5.0.2
Release: 1
Summary: Wraps the execution of processes so that a service API endpoint (CloudReactor) can monitor and manage them. Also implements retries, timeouts, and secret injection from AWS into the environment.
License: Dual license, MPL 2.0 or commercial
URL: https://cloudreactor.io
Source0: https://mirrors.aliyun.com/pypi/web/packages/85/3b/476652ec00ae0cda9d2ffa4008ebd9a59710fc8d672a90dba1f89c7d1805/cloudreactor-procwrapper-5.0.2.tar.gz
BuildArch: noarch
Requires: python3-Sphinx
Requires: python3-sphinx-rtd-theme
Requires: python3-myst-parser
Requires: python3-Jinja2
%description
# cloudreactor-procwrapper
<p align="center">
<a href="https://github.com/CloudReactor/cloudreactor-procwrapper/actions?query=workflow%3ACI">
<img src="https://img.shields.io/github/workflow/status/CloudReactor/cloudreactor-procwrapper/CI/main?label=CI&logo=github&style=flat-square" alt="CI Status" >
</a>
<a href="https://cloudreactor-procwrapper.readthedocs.io">
<img src="https://img.shields.io/readthedocs/cloudreactor-procwrapper.svg?logo=read-the-docs&logoColor=fff&style=flat-square" alt="Documentation Status">
</a>
<a href="https://codecov.io/gh/CloudReactor/cloudreactor-procwrapper">
<img src="https://img.shields.io/codecov/c/github/CloudReactor/cloudreactor-procwrapper.svg?logo=codecov&logoColor=fff&style=flat-square" alt="Test coverage percentage">
</a>
</p>
<p align="center">
<a href="https://python-poetry.org/">
<img src="https://img.shields.io/badge/packaging-poetry-299bd7?style=flat-square&logo=data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAA4AAAASCAYAAABrXO8xAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAJJSURBVHgBfZLPa1NBEMe/s7tNXoxW1KJQKaUHkXhQvHgW6UHQQ09CBS/6V3hKc/AP8CqCrUcpmop3Cx48eDB4yEECjVQrlZb80CRN8t6OM/teagVxYZi38+Yz853dJbzoMV3MM8cJUcLMSUKIE8AzQ2PieZzFxEJOHMOgMQQ+dUgSAckNXhapU/NMhDSWLs1B24A8sO1xrN4NECkcAC9ASkiIJc6k5TRiUDPhnyMMdhKc+Zx19l6SgyeW76BEONY9exVQMzKExGKwwPsCzza7KGSSWRWEQhyEaDXp6ZHEr416ygbiKYOd7TEWvvcQIeusHYMJGhTwF9y7sGnSwaWyFAiyoxzqW0PM/RjghPxF2pWReAowTEXnDh0xgcLs8l2YQmOrj3N7ByiqEoH0cARs4u78WgAVkoEDIDoOi3AkcLOHU60RIg5wC4ZuTC7FaHKQm8Hq1fQuSOBvX/sodmNJSB5geaF5CPIkUeecdMxieoRO5jz9bheL6/tXjrwCyX/UYBUcjCaWHljx1xiX6z9xEjkYAzbGVnB8pvLmyXm9ep+W8CmsSHQQY77Zx1zboxAV0w7ybMhQmfqdmmw3nEp1I0Z+FGO6M8LZdoyZnuzzBdjISicKRnpxzI9fPb+0oYXsNdyi+d3h9bm9MWYHFtPeIZfLwzmFDKy1ai3p+PDls1Llz4yyFpferxjnyjJDSEy9CaCx5m2cJPerq6Xm34eTrZt3PqxYO1XOwDYZrFlH1fWnpU38Y9HRze3lj0vOujZcXKuuXm3jP+s3KbZVra7y2EAAAAAASUVORK5CYII=" alt="Poetry">
</a>
<a href="https://github.com/pre-commit/pre-commit">
<img src="https://img.shields.io/badge/pre--commit-enabled-brightgreen?logo=pre-commit&logoColor=white&style=flat-square" alt="pre-commit">
</a>
</p>
<p align="center">
<a href="https://pypi.org/project/cloudreactor-procwrapper/">
<img src="https://img.shields.io/pypi/v/cloudreactor-procwrapper.svg?logo=python&logoColor=fff&style=flat-square" alt="PyPI Version">
</a>
<img src="https://img.shields.io/pypi/pyversions/cloudreactor-procwrapper.svg?style=flat-square&logo=python&logoColor=fff" alt="Supported Python versions">
<img src="https://img.shields.io/pypi/l/cloudreactor-procwrapper.svg?style=flat-square" alt="License">
</p>
Wraps the execution of processes so that an API server
([CloudReactor](https://cloudreactor.io/))
can monitor and manage them.
Available as a standalone executable or as a python module.
## Features
* Runs either processes started with a command line or a python function you
supply
* Implements retries and time limits
* Injects secrets from AWS Secrets Manager, AWS S3, or local files and extracts
them into the process environment (for command-lines) or configuration (for
functions)
* When used with the CloudReactor service:
* Reports when a process/function starts and when it exits, along with the
exit code and runtime metadata (if running in AWS ECS or AWS Lambda)
* Sends heartbeats, optionally with status information like the number of
items processed
* Prevents too many concurrent executions
* Stops execution when manually stopped in the CloudReactor dashboard
* Sends CloudReactor the data necessary to start the process / function if running in AWS ECS or AWS Lambda
## How it works
First, secrets and other configuration are fetched and resolved from
providers like AWS Secrets Manager, AWS S3, or the local filesystem.
Just before your code runs, the module requests the API server to create a
Task Execution associated with the Task name or UUID which you pass to the
module.
The API server may reject the request if too many instances of the Task are
currently running, but otherwise records that a Task Execution has started.
The module then passes control to your code.
While your code is running, it may report progress to the API server,
and the API server may signal that your Task stop execution (due to
user manually stopping the Task Execution), in which
case the module terminates your code and exits.
After your code finishes, the module informs the API server of
the exit code or result. CloudReactor monitors Tasks to ensure they
are still responsive, and keeps a history of the Executions of Tasks,
allowing you to view failures and run durations in the past.
### Auto-created Tasks
Before your Task is run (including this module),
the [AWS ECS CloudReactor Deployer](https://github.com/CloudReactor/aws-ecs-cloudreactor-deployer)
can be used to set it up in AWS ECS,
and inform CloudReactor of details of your Task.
That way CloudReactor can start and schedule your Task, and setup your
Task as a service.
See [CloudReactor python ECS QuickStart](https://github.com/CloudReactor/cloudreactor-python-ecs-quickstart)
for an example.
However, it may not be possible or desired to change your deployment process.
Instead, you may configure the Task to be *auto-created*.
Auto-created Tasks are created the first time your Task runs.
This means there is no need to inform the API server of the Task details
(during deployment) before it runs.
Instead, each time the module runs, it informs the API server of the
Task details at the same time as it requests the creation of a Task Execution.
One disadvantage of auto-created Tasks is that they are not available
in the CloudReactor dashboard until the first time they run.
When configuring a Task to be auto-created, you must specify the name
or UUID of the Run Environment in CloudReactor that the Task is
associated with. The Run Environment must be created ahead of time,
either by the Cloudreactor AWS Setup Wizard,
or manually in the CloudReactor dashboard.
You can also specify more Task properties, such as Alert Methods and
external links in the dashboard, by setting the environment variable
`PROC_WRAPPER_AUTO_CREATE_TASK_PROPS` set to a JSON-encoded object that has the
[CloudReactor Task schema](https://apidocs.cloudreactor.io/#operation/tasks_create).
### Execution Methods
CloudReactor currently supports three Execution Methods:
1) [AWS ECS (in Fargate)](https://aws.amazon.com/fargate/)
2) [AWS Lambda](https://aws.amazon.com/lambda/)
3) Unknown
If a Task is running in AWS ECS, CloudReactor is able to run additional
Task Executions, provided the details of running the Task is provided
during deployment with the AWS ECS CloudReactor Deployer, or if the
Task is configured to be auto-created, and this module is run. In the
second case, this module uses the ECS Metadata endpoint to detect
the ECS Task settings, and sends them to the API server. CloudReactor
can also schedule Tasks or setup long-running services using Tasks,
provided they are run in AWS ECS.
If a Task is running in AWS Lambda, CloudReactor is able to run additional
Task Executions after the first run of the function.
However, a Task may use the Unknown execution method if it is not running
in AWS ECS or Lambda. If that is the case, CloudReactor won't be able to
start the Task in the dashboard or as part of a Workflow,
schedule the Task, or setup a service with the Task. But the advantage is
that the Task code can be executed by any method available to you,
such as bare metal servers, VM's, or Kubernetes.
All Tasks in CloudReactor, regardless of execution method, have their
history kept and are monitored.
This module detects the execution method your Task is
running with and sends that information to the API server, provided
you configure your Task to be auto-created.
### Passive Tasks
Passive Tasks are Tasks that CloudReactor does not manage. This means
scheduling and service setup must be handled by other means
(cron jobs, [supervisord](http://supervisord.org/), etc).
However, Tasks marked as services or that have a schedule will still be
monitored by CloudReactor, which will send notifications if
a service Task goes down or a Task does not run on schedule.
The module reports to the API server that auto-created Tasks are passive,
unless you specify the `--force-task-passive` commmand-line option or
set the environment variable `PROC_WRAPPER_TASK_IS_PASSIVE` to `FALSE`.
If a Task uses the Unknown Execution Method, it must be marked as passive,
because CloudReactor does not know how to manage it.
## Pre-requisites
If you just want to use this module to retry processes, limit execution time,
or fetch secrets, you can use offline mode, in which case no CloudReactor API
key is required. But CloudReactor offers a free tier so we hope you
[sign up](https://dash.cloudreactor.io/signup)
for a free account to enable monitoring and/or management.
If you want CloudReactor to be able to start your Tasks, you should use the
[Cloudreactor AWS Setup Wizard](https://github.com/CloudReactor/cloudreactor-aws-setup-wizard)
to configure your AWS environment to run Tasks in ECS Fargate.
You can skip this step if running in passive mode is OK for you.
If you want to use CloudReactor to manage or just monitor your Tasks,
you need to create a Run Environment and an API key in the CloudReactor
dashboard. The API key can be scoped to the Run Environment if you
wish. The key must have at least the Task access level, but for
an auto-created Task, it must have at least the Developer access level.
## Installation
### Nuitka
Standalone executables built by
[nuitka](https://nuitka.net/index.html)
for 64-bit Linux are available, located in `bin/nuitka`. These executables bundle
python so you don't need to have python installed on your machine. They also
bundle all optional library dependencies so you can fetch secrets from AWS
Secrets Manager and extract them with jsonpath-ng, for example.
Compared to executables built by PyInstaller (see below), they start up faster,
and most likely are more efficient at runtime.
#### RHEL or derivatives
To download and run the wrapper on a RHEL/Fedora/Amazon Linux 2 machine:
RUN wget -nv https://github.com/CloudReactor/cloudreactor-procwrapper/raw/5.0.2/bin/nuitka/al2/5.0.2/proc_wrapper.bin
ENTRYPOINT ["proc_wrapper.bin"]
Example Dockerfiles of known working environments are available for
[Amazon Linux 2](tests/integration/nuitka_executable/docker_context_al2_amd64/)
and
[Fedora](tests/integration/nuitka_executable/docker_context_al2_amd64/Dockerfile).
Fedora 27 or later are supported.
#### Debian based systems
On a Debian based (including Ubuntu) machine:
RUN wget -nv https://github.com/CloudReactor/cloudreactor-procwrapper/raw/5.0.2/bin/nuitka/debian-amd64/5.0.2/proc_wrapper.bin
ENTRYPOINT ["proc_wrapper.bin"]
See the example
[Dockerfile](tests/integration/nuitka_executable/docker_context_debian_amd64/Dockerfile) for a known working Debian environment.
Debian 10 (Buster) or later are supported.
### PyInstaller
Standalone executables built by [PyInstaller](https://www.pyinstaller.org/) for 64-bit Linux and Windows are available, located in `bin/pyinstaller`.
These executables bundle
python so you don't need to have python installed on your machine. They also
bundle all optional library dependencies so you can fetch secrets from AWS
Secrets Manager and extract them with jsonpath-ng, for example. Compared to
executables built by nuitka, they start up slower but might be more reliable.
#### RHEL or derivatives
To download and run the wrapper on a RHEL/Fedora/Amazon Linux 2 machine:
RUN wget -nv https://github.com/CloudReactor/cloudreactor-procwrapper/raw/5.0.2/bin/pyinstaller/al2/5.0.2/proc_wrapper.bin
ENTRYPOINT ["proc_wrapper.bin"]
Example Dockerfiles of known working environments are available for
[Amazon Linux 2](tests/integration/pyinstaller_executable/docker_context_al2_amd64/)
and
[Fedora](tests/integration/pyinstaller_executable/docker_context_al2_amd64/Dockerfile).
Fedora 27 or later are supported.
#### Debian based machines
On a Debian based (including Ubuntu) machine:
RUN wget -nv https://github.com/CloudReactor/cloudreactor-procwrapper/raw/5.0.2/bin/pyinstaller/debian-amd64/5.0.2/proc_wrapper.bin
ENTRYPOINT ["proc_wrapper.bin"]
See the example
[Dockerfile](tests/integration/pyinstaller_executable/docker_context_debian_amd64/Dockerfile) for a known working Debian environment.
Debian 10 (Buster) or later are supported.
Special thanks to
[wine](https://www.winehq.org/) and
[PyInstaller Docker Images](https://github.com/cdrx/docker-pyinstaller)
for making it possible to cross-compile!
### When python is available
Install this module via pip (or your favorite package manager):
`pip install cloudreactor-procwrapper`
Fetching secrets from AWS Secrets Manager requires that
[boto3](https://boto3.amazonaws.com/v1/documentation/api/latest/index.html) is available to import in your python environment.
JSON Path transformation requires that [jsonpath-ng](https://github.com/h2non/jsonpath-ng)
be available to import in your python environment.
You can get the tested versions of both dependencies in
[proc_wrapper-requirements.in](https://github.com/CloudReactor/cloudreactor-procwrapper/blob/main/proc_wrapper-requirements.in)
(suitable for use by [pip-tools](https://github.com/jazzband/pip-tools/)) or the resolved requirements in
[proc_wrapper-requirements.txt](https://github.com/CloudReactor/cloudreactor-procwrapper/blob/main/proc_wrapper-requirements.txt).
## Usage
There are two ways of using the module: wrapped mode and embedded mode.
### Wrapped mode
In wrapped mode, you pass a command line to the module which it
executes in a child process. The command can be implemented in whatever
programming language the running machine supports.
Instead of running
somecommand --somearg x
you would run
./proc_wrapper somecommand --somearg x
assuming that are using the PyInstaller standalone executable, and that
you configure the program using environment variables.
Or, if you have python installed:
python -m proc_wrapper somecommand --somearg x
Here are all the options:
usage: proc_wrapper [-h] [-v] [-n TASK_NAME] [--task-uuid TASK_UUID] [-a]
[--auto-create-task-run-environment-name AUTO_CREATE_TASK_RUN_ENVIRONMENT_NAME]
[--auto-create-task-run-environment-uuid AUTO_CREATE_TASK_RUN_ENVIRONMENT_UUID]
[--auto-create-task-props AUTO_CREATE_TASK_PROPS]
[--force-task-active]
[--task-execution-uuid TASK_EXECUTION_UUID]
[--task-version-number TASK_VERSION_NUMBER]
[--task-version-text TASK_VERSION_TEXT]
[--task-version-signature TASK_VERSION_SIGNATURE]
[--execution-method-props EXECUTION_METHOD_PROPS]
[--task-instance-metadata TASK_INSTANCE_METADATA] [-s]
[--schedule SCHEDULE] [--max-concurrency MAX_CONCURRENCY]
[--max-conflicting-age MAX_CONFLICTING_AGE]
[--api-base-url API_BASE_URL] [-k API_KEY]
[--api-heartbeat-interval API_HEARTBEAT_INTERVAL]
[--api-error-timeout API_ERROR_TIMEOUT]
[--api-final-update-timeout API_FINAL_UPDATE_TIMEOUT]
[--api-retry-delay API_RETRY_DELAY]
[--api-resume-delay API_RESUME_DELAY]
[--api-task-execution-creation-error-timeout API_TASK_EXECUTION_CREATION_ERROR_TIMEOUT]
[--api-task-execution-creation-conflict-timeout API_TASK_EXECUTION_CREATION_CONFLICT_TIMEOUT]
[--api-task-execution-creation-conflict-retry-delay API_TASK_EXECUTION_CREATION_CONFLICT_RETRY_DELAY]
[--api-request-timeout API_REQUEST_TIMEOUT] [-o] [-p]
[-d DEPLOYMENT] [--send-pid] [--send-hostname]
[--no-send-runtime-metadata]
[-l {DEBUG,INFO,WARNING,ERROR,CRITICAL}] [--log-secrets]
[--exclude-timestamps-in-log] [-w WORK_DIR]
[-c COMMAND_LINE] [--shell-mode {auto,enable,disable}]
[--no-strip-shell-wrapping]
[--no-process-group-termination] [-t PROCESS_TIMEOUT]
[-r PROCESS_MAX_RETRIES]
[--process-retry-delay PROCESS_RETRY_DELAY]
[--process-check-interval PROCESS_CHECK_INTERVAL]
[--process-termination-grace-period PROCESS_TERMINATION_GRACE_PERIOD]
[--enable-status-update-listener]
[--status-update-socket-port STATUS_UPDATE_SOCKET_PORT]
[--status-update-message-max-bytes STATUS_UPDATE_MESSAGE_MAX_BYTES]
[--status-update-interval STATUS_UPDATE_INTERVAL]
[-e ENV_LOCATIONS] [--config CONFIG_LOCATIONS]
[--config-merge-strategy {DEEP,SHALLOW,REPLACE,ADDITIVE,TYPESAFE_REPLACE,TYPESAFE_ADDITIVE}]
[--overwrite_env_during_resolution]
[--config-ttl CONFIG_TTL]
[--no-fail-fast-config-resolution]
[--resolved-env-var-name-prefix RESOLVED_ENV_VAR_NAME_PREFIX]
[--resolved-env-var-name-suffix RESOLVED_ENV_VAR_NAME_SUFFIX]
[--resolved-config-property-name-prefix RESOLVED_CONFIG_PROPERTY_NAME_PREFIX]
[--resolved-config-property-name-suffix RESOLVED_CONFIG_PROPERTY_NAME_SUFFIX]
[--env-var-name-for-config ENV_VAR_NAME_FOR_CONFIG]
[--config-property-name-for-env CONFIG_PROPERTY_NAME_FOR_ENV]
[--rollbar-access-token ROLLBAR_ACCESS_TOKEN]
[--rollbar-retries ROLLBAR_RETRIES]
[--rollbar-retry-delay ROLLBAR_RETRY_DELAY]
[--rollbar-timeout ROLLBAR_TIMEOUT]
...
Wraps the execution of processes so that a service API endpoint (CloudReactor)
is optionally informed of the progress. Also implements retries, timeouts, and
secret injection into the environment.
positional arguments:
command
optional arguments:
-h, --help show this help message and exit
-v, --version Print the version and exit
task:
Task settings
-n TASK_NAME, --task-name TASK_NAME
Name of Task (either the Task Name or the Task UUID
must be specified
--task-uuid TASK_UUID
UUID of Task (either the Task Name or the Task UUID
must be specified)
-a, --auto-create-task
Create the Task even if not known by the API server
--auto-create-task-run-environment-name AUTO_CREATE_TASK_RUN_ENVIRONMENT_NAME
Name of the Run Environment to use if auto-creating
the Task (either the name or UUID of the Run
Environment must be specified if auto-creating the
Task). Defaults to the deployment name if the Run
Environment UUID is not specified.
--auto-create-task-run-environment-uuid AUTO_CREATE_TASK_RUN_ENVIRONMENT_UUID
UUID of the Run Environment to use if auto-creating
the Task (either the name or UUID of the Run
Environment must be specified if auto-creating the
Task)
--auto-create-task-props AUTO_CREATE_TASK_PROPS
Additional properties of the auto-created Task, in
JSON format. See https://apidocs.cloudreactor.io/#oper
ation/api_v1_tasks_create for the schema.
--force-task-active Indicates that the auto-created Task should be
scheduled and made a service by the API server, if
applicable. Otherwise, auto-created Tasks are marked
passive.
--task-execution-uuid TASK_EXECUTION_UUID
UUID of Task Execution to attach to
--task-version-number TASK_VERSION_NUMBER
Numeric version of the Task's source code
--task-version-text TASK_VERSION_TEXT
Human readable version of the Task's source code
--task-version-signature TASK_VERSION_SIGNATURE
Version signature of the Task's source code (such as a
git commit hash)
--execution-method-props EXECUTION_METHOD_PROPS
Additional properties of the execution method, in JSON
format. See https://apidocs.cloudreactor.io/#operation
/api_v1_task_executions_create for the schema.
--task-instance-metadata TASK_INSTANCE_METADATA
Additional metadata about the Task instance, in JSON
format
-s, --service Indicate that this is a Task that should run
indefinitely
--schedule SCHEDULE Run schedule reported to the API server
--max-concurrency MAX_CONCURRENCY
Maximum number of concurrent Task Executions of the
same Task. Defaults to 1.
--max-conflicting-age MAX_CONFLICTING_AGE
Maximum age of conflicting Tasks to consider, in
seconds. -1 means no limit. Defaults to the heartbeat
interval, plus 60 seconds for services that send
heartbeats. Otherwise, defaults to no limit.
api:
API client settings
--api-base-url API_BASE_URL
Base URL of API server. Defaults to
https://api.cloudreactor.io
-k API_KEY, --api-key API_KEY
API key. Must have at least the Task access level, or
Developer access level for auto-created Tasks.
--api-heartbeat-interval API_HEARTBEAT_INTERVAL
Number of seconds to wait between sending heartbeats
to the API server. -1 means to not send heartbeats.
Defaults to 30 for concurrency limited services, 300
otherwise.
--api-error-timeout API_ERROR_TIMEOUT
Number of seconds to wait while receiving recoverable
errors from the API server. Defaults to 300.
--api-final-update-timeout API_FINAL_UPDATE_TIMEOUT
Number of seconds to wait while receiving recoverable
errors from the API server when sending the final
update before exiting. Defaults to 1800.
--api-retry-delay API_RETRY_DELAY
Number of seconds to wait before retrying an API
request. Defaults to 120.
--api-resume-delay API_RESUME_DELAY
Number of seconds to wait before resuming API
requests, after retries are exhausted. Defaults to
600. -1 means to never resume.
--api-task-execution-creation-error-timeout API_TASK_EXECUTION_CREATION_ERROR_TIMEOUT
Number of seconds to keep retrying Task Execution
creation while receiving error responses from the API
server. -1 means to keep trying indefinitely. Defaults
to 300.
--api-task-execution-creation-conflict-timeout API_TASK_EXECUTION_CREATION_CONFLICT_TIMEOUT
Number of seconds to keep retrying Task Execution
creation while conflict is detected by the API server.
-1 means to keep trying indefinitely. Defaults to 1800
for concurrency limited services, 0 otherwise.
--api-task-execution-creation-conflict-retry-delay API_TASK_EXECUTION_CREATION_CONFLICT_RETRY_DELAY
Number of seconds between attempts to retry Task
Execution creation after conflict is detected.
Defaults to 60 for concurrency-limited services, 120
otherwise.
--api-request-timeout API_REQUEST_TIMEOUT
Timeout for contacting API server, in seconds.
Defaults to 30.
-o, --offline-mode Do not communicate with or rely on an API server
-p, --prevent-offline-execution
Do not start processes if the API server is
unavailable or the wrapper is misconfigured.
-d DEPLOYMENT, --deployment DEPLOYMENT
Deployment name (production, staging, etc.)
--send-pid Send the process ID to the API server
--send-hostname Send the hostname to the API server
--no-send-runtime-metadata
Do not send metadata about the runtime environment
log:
Logging settings
-l {DEBUG,INFO,WARNING,ERROR,CRITICAL}, --log-level {DEBUG,INFO,WARNING,ERROR,CRITICAL}
Log level
--log-secrets Log sensitive information
--exclude-timestamps-in-log
Exclude timestamps in log (possibly because the log
stream will be enriched by timestamps automatically by
a logging service like AWS CloudWatch Logs)
process:
Process settings
-w WORK_DIR, --work-dir WORK_DIR
Working directory. Defaults to the current directory.
-c COMMAND_LINE, --command-line COMMAND_LINE
Command line to execute
--shell-mode {auto,enable,disable}
Indicates if the process command should be executed in
a shell. Executing in a shell allows shell scripts,
commands, and expressions to be used, with the
disadvantage that termination signals may not be
propagated to child processes. Options are: enable --
Force the command to be executed in a shell; disable
-- Force the command to be executed without a shell;
auto -- Auto-detect the shell mode by analyzing the
command.
--no-strip-shell-wrapping
Do not strip the command-line of shell wrapping like
"/bin/sh -c" that can be introduced by Docker when
using shell form of ENTRYPOINT and CMD.
--no-process-group-termination
Send termination and kill signals to the wrapped
process only, instead of its process group (which is
the default). Sending to the process group allows all
child processes to receive the signals, even if the
wrapped process does not forward signals. However, if
your wrapped process manually handles and forwards
signals to its child processes, you probably want to
send signals to only your wrapped process.
-t PROCESS_TIMEOUT, --process-timeout PROCESS_TIMEOUT
Timeout for process completion, in seconds. -1 means
no timeout, which is the default.
-r PROCESS_MAX_RETRIES, --process-max-retries PROCESS_MAX_RETRIES
Maximum number of times to retry failed processes. -1
means to retry forever. Defaults to 0.
--process-retry-delay PROCESS_RETRY_DELAY
Number of seconds to wait before retrying a process.
Defaults to 60.
--process-check-interval PROCESS_CHECK_INTERVAL
Number of seconds to wait between checking the status
of processes. Defaults to 10.
--process-termination-grace-period PROCESS_TERMINATION_GRACE_PERIOD
Number of seconds to wait after sending SIGTERM to a
process, but before killing it with SIGKILL. Defaults
to 30.
updates:
Status update settings
--enable-status-update-listener
Listen for status updates from the process, sent on
the status socket port via UDP. If not specified,
status update messages will not be read.
--status-update-socket-port STATUS_UPDATE_SOCKET_PORT
The port used to receive status updates from the
process. Defaults to 2373.
--status-update-message-max-bytes STATUS_UPDATE_MESSAGE_MAX_BYTES
The maximum number of bytes status update messages can
be. Defaults to 65536.
--status-update-interval STATUS_UPDATE_INTERVAL
Minimum of number of seconds to wait between sending
status updates to the API server. -1 means to not send
status updates except with heartbeats. Defaults to -1.
configuration:
Environment/configuration resolution settings
-e ENV_LOCATIONS, --env ENV_LOCATIONS
Location of either local file, AWS S3 ARN, or AWS
Secrets Manager ARN containing properties used to
populate the environment for embedded mode, or the
process environment for wrapped mode. By default, the
file format is assumed to be dotenv. Specify multiple
times to include multiple locations.
--config CONFIG_LOCATIONS
Location of either local file, AWS S3 ARN, or AWS
Secrets Manager ARN containing properties used to
populate the configuration for embedded mode. By
default, the file format is assumed to be in JSON.
Specify multiple times to include multiple locations.
--config-merge-strategy {DEEP,SHALLOW,REPLACE,ADDITIVE,TYPESAFE_REPLACE,TYPESAFE_ADDITIVE}
Merge strategy for merging configurations. Defaults to
'DEEP', which does not require mergedeep. Besides the
'SHALLOW' strategy, all other strategies require the
mergedeep python package to be installed.
--overwrite_env_during_resolution
Overwrite existing environment variables when
resolving them
--config-ttl CONFIG_TTL
Number of seconds to cache resolved environment
variables and configuration properties instead of
refreshing them when a process restarts. -1 means to
never refresh. Defaults to -1.
--no-fail-fast-config-resolution
Exit immediately if an error occurs resolving the
configuration
--resolved-env-var-name-prefix RESOLVED_ENV_VAR_NAME_PREFIX
Required prefix for names of environment variables
that should resolved. The prefix will be removed in
the resolved variable name. Defaults to ''.
--resolved-env-var-name-suffix RESOLVED_ENV_VAR_NAME_SUFFIX
Required suffix for names of environment variables
that should resolved. The suffix will be removed in
the resolved variable name. Defaults to
'_FOR_PROC_WRAPPER_TO_RESOLVE'.
--resolved-config-property-name-prefix RESOLVED_CONFIG_PROPERTY_NAME_PREFIX
Required prefix for names of configuration properties
that should resolved. The prefix will be removed in
the resolved property name. Defaults to ''.
--resolved-config-property-name-suffix RESOLVED_CONFIG_PROPERTY_NAME_SUFFIX
Required suffix for names of configuration properties
that should resolved. The suffix will be removed in
the resolved property name. Defaults to
'__to_resolve'.
--env-var-name-for-config ENV_VAR_NAME_FOR_CONFIG
The name of the environment variable used to set to
the value of the JSON encoded configuration. Defaults
to not setting any environment variable.
--config-property-name-for-env CONFIG_PROPERTY_NAME_FOR_ENV
The name of the configuration property used to set to
the value of the JSON encoded environment. Defaults to
not setting any property.
rollbar:
Rollbar settings
--rollbar-access-token ROLLBAR_ACCESS_TOKEN
Access token for Rollbar (used to report error when
communicating with API server)
--rollbar-retries ROLLBAR_RETRIES
Number of retries per Rollbar request. Defaults to 2.
--rollbar-retry-delay ROLLBAR_RETRY_DELAY
Number of seconds to wait before retrying a Rollbar
request. Defaults to 120.
--rollbar-timeout ROLLBAR_TIMEOUT
Timeout for contacting Rollbar server, in seconds.
Defaults to 30.
These environment variables take precedence over command-line arguments:
* PROC_WRAPPER_TASK_NAME
* PROC_WRAPPER_TASK_UUID
* PROC_WRAPPER_TASK_EXECUTION_UUID
* PROC_WRAPPER_AUTO_CREATE_TASK (TRUE or FALSE)
* PROC_WRAPPER_AUTO_CREATE_TASK_RUN_ENVIRONMENT_NAME
* PROC_WRAPPER_AUTO_CREATE_TASK_RUN_ENVIRONMENT_UUID
* PROC_WRAPPER_AUTO_CREATE_TASK_PROPS (JSON encoded property map)
* PROC_WRAPPER_TASK_IS_PASSIVE (TRUE OR FALSE)
* PROC_WRAPPER_TASK_IS_SERVICE (TRUE or FALSE)
* PROC_WRAPPER_EXECUTION_METHOD_PROPS (JSON encoded property map)
* PROC_WRAPPER_TASK_MAX_CONCURRENCY (set to -1 to indicate no limit)
* PROC_WRAPPER_PREVENT_OFFLINE_EXECUTION (TRUE or FALSE)
* PROC_WRAPPER_TASK_VERSION_NUMBER
* PROC_WRAPPER_TASK_VERSION_TEXT
* PROC_WRAPPER_TASK_VERSION_SIGNATURE
* PROC_WRAPPER_TASK_INSTANCE_METADATA (JSON encoded property map)
* PROC_WRAPPER_LOG_LEVEL (TRACE, DEBUG, INFO, WARNING, ERROR, or CRITICAL)
* PROC_WRAPPER_LOG_SECRETS (TRUE or FALSE)
* PROC_WRAPPER_INCLUDE_TIMESTAMPS_IN_LOG (TRUE or FALSE)
* PROC_WRAPPER_DEPLOYMENT
* PROC_WRAPPER_API_BASE_URL
* PROC_WRAPPER_API_KEY
* PROC_WRAPPER_API_HEARTBEAT_INTERVAL_SECONDS
* PROC_WRAPPER_API_ERROR_TIMEOUT_SECONDS
* PROC_WRAPPER_API_RETRY_DELAY_SECONDS
* PROC_WRAPPER_API_RESUME_DELAY_SECONDS
* PROC_WRAPPER_API_TASK_EXECUTION_CREATION_ERROR_TIMEOUT_SECONDS
* PROC_WRAPPER_API_TASK_EXECUTION_CREATION_CONFLICT_TIMEOUT_SECONDS
* PROC_WRAPPER_API_TASK_EXECUTION_CREATION_CONFLICT_RETRY_DELAY_SECONDS
* PROC_WRAPPER_API_FINAL_UPDATE_TIMEOUT_SECONDS
* PROC_WRAPPER_API_REQUEST_TIMEOUT_SECONDS
* PROC_WRAPPER_ENV_LOCATIONS (comma-separated list of locations)
* PROC_WRAPPER_CONFIG_LOCATIONS (comma-separated list of locations)
* PROC_WRAPPER_OVERWRITE_ENV_WITH_SECRETS (TRUE or FALSE)
* PROC_WRAPPER_RESOLVE_SECRETS (TRUE or FALSE)
* PROC_WRAPPER_MAX_CONFIG_RESOLUTION_DEPTH
* PROC_WRAPPER_MAX_CONFIG_RESOLUTION_ITERATIONS
* PROC_WRAPPER_CONFIG_TTL_SECONDS
* PROC_WRAPPER_FAIL_FAST_CONFIG_RESOLUTION (TRUE or FALSE)
* PROC_WRAPPER_RESOLVABLE_ENV_VAR_NAME_PREFIX
* PROC_WRAPPER_RESOLVABLE_ENV_VAR_NAME_SUFFIX
* PROC_WRAPPER_RESOLVABLE_CONFIG_PROPERTY_NAME_PREFIX
* PROC_WRAPPER_RESOLVABLE_CONFIG_PROPERTY_NAME_SUFFIX
* PROC_WRAPPER_ENV_VAR_NAME_FOR_CONFIG
* PROC_WRAPPER_CONFIG_PROPERTY_NAME_FOR_ENV
* PROC_WRAPPER_SEND_PID (TRUE or FALSE)
* PROC_WRAPPER_SEND_HOSTNAME (TRUE or FALSE)
* PROC_WRAPPER_SEND_RUNTIME_METADATA (TRUE or FALSE)
* PROC_WRAPPER_ROLLBAR_ACCESS_TOKEN
* PROC_WRAPPER_ROLLBAR_TIMEOUT_SECONDS
* PROC_WRAPPER_ROLLBAR_RETRIES
* PROC_WRAPPER_ROLLBAR_RETRY_DELAY_SECONDS
* PROC_WRAPPER_MAX_CONFLICTING_AGE_SECONDS
* PROC_WRAPPER_TASK_COMMAND
* PROC_WRAPPER_SHELL_MODE (TRUE or FALSE)
* PROC_WRAPPER_STRIP_SHELL_WRAPPING (TRUE or FALSE)
* PROC_WRAPPER_WORK_DIR
* PROC_WRAPPER_PROCESS_MAX_RETRIES
* PROC_WRAPPER_PROCESS_TIMEOUT_SECONDS
* PROC_WRAPPER_PROCESS_RETRY_DELAY_SECONDS
* PROC_WRAPPER_PROCESS_CHECK_INTERVAL_SECONDS
* PROC_WRAPPER_PROCESS_TERMINATION_GRACE_PERIOD_SECONDS
* PROC_WRAPPER_PROCESS_GROUP_TERMINATION (TRUE or FALSE)
* PROC_WRAPPER_STATUS_UPDATE_SOCKET_PORT
* PROC_WRAPPER_STATUS_UPDATE_MESSAGE_MAX_BYTES
With the exception of the settings for Secret Fetching and Resolution,
these environment variables are read after Secret Fetching so that they can
come from secret values.
The command is executed with the same environment that the wrapper script gets,
except that these properties are copied/overridden:
* PROC_WRAPPER_DEPLOYMENT
* PROC_WRAPPER_API_BASE_URL
* PROC_WRAPPER_API_KEY
* PROC_WRAPPER_API_ERROR_TIMEOUT_SECONDS
* PROC_WRAPPER_API_RETRY_DELAY_SECONDS
* PROC_WRAPPER_API_RESUME_DELAY_SECONDS
* PROC_WRAPPER_API_REQUEST_TIMEOUT_SECONDS
* PROC_WRAPPER_ROLLBAR_ACCESS_TOKEN
* PROC_WRAPPER_ROLLBAR_TIMEOUT_SECONDS
* PROC_WRAPPER_ROLLBAR_RETRIES
* PROC_WRAPPER_ROLLBAR_RETRY_DELAY_SECONDS
* PROC_WRAPPER_ROLLBAR_RESUME_DELAY_SECONDS
* PROC_WRAPPER_TASK_EXECUTION_UUID
* PROC_WRAPPER_TASK_UUID
* PROC_WRAPPER_TASK_NAME
* PROC_WRAPPER_TASK_VERSION_NUMBER
* PROC_WRAPPER_TASK_VERSION_TEXT
* PROC_WRAPPER_TASK_VERSION_SIGNATURE
* PROC_WRAPPER_TASK_INSTANCE_METADATA
* PROC_WRAPPER_SCHEDULE
* PROC_WRAPPER_PROCESS_TIMEOUT_SECONDS
* PROC_WRAPPER_TASK_MAX_CONCURRENCY
* PROC_WRAPPER_PREVENT_OFFLINE_EXECUTION
* PROC_WRAPPER_PROCESS_TERMINATION_GRACE_PERIOD_SECONDS
* PROC_WRAPPER_ENABLE_STATUS_UPDATE_LISTENER
* PROC_WRAPPER_STATUS_UPDATE_SOCKET_PORT
* PROC_WRAPPER_STATUS_UPDATE_INTERVAL_SECONDS
* PROC_WRAPPER_STATUS_UPDATE_MESSAGE_MAX_BYTES
Wrapped mode is suitable for running in a shell on your own (virtual) machine
or in a Docker container. It requires multi-process support, as the module
runs at the same time as the command it wraps.
### Embedded mode
You can use embedded mode to execute python code from inside a python program.
Include the `proc_wrapper` package in your python project's
dependencies. To run a task you want to be monitored:
from typing import Any, Mapping
from proc_wrapper import ProcWrapper, ProcWrapperParams
def fun(wrapper: ProcWrapper, cbdata: dict[str, int],
config: Mapping[str, Any]) -> int:
print(cbdata)
return cbdata['a']
# This is the function signature of a function invoked by AWS Lambda.
def entrypoint(event: Any, context: Any) -> int:
params = ProcWrapperParams()
params.auto_create_task = True
# If the Task Execution is running in AWS Lambda, CloudReactor can make
# the associated Task available to run (non-passive) in the CloudReactor
# dashboard or by API, after the wrapper reports its first execution.
proc_wrapper_params.task_is_passive = False
params.task_name = 'embedded_test_production'
params.auto_create_task_run_environment_name = 'production'
# For example only, in the real world you would use Secret Fetching;
# see below.
params.api_key = 'YOUR_CLOUDREACTOR_API_KEY'
# In an AWS Lambda environment, passing the context and event allows
# CloudReactor to monitor and manage this Task.
proc_wrapper = ProcWrapper(params=params, runtime_context=context,
input_value=event)
x = proc_wrapper.managed_call(fun, {'a': 1, 'b': 2})
# Should print 1
print(x)
return x
This is suitable for running in single-threaded environments like
AWS Lambda, or as part of a larger process that executes
sub-routines that should be monitored. See
[cloudreactor-python-lambda-quickstart](https://github.com/CloudReactor/cloudreactor-python-lambda-quickstart) for an example project that uses
proc_wrapper in a function run by AWS Lambda.
#### Embedded mode configuration
In embedded mode, besides setting properties of `ProcWrapperParams` in code,
`ProcWrapper` can be also configured in two ways:
First, using environment variables, as in wrapped mode.
Second, using the configuration dictionary. If the configuration dictionary
contains the key `proc_wrapper_params` and its value is a dictionary, the
keys and values in the dictionary will be used to to set these attributes in
`ProcWrapperParams`:
| Key | Type | Mutable | Uses Resolved Config |
|---------------------------------- |----------- |--------- |---------------------- |
| log_secrets | bool | No | No |
| env_locations | list[str] | No | No |
| config_locations | list[str] | No | No |
| config_merge_strategy | str | No | No |
| overwrite_env_during_resolution | bool | No | No |
| max_config_resolution_depth | int | No | No |
| max_config_resolution_iterations | int | No | No |
| config_ttl | int | No | No |
| fail_fast_config_resolution | bool | No | No |
| resolved_env_var_name_prefix | str | No | No |
| resolved_env_var_name_suffix | str | No | No |
| resolved_config_property_name_prefix | str | No | No |
| resolved_config_property_name_suffix | str | No | No |
| schedule | str | No | Yes |
| max_concurrency | int | No | Yes |
| max_conflicting_age | int | No | Yes |
| offline_mode | bool | No | Yes |
| prevent_offline_execution | bool | No | Yes |
| service | bool | No | Yes |
| deployment | str | No | Yes |
| api_base_url | str | No | Yes |
| api_heartbeat_interval | int | No | Yes |
| enable_status_listener | bool | No | Yes |
| status_update_socket_port | int | No | Yes |
| status_update_message_max_bytes | int | No | Yes |
| status_update_interval | int | No | Yes |
| log_level | str | No | Yes |
| include_timestamps_in_log | bool | No | Yes |
| api_key | str | Yes | Yes |
| api_request_timeout | int | Yes | Yes |
| api_error_timeout | int | Yes | Yes |
| api_retry_delay | int | Yes | Yes |
| api_resume_delay | int | Yes | Yes |
| api_task_execution_creation_error_timeout | int | Yes | Yes |
| api_task_execution_creation_conflict_timeout | int | Yes | Yes |
| api_task_execution_creation_conflict_retry_delay | int | Yes | Yes |
| process_timeout | int | Yes | Yes |
| process_max_retries | int | Yes | Yes |
| process_retry_delay | int | Yes | Yes |
| command | list[str] | Yes | Yes |
| command_line | str | Yes | Yes |
| shell_mode | bool | Yes | Yes |
| strip_shell_wrapping | bool | Yes | Yes |
| work_dir | str | Yes | Yes |
| process_termination_grace_period | int | Yes | Yes |
| send_pid | bool | Yes | Yes |
| send_hostname | bool | Yes | Yes |
| send_runtime_metadata | bool | Yes | Yes |
Keys that are marked with "Mutable" -- "No" in the table above can be
overridden when the configuration is reloaded after the `config_ttl` expires.
Keys that are marked as "Uses Resolved Config" -- "Yes" in the table above can
come from the resolved configuration after secret resolution (see below).
## Secret Fetching and Resolution
A common requirement is that deployed code / images do not contain secrets
internally which could be decompiled. Instead, programs should fetch secrets
from an external source in a secure manner. If your program runs in AWS, it
can make use of AWS's roles that have permission to access data in
Secrets Manager or S3. However, in many scenarios, having your program access
AWS directly has the following disadvantages:
1) Your program becomes coupled to AWS, so it is difficult to run locally or
switch to another infrastructure provider
2) You need to write code or use a library for each programming language you
use, so secret fetching is done in a non-uniform way
3) Writing code to merge and parse secrets from different sources is tedious
Therefore, proc_wrapper implements Secret Fetching and Resolution to solve
these problems so your programs don't have to. Both usage modes can fetch secrets from
[AWS Secrets Manager](https://aws.amazon.com/secrets-manager/),
AWS S3, or the local filesystem, and optionally extract embedded data
into the environment or a configuration dictionary. The environment is used to
pass values to processes run in wrapped mode,
while the configuration dictionary is passed to the callback function in
embedded mode.
proc_wrapper parses secret location strings that specify the how to resolve
a secret value. Each secret location string has the format:
`[PROVIDER_CODE:]<Provider specific address>[!FORMAT][|JP:<JSON Path expression>]`
### Secret Providers
Providers indicate the raw source of the secret data. The table below lists the
supported providers:
| Provider Code | Value Prefix | Provider | Example Address | Required libs | Notes |
|--------------- |--------------------------- |------------------------------ |------------------------------------------------------------- |----------------------------------------------------------------------------- |--------------------------------------------------------------- |
| `AWS_SM` | `arn:aws:secretsmanager:` | AWS Secrets Manager | `arn:aws:secretsmanager:us-east-2:1234567890:secret:config` | [boto3](https://boto3.amazonaws.com/v1/documentation/api/latest/index.html) | Can also include version suffix like `-PPrpY` |
| `AWS_S3` | `arn:aws:s3:::` | AWS S3 Object | `arn:aws:s3:::examplebucket/staging/app1/config.json` | [boto3](https://boto3.amazonaws.com/v1/documentation/api/latest/index.html) | |
| `FILE` | `file://` | Local file | `file:///home/appuser/app/.env` | | The default provider if no provider is auto-detected |
| `ENV` | | The process environment | `SOME_TOKEN` | | The name of another environment variable |
| `CONFIG` | | The configuration dictionary | `$.db` | [jsonpath-ng](https://github.com/h2non/jsonpath-ng) | JSON path expression to extract the data in the configuration |
| `PLAIN` | | Plaintext | `{"user": "postgres", "password": "badpassword"}` | | |
If you don't specify an explicit provider prefix in a secret location
(e.g. `AWS_SM:`), the provider can be auto-detected from the address portion
using the Value Prefix. For example the secret location
`arn:aws:s3:::examplebucket/staging/app1/config.json` will be auto-detected
to with the AWS_S3 provider because it starts with `arn:aws:s3:::`.
### Secret Formats
Formats indicate how the raw string data is parsed into a secret value (which may be
a string, number, boolean, dictionary, or array). The table below lists the
supported formats:
| Format Code | Extensions | MIME types | Required libs | Notes |
|------------- |----------------- |--------------------------------------------------------------------------------------- |------------------------------------------------------ |-------------------------------------------------- |
| `dotenv` | `.env` | None | [dotenv](https://github.com/theskumar/python-dotenv) | Also auto-detected if location includes `.env.` |
| `json` | `.json` | `application/json`, `text/x-json` | | |
| `yaml` | `.yaml`, `.yml` | `application/x-yaml`, `application/yaml`, `text/vnd.yaml`, `text/yaml`, `text/x-yaml` | [pyyaml](https://pyyaml.org/) | `safe_load()` is used for security |
The format of a secret value can be auto-detected from the extension or by the
MIME type if available. Otherwise, you may need to an explicit format code
(e.g. `!yaml`).
#### AWS Secrets Manager / S3 notes
[boto3](https://boto3.amazonaws.com/v1/documentation/api/latest/index.html)
is used to fetch secrets. It will try to access to AWS Secrets Manager
or S3 using environment variables `AWS_ACCESS_KEY_ID` and
`AWS_SECRET_ACCESS_KEY` if they are set, or use the EC2 instance role, ECS task
role, or Lambda execution role if available.
For Secrets Manager, you can also use "partial ARNs"
(without the hyphened suffix) as keys.
In the example above
arn:aws:secretsmanager:us-east-2:1234567890:secret:config
could be used to fetch the same secret, provided there are no conflicting secret ARNs.
This allows you to get the latest version of the secret.
If the secret was stored in Secrets Manager as binary, the
corresponding value will be set to the Base-64 encoded value.
If you're deploying a python function using AWS Lambda, note that boto3 is
already included in the available packages, so there's no need to include it
(unless the bundled version isn't compatible). Also we strongly encourage you
to add:
logging.getLogger("botocore").setLevel(logging.INFO)
to your code if you are using proc_wrapper for secrets resolution. This
prevent secrets from Secrets Manager from being leaked. For details, see this
[issue](https://github.com/boto/boto3/issues/2292).
### Secret Tranformation
Fetching secrets can be relatively expensive and it makes sense to group related
secrets together. Therefore it is common to store dictionaries (formatted
as JSON or YAML) as secrets. However, each desired environment variable
or configuration property may only consist of a fragment of the dictionary.
For example, given the JSON-formatted dictionary
{
"username": "postgres",
"password": "badpassword"
}
you may want to populate the environment variable `DB_USERNAME` with
`postgres`.
To facilitate this, dictionary fragments can be extracted to individual
environment variables using [jsonpath-ng](https://github.com/h2non/jsonpath-ng).
To specify that a variable be extracted from a dictionary using
a JSON Path expression, append `|JP:` followed by the JSON Path expression
to the secret location string. For example, if the AWS Secrets Manager
ARN
arn:aws:secretsmanager:us-east-2:1234567890:secret:db-PPrpY
contains the dictionary above, then the secret location string
arn:aws:secretsmanager:us-east-2:1234567890:secret:db-PPrpY|JP:$.username
will resolve to `postgres` as desired.
If you do something similar to get the password from the same JSON value,
proc_wrapper is smart enough to cache the fetched dictionary, so that the
raw data is only fetched once.
Since JSON path expressions yield a list of results, the secrets fetcher
implements the following rules to transform the list to the final value:
1. If the list of results has a single value, that value is used as the
final value, unless `[*]` is appended to the JSON path expression.
2. Otherwise, the final value is the list of results
#### Fetching from another environment variable
In some deployment scenarios, multiple secrets can be injected into a
single environment variable as a JSON encoded object. In that case,
the module can extract secrets using the *ENV* secret source. For example,
you may have arranged to have the environment variable DB_CONFIG injected
with the JSON encoded value:
{ "username": "postgres", "password": "nohackme" }
Then to extract the username to the environment variable DB_USERNAME you
you would add the environment variable DB_USER_FOR_PROC_WRAPPER_TO_RESOLVE
set to
ENV:DB_CONFIG|JP:$.username
### Secret injection into environment and configuration
Now let's use secret location strings to
inject the values into the environment (for wrapped mode)
and/or the the configuration dictionary (for embedded mode). proc_wrapper
supports two methods of secret injection which can be combined together:
* Top-level fetching
* Secrets Resolution
### Top-level fetching
Top-level fetching refers to fetching a dictionary that contains multiple secrets
and populating the environment / configuration dictionary with it.
To use top-level fetching, you specify the secret locations
from which you want to fetch the secrets and the corresponding values are
merged together into the environment / configuration.
To use top-level fetching in wrapped mode, populate the
environment variables `PROC_WRAPPER_ENV_LOCATIONS` with a comma-separated
list of secret locations, or use the command-line option
`--env-locations <secret_location>` one or more times. Secret location
strings passed in via `PROC_WRAPPER_ENV_LOCATIONS` or `--env-locations`
will be parsed as `dotenv` files unless format is auto-detected or
explicitly specified.
To use top-level fetching in embedded mode, set the `ProcWrapperParams` property
`config_locations` to a list of secret locations. Alternatively, you can set
the environment variable `PROC_WRAPPER_CONFIG_LOCATIONS` to a comma-separated
list, and this will be picked up automatically. Secret location values
will be parsed as JSON unless the format is auto-detected or explicitly
specified. The `config` argument
passed to the your callback function will contain a merged dictionary of all
fetched and parsed dictionary values. For example:
def callback(wrapper: ProcWrapper, cbdata: str,
config: Dict[str, Any]) -> str:
return "super" + cbdata + config["username"]
def main():
params = ProcWrapperParams()
# Optional: you can set an initial configuration dictionary which will
# have its values included in the final configuration unless overridden.
params.initial_config = {
"log_level": "DEBUG"
}
# You can omit this if you set PROC_WRAPPER_CONFIG_LOCATIONS environment
# variable to the same ARN
params.config_locations = [
"arn:aws:secretsmanager:us-east-2:1234567890:secret:db-PPrpY",
# More secret locations can be added here, and their values will
# be merged
]
wrapper = ProcWrapper(params=params)
# Returns "superduperpostgres"
return wrapper.managed_call(callback, "duper")
#### Merging Secrets
Top-level fetching can potentially fetch multiple dictionaries which are
merged together in the final environment / configuration dictionary.
The default merge strategy (`DEEP`) merges recursively, even dictionaries
in lists. The `SHALLOW` merge strategy just overwrites top-level keys, with later
secret locations taking precedence. However, if you include the
[mergedeep](https://github.com/clarketm/mergedeep) library, you can also
set the merge strategy to one of:
* `REPLACE`
* `ADDITIVE`
* `TYPESAFE_REPLACE`
* `TYPESAFE_ADDITIVE`
so that nested lists can be appended to instead of replaced (in the case of the
`ADDITIVE` strategies), or errors will be raised if incompatibly-typed values
are merged (in the case of the `TYPESAFE` strategies). In wrapped mode,
the merge strategy can be set with the `--config-merge-strategy` command-line
argument or `PROC_WRAPPER_CONFIG_MERGE_STRATEGY` environment variable. In
embedded mode, the merge strategy can be set in the
`config_merge_strategy` string property of `ProcWrapperParams`.
### Secret Resolution
Secret Resolution substitutes configuration or environment values that are
secret location strings with the computed values of those strings. Compared
to Secret Fetching, Secret Resolution is more useful when you want more
control over the names of variables or when you have secret values deep
inside your configuration.
In wrapped mode, if you want to set the environment variable `MY_SECRET` with
a value fetched
from AWS Secrets Manager, you would set the environment variable
`MY_SECRET_FOR_PROC_WRAPPER_TO_RESOLVE` to a secret location string
which is ARN of the secret, for example:
arn:aws:secretsmanager:us-east-2:1234567890:secret:db-PPrpY
(The `_FOR_PROC_WRAPPER_TO_RESOLVE` suffix of environment variable names is
removed during resolution. It can also be configured with the `PROC_WRAPPER_RESOLVABLE_ENV_VAR_NAME_SUFFIX` environment variable.)
In embedded mode, if you want the final configuration dictionary to look like:
{
"db_username": "postgres",
"db_password": "badpassword",
...
}
The initial configuration dictionary would look like:
{
"db_username__to_resolve": "arn:aws:secretsmanager:us-east-2:1234567890:secret:db-PPrpY|JP:$.username",
"db_password__to_resolve": "arn:aws:secretsmanager:us-east-2:1234567890:secret:db-PPrpY|JP:$.password",
...
}
(The `__to_resolve` suffix (with 2 underscores!) of keys is removed during
resolution. It can also be configured with the `resolved_config_property_name_suffix`
property of `ProcWrapperParams`.)
proc_wrapper can also resolve keys in embedded dictionaries, like:
{
"db": {
"username__to_resolve": "arn:aws:secretsmanager:us-east-2:1234567890:secret:config-PPrpY|JP:$.username",
"password__to_resolve":
"arn:aws:secretsmanager:us-east-2:1234567890:secret:config-PPrpY|JP:$.password",
...
},
...
}
up to a maximum depth that you can control with `ProcWrapperParams.max_config_resolution_depth` (which defaults to 5). That would resolve to
{
"db": {
"username": "postgres",
"password": "badpassword"
...
},
...
}
You can also inject entire dictionaries, like:
{
"db__to_resolve": "arn:aws:secretsmanager:us-east-2:1234567890:secret:config-PPrpY",
...
}
which would resolve to
{
"db": {
"username": "postgres",
"password": "badpassword"
},
...
}
To enable secret resolution in wrapped mode, set environment variable `PROC_WRAPPER_RESOLVE_SECRETS` to `TRUE`. In embedded mode, secret
resolution is enabled by default; set the
`max_config_resolution_iterations` property of `ProcWrapperParams` to `0`
to disable resolution.
Secret resolution is run multiple times so that if a resolved value contains
a secret location string, it will be resolved on the next pass. By default,
proc_wrapper limits the maximum number of resolution passes to 3 but you
can control this with the environment variable
`PROC_WRAPPER_MAX_CONFIG_RESOLUTION_ITERATIONS` in embedded mode,
or by setting the `max_config_resolution_iterations` property of
`ProcWrapperParams` in wrapped mode.
### Environment Projection
During secret fetching and secret resolution, proc_wrapper internally maintains
the computed environment as a dictionary which may have embedded lists and
dictionaries. However, the final environment passed to the process is a flat
dictionary containing only string values. So proc_wrapper converts
all top-level values to strings using these rules:
* Lists and dictionaries are converted to their JSON-encoded string value
* Boolean values are converted to their upper-cased string representation
(e.g. the string `FALSE` for the boolean value `false`)
* The `None` value is converted to the empty string
* All other values are converted using python's `str()` function
### Secrets Refreshing
You can set a Time to Live (TTL) on the duration that secret values are cached.
Caching helps reduce expensive lookups of secrets and bandwidth usage.
In wrapped mode, set the TTL of environment variables set from secret locations
using the `--config-ttl` command-line argument or
`PROC_WRAPPER_CONFIG_TTL_SECONDS` environment variable.
If the process exits, you have configured the script to retry,
and the TTL has expired since the last fetch,
proc_wrapper will re-fetch the secrets
and resolve them again, for the environment passed to the next invocation of
your process.
In embedded mode, set the TTL of configuration dictionary values set from
secret locations by setting the `config_ttl` property of
`ProcWrapperParams`. If 1) your callback function raises an exception, 2) you have
configured the script to retry; and 3) the TTL has expired since the last fetch,
proc_wrapper will re-fetch the secrets
and resolve them again, for the configuration passed to the next invocation of
the callback function.
## Status Updates
### Status Updates in Wrapped Mode
While your process in running, you can send status updates to
CloudReactor by using the StatusUpdater class. Status updates are shown in
the CloudReactor dashboard and allow you to track the current progress of a
Task and also how many items are being processed in multiple executions
over time.
In wrapped mode, your application code would send updates to the
proc_wrapper program via UDP port 2373 (configurable with the PROC_WRAPPER_STATUS_UPDATE_PORT environment variable).
If your application code is in python, you can use the provided
StatusUpdater class to do this:
from proc_wrapper import StatusUpdater
with StatusUpdater() as updater:
updater.send_update(last_status_message="Starting ...")
success_count = 0
for i in range(100):
try:
do_work()
success_count += 1
updater.send_update(success_count=success_count)
except Exception:
failed_count += 1
updater.send_update(failed_count=failed_count)
updater.send_update(last_status_message="Finished!")
### Status Updates in Embedded Mode
In embedded mode, your callback in python code can use the wrapper instance to
send updates:
from typing import Any, Mapping
import proc_wrapper
from proc_wrapper import ProcWrapper
def fun(wrapper: ProcWrapper, cbdata: dict[str, int],
config: Mapping[str, Any]) -> int:
wrapper.update_status(last_status_message="Starting the fun ...")
success_count = 0
error_count = 0
for i in range(100):
try:
do_work()
success_count += 1
except Exception:
error_count += 1
wrapper.update_status(success_count=success_count,
error_count=error_count)
wrapper.update_status(last_status_message="The fun is over.")
return cbdata["a"]
params = ProcWrapperParams()
params.auto_create_task = True
params.auto_create_task_run_environment_name = "production"
params.task_name = "embedded_test"
params.api_key = "YOUR_CLOUDREACTOR_API_KEY"
proc_wrapper = ProcWrapper(params=params)
proc_wrapper.managed_call(fun, {"a": 1, "b": 2})
## Example Projects
These projects contain sample Tasks that use this library to report their
execution status and results to CloudReactor
* [cloudreactor-python-ecs-quickstart](https://github.com/CloudReactor/cloudreactor-python-ecs-quickstart) runs python code in a Docker container
in AWS ECS Fargate (wrapped mode)
* [cloudreactor-python-lambda-quickstart](https://github.com/CloudReactor/cloudreactor-python-lambda-quickstart) runs python code in AWS Lambda
(embedded mode)
* [cloudreactor-java-ecs-quickstart](https://github.com/CloudReactor/cloudreactor-java-ecs-quickstart) runs Java code in a Docker container in
AWS ECS Fargate (wrapped mode)
## License
This software is dual-licensed under open source (MPL 2.0) and commercial
licenses. See `LICENSE` for details.
## Contributors ✨
Thanks goes to these wonderful people ([emoji key](https://allcontributors.org/docs/en/emoji-key)):
<!-- ALL-CONTRIBUTORS-LIST:START - Do not remove or modify this section -->
<!-- prettier-ignore-start -->
<!-- markdownlint-disable -->
<table>
<tr>
<td align="center"><a href="https://github.com/jtsay362"><img src="https://avatars0.githubusercontent.com/u/1079646?s=460&v=4?s=80" width="80px;" alt=""/><br /><sub><b>Jeff Tsay</b></sub></a><br /><a href="https://github.com/CloudReactor/cloudreactor-procwrapper/commits?author=jtsay362" title="Code">💻</a> <a href="https://github.com/CloudReactor/cloudreactor-procwrapper/commits?author=jtsay362" title="Documentation">📖</a> <a href="#infra-jtsay362" title="Infrastructure (Hosting, Build-Tools, etc)">🚇</a> <a href="#maintenance-jtsay362" title="Maintenance">🚧</a></td>
<td align="center"><a href="https://github.com/mwaldne"><img src="https://avatars0.githubusercontent.com/u/40419?s=460&u=3a5266861feeb27db392622371ecc57ebca09f32&v=4?s=80" width="80px;" alt=""/><br /><sub><b>Mike Waldner</b></sub></a><br /><a href="https://github.com/CloudReactor/cloudreactor-procwrapper/commits?author=mwaldne" title="Code">💻</a></td>
<td align="center"><a href="https://browniebroke.com/"><img src="https://avatars.githubusercontent.com/u/861044?v=4?s=80" width="80px;" alt=""/><br /><sub><b>Bruno Alla</b></sub></a><br /><a href="https://github.com/CloudReactor/cloudreactor-procwrapper/commits?author=browniebroke" title="Code">💻</a> <a href="#ideas-browniebroke" title="Ideas, Planning, & Feedback">🤔</a> <a href="https://github.com/CloudReactor/cloudreactor-procwrapper/commits?author=browniebroke" title="Documentation">📖</a></td>
</tr>
</table>
<!-- markdownlint-restore -->
<!-- prettier-ignore-end -->
<!-- ALL-CONTRIBUTORS-LIST:END -->
This project follows the [all-contributors](https://github.com/all-contributors/all-contributors) specification. Contributions of any kind welcome!
## Credits
This package was created with
[Cookiecutter](https://github.com/audreyr/cookiecutter) and the
[browniebroke/cookiecutter-pypackage](https://github.com/browniebroke/cookiecutter-pypackage)
project template.
%package -n python3-cloudreactor-procwrapper
Summary: Wraps the execution of processes so that a service API endpoint (CloudReactor) can monitor and manage them. Also implements retries, timeouts, and secret injection from AWS into the environment.
Provides: python-cloudreactor-procwrapper
BuildRequires: python3-devel
BuildRequires: python3-setuptools
BuildRequires: python3-pip
%description -n python3-cloudreactor-procwrapper
# cloudreactor-procwrapper
<p align="center">
<a href="https://github.com/CloudReactor/cloudreactor-procwrapper/actions?query=workflow%3ACI">
<img src="https://img.shields.io/github/workflow/status/CloudReactor/cloudreactor-procwrapper/CI/main?label=CI&logo=github&style=flat-square" alt="CI Status" >
</a>
<a href="https://cloudreactor-procwrapper.readthedocs.io">
<img src="https://img.shields.io/readthedocs/cloudreactor-procwrapper.svg?logo=read-the-docs&logoColor=fff&style=flat-square" alt="Documentation Status">
</a>
<a href="https://codecov.io/gh/CloudReactor/cloudreactor-procwrapper">
<img src="https://img.shields.io/codecov/c/github/CloudReactor/cloudreactor-procwrapper.svg?logo=codecov&logoColor=fff&style=flat-square" alt="Test coverage percentage">
</a>
</p>
<p align="center">
<a href="https://python-poetry.org/">
<img src="https://img.shields.io/badge/packaging-poetry-299bd7?style=flat-square&logo=data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAA4AAAASCAYAAABrXO8xAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAJJSURBVHgBfZLPa1NBEMe/s7tNXoxW1KJQKaUHkXhQvHgW6UHQQ09CBS/6V3hKc/AP8CqCrUcpmop3Cx48eDB4yEECjVQrlZb80CRN8t6OM/teagVxYZi38+Yz853dJbzoMV3MM8cJUcLMSUKIE8AzQ2PieZzFxEJOHMOgMQQ+dUgSAckNXhapU/NMhDSWLs1B24A8sO1xrN4NECkcAC9ASkiIJc6k5TRiUDPhnyMMdhKc+Zx19l6SgyeW76BEONY9exVQMzKExGKwwPsCzza7KGSSWRWEQhyEaDXp6ZHEr416ygbiKYOd7TEWvvcQIeusHYMJGhTwF9y7sGnSwaWyFAiyoxzqW0PM/RjghPxF2pWReAowTEXnDh0xgcLs8l2YQmOrj3N7ByiqEoH0cARs4u78WgAVkoEDIDoOi3AkcLOHU60RIg5wC4ZuTC7FaHKQm8Hq1fQuSOBvX/sodmNJSB5geaF5CPIkUeecdMxieoRO5jz9bheL6/tXjrwCyX/UYBUcjCaWHljx1xiX6z9xEjkYAzbGVnB8pvLmyXm9ep+W8CmsSHQQY77Zx1zboxAV0w7ybMhQmfqdmmw3nEp1I0Z+FGO6M8LZdoyZnuzzBdjISicKRnpxzI9fPb+0oYXsNdyi+d3h9bm9MWYHFtPeIZfLwzmFDKy1ai3p+PDls1Llz4yyFpferxjnyjJDSEy9CaCx5m2cJPerq6Xm34eTrZt3PqxYO1XOwDYZrFlH1fWnpU38Y9HRze3lj0vOujZcXKuuXm3jP+s3KbZVra7y2EAAAAAASUVORK5CYII=" alt="Poetry">
</a>
<a href="https://github.com/pre-commit/pre-commit">
<img src="https://img.shields.io/badge/pre--commit-enabled-brightgreen?logo=pre-commit&logoColor=white&style=flat-square" alt="pre-commit">
</a>
</p>
<p align="center">
<a href="https://pypi.org/project/cloudreactor-procwrapper/">
<img src="https://img.shields.io/pypi/v/cloudreactor-procwrapper.svg?logo=python&logoColor=fff&style=flat-square" alt="PyPI Version">
</a>
<img src="https://img.shields.io/pypi/pyversions/cloudreactor-procwrapper.svg?style=flat-square&logo=python&logoColor=fff" alt="Supported Python versions">
<img src="https://img.shields.io/pypi/l/cloudreactor-procwrapper.svg?style=flat-square" alt="License">
</p>
Wraps the execution of processes so that an API server
([CloudReactor](https://cloudreactor.io/))
can monitor and manage them.
Available as a standalone executable or as a python module.
## Features
* Runs either processes started with a command line or a python function you
supply
* Implements retries and time limits
* Injects secrets from AWS Secrets Manager, AWS S3, or local files and extracts
them into the process environment (for command-lines) or configuration (for
functions)
* When used with the CloudReactor service:
* Reports when a process/function starts and when it exits, along with the
exit code and runtime metadata (if running in AWS ECS or AWS Lambda)
* Sends heartbeats, optionally with status information like the number of
items processed
* Prevents too many concurrent executions
* Stops execution when manually stopped in the CloudReactor dashboard
* Sends CloudReactor the data necessary to start the process / function if running in AWS ECS or AWS Lambda
## How it works
First, secrets and other configuration are fetched and resolved from
providers like AWS Secrets Manager, AWS S3, or the local filesystem.
Just before your code runs, the module requests the API server to create a
Task Execution associated with the Task name or UUID which you pass to the
module.
The API server may reject the request if too many instances of the Task are
currently running, but otherwise records that a Task Execution has started.
The module then passes control to your code.
While your code is running, it may report progress to the API server,
and the API server may signal that your Task stop execution (due to
user manually stopping the Task Execution), in which
case the module terminates your code and exits.
After your code finishes, the module informs the API server of
the exit code or result. CloudReactor monitors Tasks to ensure they
are still responsive, and keeps a history of the Executions of Tasks,
allowing you to view failures and run durations in the past.
### Auto-created Tasks
Before your Task is run (including this module),
the [AWS ECS CloudReactor Deployer](https://github.com/CloudReactor/aws-ecs-cloudreactor-deployer)
can be used to set it up in AWS ECS,
and inform CloudReactor of details of your Task.
That way CloudReactor can start and schedule your Task, and setup your
Task as a service.
See [CloudReactor python ECS QuickStart](https://github.com/CloudReactor/cloudreactor-python-ecs-quickstart)
for an example.
However, it may not be possible or desired to change your deployment process.
Instead, you may configure the Task to be *auto-created*.
Auto-created Tasks are created the first time your Task runs.
This means there is no need to inform the API server of the Task details
(during deployment) before it runs.
Instead, each time the module runs, it informs the API server of the
Task details at the same time as it requests the creation of a Task Execution.
One disadvantage of auto-created Tasks is that they are not available
in the CloudReactor dashboard until the first time they run.
When configuring a Task to be auto-created, you must specify the name
or UUID of the Run Environment in CloudReactor that the Task is
associated with. The Run Environment must be created ahead of time,
either by the Cloudreactor AWS Setup Wizard,
or manually in the CloudReactor dashboard.
You can also specify more Task properties, such as Alert Methods and
external links in the dashboard, by setting the environment variable
`PROC_WRAPPER_AUTO_CREATE_TASK_PROPS` set to a JSON-encoded object that has the
[CloudReactor Task schema](https://apidocs.cloudreactor.io/#operation/tasks_create).
### Execution Methods
CloudReactor currently supports three Execution Methods:
1) [AWS ECS (in Fargate)](https://aws.amazon.com/fargate/)
2) [AWS Lambda](https://aws.amazon.com/lambda/)
3) Unknown
If a Task is running in AWS ECS, CloudReactor is able to run additional
Task Executions, provided the details of running the Task is provided
during deployment with the AWS ECS CloudReactor Deployer, or if the
Task is configured to be auto-created, and this module is run. In the
second case, this module uses the ECS Metadata endpoint to detect
the ECS Task settings, and sends them to the API server. CloudReactor
can also schedule Tasks or setup long-running services using Tasks,
provided they are run in AWS ECS.
If a Task is running in AWS Lambda, CloudReactor is able to run additional
Task Executions after the first run of the function.
However, a Task may use the Unknown execution method if it is not running
in AWS ECS or Lambda. If that is the case, CloudReactor won't be able to
start the Task in the dashboard or as part of a Workflow,
schedule the Task, or setup a service with the Task. But the advantage is
that the Task code can be executed by any method available to you,
such as bare metal servers, VM's, or Kubernetes.
All Tasks in CloudReactor, regardless of execution method, have their
history kept and are monitored.
This module detects the execution method your Task is
running with and sends that information to the API server, provided
you configure your Task to be auto-created.
### Passive Tasks
Passive Tasks are Tasks that CloudReactor does not manage. This means
scheduling and service setup must be handled by other means
(cron jobs, [supervisord](http://supervisord.org/), etc).
However, Tasks marked as services or that have a schedule will still be
monitored by CloudReactor, which will send notifications if
a service Task goes down or a Task does not run on schedule.
The module reports to the API server that auto-created Tasks are passive,
unless you specify the `--force-task-passive` commmand-line option or
set the environment variable `PROC_WRAPPER_TASK_IS_PASSIVE` to `FALSE`.
If a Task uses the Unknown Execution Method, it must be marked as passive,
because CloudReactor does not know how to manage it.
## Pre-requisites
If you just want to use this module to retry processes, limit execution time,
or fetch secrets, you can use offline mode, in which case no CloudReactor API
key is required. But CloudReactor offers a free tier so we hope you
[sign up](https://dash.cloudreactor.io/signup)
for a free account to enable monitoring and/or management.
If you want CloudReactor to be able to start your Tasks, you should use the
[Cloudreactor AWS Setup Wizard](https://github.com/CloudReactor/cloudreactor-aws-setup-wizard)
to configure your AWS environment to run Tasks in ECS Fargate.
You can skip this step if running in passive mode is OK for you.
If you want to use CloudReactor to manage or just monitor your Tasks,
you need to create a Run Environment and an API key in the CloudReactor
dashboard. The API key can be scoped to the Run Environment if you
wish. The key must have at least the Task access level, but for
an auto-created Task, it must have at least the Developer access level.
## Installation
### Nuitka
Standalone executables built by
[nuitka](https://nuitka.net/index.html)
for 64-bit Linux are available, located in `bin/nuitka`. These executables bundle
python so you don't need to have python installed on your machine. They also
bundle all optional library dependencies so you can fetch secrets from AWS
Secrets Manager and extract them with jsonpath-ng, for example.
Compared to executables built by PyInstaller (see below), they start up faster,
and most likely are more efficient at runtime.
#### RHEL or derivatives
To download and run the wrapper on a RHEL/Fedora/Amazon Linux 2 machine:
RUN wget -nv https://github.com/CloudReactor/cloudreactor-procwrapper/raw/5.0.2/bin/nuitka/al2/5.0.2/proc_wrapper.bin
ENTRYPOINT ["proc_wrapper.bin"]
Example Dockerfiles of known working environments are available for
[Amazon Linux 2](tests/integration/nuitka_executable/docker_context_al2_amd64/)
and
[Fedora](tests/integration/nuitka_executable/docker_context_al2_amd64/Dockerfile).
Fedora 27 or later are supported.
#### Debian based systems
On a Debian based (including Ubuntu) machine:
RUN wget -nv https://github.com/CloudReactor/cloudreactor-procwrapper/raw/5.0.2/bin/nuitka/debian-amd64/5.0.2/proc_wrapper.bin
ENTRYPOINT ["proc_wrapper.bin"]
See the example
[Dockerfile](tests/integration/nuitka_executable/docker_context_debian_amd64/Dockerfile) for a known working Debian environment.
Debian 10 (Buster) or later are supported.
### PyInstaller
Standalone executables built by [PyInstaller](https://www.pyinstaller.org/) for 64-bit Linux and Windows are available, located in `bin/pyinstaller`.
These executables bundle
python so you don't need to have python installed on your machine. They also
bundle all optional library dependencies so you can fetch secrets from AWS
Secrets Manager and extract them with jsonpath-ng, for example. Compared to
executables built by nuitka, they start up slower but might be more reliable.
#### RHEL or derivatives
To download and run the wrapper on a RHEL/Fedora/Amazon Linux 2 machine:
RUN wget -nv https://github.com/CloudReactor/cloudreactor-procwrapper/raw/5.0.2/bin/pyinstaller/al2/5.0.2/proc_wrapper.bin
ENTRYPOINT ["proc_wrapper.bin"]
Example Dockerfiles of known working environments are available for
[Amazon Linux 2](tests/integration/pyinstaller_executable/docker_context_al2_amd64/)
and
[Fedora](tests/integration/pyinstaller_executable/docker_context_al2_amd64/Dockerfile).
Fedora 27 or later are supported.
#### Debian based machines
On a Debian based (including Ubuntu) machine:
RUN wget -nv https://github.com/CloudReactor/cloudreactor-procwrapper/raw/5.0.2/bin/pyinstaller/debian-amd64/5.0.2/proc_wrapper.bin
ENTRYPOINT ["proc_wrapper.bin"]
See the example
[Dockerfile](tests/integration/pyinstaller_executable/docker_context_debian_amd64/Dockerfile) for a known working Debian environment.
Debian 10 (Buster) or later are supported.
Special thanks to
[wine](https://www.winehq.org/) and
[PyInstaller Docker Images](https://github.com/cdrx/docker-pyinstaller)
for making it possible to cross-compile!
### When python is available
Install this module via pip (or your favorite package manager):
`pip install cloudreactor-procwrapper`
Fetching secrets from AWS Secrets Manager requires that
[boto3](https://boto3.amazonaws.com/v1/documentation/api/latest/index.html) is available to import in your python environment.
JSON Path transformation requires that [jsonpath-ng](https://github.com/h2non/jsonpath-ng)
be available to import in your python environment.
You can get the tested versions of both dependencies in
[proc_wrapper-requirements.in](https://github.com/CloudReactor/cloudreactor-procwrapper/blob/main/proc_wrapper-requirements.in)
(suitable for use by [pip-tools](https://github.com/jazzband/pip-tools/)) or the resolved requirements in
[proc_wrapper-requirements.txt](https://github.com/CloudReactor/cloudreactor-procwrapper/blob/main/proc_wrapper-requirements.txt).
## Usage
There are two ways of using the module: wrapped mode and embedded mode.
### Wrapped mode
In wrapped mode, you pass a command line to the module which it
executes in a child process. The command can be implemented in whatever
programming language the running machine supports.
Instead of running
somecommand --somearg x
you would run
./proc_wrapper somecommand --somearg x
assuming that are using the PyInstaller standalone executable, and that
you configure the program using environment variables.
Or, if you have python installed:
python -m proc_wrapper somecommand --somearg x
Here are all the options:
usage: proc_wrapper [-h] [-v] [-n TASK_NAME] [--task-uuid TASK_UUID] [-a]
[--auto-create-task-run-environment-name AUTO_CREATE_TASK_RUN_ENVIRONMENT_NAME]
[--auto-create-task-run-environment-uuid AUTO_CREATE_TASK_RUN_ENVIRONMENT_UUID]
[--auto-create-task-props AUTO_CREATE_TASK_PROPS]
[--force-task-active]
[--task-execution-uuid TASK_EXECUTION_UUID]
[--task-version-number TASK_VERSION_NUMBER]
[--task-version-text TASK_VERSION_TEXT]
[--task-version-signature TASK_VERSION_SIGNATURE]
[--execution-method-props EXECUTION_METHOD_PROPS]
[--task-instance-metadata TASK_INSTANCE_METADATA] [-s]
[--schedule SCHEDULE] [--max-concurrency MAX_CONCURRENCY]
[--max-conflicting-age MAX_CONFLICTING_AGE]
[--api-base-url API_BASE_URL] [-k API_KEY]
[--api-heartbeat-interval API_HEARTBEAT_INTERVAL]
[--api-error-timeout API_ERROR_TIMEOUT]
[--api-final-update-timeout API_FINAL_UPDATE_TIMEOUT]
[--api-retry-delay API_RETRY_DELAY]
[--api-resume-delay API_RESUME_DELAY]
[--api-task-execution-creation-error-timeout API_TASK_EXECUTION_CREATION_ERROR_TIMEOUT]
[--api-task-execution-creation-conflict-timeout API_TASK_EXECUTION_CREATION_CONFLICT_TIMEOUT]
[--api-task-execution-creation-conflict-retry-delay API_TASK_EXECUTION_CREATION_CONFLICT_RETRY_DELAY]
[--api-request-timeout API_REQUEST_TIMEOUT] [-o] [-p]
[-d DEPLOYMENT] [--send-pid] [--send-hostname]
[--no-send-runtime-metadata]
[-l {DEBUG,INFO,WARNING,ERROR,CRITICAL}] [--log-secrets]
[--exclude-timestamps-in-log] [-w WORK_DIR]
[-c COMMAND_LINE] [--shell-mode {auto,enable,disable}]
[--no-strip-shell-wrapping]
[--no-process-group-termination] [-t PROCESS_TIMEOUT]
[-r PROCESS_MAX_RETRIES]
[--process-retry-delay PROCESS_RETRY_DELAY]
[--process-check-interval PROCESS_CHECK_INTERVAL]
[--process-termination-grace-period PROCESS_TERMINATION_GRACE_PERIOD]
[--enable-status-update-listener]
[--status-update-socket-port STATUS_UPDATE_SOCKET_PORT]
[--status-update-message-max-bytes STATUS_UPDATE_MESSAGE_MAX_BYTES]
[--status-update-interval STATUS_UPDATE_INTERVAL]
[-e ENV_LOCATIONS] [--config CONFIG_LOCATIONS]
[--config-merge-strategy {DEEP,SHALLOW,REPLACE,ADDITIVE,TYPESAFE_REPLACE,TYPESAFE_ADDITIVE}]
[--overwrite_env_during_resolution]
[--config-ttl CONFIG_TTL]
[--no-fail-fast-config-resolution]
[--resolved-env-var-name-prefix RESOLVED_ENV_VAR_NAME_PREFIX]
[--resolved-env-var-name-suffix RESOLVED_ENV_VAR_NAME_SUFFIX]
[--resolved-config-property-name-prefix RESOLVED_CONFIG_PROPERTY_NAME_PREFIX]
[--resolved-config-property-name-suffix RESOLVED_CONFIG_PROPERTY_NAME_SUFFIX]
[--env-var-name-for-config ENV_VAR_NAME_FOR_CONFIG]
[--config-property-name-for-env CONFIG_PROPERTY_NAME_FOR_ENV]
[--rollbar-access-token ROLLBAR_ACCESS_TOKEN]
[--rollbar-retries ROLLBAR_RETRIES]
[--rollbar-retry-delay ROLLBAR_RETRY_DELAY]
[--rollbar-timeout ROLLBAR_TIMEOUT]
...
Wraps the execution of processes so that a service API endpoint (CloudReactor)
is optionally informed of the progress. Also implements retries, timeouts, and
secret injection into the environment.
positional arguments:
command
optional arguments:
-h, --help show this help message and exit
-v, --version Print the version and exit
task:
Task settings
-n TASK_NAME, --task-name TASK_NAME
Name of Task (either the Task Name or the Task UUID
must be specified
--task-uuid TASK_UUID
UUID of Task (either the Task Name or the Task UUID
must be specified)
-a, --auto-create-task
Create the Task even if not known by the API server
--auto-create-task-run-environment-name AUTO_CREATE_TASK_RUN_ENVIRONMENT_NAME
Name of the Run Environment to use if auto-creating
the Task (either the name or UUID of the Run
Environment must be specified if auto-creating the
Task). Defaults to the deployment name if the Run
Environment UUID is not specified.
--auto-create-task-run-environment-uuid AUTO_CREATE_TASK_RUN_ENVIRONMENT_UUID
UUID of the Run Environment to use if auto-creating
the Task (either the name or UUID of the Run
Environment must be specified if auto-creating the
Task)
--auto-create-task-props AUTO_CREATE_TASK_PROPS
Additional properties of the auto-created Task, in
JSON format. See https://apidocs.cloudreactor.io/#oper
ation/api_v1_tasks_create for the schema.
--force-task-active Indicates that the auto-created Task should be
scheduled and made a service by the API server, if
applicable. Otherwise, auto-created Tasks are marked
passive.
--task-execution-uuid TASK_EXECUTION_UUID
UUID of Task Execution to attach to
--task-version-number TASK_VERSION_NUMBER
Numeric version of the Task's source code
--task-version-text TASK_VERSION_TEXT
Human readable version of the Task's source code
--task-version-signature TASK_VERSION_SIGNATURE
Version signature of the Task's source code (such as a
git commit hash)
--execution-method-props EXECUTION_METHOD_PROPS
Additional properties of the execution method, in JSON
format. See https://apidocs.cloudreactor.io/#operation
/api_v1_task_executions_create for the schema.
--task-instance-metadata TASK_INSTANCE_METADATA
Additional metadata about the Task instance, in JSON
format
-s, --service Indicate that this is a Task that should run
indefinitely
--schedule SCHEDULE Run schedule reported to the API server
--max-concurrency MAX_CONCURRENCY
Maximum number of concurrent Task Executions of the
same Task. Defaults to 1.
--max-conflicting-age MAX_CONFLICTING_AGE
Maximum age of conflicting Tasks to consider, in
seconds. -1 means no limit. Defaults to the heartbeat
interval, plus 60 seconds for services that send
heartbeats. Otherwise, defaults to no limit.
api:
API client settings
--api-base-url API_BASE_URL
Base URL of API server. Defaults to
https://api.cloudreactor.io
-k API_KEY, --api-key API_KEY
API key. Must have at least the Task access level, or
Developer access level for auto-created Tasks.
--api-heartbeat-interval API_HEARTBEAT_INTERVAL
Number of seconds to wait between sending heartbeats
to the API server. -1 means to not send heartbeats.
Defaults to 30 for concurrency limited services, 300
otherwise.
--api-error-timeout API_ERROR_TIMEOUT
Number of seconds to wait while receiving recoverable
errors from the API server. Defaults to 300.
--api-final-update-timeout API_FINAL_UPDATE_TIMEOUT
Number of seconds to wait while receiving recoverable
errors from the API server when sending the final
update before exiting. Defaults to 1800.
--api-retry-delay API_RETRY_DELAY
Number of seconds to wait before retrying an API
request. Defaults to 120.
--api-resume-delay API_RESUME_DELAY
Number of seconds to wait before resuming API
requests, after retries are exhausted. Defaults to
600. -1 means to never resume.
--api-task-execution-creation-error-timeout API_TASK_EXECUTION_CREATION_ERROR_TIMEOUT
Number of seconds to keep retrying Task Execution
creation while receiving error responses from the API
server. -1 means to keep trying indefinitely. Defaults
to 300.
--api-task-execution-creation-conflict-timeout API_TASK_EXECUTION_CREATION_CONFLICT_TIMEOUT
Number of seconds to keep retrying Task Execution
creation while conflict is detected by the API server.
-1 means to keep trying indefinitely. Defaults to 1800
for concurrency limited services, 0 otherwise.
--api-task-execution-creation-conflict-retry-delay API_TASK_EXECUTION_CREATION_CONFLICT_RETRY_DELAY
Number of seconds between attempts to retry Task
Execution creation after conflict is detected.
Defaults to 60 for concurrency-limited services, 120
otherwise.
--api-request-timeout API_REQUEST_TIMEOUT
Timeout for contacting API server, in seconds.
Defaults to 30.
-o, --offline-mode Do not communicate with or rely on an API server
-p, --prevent-offline-execution
Do not start processes if the API server is
unavailable or the wrapper is misconfigured.
-d DEPLOYMENT, --deployment DEPLOYMENT
Deployment name (production, staging, etc.)
--send-pid Send the process ID to the API server
--send-hostname Send the hostname to the API server
--no-send-runtime-metadata
Do not send metadata about the runtime environment
log:
Logging settings
-l {DEBUG,INFO,WARNING,ERROR,CRITICAL}, --log-level {DEBUG,INFO,WARNING,ERROR,CRITICAL}
Log level
--log-secrets Log sensitive information
--exclude-timestamps-in-log
Exclude timestamps in log (possibly because the log
stream will be enriched by timestamps automatically by
a logging service like AWS CloudWatch Logs)
process:
Process settings
-w WORK_DIR, --work-dir WORK_DIR
Working directory. Defaults to the current directory.
-c COMMAND_LINE, --command-line COMMAND_LINE
Command line to execute
--shell-mode {auto,enable,disable}
Indicates if the process command should be executed in
a shell. Executing in a shell allows shell scripts,
commands, and expressions to be used, with the
disadvantage that termination signals may not be
propagated to child processes. Options are: enable --
Force the command to be executed in a shell; disable
-- Force the command to be executed without a shell;
auto -- Auto-detect the shell mode by analyzing the
command.
--no-strip-shell-wrapping
Do not strip the command-line of shell wrapping like
"/bin/sh -c" that can be introduced by Docker when
using shell form of ENTRYPOINT and CMD.
--no-process-group-termination
Send termination and kill signals to the wrapped
process only, instead of its process group (which is
the default). Sending to the process group allows all
child processes to receive the signals, even if the
wrapped process does not forward signals. However, if
your wrapped process manually handles and forwards
signals to its child processes, you probably want to
send signals to only your wrapped process.
-t PROCESS_TIMEOUT, --process-timeout PROCESS_TIMEOUT
Timeout for process completion, in seconds. -1 means
no timeout, which is the default.
-r PROCESS_MAX_RETRIES, --process-max-retries PROCESS_MAX_RETRIES
Maximum number of times to retry failed processes. -1
means to retry forever. Defaults to 0.
--process-retry-delay PROCESS_RETRY_DELAY
Number of seconds to wait before retrying a process.
Defaults to 60.
--process-check-interval PROCESS_CHECK_INTERVAL
Number of seconds to wait between checking the status
of processes. Defaults to 10.
--process-termination-grace-period PROCESS_TERMINATION_GRACE_PERIOD
Number of seconds to wait after sending SIGTERM to a
process, but before killing it with SIGKILL. Defaults
to 30.
updates:
Status update settings
--enable-status-update-listener
Listen for status updates from the process, sent on
the status socket port via UDP. If not specified,
status update messages will not be read.
--status-update-socket-port STATUS_UPDATE_SOCKET_PORT
The port used to receive status updates from the
process. Defaults to 2373.
--status-update-message-max-bytes STATUS_UPDATE_MESSAGE_MAX_BYTES
The maximum number of bytes status update messages can
be. Defaults to 65536.
--status-update-interval STATUS_UPDATE_INTERVAL
Minimum of number of seconds to wait between sending
status updates to the API server. -1 means to not send
status updates except with heartbeats. Defaults to -1.
configuration:
Environment/configuration resolution settings
-e ENV_LOCATIONS, --env ENV_LOCATIONS
Location of either local file, AWS S3 ARN, or AWS
Secrets Manager ARN containing properties used to
populate the environment for embedded mode, or the
process environment for wrapped mode. By default, the
file format is assumed to be dotenv. Specify multiple
times to include multiple locations.
--config CONFIG_LOCATIONS
Location of either local file, AWS S3 ARN, or AWS
Secrets Manager ARN containing properties used to
populate the configuration for embedded mode. By
default, the file format is assumed to be in JSON.
Specify multiple times to include multiple locations.
--config-merge-strategy {DEEP,SHALLOW,REPLACE,ADDITIVE,TYPESAFE_REPLACE,TYPESAFE_ADDITIVE}
Merge strategy for merging configurations. Defaults to
'DEEP', which does not require mergedeep. Besides the
'SHALLOW' strategy, all other strategies require the
mergedeep python package to be installed.
--overwrite_env_during_resolution
Overwrite existing environment variables when
resolving them
--config-ttl CONFIG_TTL
Number of seconds to cache resolved environment
variables and configuration properties instead of
refreshing them when a process restarts. -1 means to
never refresh. Defaults to -1.
--no-fail-fast-config-resolution
Exit immediately if an error occurs resolving the
configuration
--resolved-env-var-name-prefix RESOLVED_ENV_VAR_NAME_PREFIX
Required prefix for names of environment variables
that should resolved. The prefix will be removed in
the resolved variable name. Defaults to ''.
--resolved-env-var-name-suffix RESOLVED_ENV_VAR_NAME_SUFFIX
Required suffix for names of environment variables
that should resolved. The suffix will be removed in
the resolved variable name. Defaults to
'_FOR_PROC_WRAPPER_TO_RESOLVE'.
--resolved-config-property-name-prefix RESOLVED_CONFIG_PROPERTY_NAME_PREFIX
Required prefix for names of configuration properties
that should resolved. The prefix will be removed in
the resolved property name. Defaults to ''.
--resolved-config-property-name-suffix RESOLVED_CONFIG_PROPERTY_NAME_SUFFIX
Required suffix for names of configuration properties
that should resolved. The suffix will be removed in
the resolved property name. Defaults to
'__to_resolve'.
--env-var-name-for-config ENV_VAR_NAME_FOR_CONFIG
The name of the environment variable used to set to
the value of the JSON encoded configuration. Defaults
to not setting any environment variable.
--config-property-name-for-env CONFIG_PROPERTY_NAME_FOR_ENV
The name of the configuration property used to set to
the value of the JSON encoded environment. Defaults to
not setting any property.
rollbar:
Rollbar settings
--rollbar-access-token ROLLBAR_ACCESS_TOKEN
Access token for Rollbar (used to report error when
communicating with API server)
--rollbar-retries ROLLBAR_RETRIES
Number of retries per Rollbar request. Defaults to 2.
--rollbar-retry-delay ROLLBAR_RETRY_DELAY
Number of seconds to wait before retrying a Rollbar
request. Defaults to 120.
--rollbar-timeout ROLLBAR_TIMEOUT
Timeout for contacting Rollbar server, in seconds.
Defaults to 30.
These environment variables take precedence over command-line arguments:
* PROC_WRAPPER_TASK_NAME
* PROC_WRAPPER_TASK_UUID
* PROC_WRAPPER_TASK_EXECUTION_UUID
* PROC_WRAPPER_AUTO_CREATE_TASK (TRUE or FALSE)
* PROC_WRAPPER_AUTO_CREATE_TASK_RUN_ENVIRONMENT_NAME
* PROC_WRAPPER_AUTO_CREATE_TASK_RUN_ENVIRONMENT_UUID
* PROC_WRAPPER_AUTO_CREATE_TASK_PROPS (JSON encoded property map)
* PROC_WRAPPER_TASK_IS_PASSIVE (TRUE OR FALSE)
* PROC_WRAPPER_TASK_IS_SERVICE (TRUE or FALSE)
* PROC_WRAPPER_EXECUTION_METHOD_PROPS (JSON encoded property map)
* PROC_WRAPPER_TASK_MAX_CONCURRENCY (set to -1 to indicate no limit)
* PROC_WRAPPER_PREVENT_OFFLINE_EXECUTION (TRUE or FALSE)
* PROC_WRAPPER_TASK_VERSION_NUMBER
* PROC_WRAPPER_TASK_VERSION_TEXT
* PROC_WRAPPER_TASK_VERSION_SIGNATURE
* PROC_WRAPPER_TASK_INSTANCE_METADATA (JSON encoded property map)
* PROC_WRAPPER_LOG_LEVEL (TRACE, DEBUG, INFO, WARNING, ERROR, or CRITICAL)
* PROC_WRAPPER_LOG_SECRETS (TRUE or FALSE)
* PROC_WRAPPER_INCLUDE_TIMESTAMPS_IN_LOG (TRUE or FALSE)
* PROC_WRAPPER_DEPLOYMENT
* PROC_WRAPPER_API_BASE_URL
* PROC_WRAPPER_API_KEY
* PROC_WRAPPER_API_HEARTBEAT_INTERVAL_SECONDS
* PROC_WRAPPER_API_ERROR_TIMEOUT_SECONDS
* PROC_WRAPPER_API_RETRY_DELAY_SECONDS
* PROC_WRAPPER_API_RESUME_DELAY_SECONDS
* PROC_WRAPPER_API_TASK_EXECUTION_CREATION_ERROR_TIMEOUT_SECONDS
* PROC_WRAPPER_API_TASK_EXECUTION_CREATION_CONFLICT_TIMEOUT_SECONDS
* PROC_WRAPPER_API_TASK_EXECUTION_CREATION_CONFLICT_RETRY_DELAY_SECONDS
* PROC_WRAPPER_API_FINAL_UPDATE_TIMEOUT_SECONDS
* PROC_WRAPPER_API_REQUEST_TIMEOUT_SECONDS
* PROC_WRAPPER_ENV_LOCATIONS (comma-separated list of locations)
* PROC_WRAPPER_CONFIG_LOCATIONS (comma-separated list of locations)
* PROC_WRAPPER_OVERWRITE_ENV_WITH_SECRETS (TRUE or FALSE)
* PROC_WRAPPER_RESOLVE_SECRETS (TRUE or FALSE)
* PROC_WRAPPER_MAX_CONFIG_RESOLUTION_DEPTH
* PROC_WRAPPER_MAX_CONFIG_RESOLUTION_ITERATIONS
* PROC_WRAPPER_CONFIG_TTL_SECONDS
* PROC_WRAPPER_FAIL_FAST_CONFIG_RESOLUTION (TRUE or FALSE)
* PROC_WRAPPER_RESOLVABLE_ENV_VAR_NAME_PREFIX
* PROC_WRAPPER_RESOLVABLE_ENV_VAR_NAME_SUFFIX
* PROC_WRAPPER_RESOLVABLE_CONFIG_PROPERTY_NAME_PREFIX
* PROC_WRAPPER_RESOLVABLE_CONFIG_PROPERTY_NAME_SUFFIX
* PROC_WRAPPER_ENV_VAR_NAME_FOR_CONFIG
* PROC_WRAPPER_CONFIG_PROPERTY_NAME_FOR_ENV
* PROC_WRAPPER_SEND_PID (TRUE or FALSE)
* PROC_WRAPPER_SEND_HOSTNAME (TRUE or FALSE)
* PROC_WRAPPER_SEND_RUNTIME_METADATA (TRUE or FALSE)
* PROC_WRAPPER_ROLLBAR_ACCESS_TOKEN
* PROC_WRAPPER_ROLLBAR_TIMEOUT_SECONDS
* PROC_WRAPPER_ROLLBAR_RETRIES
* PROC_WRAPPER_ROLLBAR_RETRY_DELAY_SECONDS
* PROC_WRAPPER_MAX_CONFLICTING_AGE_SECONDS
* PROC_WRAPPER_TASK_COMMAND
* PROC_WRAPPER_SHELL_MODE (TRUE or FALSE)
* PROC_WRAPPER_STRIP_SHELL_WRAPPING (TRUE or FALSE)
* PROC_WRAPPER_WORK_DIR
* PROC_WRAPPER_PROCESS_MAX_RETRIES
* PROC_WRAPPER_PROCESS_TIMEOUT_SECONDS
* PROC_WRAPPER_PROCESS_RETRY_DELAY_SECONDS
* PROC_WRAPPER_PROCESS_CHECK_INTERVAL_SECONDS
* PROC_WRAPPER_PROCESS_TERMINATION_GRACE_PERIOD_SECONDS
* PROC_WRAPPER_PROCESS_GROUP_TERMINATION (TRUE or FALSE)
* PROC_WRAPPER_STATUS_UPDATE_SOCKET_PORT
* PROC_WRAPPER_STATUS_UPDATE_MESSAGE_MAX_BYTES
With the exception of the settings for Secret Fetching and Resolution,
these environment variables are read after Secret Fetching so that they can
come from secret values.
The command is executed with the same environment that the wrapper script gets,
except that these properties are copied/overridden:
* PROC_WRAPPER_DEPLOYMENT
* PROC_WRAPPER_API_BASE_URL
* PROC_WRAPPER_API_KEY
* PROC_WRAPPER_API_ERROR_TIMEOUT_SECONDS
* PROC_WRAPPER_API_RETRY_DELAY_SECONDS
* PROC_WRAPPER_API_RESUME_DELAY_SECONDS
* PROC_WRAPPER_API_REQUEST_TIMEOUT_SECONDS
* PROC_WRAPPER_ROLLBAR_ACCESS_TOKEN
* PROC_WRAPPER_ROLLBAR_TIMEOUT_SECONDS
* PROC_WRAPPER_ROLLBAR_RETRIES
* PROC_WRAPPER_ROLLBAR_RETRY_DELAY_SECONDS
* PROC_WRAPPER_ROLLBAR_RESUME_DELAY_SECONDS
* PROC_WRAPPER_TASK_EXECUTION_UUID
* PROC_WRAPPER_TASK_UUID
* PROC_WRAPPER_TASK_NAME
* PROC_WRAPPER_TASK_VERSION_NUMBER
* PROC_WRAPPER_TASK_VERSION_TEXT
* PROC_WRAPPER_TASK_VERSION_SIGNATURE
* PROC_WRAPPER_TASK_INSTANCE_METADATA
* PROC_WRAPPER_SCHEDULE
* PROC_WRAPPER_PROCESS_TIMEOUT_SECONDS
* PROC_WRAPPER_TASK_MAX_CONCURRENCY
* PROC_WRAPPER_PREVENT_OFFLINE_EXECUTION
* PROC_WRAPPER_PROCESS_TERMINATION_GRACE_PERIOD_SECONDS
* PROC_WRAPPER_ENABLE_STATUS_UPDATE_LISTENER
* PROC_WRAPPER_STATUS_UPDATE_SOCKET_PORT
* PROC_WRAPPER_STATUS_UPDATE_INTERVAL_SECONDS
* PROC_WRAPPER_STATUS_UPDATE_MESSAGE_MAX_BYTES
Wrapped mode is suitable for running in a shell on your own (virtual) machine
or in a Docker container. It requires multi-process support, as the module
runs at the same time as the command it wraps.
### Embedded mode
You can use embedded mode to execute python code from inside a python program.
Include the `proc_wrapper` package in your python project's
dependencies. To run a task you want to be monitored:
from typing import Any, Mapping
from proc_wrapper import ProcWrapper, ProcWrapperParams
def fun(wrapper: ProcWrapper, cbdata: dict[str, int],
config: Mapping[str, Any]) -> int:
print(cbdata)
return cbdata['a']
# This is the function signature of a function invoked by AWS Lambda.
def entrypoint(event: Any, context: Any) -> int:
params = ProcWrapperParams()
params.auto_create_task = True
# If the Task Execution is running in AWS Lambda, CloudReactor can make
# the associated Task available to run (non-passive) in the CloudReactor
# dashboard or by API, after the wrapper reports its first execution.
proc_wrapper_params.task_is_passive = False
params.task_name = 'embedded_test_production'
params.auto_create_task_run_environment_name = 'production'
# For example only, in the real world you would use Secret Fetching;
# see below.
params.api_key = 'YOUR_CLOUDREACTOR_API_KEY'
# In an AWS Lambda environment, passing the context and event allows
# CloudReactor to monitor and manage this Task.
proc_wrapper = ProcWrapper(params=params, runtime_context=context,
input_value=event)
x = proc_wrapper.managed_call(fun, {'a': 1, 'b': 2})
# Should print 1
print(x)
return x
This is suitable for running in single-threaded environments like
AWS Lambda, or as part of a larger process that executes
sub-routines that should be monitored. See
[cloudreactor-python-lambda-quickstart](https://github.com/CloudReactor/cloudreactor-python-lambda-quickstart) for an example project that uses
proc_wrapper in a function run by AWS Lambda.
#### Embedded mode configuration
In embedded mode, besides setting properties of `ProcWrapperParams` in code,
`ProcWrapper` can be also configured in two ways:
First, using environment variables, as in wrapped mode.
Second, using the configuration dictionary. If the configuration dictionary
contains the key `proc_wrapper_params` and its value is a dictionary, the
keys and values in the dictionary will be used to to set these attributes in
`ProcWrapperParams`:
| Key | Type | Mutable | Uses Resolved Config |
|---------------------------------- |----------- |--------- |---------------------- |
| log_secrets | bool | No | No |
| env_locations | list[str] | No | No |
| config_locations | list[str] | No | No |
| config_merge_strategy | str | No | No |
| overwrite_env_during_resolution | bool | No | No |
| max_config_resolution_depth | int | No | No |
| max_config_resolution_iterations | int | No | No |
| config_ttl | int | No | No |
| fail_fast_config_resolution | bool | No | No |
| resolved_env_var_name_prefix | str | No | No |
| resolved_env_var_name_suffix | str | No | No |
| resolved_config_property_name_prefix | str | No | No |
| resolved_config_property_name_suffix | str | No | No |
| schedule | str | No | Yes |
| max_concurrency | int | No | Yes |
| max_conflicting_age | int | No | Yes |
| offline_mode | bool | No | Yes |
| prevent_offline_execution | bool | No | Yes |
| service | bool | No | Yes |
| deployment | str | No | Yes |
| api_base_url | str | No | Yes |
| api_heartbeat_interval | int | No | Yes |
| enable_status_listener | bool | No | Yes |
| status_update_socket_port | int | No | Yes |
| status_update_message_max_bytes | int | No | Yes |
| status_update_interval | int | No | Yes |
| log_level | str | No | Yes |
| include_timestamps_in_log | bool | No | Yes |
| api_key | str | Yes | Yes |
| api_request_timeout | int | Yes | Yes |
| api_error_timeout | int | Yes | Yes |
| api_retry_delay | int | Yes | Yes |
| api_resume_delay | int | Yes | Yes |
| api_task_execution_creation_error_timeout | int | Yes | Yes |
| api_task_execution_creation_conflict_timeout | int | Yes | Yes |
| api_task_execution_creation_conflict_retry_delay | int | Yes | Yes |
| process_timeout | int | Yes | Yes |
| process_max_retries | int | Yes | Yes |
| process_retry_delay | int | Yes | Yes |
| command | list[str] | Yes | Yes |
| command_line | str | Yes | Yes |
| shell_mode | bool | Yes | Yes |
| strip_shell_wrapping | bool | Yes | Yes |
| work_dir | str | Yes | Yes |
| process_termination_grace_period | int | Yes | Yes |
| send_pid | bool | Yes | Yes |
| send_hostname | bool | Yes | Yes |
| send_runtime_metadata | bool | Yes | Yes |
Keys that are marked with "Mutable" -- "No" in the table above can be
overridden when the configuration is reloaded after the `config_ttl` expires.
Keys that are marked as "Uses Resolved Config" -- "Yes" in the table above can
come from the resolved configuration after secret resolution (see below).
## Secret Fetching and Resolution
A common requirement is that deployed code / images do not contain secrets
internally which could be decompiled. Instead, programs should fetch secrets
from an external source in a secure manner. If your program runs in AWS, it
can make use of AWS's roles that have permission to access data in
Secrets Manager or S3. However, in many scenarios, having your program access
AWS directly has the following disadvantages:
1) Your program becomes coupled to AWS, so it is difficult to run locally or
switch to another infrastructure provider
2) You need to write code or use a library for each programming language you
use, so secret fetching is done in a non-uniform way
3) Writing code to merge and parse secrets from different sources is tedious
Therefore, proc_wrapper implements Secret Fetching and Resolution to solve
these problems so your programs don't have to. Both usage modes can fetch secrets from
[AWS Secrets Manager](https://aws.amazon.com/secrets-manager/),
AWS S3, or the local filesystem, and optionally extract embedded data
into the environment or a configuration dictionary. The environment is used to
pass values to processes run in wrapped mode,
while the configuration dictionary is passed to the callback function in
embedded mode.
proc_wrapper parses secret location strings that specify the how to resolve
a secret value. Each secret location string has the format:
`[PROVIDER_CODE:]<Provider specific address>[!FORMAT][|JP:<JSON Path expression>]`
### Secret Providers
Providers indicate the raw source of the secret data. The table below lists the
supported providers:
| Provider Code | Value Prefix | Provider | Example Address | Required libs | Notes |
|--------------- |--------------------------- |------------------------------ |------------------------------------------------------------- |----------------------------------------------------------------------------- |--------------------------------------------------------------- |
| `AWS_SM` | `arn:aws:secretsmanager:` | AWS Secrets Manager | `arn:aws:secretsmanager:us-east-2:1234567890:secret:config` | [boto3](https://boto3.amazonaws.com/v1/documentation/api/latest/index.html) | Can also include version suffix like `-PPrpY` |
| `AWS_S3` | `arn:aws:s3:::` | AWS S3 Object | `arn:aws:s3:::examplebucket/staging/app1/config.json` | [boto3](https://boto3.amazonaws.com/v1/documentation/api/latest/index.html) | |
| `FILE` | `file://` | Local file | `file:///home/appuser/app/.env` | | The default provider if no provider is auto-detected |
| `ENV` | | The process environment | `SOME_TOKEN` | | The name of another environment variable |
| `CONFIG` | | The configuration dictionary | `$.db` | [jsonpath-ng](https://github.com/h2non/jsonpath-ng) | JSON path expression to extract the data in the configuration |
| `PLAIN` | | Plaintext | `{"user": "postgres", "password": "badpassword"}` | | |
If you don't specify an explicit provider prefix in a secret location
(e.g. `AWS_SM:`), the provider can be auto-detected from the address portion
using the Value Prefix. For example the secret location
`arn:aws:s3:::examplebucket/staging/app1/config.json` will be auto-detected
to with the AWS_S3 provider because it starts with `arn:aws:s3:::`.
### Secret Formats
Formats indicate how the raw string data is parsed into a secret value (which may be
a string, number, boolean, dictionary, or array). The table below lists the
supported formats:
| Format Code | Extensions | MIME types | Required libs | Notes |
|------------- |----------------- |--------------------------------------------------------------------------------------- |------------------------------------------------------ |-------------------------------------------------- |
| `dotenv` | `.env` | None | [dotenv](https://github.com/theskumar/python-dotenv) | Also auto-detected if location includes `.env.` |
| `json` | `.json` | `application/json`, `text/x-json` | | |
| `yaml` | `.yaml`, `.yml` | `application/x-yaml`, `application/yaml`, `text/vnd.yaml`, `text/yaml`, `text/x-yaml` | [pyyaml](https://pyyaml.org/) | `safe_load()` is used for security |
The format of a secret value can be auto-detected from the extension or by the
MIME type if available. Otherwise, you may need to an explicit format code
(e.g. `!yaml`).
#### AWS Secrets Manager / S3 notes
[boto3](https://boto3.amazonaws.com/v1/documentation/api/latest/index.html)
is used to fetch secrets. It will try to access to AWS Secrets Manager
or S3 using environment variables `AWS_ACCESS_KEY_ID` and
`AWS_SECRET_ACCESS_KEY` if they are set, or use the EC2 instance role, ECS task
role, or Lambda execution role if available.
For Secrets Manager, you can also use "partial ARNs"
(without the hyphened suffix) as keys.
In the example above
arn:aws:secretsmanager:us-east-2:1234567890:secret:config
could be used to fetch the same secret, provided there are no conflicting secret ARNs.
This allows you to get the latest version of the secret.
If the secret was stored in Secrets Manager as binary, the
corresponding value will be set to the Base-64 encoded value.
If you're deploying a python function using AWS Lambda, note that boto3 is
already included in the available packages, so there's no need to include it
(unless the bundled version isn't compatible). Also we strongly encourage you
to add:
logging.getLogger("botocore").setLevel(logging.INFO)
to your code if you are using proc_wrapper for secrets resolution. This
prevent secrets from Secrets Manager from being leaked. For details, see this
[issue](https://github.com/boto/boto3/issues/2292).
### Secret Tranformation
Fetching secrets can be relatively expensive and it makes sense to group related
secrets together. Therefore it is common to store dictionaries (formatted
as JSON or YAML) as secrets. However, each desired environment variable
or configuration property may only consist of a fragment of the dictionary.
For example, given the JSON-formatted dictionary
{
"username": "postgres",
"password": "badpassword"
}
you may want to populate the environment variable `DB_USERNAME` with
`postgres`.
To facilitate this, dictionary fragments can be extracted to individual
environment variables using [jsonpath-ng](https://github.com/h2non/jsonpath-ng).
To specify that a variable be extracted from a dictionary using
a JSON Path expression, append `|JP:` followed by the JSON Path expression
to the secret location string. For example, if the AWS Secrets Manager
ARN
arn:aws:secretsmanager:us-east-2:1234567890:secret:db-PPrpY
contains the dictionary above, then the secret location string
arn:aws:secretsmanager:us-east-2:1234567890:secret:db-PPrpY|JP:$.username
will resolve to `postgres` as desired.
If you do something similar to get the password from the same JSON value,
proc_wrapper is smart enough to cache the fetched dictionary, so that the
raw data is only fetched once.
Since JSON path expressions yield a list of results, the secrets fetcher
implements the following rules to transform the list to the final value:
1. If the list of results has a single value, that value is used as the
final value, unless `[*]` is appended to the JSON path expression.
2. Otherwise, the final value is the list of results
#### Fetching from another environment variable
In some deployment scenarios, multiple secrets can be injected into a
single environment variable as a JSON encoded object. In that case,
the module can extract secrets using the *ENV* secret source. For example,
you may have arranged to have the environment variable DB_CONFIG injected
with the JSON encoded value:
{ "username": "postgres", "password": "nohackme" }
Then to extract the username to the environment variable DB_USERNAME you
you would add the environment variable DB_USER_FOR_PROC_WRAPPER_TO_RESOLVE
set to
ENV:DB_CONFIG|JP:$.username
### Secret injection into environment and configuration
Now let's use secret location strings to
inject the values into the environment (for wrapped mode)
and/or the the configuration dictionary (for embedded mode). proc_wrapper
supports two methods of secret injection which can be combined together:
* Top-level fetching
* Secrets Resolution
### Top-level fetching
Top-level fetching refers to fetching a dictionary that contains multiple secrets
and populating the environment / configuration dictionary with it.
To use top-level fetching, you specify the secret locations
from which you want to fetch the secrets and the corresponding values are
merged together into the environment / configuration.
To use top-level fetching in wrapped mode, populate the
environment variables `PROC_WRAPPER_ENV_LOCATIONS` with a comma-separated
list of secret locations, or use the command-line option
`--env-locations <secret_location>` one or more times. Secret location
strings passed in via `PROC_WRAPPER_ENV_LOCATIONS` or `--env-locations`
will be parsed as `dotenv` files unless format is auto-detected or
explicitly specified.
To use top-level fetching in embedded mode, set the `ProcWrapperParams` property
`config_locations` to a list of secret locations. Alternatively, you can set
the environment variable `PROC_WRAPPER_CONFIG_LOCATIONS` to a comma-separated
list, and this will be picked up automatically. Secret location values
will be parsed as JSON unless the format is auto-detected or explicitly
specified. The `config` argument
passed to the your callback function will contain a merged dictionary of all
fetched and parsed dictionary values. For example:
def callback(wrapper: ProcWrapper, cbdata: str,
config: Dict[str, Any]) -> str:
return "super" + cbdata + config["username"]
def main():
params = ProcWrapperParams()
# Optional: you can set an initial configuration dictionary which will
# have its values included in the final configuration unless overridden.
params.initial_config = {
"log_level": "DEBUG"
}
# You can omit this if you set PROC_WRAPPER_CONFIG_LOCATIONS environment
# variable to the same ARN
params.config_locations = [
"arn:aws:secretsmanager:us-east-2:1234567890:secret:db-PPrpY",
# More secret locations can be added here, and their values will
# be merged
]
wrapper = ProcWrapper(params=params)
# Returns "superduperpostgres"
return wrapper.managed_call(callback, "duper")
#### Merging Secrets
Top-level fetching can potentially fetch multiple dictionaries which are
merged together in the final environment / configuration dictionary.
The default merge strategy (`DEEP`) merges recursively, even dictionaries
in lists. The `SHALLOW` merge strategy just overwrites top-level keys, with later
secret locations taking precedence. However, if you include the
[mergedeep](https://github.com/clarketm/mergedeep) library, you can also
set the merge strategy to one of:
* `REPLACE`
* `ADDITIVE`
* `TYPESAFE_REPLACE`
* `TYPESAFE_ADDITIVE`
so that nested lists can be appended to instead of replaced (in the case of the
`ADDITIVE` strategies), or errors will be raised if incompatibly-typed values
are merged (in the case of the `TYPESAFE` strategies). In wrapped mode,
the merge strategy can be set with the `--config-merge-strategy` command-line
argument or `PROC_WRAPPER_CONFIG_MERGE_STRATEGY` environment variable. In
embedded mode, the merge strategy can be set in the
`config_merge_strategy` string property of `ProcWrapperParams`.
### Secret Resolution
Secret Resolution substitutes configuration or environment values that are
secret location strings with the computed values of those strings. Compared
to Secret Fetching, Secret Resolution is more useful when you want more
control over the names of variables or when you have secret values deep
inside your configuration.
In wrapped mode, if you want to set the environment variable `MY_SECRET` with
a value fetched
from AWS Secrets Manager, you would set the environment variable
`MY_SECRET_FOR_PROC_WRAPPER_TO_RESOLVE` to a secret location string
which is ARN of the secret, for example:
arn:aws:secretsmanager:us-east-2:1234567890:secret:db-PPrpY
(The `_FOR_PROC_WRAPPER_TO_RESOLVE` suffix of environment variable names is
removed during resolution. It can also be configured with the `PROC_WRAPPER_RESOLVABLE_ENV_VAR_NAME_SUFFIX` environment variable.)
In embedded mode, if you want the final configuration dictionary to look like:
{
"db_username": "postgres",
"db_password": "badpassword",
...
}
The initial configuration dictionary would look like:
{
"db_username__to_resolve": "arn:aws:secretsmanager:us-east-2:1234567890:secret:db-PPrpY|JP:$.username",
"db_password__to_resolve": "arn:aws:secretsmanager:us-east-2:1234567890:secret:db-PPrpY|JP:$.password",
...
}
(The `__to_resolve` suffix (with 2 underscores!) of keys is removed during
resolution. It can also be configured with the `resolved_config_property_name_suffix`
property of `ProcWrapperParams`.)
proc_wrapper can also resolve keys in embedded dictionaries, like:
{
"db": {
"username__to_resolve": "arn:aws:secretsmanager:us-east-2:1234567890:secret:config-PPrpY|JP:$.username",
"password__to_resolve":
"arn:aws:secretsmanager:us-east-2:1234567890:secret:config-PPrpY|JP:$.password",
...
},
...
}
up to a maximum depth that you can control with `ProcWrapperParams.max_config_resolution_depth` (which defaults to 5). That would resolve to
{
"db": {
"username": "postgres",
"password": "badpassword"
...
},
...
}
You can also inject entire dictionaries, like:
{
"db__to_resolve": "arn:aws:secretsmanager:us-east-2:1234567890:secret:config-PPrpY",
...
}
which would resolve to
{
"db": {
"username": "postgres",
"password": "badpassword"
},
...
}
To enable secret resolution in wrapped mode, set environment variable `PROC_WRAPPER_RESOLVE_SECRETS` to `TRUE`. In embedded mode, secret
resolution is enabled by default; set the
`max_config_resolution_iterations` property of `ProcWrapperParams` to `0`
to disable resolution.
Secret resolution is run multiple times so that if a resolved value contains
a secret location string, it will be resolved on the next pass. By default,
proc_wrapper limits the maximum number of resolution passes to 3 but you
can control this with the environment variable
`PROC_WRAPPER_MAX_CONFIG_RESOLUTION_ITERATIONS` in embedded mode,
or by setting the `max_config_resolution_iterations` property of
`ProcWrapperParams` in wrapped mode.
### Environment Projection
During secret fetching and secret resolution, proc_wrapper internally maintains
the computed environment as a dictionary which may have embedded lists and
dictionaries. However, the final environment passed to the process is a flat
dictionary containing only string values. So proc_wrapper converts
all top-level values to strings using these rules:
* Lists and dictionaries are converted to their JSON-encoded string value
* Boolean values are converted to their upper-cased string representation
(e.g. the string `FALSE` for the boolean value `false`)
* The `None` value is converted to the empty string
* All other values are converted using python's `str()` function
### Secrets Refreshing
You can set a Time to Live (TTL) on the duration that secret values are cached.
Caching helps reduce expensive lookups of secrets and bandwidth usage.
In wrapped mode, set the TTL of environment variables set from secret locations
using the `--config-ttl` command-line argument or
`PROC_WRAPPER_CONFIG_TTL_SECONDS` environment variable.
If the process exits, you have configured the script to retry,
and the TTL has expired since the last fetch,
proc_wrapper will re-fetch the secrets
and resolve them again, for the environment passed to the next invocation of
your process.
In embedded mode, set the TTL of configuration dictionary values set from
secret locations by setting the `config_ttl` property of
`ProcWrapperParams`. If 1) your callback function raises an exception, 2) you have
configured the script to retry; and 3) the TTL has expired since the last fetch,
proc_wrapper will re-fetch the secrets
and resolve them again, for the configuration passed to the next invocation of
the callback function.
## Status Updates
### Status Updates in Wrapped Mode
While your process in running, you can send status updates to
CloudReactor by using the StatusUpdater class. Status updates are shown in
the CloudReactor dashboard and allow you to track the current progress of a
Task and also how many items are being processed in multiple executions
over time.
In wrapped mode, your application code would send updates to the
proc_wrapper program via UDP port 2373 (configurable with the PROC_WRAPPER_STATUS_UPDATE_PORT environment variable).
If your application code is in python, you can use the provided
StatusUpdater class to do this:
from proc_wrapper import StatusUpdater
with StatusUpdater() as updater:
updater.send_update(last_status_message="Starting ...")
success_count = 0
for i in range(100):
try:
do_work()
success_count += 1
updater.send_update(success_count=success_count)
except Exception:
failed_count += 1
updater.send_update(failed_count=failed_count)
updater.send_update(last_status_message="Finished!")
### Status Updates in Embedded Mode
In embedded mode, your callback in python code can use the wrapper instance to
send updates:
from typing import Any, Mapping
import proc_wrapper
from proc_wrapper import ProcWrapper
def fun(wrapper: ProcWrapper, cbdata: dict[str, int],
config: Mapping[str, Any]) -> int:
wrapper.update_status(last_status_message="Starting the fun ...")
success_count = 0
error_count = 0
for i in range(100):
try:
do_work()
success_count += 1
except Exception:
error_count += 1
wrapper.update_status(success_count=success_count,
error_count=error_count)
wrapper.update_status(last_status_message="The fun is over.")
return cbdata["a"]
params = ProcWrapperParams()
params.auto_create_task = True
params.auto_create_task_run_environment_name = "production"
params.task_name = "embedded_test"
params.api_key = "YOUR_CLOUDREACTOR_API_KEY"
proc_wrapper = ProcWrapper(params=params)
proc_wrapper.managed_call(fun, {"a": 1, "b": 2})
## Example Projects
These projects contain sample Tasks that use this library to report their
execution status and results to CloudReactor
* [cloudreactor-python-ecs-quickstart](https://github.com/CloudReactor/cloudreactor-python-ecs-quickstart) runs python code in a Docker container
in AWS ECS Fargate (wrapped mode)
* [cloudreactor-python-lambda-quickstart](https://github.com/CloudReactor/cloudreactor-python-lambda-quickstart) runs python code in AWS Lambda
(embedded mode)
* [cloudreactor-java-ecs-quickstart](https://github.com/CloudReactor/cloudreactor-java-ecs-quickstart) runs Java code in a Docker container in
AWS ECS Fargate (wrapped mode)
## License
This software is dual-licensed under open source (MPL 2.0) and commercial
licenses. See `LICENSE` for details.
## Contributors ✨
Thanks goes to these wonderful people ([emoji key](https://allcontributors.org/docs/en/emoji-key)):
<!-- ALL-CONTRIBUTORS-LIST:START - Do not remove or modify this section -->
<!-- prettier-ignore-start -->
<!-- markdownlint-disable -->
<table>
<tr>
<td align="center"><a href="https://github.com/jtsay362"><img src="https://avatars0.githubusercontent.com/u/1079646?s=460&v=4?s=80" width="80px;" alt=""/><br /><sub><b>Jeff Tsay</b></sub></a><br /><a href="https://github.com/CloudReactor/cloudreactor-procwrapper/commits?author=jtsay362" title="Code">💻</a> <a href="https://github.com/CloudReactor/cloudreactor-procwrapper/commits?author=jtsay362" title="Documentation">📖</a> <a href="#infra-jtsay362" title="Infrastructure (Hosting, Build-Tools, etc)">🚇</a> <a href="#maintenance-jtsay362" title="Maintenance">🚧</a></td>
<td align="center"><a href="https://github.com/mwaldne"><img src="https://avatars0.githubusercontent.com/u/40419?s=460&u=3a5266861feeb27db392622371ecc57ebca09f32&v=4?s=80" width="80px;" alt=""/><br /><sub><b>Mike Waldner</b></sub></a><br /><a href="https://github.com/CloudReactor/cloudreactor-procwrapper/commits?author=mwaldne" title="Code">💻</a></td>
<td align="center"><a href="https://browniebroke.com/"><img src="https://avatars.githubusercontent.com/u/861044?v=4?s=80" width="80px;" alt=""/><br /><sub><b>Bruno Alla</b></sub></a><br /><a href="https://github.com/CloudReactor/cloudreactor-procwrapper/commits?author=browniebroke" title="Code">💻</a> <a href="#ideas-browniebroke" title="Ideas, Planning, & Feedback">🤔</a> <a href="https://github.com/CloudReactor/cloudreactor-procwrapper/commits?author=browniebroke" title="Documentation">📖</a></td>
</tr>
</table>
<!-- markdownlint-restore -->
<!-- prettier-ignore-end -->
<!-- ALL-CONTRIBUTORS-LIST:END -->
This project follows the [all-contributors](https://github.com/all-contributors/all-contributors) specification. Contributions of any kind welcome!
## Credits
This package was created with
[Cookiecutter](https://github.com/audreyr/cookiecutter) and the
[browniebroke/cookiecutter-pypackage](https://github.com/browniebroke/cookiecutter-pypackage)
project template.
%package help
Summary: Development documents and examples for cloudreactor-procwrapper
Provides: python3-cloudreactor-procwrapper-doc
%description help
# cloudreactor-procwrapper
<p align="center">
<a href="https://github.com/CloudReactor/cloudreactor-procwrapper/actions?query=workflow%3ACI">
<img src="https://img.shields.io/github/workflow/status/CloudReactor/cloudreactor-procwrapper/CI/main?label=CI&logo=github&style=flat-square" alt="CI Status" >
</a>
<a href="https://cloudreactor-procwrapper.readthedocs.io">
<img src="https://img.shields.io/readthedocs/cloudreactor-procwrapper.svg?logo=read-the-docs&logoColor=fff&style=flat-square" alt="Documentation Status">
</a>
<a href="https://codecov.io/gh/CloudReactor/cloudreactor-procwrapper">
<img src="https://img.shields.io/codecov/c/github/CloudReactor/cloudreactor-procwrapper.svg?logo=codecov&logoColor=fff&style=flat-square" alt="Test coverage percentage">
</a>
</p>
<p align="center">
<a href="https://python-poetry.org/">
<img src="https://img.shields.io/badge/packaging-poetry-299bd7?style=flat-square&logo=data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAA4AAAASCAYAAABrXO8xAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAJJSURBVHgBfZLPa1NBEMe/s7tNXoxW1KJQKaUHkXhQvHgW6UHQQ09CBS/6V3hKc/AP8CqCrUcpmop3Cx48eDB4yEECjVQrlZb80CRN8t6OM/teagVxYZi38+Yz853dJbzoMV3MM8cJUcLMSUKIE8AzQ2PieZzFxEJOHMOgMQQ+dUgSAckNXhapU/NMhDSWLs1B24A8sO1xrN4NECkcAC9ASkiIJc6k5TRiUDPhnyMMdhKc+Zx19l6SgyeW76BEONY9exVQMzKExGKwwPsCzza7KGSSWRWEQhyEaDXp6ZHEr416ygbiKYOd7TEWvvcQIeusHYMJGhTwF9y7sGnSwaWyFAiyoxzqW0PM/RjghPxF2pWReAowTEXnDh0xgcLs8l2YQmOrj3N7ByiqEoH0cARs4u78WgAVkoEDIDoOi3AkcLOHU60RIg5wC4ZuTC7FaHKQm8Hq1fQuSOBvX/sodmNJSB5geaF5CPIkUeecdMxieoRO5jz9bheL6/tXjrwCyX/UYBUcjCaWHljx1xiX6z9xEjkYAzbGVnB8pvLmyXm9ep+W8CmsSHQQY77Zx1zboxAV0w7ybMhQmfqdmmw3nEp1I0Z+FGO6M8LZdoyZnuzzBdjISicKRnpxzI9fPb+0oYXsNdyi+d3h9bm9MWYHFtPeIZfLwzmFDKy1ai3p+PDls1Llz4yyFpferxjnyjJDSEy9CaCx5m2cJPerq6Xm34eTrZt3PqxYO1XOwDYZrFlH1fWnpU38Y9HRze3lj0vOujZcXKuuXm3jP+s3KbZVra7y2EAAAAAASUVORK5CYII=" alt="Poetry">
</a>
<a href="https://github.com/pre-commit/pre-commit">
<img src="https://img.shields.io/badge/pre--commit-enabled-brightgreen?logo=pre-commit&logoColor=white&style=flat-square" alt="pre-commit">
</a>
</p>
<p align="center">
<a href="https://pypi.org/project/cloudreactor-procwrapper/">
<img src="https://img.shields.io/pypi/v/cloudreactor-procwrapper.svg?logo=python&logoColor=fff&style=flat-square" alt="PyPI Version">
</a>
<img src="https://img.shields.io/pypi/pyversions/cloudreactor-procwrapper.svg?style=flat-square&logo=python&logoColor=fff" alt="Supported Python versions">
<img src="https://img.shields.io/pypi/l/cloudreactor-procwrapper.svg?style=flat-square" alt="License">
</p>
Wraps the execution of processes so that an API server
([CloudReactor](https://cloudreactor.io/))
can monitor and manage them.
Available as a standalone executable or as a python module.
## Features
* Runs either processes started with a command line or a python function you
supply
* Implements retries and time limits
* Injects secrets from AWS Secrets Manager, AWS S3, or local files and extracts
them into the process environment (for command-lines) or configuration (for
functions)
* When used with the CloudReactor service:
* Reports when a process/function starts and when it exits, along with the
exit code and runtime metadata (if running in AWS ECS or AWS Lambda)
* Sends heartbeats, optionally with status information like the number of
items processed
* Prevents too many concurrent executions
* Stops execution when manually stopped in the CloudReactor dashboard
* Sends CloudReactor the data necessary to start the process / function if running in AWS ECS or AWS Lambda
## How it works
First, secrets and other configuration are fetched and resolved from
providers like AWS Secrets Manager, AWS S3, or the local filesystem.
Just before your code runs, the module requests the API server to create a
Task Execution associated with the Task name or UUID which you pass to the
module.
The API server may reject the request if too many instances of the Task are
currently running, but otherwise records that a Task Execution has started.
The module then passes control to your code.
While your code is running, it may report progress to the API server,
and the API server may signal that your Task stop execution (due to
user manually stopping the Task Execution), in which
case the module terminates your code and exits.
After your code finishes, the module informs the API server of
the exit code or result. CloudReactor monitors Tasks to ensure they
are still responsive, and keeps a history of the Executions of Tasks,
allowing you to view failures and run durations in the past.
### Auto-created Tasks
Before your Task is run (including this module),
the [AWS ECS CloudReactor Deployer](https://github.com/CloudReactor/aws-ecs-cloudreactor-deployer)
can be used to set it up in AWS ECS,
and inform CloudReactor of details of your Task.
That way CloudReactor can start and schedule your Task, and setup your
Task as a service.
See [CloudReactor python ECS QuickStart](https://github.com/CloudReactor/cloudreactor-python-ecs-quickstart)
for an example.
However, it may not be possible or desired to change your deployment process.
Instead, you may configure the Task to be *auto-created*.
Auto-created Tasks are created the first time your Task runs.
This means there is no need to inform the API server of the Task details
(during deployment) before it runs.
Instead, each time the module runs, it informs the API server of the
Task details at the same time as it requests the creation of a Task Execution.
One disadvantage of auto-created Tasks is that they are not available
in the CloudReactor dashboard until the first time they run.
When configuring a Task to be auto-created, you must specify the name
or UUID of the Run Environment in CloudReactor that the Task is
associated with. The Run Environment must be created ahead of time,
either by the Cloudreactor AWS Setup Wizard,
or manually in the CloudReactor dashboard.
You can also specify more Task properties, such as Alert Methods and
external links in the dashboard, by setting the environment variable
`PROC_WRAPPER_AUTO_CREATE_TASK_PROPS` set to a JSON-encoded object that has the
[CloudReactor Task schema](https://apidocs.cloudreactor.io/#operation/tasks_create).
### Execution Methods
CloudReactor currently supports three Execution Methods:
1) [AWS ECS (in Fargate)](https://aws.amazon.com/fargate/)
2) [AWS Lambda](https://aws.amazon.com/lambda/)
3) Unknown
If a Task is running in AWS ECS, CloudReactor is able to run additional
Task Executions, provided the details of running the Task is provided
during deployment with the AWS ECS CloudReactor Deployer, or if the
Task is configured to be auto-created, and this module is run. In the
second case, this module uses the ECS Metadata endpoint to detect
the ECS Task settings, and sends them to the API server. CloudReactor
can also schedule Tasks or setup long-running services using Tasks,
provided they are run in AWS ECS.
If a Task is running in AWS Lambda, CloudReactor is able to run additional
Task Executions after the first run of the function.
However, a Task may use the Unknown execution method if it is not running
in AWS ECS or Lambda. If that is the case, CloudReactor won't be able to
start the Task in the dashboard or as part of a Workflow,
schedule the Task, or setup a service with the Task. But the advantage is
that the Task code can be executed by any method available to you,
such as bare metal servers, VM's, or Kubernetes.
All Tasks in CloudReactor, regardless of execution method, have their
history kept and are monitored.
This module detects the execution method your Task is
running with and sends that information to the API server, provided
you configure your Task to be auto-created.
### Passive Tasks
Passive Tasks are Tasks that CloudReactor does not manage. This means
scheduling and service setup must be handled by other means
(cron jobs, [supervisord](http://supervisord.org/), etc).
However, Tasks marked as services or that have a schedule will still be
monitored by CloudReactor, which will send notifications if
a service Task goes down or a Task does not run on schedule.
The module reports to the API server that auto-created Tasks are passive,
unless you specify the `--force-task-passive` commmand-line option or
set the environment variable `PROC_WRAPPER_TASK_IS_PASSIVE` to `FALSE`.
If a Task uses the Unknown Execution Method, it must be marked as passive,
because CloudReactor does not know how to manage it.
## Pre-requisites
If you just want to use this module to retry processes, limit execution time,
or fetch secrets, you can use offline mode, in which case no CloudReactor API
key is required. But CloudReactor offers a free tier so we hope you
[sign up](https://dash.cloudreactor.io/signup)
for a free account to enable monitoring and/or management.
If you want CloudReactor to be able to start your Tasks, you should use the
[Cloudreactor AWS Setup Wizard](https://github.com/CloudReactor/cloudreactor-aws-setup-wizard)
to configure your AWS environment to run Tasks in ECS Fargate.
You can skip this step if running in passive mode is OK for you.
If you want to use CloudReactor to manage or just monitor your Tasks,
you need to create a Run Environment and an API key in the CloudReactor
dashboard. The API key can be scoped to the Run Environment if you
wish. The key must have at least the Task access level, but for
an auto-created Task, it must have at least the Developer access level.
## Installation
### Nuitka
Standalone executables built by
[nuitka](https://nuitka.net/index.html)
for 64-bit Linux are available, located in `bin/nuitka`. These executables bundle
python so you don't need to have python installed on your machine. They also
bundle all optional library dependencies so you can fetch secrets from AWS
Secrets Manager and extract them with jsonpath-ng, for example.
Compared to executables built by PyInstaller (see below), they start up faster,
and most likely are more efficient at runtime.
#### RHEL or derivatives
To download and run the wrapper on a RHEL/Fedora/Amazon Linux 2 machine:
RUN wget -nv https://github.com/CloudReactor/cloudreactor-procwrapper/raw/5.0.2/bin/nuitka/al2/5.0.2/proc_wrapper.bin
ENTRYPOINT ["proc_wrapper.bin"]
Example Dockerfiles of known working environments are available for
[Amazon Linux 2](tests/integration/nuitka_executable/docker_context_al2_amd64/)
and
[Fedora](tests/integration/nuitka_executable/docker_context_al2_amd64/Dockerfile).
Fedora 27 or later are supported.
#### Debian based systems
On a Debian based (including Ubuntu) machine:
RUN wget -nv https://github.com/CloudReactor/cloudreactor-procwrapper/raw/5.0.2/bin/nuitka/debian-amd64/5.0.2/proc_wrapper.bin
ENTRYPOINT ["proc_wrapper.bin"]
See the example
[Dockerfile](tests/integration/nuitka_executable/docker_context_debian_amd64/Dockerfile) for a known working Debian environment.
Debian 10 (Buster) or later are supported.
### PyInstaller
Standalone executables built by [PyInstaller](https://www.pyinstaller.org/) for 64-bit Linux and Windows are available, located in `bin/pyinstaller`.
These executables bundle
python so you don't need to have python installed on your machine. They also
bundle all optional library dependencies so you can fetch secrets from AWS
Secrets Manager and extract them with jsonpath-ng, for example. Compared to
executables built by nuitka, they start up slower but might be more reliable.
#### RHEL or derivatives
To download and run the wrapper on a RHEL/Fedora/Amazon Linux 2 machine:
RUN wget -nv https://github.com/CloudReactor/cloudreactor-procwrapper/raw/5.0.2/bin/pyinstaller/al2/5.0.2/proc_wrapper.bin
ENTRYPOINT ["proc_wrapper.bin"]
Example Dockerfiles of known working environments are available for
[Amazon Linux 2](tests/integration/pyinstaller_executable/docker_context_al2_amd64/)
and
[Fedora](tests/integration/pyinstaller_executable/docker_context_al2_amd64/Dockerfile).
Fedora 27 or later are supported.
#### Debian based machines
On a Debian based (including Ubuntu) machine:
RUN wget -nv https://github.com/CloudReactor/cloudreactor-procwrapper/raw/5.0.2/bin/pyinstaller/debian-amd64/5.0.2/proc_wrapper.bin
ENTRYPOINT ["proc_wrapper.bin"]
See the example
[Dockerfile](tests/integration/pyinstaller_executable/docker_context_debian_amd64/Dockerfile) for a known working Debian environment.
Debian 10 (Buster) or later are supported.
Special thanks to
[wine](https://www.winehq.org/) and
[PyInstaller Docker Images](https://github.com/cdrx/docker-pyinstaller)
for making it possible to cross-compile!
### When python is available
Install this module via pip (or your favorite package manager):
`pip install cloudreactor-procwrapper`
Fetching secrets from AWS Secrets Manager requires that
[boto3](https://boto3.amazonaws.com/v1/documentation/api/latest/index.html) is available to import in your python environment.
JSON Path transformation requires that [jsonpath-ng](https://github.com/h2non/jsonpath-ng)
be available to import in your python environment.
You can get the tested versions of both dependencies in
[proc_wrapper-requirements.in](https://github.com/CloudReactor/cloudreactor-procwrapper/blob/main/proc_wrapper-requirements.in)
(suitable for use by [pip-tools](https://github.com/jazzband/pip-tools/)) or the resolved requirements in
[proc_wrapper-requirements.txt](https://github.com/CloudReactor/cloudreactor-procwrapper/blob/main/proc_wrapper-requirements.txt).
## Usage
There are two ways of using the module: wrapped mode and embedded mode.
### Wrapped mode
In wrapped mode, you pass a command line to the module which it
executes in a child process. The command can be implemented in whatever
programming language the running machine supports.
Instead of running
somecommand --somearg x
you would run
./proc_wrapper somecommand --somearg x
assuming that are using the PyInstaller standalone executable, and that
you configure the program using environment variables.
Or, if you have python installed:
python -m proc_wrapper somecommand --somearg x
Here are all the options:
usage: proc_wrapper [-h] [-v] [-n TASK_NAME] [--task-uuid TASK_UUID] [-a]
[--auto-create-task-run-environment-name AUTO_CREATE_TASK_RUN_ENVIRONMENT_NAME]
[--auto-create-task-run-environment-uuid AUTO_CREATE_TASK_RUN_ENVIRONMENT_UUID]
[--auto-create-task-props AUTO_CREATE_TASK_PROPS]
[--force-task-active]
[--task-execution-uuid TASK_EXECUTION_UUID]
[--task-version-number TASK_VERSION_NUMBER]
[--task-version-text TASK_VERSION_TEXT]
[--task-version-signature TASK_VERSION_SIGNATURE]
[--execution-method-props EXECUTION_METHOD_PROPS]
[--task-instance-metadata TASK_INSTANCE_METADATA] [-s]
[--schedule SCHEDULE] [--max-concurrency MAX_CONCURRENCY]
[--max-conflicting-age MAX_CONFLICTING_AGE]
[--api-base-url API_BASE_URL] [-k API_KEY]
[--api-heartbeat-interval API_HEARTBEAT_INTERVAL]
[--api-error-timeout API_ERROR_TIMEOUT]
[--api-final-update-timeout API_FINAL_UPDATE_TIMEOUT]
[--api-retry-delay API_RETRY_DELAY]
[--api-resume-delay API_RESUME_DELAY]
[--api-task-execution-creation-error-timeout API_TASK_EXECUTION_CREATION_ERROR_TIMEOUT]
[--api-task-execution-creation-conflict-timeout API_TASK_EXECUTION_CREATION_CONFLICT_TIMEOUT]
[--api-task-execution-creation-conflict-retry-delay API_TASK_EXECUTION_CREATION_CONFLICT_RETRY_DELAY]
[--api-request-timeout API_REQUEST_TIMEOUT] [-o] [-p]
[-d DEPLOYMENT] [--send-pid] [--send-hostname]
[--no-send-runtime-metadata]
[-l {DEBUG,INFO,WARNING,ERROR,CRITICAL}] [--log-secrets]
[--exclude-timestamps-in-log] [-w WORK_DIR]
[-c COMMAND_LINE] [--shell-mode {auto,enable,disable}]
[--no-strip-shell-wrapping]
[--no-process-group-termination] [-t PROCESS_TIMEOUT]
[-r PROCESS_MAX_RETRIES]
[--process-retry-delay PROCESS_RETRY_DELAY]
[--process-check-interval PROCESS_CHECK_INTERVAL]
[--process-termination-grace-period PROCESS_TERMINATION_GRACE_PERIOD]
[--enable-status-update-listener]
[--status-update-socket-port STATUS_UPDATE_SOCKET_PORT]
[--status-update-message-max-bytes STATUS_UPDATE_MESSAGE_MAX_BYTES]
[--status-update-interval STATUS_UPDATE_INTERVAL]
[-e ENV_LOCATIONS] [--config CONFIG_LOCATIONS]
[--config-merge-strategy {DEEP,SHALLOW,REPLACE,ADDITIVE,TYPESAFE_REPLACE,TYPESAFE_ADDITIVE}]
[--overwrite_env_during_resolution]
[--config-ttl CONFIG_TTL]
[--no-fail-fast-config-resolution]
[--resolved-env-var-name-prefix RESOLVED_ENV_VAR_NAME_PREFIX]
[--resolved-env-var-name-suffix RESOLVED_ENV_VAR_NAME_SUFFIX]
[--resolved-config-property-name-prefix RESOLVED_CONFIG_PROPERTY_NAME_PREFIX]
[--resolved-config-property-name-suffix RESOLVED_CONFIG_PROPERTY_NAME_SUFFIX]
[--env-var-name-for-config ENV_VAR_NAME_FOR_CONFIG]
[--config-property-name-for-env CONFIG_PROPERTY_NAME_FOR_ENV]
[--rollbar-access-token ROLLBAR_ACCESS_TOKEN]
[--rollbar-retries ROLLBAR_RETRIES]
[--rollbar-retry-delay ROLLBAR_RETRY_DELAY]
[--rollbar-timeout ROLLBAR_TIMEOUT]
...
Wraps the execution of processes so that a service API endpoint (CloudReactor)
is optionally informed of the progress. Also implements retries, timeouts, and
secret injection into the environment.
positional arguments:
command
optional arguments:
-h, --help show this help message and exit
-v, --version Print the version and exit
task:
Task settings
-n TASK_NAME, --task-name TASK_NAME
Name of Task (either the Task Name or the Task UUID
must be specified
--task-uuid TASK_UUID
UUID of Task (either the Task Name or the Task UUID
must be specified)
-a, --auto-create-task
Create the Task even if not known by the API server
--auto-create-task-run-environment-name AUTO_CREATE_TASK_RUN_ENVIRONMENT_NAME
Name of the Run Environment to use if auto-creating
the Task (either the name or UUID of the Run
Environment must be specified if auto-creating the
Task). Defaults to the deployment name if the Run
Environment UUID is not specified.
--auto-create-task-run-environment-uuid AUTO_CREATE_TASK_RUN_ENVIRONMENT_UUID
UUID of the Run Environment to use if auto-creating
the Task (either the name or UUID of the Run
Environment must be specified if auto-creating the
Task)
--auto-create-task-props AUTO_CREATE_TASK_PROPS
Additional properties of the auto-created Task, in
JSON format. See https://apidocs.cloudreactor.io/#oper
ation/api_v1_tasks_create for the schema.
--force-task-active Indicates that the auto-created Task should be
scheduled and made a service by the API server, if
applicable. Otherwise, auto-created Tasks are marked
passive.
--task-execution-uuid TASK_EXECUTION_UUID
UUID of Task Execution to attach to
--task-version-number TASK_VERSION_NUMBER
Numeric version of the Task's source code
--task-version-text TASK_VERSION_TEXT
Human readable version of the Task's source code
--task-version-signature TASK_VERSION_SIGNATURE
Version signature of the Task's source code (such as a
git commit hash)
--execution-method-props EXECUTION_METHOD_PROPS
Additional properties of the execution method, in JSON
format. See https://apidocs.cloudreactor.io/#operation
/api_v1_task_executions_create for the schema.
--task-instance-metadata TASK_INSTANCE_METADATA
Additional metadata about the Task instance, in JSON
format
-s, --service Indicate that this is a Task that should run
indefinitely
--schedule SCHEDULE Run schedule reported to the API server
--max-concurrency MAX_CONCURRENCY
Maximum number of concurrent Task Executions of the
same Task. Defaults to 1.
--max-conflicting-age MAX_CONFLICTING_AGE
Maximum age of conflicting Tasks to consider, in
seconds. -1 means no limit. Defaults to the heartbeat
interval, plus 60 seconds for services that send
heartbeats. Otherwise, defaults to no limit.
api:
API client settings
--api-base-url API_BASE_URL
Base URL of API server. Defaults to
https://api.cloudreactor.io
-k API_KEY, --api-key API_KEY
API key. Must have at least the Task access level, or
Developer access level for auto-created Tasks.
--api-heartbeat-interval API_HEARTBEAT_INTERVAL
Number of seconds to wait between sending heartbeats
to the API server. -1 means to not send heartbeats.
Defaults to 30 for concurrency limited services, 300
otherwise.
--api-error-timeout API_ERROR_TIMEOUT
Number of seconds to wait while receiving recoverable
errors from the API server. Defaults to 300.
--api-final-update-timeout API_FINAL_UPDATE_TIMEOUT
Number of seconds to wait while receiving recoverable
errors from the API server when sending the final
update before exiting. Defaults to 1800.
--api-retry-delay API_RETRY_DELAY
Number of seconds to wait before retrying an API
request. Defaults to 120.
--api-resume-delay API_RESUME_DELAY
Number of seconds to wait before resuming API
requests, after retries are exhausted. Defaults to
600. -1 means to never resume.
--api-task-execution-creation-error-timeout API_TASK_EXECUTION_CREATION_ERROR_TIMEOUT
Number of seconds to keep retrying Task Execution
creation while receiving error responses from the API
server. -1 means to keep trying indefinitely. Defaults
to 300.
--api-task-execution-creation-conflict-timeout API_TASK_EXECUTION_CREATION_CONFLICT_TIMEOUT
Number of seconds to keep retrying Task Execution
creation while conflict is detected by the API server.
-1 means to keep trying indefinitely. Defaults to 1800
for concurrency limited services, 0 otherwise.
--api-task-execution-creation-conflict-retry-delay API_TASK_EXECUTION_CREATION_CONFLICT_RETRY_DELAY
Number of seconds between attempts to retry Task
Execution creation after conflict is detected.
Defaults to 60 for concurrency-limited services, 120
otherwise.
--api-request-timeout API_REQUEST_TIMEOUT
Timeout for contacting API server, in seconds.
Defaults to 30.
-o, --offline-mode Do not communicate with or rely on an API server
-p, --prevent-offline-execution
Do not start processes if the API server is
unavailable or the wrapper is misconfigured.
-d DEPLOYMENT, --deployment DEPLOYMENT
Deployment name (production, staging, etc.)
--send-pid Send the process ID to the API server
--send-hostname Send the hostname to the API server
--no-send-runtime-metadata
Do not send metadata about the runtime environment
log:
Logging settings
-l {DEBUG,INFO,WARNING,ERROR,CRITICAL}, --log-level {DEBUG,INFO,WARNING,ERROR,CRITICAL}
Log level
--log-secrets Log sensitive information
--exclude-timestamps-in-log
Exclude timestamps in log (possibly because the log
stream will be enriched by timestamps automatically by
a logging service like AWS CloudWatch Logs)
process:
Process settings
-w WORK_DIR, --work-dir WORK_DIR
Working directory. Defaults to the current directory.
-c COMMAND_LINE, --command-line COMMAND_LINE
Command line to execute
--shell-mode {auto,enable,disable}
Indicates if the process command should be executed in
a shell. Executing in a shell allows shell scripts,
commands, and expressions to be used, with the
disadvantage that termination signals may not be
propagated to child processes. Options are: enable --
Force the command to be executed in a shell; disable
-- Force the command to be executed without a shell;
auto -- Auto-detect the shell mode by analyzing the
command.
--no-strip-shell-wrapping
Do not strip the command-line of shell wrapping like
"/bin/sh -c" that can be introduced by Docker when
using shell form of ENTRYPOINT and CMD.
--no-process-group-termination
Send termination and kill signals to the wrapped
process only, instead of its process group (which is
the default). Sending to the process group allows all
child processes to receive the signals, even if the
wrapped process does not forward signals. However, if
your wrapped process manually handles and forwards
signals to its child processes, you probably want to
send signals to only your wrapped process.
-t PROCESS_TIMEOUT, --process-timeout PROCESS_TIMEOUT
Timeout for process completion, in seconds. -1 means
no timeout, which is the default.
-r PROCESS_MAX_RETRIES, --process-max-retries PROCESS_MAX_RETRIES
Maximum number of times to retry failed processes. -1
means to retry forever. Defaults to 0.
--process-retry-delay PROCESS_RETRY_DELAY
Number of seconds to wait before retrying a process.
Defaults to 60.
--process-check-interval PROCESS_CHECK_INTERVAL
Number of seconds to wait between checking the status
of processes. Defaults to 10.
--process-termination-grace-period PROCESS_TERMINATION_GRACE_PERIOD
Number of seconds to wait after sending SIGTERM to a
process, but before killing it with SIGKILL. Defaults
to 30.
updates:
Status update settings
--enable-status-update-listener
Listen for status updates from the process, sent on
the status socket port via UDP. If not specified,
status update messages will not be read.
--status-update-socket-port STATUS_UPDATE_SOCKET_PORT
The port used to receive status updates from the
process. Defaults to 2373.
--status-update-message-max-bytes STATUS_UPDATE_MESSAGE_MAX_BYTES
The maximum number of bytes status update messages can
be. Defaults to 65536.
--status-update-interval STATUS_UPDATE_INTERVAL
Minimum of number of seconds to wait between sending
status updates to the API server. -1 means to not send
status updates except with heartbeats. Defaults to -1.
configuration:
Environment/configuration resolution settings
-e ENV_LOCATIONS, --env ENV_LOCATIONS
Location of either local file, AWS S3 ARN, or AWS
Secrets Manager ARN containing properties used to
populate the environment for embedded mode, or the
process environment for wrapped mode. By default, the
file format is assumed to be dotenv. Specify multiple
times to include multiple locations.
--config CONFIG_LOCATIONS
Location of either local file, AWS S3 ARN, or AWS
Secrets Manager ARN containing properties used to
populate the configuration for embedded mode. By
default, the file format is assumed to be in JSON.
Specify multiple times to include multiple locations.
--config-merge-strategy {DEEP,SHALLOW,REPLACE,ADDITIVE,TYPESAFE_REPLACE,TYPESAFE_ADDITIVE}
Merge strategy for merging configurations. Defaults to
'DEEP', which does not require mergedeep. Besides the
'SHALLOW' strategy, all other strategies require the
mergedeep python package to be installed.
--overwrite_env_during_resolution
Overwrite existing environment variables when
resolving them
--config-ttl CONFIG_TTL
Number of seconds to cache resolved environment
variables and configuration properties instead of
refreshing them when a process restarts. -1 means to
never refresh. Defaults to -1.
--no-fail-fast-config-resolution
Exit immediately if an error occurs resolving the
configuration
--resolved-env-var-name-prefix RESOLVED_ENV_VAR_NAME_PREFIX
Required prefix for names of environment variables
that should resolved. The prefix will be removed in
the resolved variable name. Defaults to ''.
--resolved-env-var-name-suffix RESOLVED_ENV_VAR_NAME_SUFFIX
Required suffix for names of environment variables
that should resolved. The suffix will be removed in
the resolved variable name. Defaults to
'_FOR_PROC_WRAPPER_TO_RESOLVE'.
--resolved-config-property-name-prefix RESOLVED_CONFIG_PROPERTY_NAME_PREFIX
Required prefix for names of configuration properties
that should resolved. The prefix will be removed in
the resolved property name. Defaults to ''.
--resolved-config-property-name-suffix RESOLVED_CONFIG_PROPERTY_NAME_SUFFIX
Required suffix for names of configuration properties
that should resolved. The suffix will be removed in
the resolved property name. Defaults to
'__to_resolve'.
--env-var-name-for-config ENV_VAR_NAME_FOR_CONFIG
The name of the environment variable used to set to
the value of the JSON encoded configuration. Defaults
to not setting any environment variable.
--config-property-name-for-env CONFIG_PROPERTY_NAME_FOR_ENV
The name of the configuration property used to set to
the value of the JSON encoded environment. Defaults to
not setting any property.
rollbar:
Rollbar settings
--rollbar-access-token ROLLBAR_ACCESS_TOKEN
Access token for Rollbar (used to report error when
communicating with API server)
--rollbar-retries ROLLBAR_RETRIES
Number of retries per Rollbar request. Defaults to 2.
--rollbar-retry-delay ROLLBAR_RETRY_DELAY
Number of seconds to wait before retrying a Rollbar
request. Defaults to 120.
--rollbar-timeout ROLLBAR_TIMEOUT
Timeout for contacting Rollbar server, in seconds.
Defaults to 30.
These environment variables take precedence over command-line arguments:
* PROC_WRAPPER_TASK_NAME
* PROC_WRAPPER_TASK_UUID
* PROC_WRAPPER_TASK_EXECUTION_UUID
* PROC_WRAPPER_AUTO_CREATE_TASK (TRUE or FALSE)
* PROC_WRAPPER_AUTO_CREATE_TASK_RUN_ENVIRONMENT_NAME
* PROC_WRAPPER_AUTO_CREATE_TASK_RUN_ENVIRONMENT_UUID
* PROC_WRAPPER_AUTO_CREATE_TASK_PROPS (JSON encoded property map)
* PROC_WRAPPER_TASK_IS_PASSIVE (TRUE OR FALSE)
* PROC_WRAPPER_TASK_IS_SERVICE (TRUE or FALSE)
* PROC_WRAPPER_EXECUTION_METHOD_PROPS (JSON encoded property map)
* PROC_WRAPPER_TASK_MAX_CONCURRENCY (set to -1 to indicate no limit)
* PROC_WRAPPER_PREVENT_OFFLINE_EXECUTION (TRUE or FALSE)
* PROC_WRAPPER_TASK_VERSION_NUMBER
* PROC_WRAPPER_TASK_VERSION_TEXT
* PROC_WRAPPER_TASK_VERSION_SIGNATURE
* PROC_WRAPPER_TASK_INSTANCE_METADATA (JSON encoded property map)
* PROC_WRAPPER_LOG_LEVEL (TRACE, DEBUG, INFO, WARNING, ERROR, or CRITICAL)
* PROC_WRAPPER_LOG_SECRETS (TRUE or FALSE)
* PROC_WRAPPER_INCLUDE_TIMESTAMPS_IN_LOG (TRUE or FALSE)
* PROC_WRAPPER_DEPLOYMENT
* PROC_WRAPPER_API_BASE_URL
* PROC_WRAPPER_API_KEY
* PROC_WRAPPER_API_HEARTBEAT_INTERVAL_SECONDS
* PROC_WRAPPER_API_ERROR_TIMEOUT_SECONDS
* PROC_WRAPPER_API_RETRY_DELAY_SECONDS
* PROC_WRAPPER_API_RESUME_DELAY_SECONDS
* PROC_WRAPPER_API_TASK_EXECUTION_CREATION_ERROR_TIMEOUT_SECONDS
* PROC_WRAPPER_API_TASK_EXECUTION_CREATION_CONFLICT_TIMEOUT_SECONDS
* PROC_WRAPPER_API_TASK_EXECUTION_CREATION_CONFLICT_RETRY_DELAY_SECONDS
* PROC_WRAPPER_API_FINAL_UPDATE_TIMEOUT_SECONDS
* PROC_WRAPPER_API_REQUEST_TIMEOUT_SECONDS
* PROC_WRAPPER_ENV_LOCATIONS (comma-separated list of locations)
* PROC_WRAPPER_CONFIG_LOCATIONS (comma-separated list of locations)
* PROC_WRAPPER_OVERWRITE_ENV_WITH_SECRETS (TRUE or FALSE)
* PROC_WRAPPER_RESOLVE_SECRETS (TRUE or FALSE)
* PROC_WRAPPER_MAX_CONFIG_RESOLUTION_DEPTH
* PROC_WRAPPER_MAX_CONFIG_RESOLUTION_ITERATIONS
* PROC_WRAPPER_CONFIG_TTL_SECONDS
* PROC_WRAPPER_FAIL_FAST_CONFIG_RESOLUTION (TRUE or FALSE)
* PROC_WRAPPER_RESOLVABLE_ENV_VAR_NAME_PREFIX
* PROC_WRAPPER_RESOLVABLE_ENV_VAR_NAME_SUFFIX
* PROC_WRAPPER_RESOLVABLE_CONFIG_PROPERTY_NAME_PREFIX
* PROC_WRAPPER_RESOLVABLE_CONFIG_PROPERTY_NAME_SUFFIX
* PROC_WRAPPER_ENV_VAR_NAME_FOR_CONFIG
* PROC_WRAPPER_CONFIG_PROPERTY_NAME_FOR_ENV
* PROC_WRAPPER_SEND_PID (TRUE or FALSE)
* PROC_WRAPPER_SEND_HOSTNAME (TRUE or FALSE)
* PROC_WRAPPER_SEND_RUNTIME_METADATA (TRUE or FALSE)
* PROC_WRAPPER_ROLLBAR_ACCESS_TOKEN
* PROC_WRAPPER_ROLLBAR_TIMEOUT_SECONDS
* PROC_WRAPPER_ROLLBAR_RETRIES
* PROC_WRAPPER_ROLLBAR_RETRY_DELAY_SECONDS
* PROC_WRAPPER_MAX_CONFLICTING_AGE_SECONDS
* PROC_WRAPPER_TASK_COMMAND
* PROC_WRAPPER_SHELL_MODE (TRUE or FALSE)
* PROC_WRAPPER_STRIP_SHELL_WRAPPING (TRUE or FALSE)
* PROC_WRAPPER_WORK_DIR
* PROC_WRAPPER_PROCESS_MAX_RETRIES
* PROC_WRAPPER_PROCESS_TIMEOUT_SECONDS
* PROC_WRAPPER_PROCESS_RETRY_DELAY_SECONDS
* PROC_WRAPPER_PROCESS_CHECK_INTERVAL_SECONDS
* PROC_WRAPPER_PROCESS_TERMINATION_GRACE_PERIOD_SECONDS
* PROC_WRAPPER_PROCESS_GROUP_TERMINATION (TRUE or FALSE)
* PROC_WRAPPER_STATUS_UPDATE_SOCKET_PORT
* PROC_WRAPPER_STATUS_UPDATE_MESSAGE_MAX_BYTES
With the exception of the settings for Secret Fetching and Resolution,
these environment variables are read after Secret Fetching so that they can
come from secret values.
The command is executed with the same environment that the wrapper script gets,
except that these properties are copied/overridden:
* PROC_WRAPPER_DEPLOYMENT
* PROC_WRAPPER_API_BASE_URL
* PROC_WRAPPER_API_KEY
* PROC_WRAPPER_API_ERROR_TIMEOUT_SECONDS
* PROC_WRAPPER_API_RETRY_DELAY_SECONDS
* PROC_WRAPPER_API_RESUME_DELAY_SECONDS
* PROC_WRAPPER_API_REQUEST_TIMEOUT_SECONDS
* PROC_WRAPPER_ROLLBAR_ACCESS_TOKEN
* PROC_WRAPPER_ROLLBAR_TIMEOUT_SECONDS
* PROC_WRAPPER_ROLLBAR_RETRIES
* PROC_WRAPPER_ROLLBAR_RETRY_DELAY_SECONDS
* PROC_WRAPPER_ROLLBAR_RESUME_DELAY_SECONDS
* PROC_WRAPPER_TASK_EXECUTION_UUID
* PROC_WRAPPER_TASK_UUID
* PROC_WRAPPER_TASK_NAME
* PROC_WRAPPER_TASK_VERSION_NUMBER
* PROC_WRAPPER_TASK_VERSION_TEXT
* PROC_WRAPPER_TASK_VERSION_SIGNATURE
* PROC_WRAPPER_TASK_INSTANCE_METADATA
* PROC_WRAPPER_SCHEDULE
* PROC_WRAPPER_PROCESS_TIMEOUT_SECONDS
* PROC_WRAPPER_TASK_MAX_CONCURRENCY
* PROC_WRAPPER_PREVENT_OFFLINE_EXECUTION
* PROC_WRAPPER_PROCESS_TERMINATION_GRACE_PERIOD_SECONDS
* PROC_WRAPPER_ENABLE_STATUS_UPDATE_LISTENER
* PROC_WRAPPER_STATUS_UPDATE_SOCKET_PORT
* PROC_WRAPPER_STATUS_UPDATE_INTERVAL_SECONDS
* PROC_WRAPPER_STATUS_UPDATE_MESSAGE_MAX_BYTES
Wrapped mode is suitable for running in a shell on your own (virtual) machine
or in a Docker container. It requires multi-process support, as the module
runs at the same time as the command it wraps.
### Embedded mode
You can use embedded mode to execute python code from inside a python program.
Include the `proc_wrapper` package in your python project's
dependencies. To run a task you want to be monitored:
from typing import Any, Mapping
from proc_wrapper import ProcWrapper, ProcWrapperParams
def fun(wrapper: ProcWrapper, cbdata: dict[str, int],
config: Mapping[str, Any]) -> int:
print(cbdata)
return cbdata['a']
# This is the function signature of a function invoked by AWS Lambda.
def entrypoint(event: Any, context: Any) -> int:
params = ProcWrapperParams()
params.auto_create_task = True
# If the Task Execution is running in AWS Lambda, CloudReactor can make
# the associated Task available to run (non-passive) in the CloudReactor
# dashboard or by API, after the wrapper reports its first execution.
proc_wrapper_params.task_is_passive = False
params.task_name = 'embedded_test_production'
params.auto_create_task_run_environment_name = 'production'
# For example only, in the real world you would use Secret Fetching;
# see below.
params.api_key = 'YOUR_CLOUDREACTOR_API_KEY'
# In an AWS Lambda environment, passing the context and event allows
# CloudReactor to monitor and manage this Task.
proc_wrapper = ProcWrapper(params=params, runtime_context=context,
input_value=event)
x = proc_wrapper.managed_call(fun, {'a': 1, 'b': 2})
# Should print 1
print(x)
return x
This is suitable for running in single-threaded environments like
AWS Lambda, or as part of a larger process that executes
sub-routines that should be monitored. See
[cloudreactor-python-lambda-quickstart](https://github.com/CloudReactor/cloudreactor-python-lambda-quickstart) for an example project that uses
proc_wrapper in a function run by AWS Lambda.
#### Embedded mode configuration
In embedded mode, besides setting properties of `ProcWrapperParams` in code,
`ProcWrapper` can be also configured in two ways:
First, using environment variables, as in wrapped mode.
Second, using the configuration dictionary. If the configuration dictionary
contains the key `proc_wrapper_params` and its value is a dictionary, the
keys and values in the dictionary will be used to to set these attributes in
`ProcWrapperParams`:
| Key | Type | Mutable | Uses Resolved Config |
|---------------------------------- |----------- |--------- |---------------------- |
| log_secrets | bool | No | No |
| env_locations | list[str] | No | No |
| config_locations | list[str] | No | No |
| config_merge_strategy | str | No | No |
| overwrite_env_during_resolution | bool | No | No |
| max_config_resolution_depth | int | No | No |
| max_config_resolution_iterations | int | No | No |
| config_ttl | int | No | No |
| fail_fast_config_resolution | bool | No | No |
| resolved_env_var_name_prefix | str | No | No |
| resolved_env_var_name_suffix | str | No | No |
| resolved_config_property_name_prefix | str | No | No |
| resolved_config_property_name_suffix | str | No | No |
| schedule | str | No | Yes |
| max_concurrency | int | No | Yes |
| max_conflicting_age | int | No | Yes |
| offline_mode | bool | No | Yes |
| prevent_offline_execution | bool | No | Yes |
| service | bool | No | Yes |
| deployment | str | No | Yes |
| api_base_url | str | No | Yes |
| api_heartbeat_interval | int | No | Yes |
| enable_status_listener | bool | No | Yes |
| status_update_socket_port | int | No | Yes |
| status_update_message_max_bytes | int | No | Yes |
| status_update_interval | int | No | Yes |
| log_level | str | No | Yes |
| include_timestamps_in_log | bool | No | Yes |
| api_key | str | Yes | Yes |
| api_request_timeout | int | Yes | Yes |
| api_error_timeout | int | Yes | Yes |
| api_retry_delay | int | Yes | Yes |
| api_resume_delay | int | Yes | Yes |
| api_task_execution_creation_error_timeout | int | Yes | Yes |
| api_task_execution_creation_conflict_timeout | int | Yes | Yes |
| api_task_execution_creation_conflict_retry_delay | int | Yes | Yes |
| process_timeout | int | Yes | Yes |
| process_max_retries | int | Yes | Yes |
| process_retry_delay | int | Yes | Yes |
| command | list[str] | Yes | Yes |
| command_line | str | Yes | Yes |
| shell_mode | bool | Yes | Yes |
| strip_shell_wrapping | bool | Yes | Yes |
| work_dir | str | Yes | Yes |
| process_termination_grace_period | int | Yes | Yes |
| send_pid | bool | Yes | Yes |
| send_hostname | bool | Yes | Yes |
| send_runtime_metadata | bool | Yes | Yes |
Keys that are marked with "Mutable" -- "No" in the table above can be
overridden when the configuration is reloaded after the `config_ttl` expires.
Keys that are marked as "Uses Resolved Config" -- "Yes" in the table above can
come from the resolved configuration after secret resolution (see below).
## Secret Fetching and Resolution
A common requirement is that deployed code / images do not contain secrets
internally which could be decompiled. Instead, programs should fetch secrets
from an external source in a secure manner. If your program runs in AWS, it
can make use of AWS's roles that have permission to access data in
Secrets Manager or S3. However, in many scenarios, having your program access
AWS directly has the following disadvantages:
1) Your program becomes coupled to AWS, so it is difficult to run locally or
switch to another infrastructure provider
2) You need to write code or use a library for each programming language you
use, so secret fetching is done in a non-uniform way
3) Writing code to merge and parse secrets from different sources is tedious
Therefore, proc_wrapper implements Secret Fetching and Resolution to solve
these problems so your programs don't have to. Both usage modes can fetch secrets from
[AWS Secrets Manager](https://aws.amazon.com/secrets-manager/),
AWS S3, or the local filesystem, and optionally extract embedded data
into the environment or a configuration dictionary. The environment is used to
pass values to processes run in wrapped mode,
while the configuration dictionary is passed to the callback function in
embedded mode.
proc_wrapper parses secret location strings that specify the how to resolve
a secret value. Each secret location string has the format:
`[PROVIDER_CODE:]<Provider specific address>[!FORMAT][|JP:<JSON Path expression>]`
### Secret Providers
Providers indicate the raw source of the secret data. The table below lists the
supported providers:
| Provider Code | Value Prefix | Provider | Example Address | Required libs | Notes |
|--------------- |--------------------------- |------------------------------ |------------------------------------------------------------- |----------------------------------------------------------------------------- |--------------------------------------------------------------- |
| `AWS_SM` | `arn:aws:secretsmanager:` | AWS Secrets Manager | `arn:aws:secretsmanager:us-east-2:1234567890:secret:config` | [boto3](https://boto3.amazonaws.com/v1/documentation/api/latest/index.html) | Can also include version suffix like `-PPrpY` |
| `AWS_S3` | `arn:aws:s3:::` | AWS S3 Object | `arn:aws:s3:::examplebucket/staging/app1/config.json` | [boto3](https://boto3.amazonaws.com/v1/documentation/api/latest/index.html) | |
| `FILE` | `file://` | Local file | `file:///home/appuser/app/.env` | | The default provider if no provider is auto-detected |
| `ENV` | | The process environment | `SOME_TOKEN` | | The name of another environment variable |
| `CONFIG` | | The configuration dictionary | `$.db` | [jsonpath-ng](https://github.com/h2non/jsonpath-ng) | JSON path expression to extract the data in the configuration |
| `PLAIN` | | Plaintext | `{"user": "postgres", "password": "badpassword"}` | | |
If you don't specify an explicit provider prefix in a secret location
(e.g. `AWS_SM:`), the provider can be auto-detected from the address portion
using the Value Prefix. For example the secret location
`arn:aws:s3:::examplebucket/staging/app1/config.json` will be auto-detected
to with the AWS_S3 provider because it starts with `arn:aws:s3:::`.
### Secret Formats
Formats indicate how the raw string data is parsed into a secret value (which may be
a string, number, boolean, dictionary, or array). The table below lists the
supported formats:
| Format Code | Extensions | MIME types | Required libs | Notes |
|------------- |----------------- |--------------------------------------------------------------------------------------- |------------------------------------------------------ |-------------------------------------------------- |
| `dotenv` | `.env` | None | [dotenv](https://github.com/theskumar/python-dotenv) | Also auto-detected if location includes `.env.` |
| `json` | `.json` | `application/json`, `text/x-json` | | |
| `yaml` | `.yaml`, `.yml` | `application/x-yaml`, `application/yaml`, `text/vnd.yaml`, `text/yaml`, `text/x-yaml` | [pyyaml](https://pyyaml.org/) | `safe_load()` is used for security |
The format of a secret value can be auto-detected from the extension or by the
MIME type if available. Otherwise, you may need to an explicit format code
(e.g. `!yaml`).
#### AWS Secrets Manager / S3 notes
[boto3](https://boto3.amazonaws.com/v1/documentation/api/latest/index.html)
is used to fetch secrets. It will try to access to AWS Secrets Manager
or S3 using environment variables `AWS_ACCESS_KEY_ID` and
`AWS_SECRET_ACCESS_KEY` if they are set, or use the EC2 instance role, ECS task
role, or Lambda execution role if available.
For Secrets Manager, you can also use "partial ARNs"
(without the hyphened suffix) as keys.
In the example above
arn:aws:secretsmanager:us-east-2:1234567890:secret:config
could be used to fetch the same secret, provided there are no conflicting secret ARNs.
This allows you to get the latest version of the secret.
If the secret was stored in Secrets Manager as binary, the
corresponding value will be set to the Base-64 encoded value.
If you're deploying a python function using AWS Lambda, note that boto3 is
already included in the available packages, so there's no need to include it
(unless the bundled version isn't compatible). Also we strongly encourage you
to add:
logging.getLogger("botocore").setLevel(logging.INFO)
to your code if you are using proc_wrapper for secrets resolution. This
prevent secrets from Secrets Manager from being leaked. For details, see this
[issue](https://github.com/boto/boto3/issues/2292).
### Secret Tranformation
Fetching secrets can be relatively expensive and it makes sense to group related
secrets together. Therefore it is common to store dictionaries (formatted
as JSON or YAML) as secrets. However, each desired environment variable
or configuration property may only consist of a fragment of the dictionary.
For example, given the JSON-formatted dictionary
{
"username": "postgres",
"password": "badpassword"
}
you may want to populate the environment variable `DB_USERNAME` with
`postgres`.
To facilitate this, dictionary fragments can be extracted to individual
environment variables using [jsonpath-ng](https://github.com/h2non/jsonpath-ng).
To specify that a variable be extracted from a dictionary using
a JSON Path expression, append `|JP:` followed by the JSON Path expression
to the secret location string. For example, if the AWS Secrets Manager
ARN
arn:aws:secretsmanager:us-east-2:1234567890:secret:db-PPrpY
contains the dictionary above, then the secret location string
arn:aws:secretsmanager:us-east-2:1234567890:secret:db-PPrpY|JP:$.username
will resolve to `postgres` as desired.
If you do something similar to get the password from the same JSON value,
proc_wrapper is smart enough to cache the fetched dictionary, so that the
raw data is only fetched once.
Since JSON path expressions yield a list of results, the secrets fetcher
implements the following rules to transform the list to the final value:
1. If the list of results has a single value, that value is used as the
final value, unless `[*]` is appended to the JSON path expression.
2. Otherwise, the final value is the list of results
#### Fetching from another environment variable
In some deployment scenarios, multiple secrets can be injected into a
single environment variable as a JSON encoded object. In that case,
the module can extract secrets using the *ENV* secret source. For example,
you may have arranged to have the environment variable DB_CONFIG injected
with the JSON encoded value:
{ "username": "postgres", "password": "nohackme" }
Then to extract the username to the environment variable DB_USERNAME you
you would add the environment variable DB_USER_FOR_PROC_WRAPPER_TO_RESOLVE
set to
ENV:DB_CONFIG|JP:$.username
### Secret injection into environment and configuration
Now let's use secret location strings to
inject the values into the environment (for wrapped mode)
and/or the the configuration dictionary (for embedded mode). proc_wrapper
supports two methods of secret injection which can be combined together:
* Top-level fetching
* Secrets Resolution
### Top-level fetching
Top-level fetching refers to fetching a dictionary that contains multiple secrets
and populating the environment / configuration dictionary with it.
To use top-level fetching, you specify the secret locations
from which you want to fetch the secrets and the corresponding values are
merged together into the environment / configuration.
To use top-level fetching in wrapped mode, populate the
environment variables `PROC_WRAPPER_ENV_LOCATIONS` with a comma-separated
list of secret locations, or use the command-line option
`--env-locations <secret_location>` one or more times. Secret location
strings passed in via `PROC_WRAPPER_ENV_LOCATIONS` or `--env-locations`
will be parsed as `dotenv` files unless format is auto-detected or
explicitly specified.
To use top-level fetching in embedded mode, set the `ProcWrapperParams` property
`config_locations` to a list of secret locations. Alternatively, you can set
the environment variable `PROC_WRAPPER_CONFIG_LOCATIONS` to a comma-separated
list, and this will be picked up automatically. Secret location values
will be parsed as JSON unless the format is auto-detected or explicitly
specified. The `config` argument
passed to the your callback function will contain a merged dictionary of all
fetched and parsed dictionary values. For example:
def callback(wrapper: ProcWrapper, cbdata: str,
config: Dict[str, Any]) -> str:
return "super" + cbdata + config["username"]
def main():
params = ProcWrapperParams()
# Optional: you can set an initial configuration dictionary which will
# have its values included in the final configuration unless overridden.
params.initial_config = {
"log_level": "DEBUG"
}
# You can omit this if you set PROC_WRAPPER_CONFIG_LOCATIONS environment
# variable to the same ARN
params.config_locations = [
"arn:aws:secretsmanager:us-east-2:1234567890:secret:db-PPrpY",
# More secret locations can be added here, and their values will
# be merged
]
wrapper = ProcWrapper(params=params)
# Returns "superduperpostgres"
return wrapper.managed_call(callback, "duper")
#### Merging Secrets
Top-level fetching can potentially fetch multiple dictionaries which are
merged together in the final environment / configuration dictionary.
The default merge strategy (`DEEP`) merges recursively, even dictionaries
in lists. The `SHALLOW` merge strategy just overwrites top-level keys, with later
secret locations taking precedence. However, if you include the
[mergedeep](https://github.com/clarketm/mergedeep) library, you can also
set the merge strategy to one of:
* `REPLACE`
* `ADDITIVE`
* `TYPESAFE_REPLACE`
* `TYPESAFE_ADDITIVE`
so that nested lists can be appended to instead of replaced (in the case of the
`ADDITIVE` strategies), or errors will be raised if incompatibly-typed values
are merged (in the case of the `TYPESAFE` strategies). In wrapped mode,
the merge strategy can be set with the `--config-merge-strategy` command-line
argument or `PROC_WRAPPER_CONFIG_MERGE_STRATEGY` environment variable. In
embedded mode, the merge strategy can be set in the
`config_merge_strategy` string property of `ProcWrapperParams`.
### Secret Resolution
Secret Resolution substitutes configuration or environment values that are
secret location strings with the computed values of those strings. Compared
to Secret Fetching, Secret Resolution is more useful when you want more
control over the names of variables or when you have secret values deep
inside your configuration.
In wrapped mode, if you want to set the environment variable `MY_SECRET` with
a value fetched
from AWS Secrets Manager, you would set the environment variable
`MY_SECRET_FOR_PROC_WRAPPER_TO_RESOLVE` to a secret location string
which is ARN of the secret, for example:
arn:aws:secretsmanager:us-east-2:1234567890:secret:db-PPrpY
(The `_FOR_PROC_WRAPPER_TO_RESOLVE` suffix of environment variable names is
removed during resolution. It can also be configured with the `PROC_WRAPPER_RESOLVABLE_ENV_VAR_NAME_SUFFIX` environment variable.)
In embedded mode, if you want the final configuration dictionary to look like:
{
"db_username": "postgres",
"db_password": "badpassword",
...
}
The initial configuration dictionary would look like:
{
"db_username__to_resolve": "arn:aws:secretsmanager:us-east-2:1234567890:secret:db-PPrpY|JP:$.username",
"db_password__to_resolve": "arn:aws:secretsmanager:us-east-2:1234567890:secret:db-PPrpY|JP:$.password",
...
}
(The `__to_resolve` suffix (with 2 underscores!) of keys is removed during
resolution. It can also be configured with the `resolved_config_property_name_suffix`
property of `ProcWrapperParams`.)
proc_wrapper can also resolve keys in embedded dictionaries, like:
{
"db": {
"username__to_resolve": "arn:aws:secretsmanager:us-east-2:1234567890:secret:config-PPrpY|JP:$.username",
"password__to_resolve":
"arn:aws:secretsmanager:us-east-2:1234567890:secret:config-PPrpY|JP:$.password",
...
},
...
}
up to a maximum depth that you can control with `ProcWrapperParams.max_config_resolution_depth` (which defaults to 5). That would resolve to
{
"db": {
"username": "postgres",
"password": "badpassword"
...
},
...
}
You can also inject entire dictionaries, like:
{
"db__to_resolve": "arn:aws:secretsmanager:us-east-2:1234567890:secret:config-PPrpY",
...
}
which would resolve to
{
"db": {
"username": "postgres",
"password": "badpassword"
},
...
}
To enable secret resolution in wrapped mode, set environment variable `PROC_WRAPPER_RESOLVE_SECRETS` to `TRUE`. In embedded mode, secret
resolution is enabled by default; set the
`max_config_resolution_iterations` property of `ProcWrapperParams` to `0`
to disable resolution.
Secret resolution is run multiple times so that if a resolved value contains
a secret location string, it will be resolved on the next pass. By default,
proc_wrapper limits the maximum number of resolution passes to 3 but you
can control this with the environment variable
`PROC_WRAPPER_MAX_CONFIG_RESOLUTION_ITERATIONS` in embedded mode,
or by setting the `max_config_resolution_iterations` property of
`ProcWrapperParams` in wrapped mode.
### Environment Projection
During secret fetching and secret resolution, proc_wrapper internally maintains
the computed environment as a dictionary which may have embedded lists and
dictionaries. However, the final environment passed to the process is a flat
dictionary containing only string values. So proc_wrapper converts
all top-level values to strings using these rules:
* Lists and dictionaries are converted to their JSON-encoded string value
* Boolean values are converted to their upper-cased string representation
(e.g. the string `FALSE` for the boolean value `false`)
* The `None` value is converted to the empty string
* All other values are converted using python's `str()` function
### Secrets Refreshing
You can set a Time to Live (TTL) on the duration that secret values are cached.
Caching helps reduce expensive lookups of secrets and bandwidth usage.
In wrapped mode, set the TTL of environment variables set from secret locations
using the `--config-ttl` command-line argument or
`PROC_WRAPPER_CONFIG_TTL_SECONDS` environment variable.
If the process exits, you have configured the script to retry,
and the TTL has expired since the last fetch,
proc_wrapper will re-fetch the secrets
and resolve them again, for the environment passed to the next invocation of
your process.
In embedded mode, set the TTL of configuration dictionary values set from
secret locations by setting the `config_ttl` property of
`ProcWrapperParams`. If 1) your callback function raises an exception, 2) you have
configured the script to retry; and 3) the TTL has expired since the last fetch,
proc_wrapper will re-fetch the secrets
and resolve them again, for the configuration passed to the next invocation of
the callback function.
## Status Updates
### Status Updates in Wrapped Mode
While your process in running, you can send status updates to
CloudReactor by using the StatusUpdater class. Status updates are shown in
the CloudReactor dashboard and allow you to track the current progress of a
Task and also how many items are being processed in multiple executions
over time.
In wrapped mode, your application code would send updates to the
proc_wrapper program via UDP port 2373 (configurable with the PROC_WRAPPER_STATUS_UPDATE_PORT environment variable).
If your application code is in python, you can use the provided
StatusUpdater class to do this:
from proc_wrapper import StatusUpdater
with StatusUpdater() as updater:
updater.send_update(last_status_message="Starting ...")
success_count = 0
for i in range(100):
try:
do_work()
success_count += 1
updater.send_update(success_count=success_count)
except Exception:
failed_count += 1
updater.send_update(failed_count=failed_count)
updater.send_update(last_status_message="Finished!")
### Status Updates in Embedded Mode
In embedded mode, your callback in python code can use the wrapper instance to
send updates:
from typing import Any, Mapping
import proc_wrapper
from proc_wrapper import ProcWrapper
def fun(wrapper: ProcWrapper, cbdata: dict[str, int],
config: Mapping[str, Any]) -> int:
wrapper.update_status(last_status_message="Starting the fun ...")
success_count = 0
error_count = 0
for i in range(100):
try:
do_work()
success_count += 1
except Exception:
error_count += 1
wrapper.update_status(success_count=success_count,
error_count=error_count)
wrapper.update_status(last_status_message="The fun is over.")
return cbdata["a"]
params = ProcWrapperParams()
params.auto_create_task = True
params.auto_create_task_run_environment_name = "production"
params.task_name = "embedded_test"
params.api_key = "YOUR_CLOUDREACTOR_API_KEY"
proc_wrapper = ProcWrapper(params=params)
proc_wrapper.managed_call(fun, {"a": 1, "b": 2})
## Example Projects
These projects contain sample Tasks that use this library to report their
execution status and results to CloudReactor
* [cloudreactor-python-ecs-quickstart](https://github.com/CloudReactor/cloudreactor-python-ecs-quickstart) runs python code in a Docker container
in AWS ECS Fargate (wrapped mode)
* [cloudreactor-python-lambda-quickstart](https://github.com/CloudReactor/cloudreactor-python-lambda-quickstart) runs python code in AWS Lambda
(embedded mode)
* [cloudreactor-java-ecs-quickstart](https://github.com/CloudReactor/cloudreactor-java-ecs-quickstart) runs Java code in a Docker container in
AWS ECS Fargate (wrapped mode)
## License
This software is dual-licensed under open source (MPL 2.0) and commercial
licenses. See `LICENSE` for details.
## Contributors ✨
Thanks goes to these wonderful people ([emoji key](https://allcontributors.org/docs/en/emoji-key)):
<!-- ALL-CONTRIBUTORS-LIST:START - Do not remove or modify this section -->
<!-- prettier-ignore-start -->
<!-- markdownlint-disable -->
<table>
<tr>
<td align="center"><a href="https://github.com/jtsay362"><img src="https://avatars0.githubusercontent.com/u/1079646?s=460&v=4?s=80" width="80px;" alt=""/><br /><sub><b>Jeff Tsay</b></sub></a><br /><a href="https://github.com/CloudReactor/cloudreactor-procwrapper/commits?author=jtsay362" title="Code">💻</a> <a href="https://github.com/CloudReactor/cloudreactor-procwrapper/commits?author=jtsay362" title="Documentation">📖</a> <a href="#infra-jtsay362" title="Infrastructure (Hosting, Build-Tools, etc)">🚇</a> <a href="#maintenance-jtsay362" title="Maintenance">🚧</a></td>
<td align="center"><a href="https://github.com/mwaldne"><img src="https://avatars0.githubusercontent.com/u/40419?s=460&u=3a5266861feeb27db392622371ecc57ebca09f32&v=4?s=80" width="80px;" alt=""/><br /><sub><b>Mike Waldner</b></sub></a><br /><a href="https://github.com/CloudReactor/cloudreactor-procwrapper/commits?author=mwaldne" title="Code">💻</a></td>
<td align="center"><a href="https://browniebroke.com/"><img src="https://avatars.githubusercontent.com/u/861044?v=4?s=80" width="80px;" alt=""/><br /><sub><b>Bruno Alla</b></sub></a><br /><a href="https://github.com/CloudReactor/cloudreactor-procwrapper/commits?author=browniebroke" title="Code">💻</a> <a href="#ideas-browniebroke" title="Ideas, Planning, & Feedback">🤔</a> <a href="https://github.com/CloudReactor/cloudreactor-procwrapper/commits?author=browniebroke" title="Documentation">📖</a></td>
</tr>
</table>
<!-- markdownlint-restore -->
<!-- prettier-ignore-end -->
<!-- ALL-CONTRIBUTORS-LIST:END -->
This project follows the [all-contributors](https://github.com/all-contributors/all-contributors) specification. Contributions of any kind welcome!
## Credits
This package was created with
[Cookiecutter](https://github.com/audreyr/cookiecutter) and the
[browniebroke/cookiecutter-pypackage](https://github.com/browniebroke/cookiecutter-pypackage)
project template.
%prep
%autosetup -n cloudreactor-procwrapper-5.0.2
%build
%py3_build
%install
%py3_install
install -d -m755 %{buildroot}/%{_pkgdocdir}
if [ -d doc ]; then cp -arf doc %{buildroot}/%{_pkgdocdir}; fi
if [ -d docs ]; then cp -arf docs %{buildroot}/%{_pkgdocdir}; fi
if [ -d example ]; then cp -arf example %{buildroot}/%{_pkgdocdir}; fi
if [ -d examples ]; then cp -arf examples %{buildroot}/%{_pkgdocdir}; fi
pushd %{buildroot}
if [ -d usr/lib ]; then
find usr/lib -type f -printf "\"/%h/%f\"\n" >> filelist.lst
fi
if [ -d usr/lib64 ]; then
find usr/lib64 -type f -printf "\"/%h/%f\"\n" >> filelist.lst
fi
if [ -d usr/bin ]; then
find usr/bin -type f -printf "\"/%h/%f\"\n" >> filelist.lst
fi
if [ -d usr/sbin ]; then
find usr/sbin -type f -printf "\"/%h/%f\"\n" >> filelist.lst
fi
touch doclist.lst
if [ -d usr/share/man ]; then
find usr/share/man -type f -printf "\"/%h/%f.gz\"\n" >> doclist.lst
fi
popd
mv %{buildroot}/filelist.lst .
mv %{buildroot}/doclist.lst .
%files -n python3-cloudreactor-procwrapper -f filelist.lst
%dir %{python3_sitelib}/*
%files help -f doclist.lst
%{_docdir}/*
%changelog
* Fri Jun 09 2023 Python_Bot <Python_Bot@openeuler.org> - 5.0.2-1
- Package Spec generated
|