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
|
#!/usr/bin/env python
#
# SHBASECOPYRIGHT
#
# FSL installer script.
#
"""This is the FSL installation script, which can be used to install FSL.
This script must:
- be able to be executed with Python 2.7 or newer.
- be able to be executed in a "vanilla" Python environment, with no third
party dependencies.
- be self-contained, with no dependencies on any other modules (apart from
the Python standard library).
- be importable as a Python module - this script contains functions and
classes that may be used by other scripts.
"""
from __future__ import print_function, division, unicode_literals
import functools as ft
import os.path as op
import subprocess as sp
import textwrap as tw
import argparse
import collections
import contextlib
import datetime
import fnmatch
import getpass
import hashlib
import json
import locale
import logging
import os
import platform
import pwd
import readline
import re
import shlex
import shutil
import ssl
import sys
import tempfile
import threading
import time
import traceback
try:
import urllib.request as urlrequest
except ImportError:
import urllib
import urllib2 as urlrequest
urlrequest.pathname2url = urllib.pathname2url
try: import urllib.parse as urlparse
except ImportError: import urlparse
try: import queue
except ImportError: import Queue as queue
try: from html.parser import HTMLParser
except ImportError: from HTMLParser import HTMLParser
try: from http.cookiejar import CookieJar
except ImportError: from cookielib import CookieJar
PYVER = sys.version_info[:2]
log = logging.getLogger(__name__)
# this sometimes gets set to fslinstaller.pyc, so rstrip c
__absfile__ = op.abspath(__file__).rstrip('c')
__version__ = '3.15.2'
"""Installer script version number. This must be updated
whenever a new version of the installer script is released.
"""
DEFAULT_INSTALLATION_DIRECTORY = op.join(op.expanduser('~'), 'fsl')
"""Default FSL installation directory. """
DEFAULT_ROOT_INSTALLATION_DIRECTORY = '/usr/local/fsl/'
"""Default FSL installation directory when the installer is run as root. """
FSL_RELEASE_MANIFEST = 'https://fsl.fmrib.ox.ac.uk/fsldownloads/' \
'fslconda/releases/manifest.json'
"""URL to download the FSL installer manifest file from. The installer
manifest file is a JSON file which contains information about available FSL
versions.
See the download_manifest function, and an example manifest file
in test/data/manifest.json, for more details.
A custom manifest URL can be specified with the -a/--manifest command-line
option.
"""
FSL_DEV_RELEASES = 'https://fsl.fmrib.ox.ac.uk/fsldownloads/' \
'fslconda/releases/devreleases.txt'
"""URL to the devreleases.txt file, which contains a list of available
internal/development FSL releases. See the download_dev_releases function
for more details.
"""
# List of modifiers which can be used to change how
# a message is printed by the printmsg function.
INFO = 1
IMPORTANT = 2
QUESTION = 3
PROMPT = 4
WARNING = 5
ERROR = 6
EMPH = 7
EMPHASIS = 7
UNDERLINE = 8
RESET = 9
ANSICODES = {
INFO : '\033[37m', # Light grey
IMPORTANT : '\033[92m', # Green
QUESTION : '\033[36m\033[4m', # Blue+underline
PROMPT : '\033[36m\033[1m', # Bright blue+bold
WARNING : '\033[93m', # Yellow
ERROR : '\033[91m', # Red
EMPHASIS : '\033[1m', # White+bold
UNDERLINE : '\033[4m', # Underline
RESET : '\033[0m', # Used internally
}
def get_terminal_width(fallback=None):
"""Return the number of columns in the current terminal, or fallback
if it cannot be determined.
"""
# os.get_terminal_size added in python
# 3.3, so we try it but fall back to
# COLUMNS, or tput as a last resort.
try:
return shutil.get_terminal_size()[0]
except Exception:
pass
try:
return int(os.environ['COLUMNS'])
except Exception:
pass
try:
result = Process.check_output('tput cols', log_output=False)
return int(result.strip())
except Exception:
return fallback
def str2bool(value):
"""Convert a string containing a boolean into a boolean. Assumes that
the value is encoded as "true" or "false" (case insensitive).
"""
if isinstance(value, str): return value.lower() == 'true'
else: return bool(value)
def printmsg(*args, **kwargs):
"""Prints a sequence of strings formatted with ANSI codes. Expects
positional arguments to be of the form::
printable, ANSICODE, printable, ANSICODE, ...
:arg log: Must be specified as a keyword argument. If True (default),
the message is logged.
:arg fill: Must be specified as a keyword argument. If True (default),
the message is wrapped to the terminal width.
All other keyword arguments are passed through to the print function.
"""
args = list(args)
blockids = [i for i in range(len(args)) if (args[i] not in ANSICODES)]
logmsg = kwargs.pop('log', True)
fill = kwargs.pop('fill', True)
coded = ''
uncoded = ''
for i, idx in enumerate(blockids):
if i == len(blockids) - 1:
slc = slice(idx + 1, None)
else:
slc = slice(idx + 1, blockids[i + 1])
msg = args[idx]
msgcodes = args[slc]
msgcodes = [ANSICODES[c] for c in msgcodes]
msgcodes = ''.join(msgcodes)
uncoded += msg
coded += '{}{}{}'.format(msgcodes, msg, ANSICODES[RESET])
if len(blockids) > 0:
if fill:
width = get_terminal_width(70)
coded = tw.fill(coded, width, replace_whitespace=False)
print(coded, **kwargs)
if logmsg:
# print line number of caller rather than
# this line number with the stacklevel
# argument if we are running python >= 3.8
if PYVER >= (3, 8): kwargs = {'stacklevel' : 2}
else: kwargs = {}
log.debug(uncoded, **kwargs)
sys.stdout.flush()
def prompt(promptmsg, *msgtypes, **kwargs):
"""Prompts the user for some input. msgtypes and kwargs are passed
through to the printmsg function.
"""
printmsg(promptmsg, *msgtypes, end='', log=False, **kwargs)
if PYVER[0] == 2: response = raw_input(' ').strip()
else: response = input( ' ').strip()
log.debug('%s: %s', promptmsg, response)
return response
def send_registration_info(url, data):
"""Called by register_installation. Sends information about the
installation to the FSL registration server. The data is assumed
to be a dictionary of key-value pairs to be sent.
"""
class CSRFTokenParser(HTMLParser):
"""HTML parser which extracts a CSRF token.
https://docs.djangoproject.com/en/5.0/ref/csrf/
"""
def __init__(self):
if sys.version_info[0] < 3:
HTMLParser.__init__(self)
else:
super(CSRFTokenParser, self).__init__()
self.csrf_token = None
def handle_starttag(self, tag, attrs):
if tag == 'input':
attr_dict = dict(attrs)
if attr_dict.get('name') == 'csrfmiddlewaretoken':
self.csrf_token = attr_dict.get('value')
data = dict(data)
headers = {}
headers['Content-Type'] = 'application/x-www-form-urlencoded'
headers['Referer'] = url
resp = None
try:
# Use cookie jar to store CSRF token
cj = CookieJar()
# Download the HTML form (which will
# contain the CSRF token)
opener = urlrequest.build_opener(urlrequest.HTTPCookieProcessor(cj))
resp = opener.open(url)
if PYVER[0] == 2: form = resp.read()
else: form = resp.read().decode('utf-8')
# extract CSRF token
parser = CSRFTokenParser()
parser.feed(form)
csrf_token = parser.csrf_token
# Send installation data to
# server via POST request
data['csrfmiddlewaretoken'] = csrf_token
data['emailaddress'] = ''
if PYVER[0] == 2: data_enc = urllib.urlencode(data)
else: data_enc = urlparse.urlencode(data).encode('utf-8')
req = urlrequest.Request(url,
headers=headers,
data=data_enc)
resp = opener.open(req)
if PYVER[0] == 2: msg = resp.read()
else: msg = resp.read().decode('utf-8')
log.debug(msg)
if 'Registered' in msg:
log.debug("Registration with %s successful", url)
else:
log.debug("Registration with %s failed", url)
finally:
if resp:
resp.close()
def funccache(func):
"""Memoisation decorator for a function. Alternative to
``functools.lru_cache``, which is not available in Python 2.x.
"""
cache = {}
def decorator(*args, **kwargs):
key = list()
key.extend(args)
key.extend([kwargs[k] for k in sorted(kwargs.keys())])
if len(key) > 0: key = tuple(key)
else: key = ('default',)
value = cache.get(key, None)
if value is None:
value = func(*args, **kwargs)
cache[key] = value
return value
def reset():
cache.clear()
decorator.reset = reset
return decorator
def identify_platform():
"""Figures out what platform we are running on. Returns a platform
identifier string - one of:
- "linux-64" (Linux, x86_64)
- "macos-64" (macOS, x86_64)
- "macos-M1" (macOS, M1)
Note that these identifiers are for FSL releases, and are not the
same as the platform identifiers used by conda.
"""
platforms = {
('linux', 'x86_64') : 'linux-64',
('darwin', 'x86_64') : 'macos-64',
('darwin', 'arm64') : 'macos-M1',
}
system = platform.system().lower()
cpu = platform.machine()
key = (system, cpu)
if key not in platforms:
supported = ', '.join(['[{}, {}]' for s, c in platforms])
raise Exception('This platform [{}, {}] is unrecognised or '
'unsupported! Supported platforms: {}'.format(
system, cpu, supported))
return platforms[key]
def getlocale():
"""Returns an ID describing the user locale. This is sent to the FSL
regstration server to give information about the host language.
"""
try:
# returns a tuple like ('en_US', 'UTF-8')
locale_tup = locale.getlocale()
if locale_tup[0] is None:
locale_str = locale.setlocale(locale.LC_ALL, '')
locale_str = locale_str.replace('C.UTF-8', 'en_US.UTF-8')
else:
locale_str = '.'.join(locale_tup)
except TypeError:
locale_str = 'en_US.UTF-8'
return locale_str
@funccache
def identify_cuda(device=None):
"""Tries to call nvidia-smi to interrogate the supported CUDA runtime
version for the specified device (default: 0).
If nvidia-smi cannot be called, returns None.
Otherwise returns the latest CUDA version supported by the driver, as a
tuple of (major, minor) ints.
"""
if device is None:
device = 0
# We can use the nvidia-smi --query-gpu option to
# selectively query device name, compute capability,
# driver version, etc, e.g.:
#
# nvidia-smi -i <device> \
# --query-gpu=name,compute_cap,driver_version \
# --format=noheader
#
# But this option doesn't allow us to query the
# supported CUDA version. So here we just scrape the
# human-readable output to get that information.
cudaver = None
try:
output = Process.check_output('nvidia-smi -i {}'.format(device))
output = output.split('\n')
pat = r'CUDA Version: (\S+)'
for line in output:
match = re.search(pat, line)
if match:
cudaver = match.group(1)
major, minor = cudaver.split('.')
cudaver = (int(major), int(minor))
break
except Exception as e:
log.debug('Unable to interrogate CUDA version: %s', e, exc_info=True)
return None
return cudaver
def check_need_admin(dirname):
"""Returns True if dirname needs administrator privileges to write to,
False otherwise.
"""
# os.supports_effective_ids added in
# python 3.3, so can't be used here
return not os.access(dirname, os.W_OK | os.X_OK)
def get_admin_password(action='install FSL'):
"""Prompt the user for their administrator password. An Exception is raised
if an incorrect password is entered three times.a
:arg action: String which describes what the password is needed for, i.e.:
"Your administrator password is needed to {action}"
:returns: the validated administrator password
"""
def validate_admin_password(password):
proc = Process.sudo_popen(['true'], password, stdin=sp.PIPE)
proc.communicate()
return proc.returncode == 0
msg = 'Your administrator password is needed to {}'.format(action)
for attempt in range(3):
if attempt == 0: msg = '{}:'.format(msg)
else: msg = '{} [attempt {} of 3]:'.format(msg, attempt + 1)
printmsg(msg, IMPORTANT, end='')
password = getpass.getpass('')
valid = validate_admin_password(password)
if valid:
printmsg('Password accepted', INFO)
break
else:
printmsg('Incorrect password', WARNING)
if not valid:
raise Exception('Incorrect password')
return password
def isstr(s):
"""Returns True if s is a string, False otherwise. Works on python 2.7
and >=3.3.
"""
try: return isinstance(s, basestring)
except Exception: return isinstance(s, str)
def match_any(s, patterns):
"""Test if the string s matches any of the fnmatch-style patterns.
Returns the matched pattern, or None.
"""
for pat in patterns:
if fnmatch.fnmatch(s, pat):
return pat
return None
@contextlib.contextmanager
def tempdir(override_dir=None, change_into=True, delete=True):
"""Returns a context manager which creates, changes into, and returns a
temporary directory, and then deletes it on exit (unless delete is False).
If override_dir is not None, instead of creating and changing into a
temporary directory, this function just changes into override_dir.
"""
if override_dir is None: tmpdir = tempfile.mkdtemp()
else: tmpdir = override_dir
prevdir = os.getcwd()
try:
if change_into:
os.chdir(tmpdir)
yield tmpdir
finally:
if change_into:
os.chdir(prevdir)
if delete and override_dir is None:
shutil.rmtree(tmpdir)
def warn_on_error(*msgargs, **msgkwargs):
"""Decorator which tries to run a function, and prints a message if it
fails. The arguments after the function are passed to the printmsg
function, e.g.:
@warn_on_error('Function failed!', WARNING)
def function(a, b):
...
function('a', 'b')
:arg toscreen: Defaults to True. Print the warning to the screen.
:arg tolog: Defaults to True. Print the warning to the log file.
"""
toscreen = msgkwargs.pop('toscreen', True)
tolog = msgkwargs.pop('tolog', True)
def decorator(function):
def wrapper(*args, **kwargs):
try:
function(*args, **kwargs)
except Exception as e:
if toscreen: printmsg(*msgargs, **msgkwargs)
if tolog: log.debug('%s', e, exc_info=True)
return wrapper
return decorator
def retry_on_error(func, num_attempts, *args, **kwargs):
"""Run func(*args, **kwargs), re-calling it up to num_attempts if it fails.
In addition to num_attempts, this function accepts two options, which must
be specified as keyword arguments. All other arguments will be passed
through to func when it is called.
:arg retry_error_message: Message to print when func fails, and before the
next retry.
:arg retry_condition: Function which is called when func fails. Passed
the Exception object that was raised. If this
function returns False, the function is not
retried, and the exception is re-raised..
"""
error_message = kwargs.pop('retry_error_message', '')
retry_condition = kwargs.pop('retry_condition', lambda e : True)
attempts = 0
while True:
try:
return func(*args, **kwargs)
except Exception as e:
attempts += 1
if (attempts >= num_attempts) or (not retry_condition(e)):
raise e
else:
printmsg('{} Trying again (attempt {} of {})'.format(
error_message, attempts + 1, num_attempts),
WARNING, EMPHASIS)
log.debug('retry_on_error - reason for failure: {}'.format(
str(e), WARNING))
class LogRecordingHandler(logging.Handler):
"""Custom logging handler which simply records log messages to an internal
queue. When used as a context manager, will install itself as a handler
on the fsl.installer.log logger object.
"""
def __init__(self, patterns, logobj=None):
"""Create a LogRecordingHandler.
:arg patterns: Sequence of strings - any log record which contains any
of these strings will be recorded.
:arg logobj: Log to register this handler with, when used as a
context manager. Defaults to the fsl.installer.log
object.
"""
if logobj is None:
logobj = log
logging.Handler.__init__(self, level=logging.DEBUG)
self.__records = []
self.__patterns = list(patterns)
self.__log = logobj
def __enter__(self):
self.__log.addHandler(self)
return self
def __exit__(self, *args):
self.__log.removeHandler(self)
def emit(self, record):
record = record.getMessage()
if any([pat in record for pat in self.__patterns]):
self.__records.append(record)
def records(self):
return list(self.__records)
def clear(self):
self.__records = []
@contextlib.contextmanager
def tempfilename(permissions=None, delete=True):
"""Returns a context manager which creates a temporary file, yields its
name, then deletes the file on exit.
"""
fname = None
try:
tmpf = tempfile.NamedTemporaryFile(delete=False)
fname = tmpf.name
tmpf.close()
if permissions:
os.chmod(fname, permissions)
yield fname
finally:
if delete and fname and op.exists(fname):
os.remove(fname)
def sha256(filename, check_against=None, blocksize=1048576):
"""Calculate the SHA256 checksum of the given file. If check_against
is provided, it is compared against the calculated checksum, and an
error is raised if they are not the same.
"""
hashobj = hashlib.sha256()
with open(filename, 'rb') as f:
while True:
block = f.read(blocksize)
if len(block) == 0:
break
hashobj.update(block)
checksum = hashobj.hexdigest()
if check_against is not None:
if checksum != check_against:
raise Exception('File {} does not match expected checksum '
'({})'.format(filename, check_against))
return checksum
def clean_environ():
"""Return a dict containing a set of sanitised environment variables.
All FSL and conda related variables are removed.
"""
blacklist = [
'*FSL*',
'*CONDA*',
'*MAMBA*',
'*PYTHON*',
'*PYVENV*'
]
env = os.environ.copy()
for v in list(env.keys()):
if match_any(v, blacklist) is not None:
env.pop(v)
return env
def install_environ(fsldir, username=None, password=None, cuda_version=None):
"""Returns a dict containing some environment variables that should
be added to the shell environment when the FSL conda environment is
being installed.
"""
env = {}
# post-link scripts call $FSLDIR/share/fsl/sbin/createFSLWrapper
# (part of fsl/base), which will only do its thing if the following
# env vars are set
env['FSL_CREATE_WRAPPER_SCRIPTS'] = '1'
env['FSLDIR'] = fsldir
# Make sure HTTP proxy variables, if set,
# are available to the conda env command
for v in ['http_proxy', 'https_proxy',
'HTTP_PROXY', 'HTTPS_PROXY']:
if v in os.environ:
env[v] = os.environ[v]
# Tell mamba not to abort if the download is taking time
# https://github.com/mamba-org/mamba/issues/1941
env['MAMBA_NO_LOW_SPEED_LIMIT'] = '1'
# FSL environments which source packages from the internal
# FSL conda channel will refer to the channel as:
#
# http://${FSLCONDA_USERNAME}:${FSLCONDA_PASSWORD}/abc.com/
#
# so we need to set those variables
if username: env['FSLCONDA_USERNAME'] = username
if password: env['FSLCONDA_PASSWORD'] = password
# Some versions of miniconda seem to have trouble on
# some versions of macOS, where macOS reports its
# version as being 10.16 (which for some reason is
# equivalent to macOS 11.0), which causes errors with
# "__osx >= 11.0" constraints.
#
# https://eclecticlight.co/2020/08/13/macos-version-numbering-isnt-so-simple/
# https://github.com/conda/conda/issues/13832
if platform.system().lower() == 'darwin':
env['SYSTEM_VERSION_COMPAT'] = '0'
# Trick conda into thinking that CUDA is
# available on this platform if it is, or if
# the user has specifically requested that
# CUDA packages be installed
#
# Otherwise clear the var in case we have a
# local GPU that the user wishes to ignore (if
# they passed --cuda=none)
#
# https://conda.io/projects/conda/en/\
# latest/user-guide/tasks/manage-virtual.html
if cuda_version is not None: env['CONDA_OVERRIDE_CUDA'] = cuda_version
else: env['CONDA_OVERRIDE_CUDA'] = ''
return env
def download_file(url,
destination,
progress=None,
blocksize=131072,
ssl_verify=True):
"""Download a file from url, saving it to destination. """
def default_progress(downloaded, total):
pass
if progress is None:
progress = default_progress
log.debug('Downloading %s ...', url)
# Path to local file
if op.exists(url):
url = 'file:' + urlrequest.pathname2url(op.abspath(url))
# We create and use an unconfigured SSL
# context to disable SSL verification.
# Otherwise pass None causes urlopen to
# use default behaviour.
kwargs = {}
if not ssl_verify:
# - The urlopen(context) argument is not available in py3.3
# - py3.4 does not have PROTOCOL_TLS
# - PROTOCOL_TLS deprecated in py3.10
if PYVER == (3, 3): pro = None
elif hasattr(ssl, 'PROTOCOL_TLS_CLIENT'): pro = ssl.PROTOCOL_TLS_CLIENT
elif hasattr(ssl, 'PROTOCOL_TLS'): pro = ssl.PROTOCOL_TLS
elif hasattr(ssl, 'PROTOCOL_TLSv1_2'): pro = ssl.PROTOCOL_TLSv1_2
elif hasattr(ssl, 'PROTOCOL_TLSv1_1'): pro = ssl.PROTOCOL_TLSv1_1
elif hasattr(ssl, 'PROTOCOL_TLSv1'): pro = ssl.PROTOCOL_TLSv1
else: pro = None
if pro is None:
printmsg('SSL verification cannot be skipped - if this is '
'a problem, try running the installer with a newer '
'version of Python.', INFO)
else:
printmsg('Skipping SSL verification - this '
'is not recommended!', WARNING)
sslctx = ssl.SSLContext(pro)
sslctx.check_hostname = False
sslctx.verify_mode = ssl.CERT_NONE
kwargs['context'] = sslctx
req = None
try:
# py2: urlopen result cannot be
# used as a context manager
req = urlrequest.urlopen(url, **kwargs)
with open(destination, 'wb') as outf:
try: total = int(req.headers['content-length'])
except KeyError: total = None
downloaded = 0
progress(downloaded, total)
while True:
block = req.read(blocksize)
if len(block) == 0:
break
downloaded += len(block)
outf.write(block)
progress(downloaded, total)
finally:
if req:
req.close()
def download_manifest(url, workdir=None, **kwargs):
"""Downloads the installer manifest file, which contains information
about available FSL versions, and the most recent version number of the
installer (this script).
Keyword arguments are passed through to the download_file function.
The manifest file is a JSON file. Lines beginning with a double-forward
slash are ignored.
This function modifies the manifest structure by adding a 'version'
attribute to all FSL build entries.
"""
log.debug('Downloading FSL installer manifest from %s', url)
with tempdir(workdir):
try:
download_file(url, 'manifest.json', **kwargs)
except Exception as e:
log.debug('Error downloading FSL release manifest from %s',
url, exc_info=True)
raise Exception('Unable to download FSL release manifest '
'from {} [{}]!'.format(url, str(e)))
with open('manifest.json') as f:
lines = f.readlines()
# Drop comments
lines = [l for l in lines if not l.lstrip().startswith('//')]
manifest = json.loads('\n'.join(lines))
# Add "version" to every build
for version, builds in manifest['versions'].items():
if version == 'latest':
continue
for build in builds:
build['version'] = version
return manifest
def download_dev_releases(url, workdir=None, **kwargs):
"""Downloads the FSL_DEV_RELEASES file. This file contains a list of
available development manifest URLS. Returns a list of tuples, one
for each development release, with each tuple containing:
- URL to the manifest file
- Version identifier
- Commit hash (on the fsl/conda/manifest repository)
- Branch name (on the fsl/conda/manifest repository)
The list is sorted by date, newest first.
Keyword arguments are passed through to the download_file function.
"""
# parse a dev manifest file name, returning
# a sequence containing the tage, date, commit
# hash, and branch name. Dev manifest files
# are named like so:
#
# manifest-<tag>.<date>.<commit>.<branch>.json
#
# where <tag> is the tag of the most recent
# public FSL release, and everything else is
# self-explanatory.
def parse_devrelease_name(url):
name = urlparse.urlparse(url).path
name = op.basename(name)
# strip "manifest-" and ".json"
name = name[9:-5]
# The devrelease list may contain public
# releases too - sniff the commit, and if
# it doesn't look like a commit hash,
# assume that this file corresponds to a
# public release.
commit = name.rsplit('.', 2)[-2]
# public release or dev release
if len(commit) < 7: bits = [name, None, None]
else: bits = name.rsplit('.', 2)
return bits
# list of (url, version, commit, branch)
devreleases = []
with tempdir(workdir):
try:
download_file(url, 'devreleases.txt', **kwargs)
except Exception as e:
log.debug('Error downloading devreleases.txt from %s',
url, exc_info=True)
raise Exception('Unable to download development manifest '
'list from {}!'.format(url))
with open('devreleases.txt', 'rt') as f:
urls = f.read().strip().split('\n')
urls = [l.strip() for l in urls]
for url in urls:
devreleases.append([url] + parse_devrelease_name(url))
# sort by version, newest first
return sorted(devreleases, key=lambda r: Version(r[1]), reverse=True)
class Progress(object):
"""Simple progress reporter. Displays one of the following:
- If both a value and total are provided, a progress bar is shown
- If only a value is provided, a cumulative count is shown
- If nothing is provided, a spinner is shown.
Use as a context manager, and call the update method to report progress,
e,g:
with Progress('%') as p:
for i in range(100):
p.update(i + 1, 100)
"""
def __init__(self,
label='',
transform=None,
fmt='{:.1f}',
total=None,
width=None,
proglabel='progress',
progfile=None,
prefix=None):
"""Create a Progress reporter.
:arg label: Units (e.g. "MB", "%",)
:arg transform: Function to transform values (see e.g.
Progress.bytes_to_mb)
:arg fmt: Template string used to format value / total.
:arg total: Maximum value - overrides the total value passed to
the update method.
:arg width: Maximum width, if a progress bar is displayed. Default
is to automatically infer the terminal width (see
get_terminal_width). Not applied to count/spin
displays.
:arg proglabel: Label to use when writing progress updates to progfile.
:arg progfile: File to write progress updates to. Each update is
written on a new line, and has the form:
<proglabel> <value>[ <total>]
:arg prefix: Text to display before the progress bar
"""
if transform is None:
transform = Progress.default_transform
if prefix is None: prefix = ''
else: prefix = '{} '.format(prefix)
self.width = width
self.fmt = fmt.format
self.total = total
self.label = label
self.transform = transform
self.proglabel = proglabel
self.progfile = progfile
self.prefix = prefix
# used by the spin function
self.__last_spin = None
@staticmethod
def default_transform(val, total):
return val, total
@staticmethod
def bytes_to_mb(val, total):
if val is not None: val = val / 1048576
if total is not None: total = total / 1048576
return val, total
@staticmethod
def percent(val, total):
if val is None or total is None:
return val, total
return 100 * (val / total), 100
def __enter__(self):
return self
def __exit__(self, *args, **kwargs):
printmsg('', log=False, fill=False)
def write_progress(self, value, total):
if self.progfile is None:
return
if value is None: value = ''
if total is None: total = ''
with open(self.progfile, 'at') as f:
f.write('{} {} {}\n'.format(self.proglabel, value, total))
def update(self, value=None, total=None):
if total is None:
total = self.total
value, total = self.transform(value, total)
if value is None and total is None:
self.spin()
elif value is not None and total is None:
self.count(value)
elif value is not None and total is not None:
self.progress(value, total)
self.write_progress(value, total)
def spin(self, show_prefix=True):
symbols = ['|', '/', '-', '\\']
if self.__last_spin is not None: last = self.__last_spin
else: last = symbols[-1]
idx = symbols.index(last)
idx = (idx + 1) % len(symbols)
this = symbols[idx]
if show_prefix: msg = '{}{}'.format(self.prefix, this)
else: msg = this
printmsg(msg, end='\r', log=False, fill=False)
self.__last_spin = this
def count(self, value):
value = self.fmt(value)
if self.label is None: line = '{} ...'.format(value)
else: line = '{}{} ...'.format(value, self.label)
msg = '{}{}'.format(self.prefix, line)
printmsg(msg, end='\r', log=False, fill=False)
def progress(self, value, total):
value = min(value, total)
# arbitrary fallback of 50 columns if
# terminal width cannot be determined
if self.width is None: width = get_terminal_width(50)
else: width = self.width
fvalue = self.fmt(value)
ftotal = self.fmt(total)
prefix = self.prefix
suffix = '{} / {} {}'.format(fvalue, ftotal, self.label).rstrip()
# +6: - square brackets around bar
# - space between bar and tally
# - space+spin+space at the end
width = width - (len(prefix) + len(suffix) + 6)
completed = int(round(width * (value / total)))
remaining = width - completed
progress = '{}[{}{}] {}'.format(prefix,
'#' * completed,
' ' * remaining,
suffix)
printmsg(progress, end='', fill=False)
printmsg(' ', end='', log=False, fill=False)
self.spin(False)
printmsg(end='\r', log=False, fill=False)
class Process(object):
"""Container for a subprocess.Popen object, allowing non-blocking
line-based access to its standard output and error streams via separate
queues, while logging all outputs.
Don't create a Process directly - use one of the following static methods:
- Process.check_output
- Process.check_call
- Process.monitor_progress
"""
def __init__(self,
cmd,
admin=False,
password=None,
log_output=True,
print_output=False,
append_env=None,
**kwargs):
"""Run the specified command. Starts threads to capture stdout and
stderr.
:arg cmd: Command to run - passed through shlex.split, then
passed to subprocess.Popen
:arg admin: Run the command with administrative privileges
:arg password: Administrator password - can be None if admin is
False.
:arg log_output: If True, the command and all of its stdout/stderr
are logged.
:arg print_output: If True, the command and all of its stdout/stderr
are logged.
:arg append_env: Dictionary of additional environment to be set when
the command is run.
:arg kwargs: Passed to subprocess.Popen
"""
self.cmd = cmd
self.stdoutq = queue.Queue()
self.stderrq = queue.Queue()
if log_output:
log.debug('Running %s [as admin: %s]', cmd, admin)
self.popen = Process.popen(cmd, admin, password,
append_env=append_env, **kwargs)
# threads for consuming stdout/stderr
self.stdout_thread = threading.Thread(
target=Process.forward_stream,
args=(self.popen.stdout, self.stdoutq, cmd,
'stdout', log_output, print_output))
self.stderr_thread = threading.Thread(
target=Process.forward_stream,
args=(self.popen.stderr, self.stderrq, cmd,
'stderr', log_output, print_output))
self.stdout_thread.daemon = True
self.stderr_thread.daemon = True
self.stdout_thread.start()
self.stderr_thread.start()
def wait(self):
"""Waits for the process to terminate, then waits for the stdout
and stderr consumer threads to finish.
"""
self.popen.wait()
self.stdout_thread.join()
self.stderr_thread.join()
@property
def returncode(self):
"""Process return code. Returns None until the process has terminated,
and the stdout/stderr consumer threads have finished.
"""
if self.popen.returncode is None: return None
if self.stdout_thread.is_alive(): return None
if self.stderr_thread.is_alive(): return None
return self.popen.returncode
@staticmethod
def check_output(cmd, *args, **kwargs):
"""Behaves like subprocess.check_output. Runs the given command, then
waits until it finishes, and return its standard output. An error
is raised if the process returns a non-zero exit code, unless a keyword
argument `check=False` is specified.
:arg cmd: The command to run, as a string
"""
check = kwargs.pop('check', True)
proc = Process(cmd, *args, **kwargs)
proc.wait()
if check and (proc.returncode != 0):
raise RuntimeError('This command returned an error: ' + cmd)
stdout = ''
while True:
try:
stdout += proc.stdoutq.get_nowait()
except queue.Empty:
break
return stdout
@staticmethod
def check_call(cmd, *args, **kwargs):
"""Behaves like subprocess.check_call. Runs the given command, then
waits until it finishes. An error is raised if the process returns a
non-zero exit code, unless a keyword argument `check=False` is
specified.
:arg cmd: The command to run, as a string
"""
check = kwargs.pop('check', True)
proc = Process(cmd, *args, **kwargs)
proc.wait()
if check and proc.returncode != 0:
raise RuntimeError('This command returned an error: ' + cmd)
return proc.returncode
@staticmethod
def monitor_progress(cmd, total=None, *args, **kwargs):
"""Runs the given command(s), and shows a progress bar under the
assumption that cmd will produce "total" number of lines of output.
:arg cmd: The commmand to run as a string, or a sequence of
multiple commands.
:arg total: Total number of lines of standard output to expect.
:arg timeout: Refresh rate in seconds. Must be passed as a keyword
argument.
:arg progfunc: Function which returns a number indicating how far
the process has progressed. If provided, this
function is called, instead of standard output
lines being monitored. The function is passed a
reference to the Process object. Must be passed as a
keyword argument.
:arg progfile: File to write progress updates to.
:arg proglabel: Label to use when writing progress updates to progfile.
:arg prefix: Label to show before progress bar
"""
timeout = kwargs.pop('timeout', 0.5)
progfunc = kwargs.pop('progfunc', None)
proglabel = kwargs.pop('proglabel', None)
progfile = kwargs.pop('progfile', None)
prefix = kwargs.pop('prefix', None)
if total is None: label = None
else: label = '%'
if progfunc is None:
nlines = [0]
def progfunc(proc):
try:
_ = proc.stdoutq.get_nowait()
nlines[0] = nlines[0] + 1
except queue.Empty:
pass
return nlines[0]
if isstr(cmd): cmds = [cmd]
else: cmds = cmd
with Progress(label=label,
fmt='{:.0f}',
transform=Progress.percent,
proglabel=proglabel,
progfile=progfile,
prefix=prefix) as prog:
progcount = 0 if total else None
for cmd in cmds:
proc = Process(cmd, *args, **kwargs)
prog.update(progcount, total)
while proc.returncode is None:
time.sleep(timeout)
progcount = progfunc(proc) if total else None
prog.update(progcount, total)
proc.popen.poll()
# force progress bar to 100% when finished
if proc.returncode == 0:
prog.update(total, total)
else:
raise RuntimeError('This command returned '
'an error: ' + cmd)
@staticmethod
def forward_stream(stream,
queue,
cmd,
streamname,
log_output,
print_output):
"""Reads lines from stream and pushes them onto queue until popen
is finished. Logs every line.
:arg stream: stream to forward
:arg queue: queue.Queue to push lines onto
:arg cmd: string - the command that is running
:arg streamname: string - 'stdout' or 'stderr'
:arg log_output: If True, log all stdout/stderr.
:arg print_output: If True, print all stdout/stderr.
"""
while True:
line = stream.readline().decode('utf-8')
if line == '':
break
queue.put(line)
if log_output:
log.debug(' [%s]: %s', streamname, line.rstrip())
if print_output:
print(' [{}]: {}'.format(streamname, line.rstrip()))
@staticmethod
def popen(cmd, admin=False, password=None, append_env=None, **kwargs):
"""Runs the given command via subprocess.Popen, as administrator if
requested.
:arg cmd: The command to run, as a string
:arg admin: Whether to run with administrative privileges
:arg pssword: Administrator password. Only required if admin is
True.
:arg append_env: Dictionary of additional environment to be set when
the command is run.
:arg kwargs: Passed to subprocess.Popen. stdin, stdout, and stderr
will be silently clobbered
:returns: The subprocess.Popen object.
"""
admin = admin and os.getuid() != 0
cmd = shlex.split(cmd)
kwargs['stdin'] = sp.PIPE
kwargs['stdout'] = sp.PIPE
kwargs['stderr'] = sp.PIPE
if admin:
proc = Process.sudo_popen(cmd, password, append_env, **kwargs)
else:
# if append_env has been specified,
# add it to the normal env option.
if append_env is not None:
env = kwargs.get('env', os.environ.copy())
env.update(append_env)
kwargs['env'] = env
proc = sp.Popen(cmd, **kwargs)
return proc
@staticmethod
def sudo_popen(cmd, password, append_env=None, **kwargs):
"""Runs "sudo cmd" using subprocess.Popen. Used by Process.popen.
Assumes that kwargs contains stdin=sp.PIPE
"""
# sudo will not necessarily propagate environment
# variables, and there is no guarantee that the
# sudo -E option will work. So here we create a
# wrapper shell script with "export VAR=VALUE"
# statements for all environment variables that
# are set.
if append_env is None:
append_env = {}
# Make the wrapper script delete itself
# after the command has been executed.
with tempfilename(0o755, delete=False) as wrapper:
with open(wrapper, 'wt') as f:
f.write('#!/usr/bin/env sh\n')
f.write('set -e\n')
f.write('thisfile=$0\n')
f.write('thisdir=$(cd $(dirname $0) && pwd)\n')
for k, v in append_env.items():
f.write('export {}="{}"\n'.format(k, v))
# shlex.join not available in py27
f.write(' '.join(cmd) + '\n')
f.write('cd ${thisdir} && rm ${thisfile}\n')
cmd = ['sudo', '-S', '-k', wrapper]
proc = sp.Popen(cmd, **kwargs)
proc.stdin.write('{}\n'.format(password).encode())
proc.stdin.flush()
return proc
@ft.total_ordering
class Version(object):
"""Class to represent and compare version strings. Accepted version
strings are of the form W.X.Y.Z, where W, X, Y, and Z are all integers.
"""
def __init__(self, verstr):
# Version identifiers for official FSL
# releases will have up to four
# components (X.Y.Z.W), but we accept
# any number of (integer) components,
# as internal releases may have more.
components = []
# ignore a leading "v", e.g. v1.2.3
verstr = verstr.lower()
if verstr.startswith('v'):
verstr = verstr[1:]
for comp in verstr.split('.'):
try: components.append(int(comp))
except Exception: break
self.components = components
self.verstr = verstr
def __str__(self):
return self.verstr
def __eq__(self, other):
for sn, on in zip(self.components, other.components):
if sn != on:
return False
return len(self.components) == len(other.components)
def __lt__(self, other):
for p1, p2 in zip(self.components, other.components):
if p1 < p2: return True
if p1 > p2: return False
return len(self.components) < len(other.components)
class Context(object):
"""Bag of information and settings created in the main function, and passed
around this script.
Several settings are lazily evaluated on first access, but once evaluated,
their values are immutable.
"""
def __init__(self, args, destdir=None, action='install FSL'):
"""Create the context with the argparse.Namespace object containing
parsed command-line arguments.
:arg args: argparse.Namespace containing command-line arguments
:arg destdir: Installation directory. If not provided, read from
args.dest, or read from the user,
:arg action: Passed to get_admin_password as a prompt.
"""
if destdir is not None:
destdir = op.abspath(destdir)
self.args = args
self.shell = op.basename(os.environ.get('SHELL', 'sh')).lower()
# These attributes are updated on-demand via
# the property accessors defined below, or are
# all updated via the finalise_settings method.
self.__platform = None
self.__manifest = None
self.__devmanifest = None
self.__candidate_builds = None
self.__build = None
self.__destdir = destdir
self.__need_admin = None
self.__admin_password = None
self.__action = action
# If the destination directory already exists,
# and the user chooses to overwrite it, it is
# moved so that, if the installation fails, it
# can be restored. The new path is stored
# here - refer to overwrite_destdir.
self.old_destdir = None
# The download_fsl_environment_files function
# stores the path to the FSL conda environment
# files, list of conda channels, python
# version to be installed, and cuda version if
# applicable. The cuda version is used during
# installation to ensure that the correct CUDA
# packages are installed.
self.environment_file = None
self.extra_environment_files = None
self.environment_channels = None
self.python_version = None
self.cuda_version = None
# The config_logging function stores the path
# to the fslinstaller log file here.
self.logfile = None
def finalise_settings(self):
"""Finalise values for all information and settings in the Context.
"""
self.manifest
self.candidate_builds
self.platform
self.build
self.destdir
self.need_admin
self.admin_password
self.extras_dir
@property
def license_url(self):
"""Return the FSL license URL from the manifest, or None if it is not
present.
"""
return self.manifest['installer'].get('license_url')
@property
def registration_url(self):
"""Return the FSL registration URL from the manifest, or None if it is
not present.
"""
return self.manifest['installer'].get('registration_url')
@property
def platform(self):
"""The platform we are running on, e.g. "linux-64", "macos-64",
"macos-M1". This identifier is used to determine which FSL build to
install.
Note that this function may report a different platform identifier than
the actual platform - specifically, if running on a M1 mac, and there
is no M1 FSL build for the requested FSL version, this function will
report "macos-64". This is because some older FSL releases do not have
M1 builds available.
"""
if self.__platform is None:
plat = identify_platform()
# if M1, check that we have a suitable
# FSL build, falling back to x86 if not.
if plat == 'macos-M1':
candidates = self.candidate_builds
if not any(c['platform'] == 'macos-M1' for c in candidates):
plat = 'macos-64'
self.__platform = plat
return self.__platform
@property
def miniconda_metadata(self):
"""Returns a dict with information about the miniconda installer
to use as the base of the FSL installation. This must not be called
until after the download_fsl_environment_files function has been
called.
The returned dict has `'url'`, `'sha256'` and `'output'` keys.
"""
# Get information about the miniconda installer
# from the manifest.
metadata = self.manifest['miniconda'][self.platform]
pyver = 'python{}'.format(self.python_version)
# From FSL 6.0.7.12 and newer, the manifest
# contains a separate miniconda installer URL
# for each Python version that is used in the
# different FSL versions. Prior to this, the
# manifest just contained a single miniconda URL
# for each platform. This code supports both the
# old and new manifest formats.
if pyver in metadata:
metadata = metadata[pyver]
# if pyver is not in metadata, we either have an
# old manifest format which contains info for a
# single miniconda installer, or the manifest
# does not contain a miniconda installer entry
# for the python version to be installed.
elif 'url' not in metadata:
raise Exception('Manifest does not contain metadata for a Python '
'{} miniconda installer!'.format(pyver))
return metadata
@property
def candidate_builds(self):
"""Query the manifest and return a list of available builds for the
requested FSL release, for all platforms.
"""
if self.__candidate_builds is not None:
return self.__candidate_builds
# defaults to "latest" if
# not specified by the user
fslversion = self.args.fslversion
if fslversion is None:
fslversion = 'latest'
if fslversion not in self.manifest['versions']:
available = ', '.join(self.manifest['versions'].keys())
raise Exception(
'FSL version "{}" is not available - available '
'versions: {}'.format(fslversion, available))
if fslversion == 'latest':
fslversion = self.manifest['versions']['latest']
self.__candidate_builds = list(self.manifest['versions'][fslversion])
return self.__candidate_builds
@property
def build(self):
"""Returns a suitable FSL build (a dictionary entry from the FSL
installer manifest) for the target platform.
The returned dictionary has the following elements:
- 'version' FSL version.
- 'platform': Platform identifier (e.g. 'linux-64')
- 'environment': Environment file to download
- 'sha256': Checksum of environment file
- 'cuda_enabled': Boolean flag indicating whether any packages in
this build is CUDA-capable.
- 'output': Number of lines of expected output, for reporting
progress
"""
if self.__build is not None:
return self.__build
# Find refs to a suitable build for this
# platform. We assume that there is only
# one default build for each platform.
# in the list of builds for a given FSL
# version.
candidates = self.candidate_builds
build = None
for candidate in candidates:
if candidate['platform'] == self.platform:
build = candidate
break
else:
raise Exception(
'Cannot find a version of FSL matching '
'platform {}'.format(self.platform))
printmsg('FSL {} selected for installation'.format(build['version']))
# Make sure the cuda_enabled flag is present
# for all environments specified in the build
# entry
build['cuda_enabled'] = str2bool(build.get('cuda_enabled', False))
for extra in build.get('extras', {}).values():
extra['cuda_enabled'] = str2bool(extra.get('cuda_enabled', False))
self.__build = build
return build
@property
def destdir(self):
"""Installation directory. If not specified at the command line, the
user is prompted to enter a directory.
"""
if self.__destdir is not None:
return self.__destdir
fsldir = os.environ.get('FSLDIR', None)
if fsldir is not None: defdestdir = fsldir
elif os.getuid() != 0: defdestdir = DEFAULT_INSTALLATION_DIRECTORY
else: defdestdir = DEFAULT_ROOT_INSTALLATION_DIRECTORY
# The loop below validates the destination directory
# both when specified at commmand line or
# interactively. In either case, if invalid, the
# user is re-prompted to enter a new destination.
destdir = None
if self.args.dest is not None: response = self.args.dest
else: response = None
while destdir is None:
if response is None:
printmsg('\nWhere do you want to install FSL?',
IMPORTANT, EMPHASIS)
printmsg('Press enter to install to the default location '
'[{}]\n'.format(defdestdir), INFO)
response = prompt('FSL installation directory [{}]:'.format(
defdestdir), QUESTION, EMPHASIS)
response = response.rstrip(op.sep)
if response == '':
response = defdestdir
response = op.expanduser(op.expandvars(response))
response = op.abspath(response)
parentdir = op.dirname(response)
if op.exists(parentdir):
destdir = response
else:
printmsg('Destination directory {} does not '
'exist!'.format(parentdir), ERROR)
response = None
self.__destdir = destdir
return self.__destdir
@property
def conda(self):
"""Return a path to the ``conda`` or ``mamba`` executable. """
bindir = op.join(self.basedir, 'bin')
condabin = op.join(bindir, 'conda')
mambabin = op.join(bindir, 'mamba')
# If mamba is present, prefer it over conda, unless
# the user requestd otherwise via the --conda flag
if not self.args.conda: candidates = [mambabin, condabin]
else: candidates = [condabin, mambabin]
for c in candidates:
if op.exists(c):
return c
raise RuntimeError('Cannot find conda/mamba '
'executable in {}'.format(bindir))
@property
def basedir(self):
"""Return the path to the base conda installation. For normal
installations this is equivalent to destdir / $FSLDIR, but may be
different if the fslinstaller was instructed to use an existing
[mini]conda installation.
"""
# Either the user gave a path to an existing
# miniconda installation, or $FSLDIR is the
# base miniconda installation
if (self.args.miniconda is not None) and op.isdir(self.args.miniconda):
return self.args.miniconda
else:
return self.destdir
@property
def extras_dir(self):
"""Return the path to a directory into which child environments for
additional FSL modules should be installed into. For a normal FSL
installation, this is set to $FSLDIR/envs/.
"""
if self.basedir == self.destdir:
return op.join(self.destdir, 'envs')
if self.args.extras_dir is None:
raise RuntimeError('--extras_dir must be specified when '
'installing FSL as a child environment!')
return self.args.extras_dir
@property
def use_existing_base(self):
"""Return True if we have been instructed to use an existing
[mini]conda installation, as opposed to downloading/installing one.
"""
return ((self.args.miniconda is not None) and
op.isdir(self.args.miniconda))
@property
def need_admin(self):
"""Returns True if administrator privileges will be needed to install
FSL.
"""
if self.__need_admin is not None:
return self.__need_admin
parentdir = op.dirname(self.destdir)
self.__need_admin = check_need_admin(parentdir)
return self.__need_admin
@property
def admin_password(self):
"""Returns the user's administrator password, prompting them if needed.
"""
# need_admin may be None or False,
# so don't rely on truthiness.
if not self.need_admin:
return None
if self.__admin_password is None:
self.__admin_password = get_admin_password(self.__action)
return self.__admin_password
@property
def manifest(self):
"""Returns the FSL installer manifest as a dictionary. """
if self.__manifest is None:
if self.devmanifest is not None:
self.args.manifest = self.devmanifest
self.__manifest = download_manifest(
self.args.manifest,
self.args.workdir,
ssl_verify=(not self.args.skip_ssl_verify))
return self.__manifest
@property
def devmanifest(self):
"""Returns a URL to a development manifest to use for installation.
This will only return a value if the --devrelease or --devlatest
options are active.
If this is the case, the FSL_DEV_RELEASES file is downloaded - this
file contains a list of available development manifest URLS. The
user is then prompted to choose which development manifest to use
for the installation, unless --devlatest is active, in which case
the newest manifest is selected.
"""
if not self.args.devrelease:
return None
if self.__devmanifest == 'na':
return None
elif self.__devmanifest is not None:
return self.__devmanifest
devreleases = download_dev_releases(
FSL_DEV_RELEASES,
self.args.workdir,
ssl_verify=(not self.args.skip_ssl_verify))
if len(devreleases) == 0:
self.__devmanifest = 'na'
return None
self.__devmanifest = prompt_dev_release(devreleases,
self.args.devlatest)
return self.__devmanifest
def run(self, process_func, *args, **kwargs):
"""Run a command via a static Process method. Handles sudo/
administrator authentication, and ensures that the shell
environment in which the command is executed is sanitised.
Can be used with Process.check_call, Process.check_output, and
Process.monitor_progress. For example:
ctx = Context(...)
ctx.run(Process.check_call, 'my_command')
ctx.run(Process.monitor_progress, 'my_command', total=100)
"""
env = kwargs.pop('env', {})
append_env = kwargs.pop('append_env', {})
process_func = ft.partial(process_func, *args, **kwargs)
# Clear any environment variables that refer to
# existing FSL or conda installations, and ensure
# that some specific FSL environment variables
# are set while the command is running. See
# clean_environ and install_environ for more
# details, and see Process.sudo_popen regarding
# append_env.
env.update(clean_environ())
append_env.update(install_environ(self.destdir,
self.args.username,
self.args.password,
self.cuda_version))
return process_func(admin=self.need_admin,
password=self.admin_password,
env=env,
append_env=append_env)
def agree_to_license(ctx):
"""Prompts the user to agree to the terms of the FSL license."""
msg = ['Installing FSL implies agreement with the terms of the FSL '
'license - if you do not agree with these terms, you can '
'cancel the installation by pressing CTRL+C.', IMPORTANT]
if ctx.license_url is not None:
msg = msg + [' You can view the license at ', IMPORTANT,
ctx.license_url, IMPORTANT, UNDERLINE]
printmsg(*msg)
printmsg('')
def check_rosetta_status(ctx):
"""Called from the main routine, before installation is attempted. If
running on a M1 macos machine, and a x86 version of FSL has been selected
for installation, checks whether rosetta emulation is enabled. If so,
does nothing further. Otherwise, prints a message and exits.
"""
if not all((identify_platform() == 'macos-M1',
ctx.platform == 'macos-64')):
return
# Using the strategy discussed at
# https://forum.latenightsw.com/t/possible-for-a-script-\
# to-test-whether-rosetta-2-is-installed/3207/6
#
# The pkgutil command should return 0 if
# rosetta is installed, non-0 otherwise.
try:
Process.check_output('pkgutil --files com.apple.pkg.RosettaUpdateAuto')
except RuntimeError:
printmsg('Rosetta emulation does not appear to be enabled!\n', ERROR)
printmsg('Enable rosetta emulation, and then run this installer '
'again. You can enable rosetta emulation by running this '
'command:\n', INFO)
printmsg(' /usr/sbin/softwareupdate --install-rosetta '
'--agree-to-license\n', IMPORTANT)
printmsg('Aborting installation', ERROR)
sys.exit(1)
# pkgutil command not found - should
# never happen, but print a warning
# just in case
except Exception as e:
printmsg('An error occurred calling the pkgutil command - this '
'may not be a problem, so I\'ll attempt to proceed '
'with the installation. ({}'.format(e), WARNING)
def list_available_versions(manifest):
"""Lists available FSL versions. """
printmsg('Available FSL versions:', EMPHASIS)
versions = list(manifest['versions'].keys())
versions = reversed(sorted([Version(v) for v in versions]))
for version in versions:
if str(version) == 'latest':
continue
printmsg(str(version), IMPORTANT, EMPHASIS)
for build in manifest['versions'][str(version)]:
printmsg(' {}'.format(build['platform']), EMPHASIS, end=' ')
printmsg(build['environment'], INFO)
if len(build.get('extras', [])) > 0:
extras = ', '.join(build['extras'])
printmsg(' Extras: {}'.format(extras), INFO)
def prompt_dev_release(devreleases, latest):
"""Prompts the user to select a development release.
:arg devreleases: List of development releases, as returned by
download_dev_releases.
:arg latest: If True, the latest develeopment release is returned.
"""
if len(devreleases) == 0:
return None
# automatically choose latest dev manifest?
if latest:
return devreleases[0][0]
# show the user a list, ask them which one they want
printmsg('Available development releases:', EMPHASIS)
for i, (url, tag, commit, branch) in enumerate(devreleases):
# dev release
if commit is not None:
printmsg(' [{}]: {} [{} commit {}]'.format(
i + 1, tag, branch, commit), IMPORTANT)
# public release
else:
printmsg(' [{}]: {}'.format(i + 1, tag), IMPORTANT)
while True:
selection = prompt('Which release would you like to '
'install? [1]:', PROMPT)
if selection == '':
selection = '1'
try:
selection = int(selection) - 1
except Exception:
continue
if selection >= 0 and selection < len(devreleases):
break
return devreleases[selection][0]
def add_cuda_packages(ctx):
"""Used by download_fsl_environment_files. If the target system has a GPU,
or the user has explicitly requested a CUDA version, returns a set of
package constraints to be added to the conda environment specifications.
The way that CUDA libraries are packaged on conda-forge has changed
a few times. The current state of affairs is described in a github issue:
https://github.com/conda-forge/conda-forge.github.io/issues/1963
This function just adds "cuda-version" to the list of packages to be
installed, which should cause conda to install packages compatible with
that version.
Returns a tuple containing:
- a dict of packages, of the form "{package : version};", to be
installed. Prints warnings if it appears that the requested CUDA version
might not be compatible with the system, or might not be available on
conda-forge.
- A string containing the X.Y CUDA version, or None if CUDA libraries are
not to be installed.
"""
# User has requested no CUDA
if ctx.args.cuda == 'none':
return {}, None
# If user has requested a specific CUDA/
# compute capability, ignore the version
# supported by the local GPU (if present)
if ctx.args.cuda is not None:
cuda = ctx.args.cuda
# Otherwise interrogate the local GPU to
# select a suitable CUDA version. The
# returned value will be None if there
# is no GPU available on this system.
else:
cuda = identify_cuda()
# There is no GPU on this system, and the
# user has not requested a particular CUDA
# version, so we don't add any CUDA pins
if cuda is None:
return {}, None
# We have a GPU, and/or the user
# has requested CUDA packages.
printmsg('\nBy downloading and using the CUDA Toolkit conda packages, you '
'accept the terms and conditions of the CUDA End User License '
'Agreement (EULA): https://docs.nvidia.com/cuda/eula/index.html'
'\n', IMPORTANT)
# CUDA >= 11 should have binary compatibility
# within major release, so we set the version
# constraint accordingly. Conda-forge has
# limited support for CUDA versions older
# than 11.2, so we are not doing anything
# special to handle older versions.
major, minor = cuda
packages = {
'cuda-version' : '>={}.{},<{}'.format(major, minor, major + 1)
}
return packages, '{}.{}'.format(*cuda)
def read_environment_file(filename):
"""Very primitive routine which loads a conda environment.yml file.
Returns:
- An environment name
- A list of conda channels
- A dict of { package : version } packages (where version may be None)
"""
name = None
channels = []
packages = collections.OrderedDict()
# load the channel and package lists
# from the environment file.
with open(filename, 'rt') as f:
in_channels_section = False
in_deps_section = False
for line in f:
line = line.strip()
# environment name
if line.startswith('name:'):
name = line.split(':')[1].strip()
continue
line = line.strip()
if line == '': continue
if line.startswith('#'): continue
# start of channels list
if line == 'channels:':
in_channels_section = True
continue
if in_channels_section:
# end of channels list
if not line.startswith('-'):
in_channels_section = False
else:
channels.append(line[1:].strip())
continue
# start of deps list
if line == 'dependencies:':
in_deps_section = True
continue
if in_deps_section:
# end of deps list
if not line.startswith('-'):
in_deps_section = False
else:
# Split line into (package, version+build).
# Setting maxsplit=1 ensures the result will
# be either length 1 or 2 (unless the line
# was just a single "-", in which case it is
# an invalid file).
#
# Note that we assume here that packages are
# specified as "package version", rather than
# "package=version".
pkg = line.strip('- ').split(' ', 1)
if len(pkg) == 1: pkg, ver = pkg[0], None
else: pkg, ver = pkg
packages[pkg] = ver
continue
return name, channels, packages
def write_environment_file(filename, name, channels, packages):
"""Writes a conda environment.yml file with the given channels and
and packages.
"""
with open(filename, 'wt') as f:
if name is not None:
f.write('name: {}\n'.format(name))
if len(channels) > 0:
f.write('channels:\n')
for channel in channels:
f.write(' - {}\n'.format(channel))
f.write('dependencies:\n')
for package, version in packages.items():
if version is None: version = ''
else: version = ' {}'.format(version)
f.write(' - {}{}\n'.format(package, version))
def download_fsl_environment_files(ctx):
"""Downloads the environment specification files for the selected FSL
version.
A copy of each environment file is made. Any packages specified by
--exclude_package will be removed from the environment specifications.
Internal/development FSL versions may source packages from the internal
FSL conda channel, which requires a username+password to authenticate.
These are referred to in the environment file as ${FSLCONDA_USERNAME} and
${FSLCONDA_PASSWORD}. If the user has not provided a username+password on
the command-line, they are prompted for them.
The downloaded files may be modified, e.g. if the user has used
--exclude_package, and/or if CUDA software is to be installed.
"""
# If installing CUDA libraries, we add
# appropriate versions of CUDA packges to
# the package list for each conda
# environment to be installed.
cuda_pkgs, cuda_ver = add_cuda_packages(ctx)
ctx.cuda_version = cuda_ver
# A FSL release may comprise multiple
# separate environment files - a "main"
# environment, and a set of additional/
# extra environments - these extra envs
# are installed as child environemnts.
# We gather all fo the environment file
# URLs and loop through and download+
# process them one-by-one.
#
# We identify the main env with an empty
# string - extra/child environments are
# all named in the manifest.
allenvs = [('', ctx.build)]
allenvs += list(ctx.build.get('extras', {}).items())
ctx.extra_environment_files = {}
for envname, build in allenvs:
url = build['environment']
checksum = build.get('sha256', None)
printmsg('Downloading FSL environment specification '
'from {}...'.format(url))
fname = url.split('/')[-1]
download_file(url, fname, ssl_verify=(not ctx.args.skip_ssl_verify))
if (checksum is not None) and (not ctx.args.no_checksum):
sha256(fname, checksum)
# Environment files for internal/dev FSL versions
# will list the internal FSL conda channel with
# ${FSLCONDA_USERNAME} and ${FSLCONDA_PASSWORD}
# as placeholders for the username/password.
with open(fname, 'rt') as f:
need_auth = '${FSLCONDA_USERNAME}' in f.read()
# We need a username/password to access the internal
# FSL conda channel. Prompt the user if they haven't
# provided credentials.
if need_auth and (ctx.args.username is None):
printmsg('A username and password are required to install '
'this version of FSL.', WARNING, EMPHASIS)
ctx.args.username = prompt('Username:').strip()
ctx.args.password = getpass.getpass('Password: ').strip()
# We are now going to load, modify, and re-write, the
# FSL environment file.
#
# Conda expands environment variables within a
# .condarc file, but *not* within an environment.yml
# file. So to authenticate to our internal channel
# without storing credentials anywhere in plain text,
# we *move* the channel list from the environment.yml
# file into $FSLDIR/.condarc.
name, channels, packages = read_environment_file(fname)
# Save some key information about the base environment
if envname == '':
ctx.environment_file = fname
# Save the python version to ctx.python_version.
# The Context.miniconda_metadata function will
# use it to select a suitable miniconda installer.
if 'python' not in packages:
raise Exception('Could not identify Python version in '
'FSL environment file ({})'.format(url))
# Just save the X.Y version
pyver = packages['python'].split('.')
pyver = '.'.join(pyver[:2])
ctx.python_version = pyver
# Save the channels to ctx.environment_channels.
# The install_miniconda function will then add the
# channels to $FSLDIR/.condarc.
# Prepend any additional channels that the user has
# specified on the command-line (e.g. file-system-
# based conda channels that can be used as local
# caches). Note though that we only consider the
# channel list in the main/base environment file -
# channels in extra/child environments are ignored.
ctx.environment_channels = ctx.args.channel + channels
else:
ctx.extra_environment_files[envname] = fname
# Remove any packages that the user has
# requested to exclude from the installation.
for package in list(packages.keys()):
exclude = match_any(package, ctx.args.exclude_package)
if exclude:
log.debug('Excluding package %s', exclude)
packages.pop(package)
# Add cuda_pkgs to each environment, but only
# if the build entry has cuda_enabled=True
if build['cuda_enabled']:
packages.update(cuda_pkgs)
# Re-generate the environment file so it contains
# the updated package list. We don't need to
# save the channels, as they will be written to
# condarc.
copy = '.' + op.basename(fname)
shutil.move(fname, copy)
write_environment_file(fname, name, [], packages)
def download_miniconda(ctx, **kwargs):
"""Downloads the miniconda/miniforge installer and saves it as
"miniconda.sh".
This function assumes that it is run within a temporary/scratch directory.
Keyword arguments are passed through to the Progress bar constructor.
"""
# The user has specified a path to an
# existing miniconda installation - we
# use that rather than downloading/
# installing a separate one.
if ctx.use_existing_base:
return
# user specified a URL/path to a
# miniconda installer
elif ctx.args.miniconda is not None:
url = ctx.args.miniconda
checksum = None
# Use miniconda installer specified
# in FSL release manifest
else:
metadata = ctx.miniconda_metadata
url = metadata['url']
checksum = metadata['sha256']
# Download
printmsg('Downloading miniconda from {}...'.format(url))
with Progress('MB', transform=Progress.bytes_to_mb,
proglabel='download_miniconda',
progfile=ctx.args.progress_file,
**kwargs) as prog:
download_file(url, 'miniconda.sh', prog.update,
ssl_verify=(not ctx.args.skip_ssl_verify))
if (not ctx.args.no_checksum) and (checksum is not None):
sha256('miniconda.sh', checksum)
def install_miniconda(ctx, **kwargs):
"""Downloads the miniconda/miniforge installer, and installs it to the
destination directory.
This function assumes that it is run within a temporary/scratch directory.
Keyword arguments are passed through to the Progress bar constructor.
"""
# We have been instructed to use an
# existing miniconda installation
if ctx.use_existing_base:
return
# Get information about the miniconda installer
# from the manifest.
metadata = ctx.miniconda_metadata
output = metadata.get('output', '')
# output may be a string or int
if isinstance(output, str):
output = output.strip()
if output == '': output = None
else: output = int(output)
# The download_miniconda function saved
# the installer to <pwd>/miniconda.sh
printmsg('Installing miniconda at {}...'.format(ctx.basedir))
cmd = 'bash miniconda.sh -b -p {}'.format(ctx.basedir)
ctx.run(Process.monitor_progress, cmd, total=output,
proglabel='install_miniconda',
progfile=ctx.args.progress_file,
**kwargs)
# Avoid WSL filesystem issue
# https://github.com/conda/conda/issues/9948
cmd = 'find {} -type f -exec touch {{}} +'.format(ctx.basedir)
ctx.run(Process.check_call, cmd)
def generate_condarc(fsldir,
channels,
skip_ssl_verify=False,
throttle_downloads=False,
pkgsdir=None):
"""Called by install_miniconda. Generates content for a .condarc file to
be saved in $FSLDIR/.condarc. This file contains some default values, and
also enforces some settings so that they cannot be overridden by the
user. For example. the list of conda channels is configured so that it
cannot be overridden by a user's ~/.condarc file.
See the following web pages for more details:
- https://docs.conda.io/projects/conda/en/latest/user-guide/configuration/use-condarc.html
- https://www.anaconda.com/blog/conda-configuration-engine-power-users
- https://docs.conda.io/projects/conda/en/latest/user-guide/tasks/manage-channels.html
"""
# Create .condarc config file
condarc = tw.dedent("""
# FSL conda configuration file, auto-generated by the fslinstaller script.
#
# WARNING: This file may be automatically re-generated
# without warning, so it is recommended that any custom
# conda settings are stored elsewhere. Refer to the conda
# documentation for more guidance:
#
# https://conda.io/projects/conda/en/latest/user-guide/configuration/use-condarc.html
# https://www.anaconda.com/blog/conda-configuration-engine-power-users
# https://docs.conda.io/projects/conda/en/latest/user-guide/tasks/manage-channels.html
# Try and make package downloads more robust
remote_read_timeout_secs: 240
remote_connect_timeout_secs: 20
remote_max_retries: 10
remote_backoff_factor: 5
safety_checks: warn
# Disable caching of remote channel repodata.
# This is a hack which is combined with the
# WSL1 filesystem hack in the fslinstaller
# script - because we have modified file
# timestamps, conda will assume that its
# channel repodata cache is up to date, and
# will not bother refreshing it in the
# commands that we run in the install_fsl
# function. When we remove the WSL1 hack from
# the fslinstaller, we can remove this config
# setting.
# https://github.com/conda/conda/issues/9948
local_repodata_ttl: 0
# Channel priority is important. In older versions
# of FSL we placed the FSL conda channel at the
# bottom (lowest priority) for legacy reasons (to
# ensure that conda-forge versions of e.g. VTK were
# preferred over legacy FSL conda versions).
#
# Use final/top/bottom marks to prevent the channel
# priority order being modified by user ~/.condarc
# configuration files.
channel_priority: strict #!final
# Prevent conda from updating itself, as conda
# can sometimes break itself by updating itself
# in-place (see e.g.
# https://github.com/conda/conda/issues/13920)
auto_update_conda: false #!final
""")
# Fix the conda package cache
# if a pkgsdir was provided
if pkgsdir is not None:
condarc += tw.dedent("""
# Fix the package cache at $FSLDIR/pkgs/. Conda
# will download packages to this directory,
# unless it is not writeable, in which case the
# user can specify another location in their
# ~/.condarc
pkgs_dirs:
- {} #!top
""".format(pkgsdir))
if skip_ssl_verify:
printmsg('Configuring conda to skip SSL verification '
'- this is not recommended!', WARNING)
condarc += tw.dedent("""
# Disable SSL verification when accessing
# conda channels over https:// (the
# fslinstaller script was called with
# --skip_ssl_verify). NOT RECOMMENDED.
ssl_verify: false
""")
if throttle_downloads:
condarc += tw.dedent("""
# Limit number of simultaneous package
# downloads - useful when installing
# over an unreliable network connection.
fetch_threads: 1
""")
channels = list(channels)
if len(channels) > 0:
channels[0] += ' #!top'
channels[-1] += ' #!bottom'
condarc += '\nchannels: #!final\n'
for channel in channels:
condarc += ' - {}\n'.format(channel)
return condarc
def get_install_fsl_progress_reporting_method(ctx, build=None, destdir=None):
"""Figure out which reporting mechansim to use for reporting progress
whilst FSL is being installed. The mechanism that is used has changed
a few times.
Returns a tuple containing values to pass to the Progress.monitor_progress
function, either of which may be None if progress cannot be reported:
- an integer value to pass as the total
- a function to pass as the progfunc.
"""
if build is None: build = ctx.build
if destdir is None: destdir = ctx.destdir
# Installation progress parameters may differ
# depending on the target system. If we are
# installing CUDA packages, and the FSL /
# extra environment is CUDA-capable, the
# manifest should contain CUDA-specific
# installation parameters.
if (ctx.cuda_version is not None) and build['cuda_enabled']:
params_key = 'cuda'
else:
params_key = 'install'
# We calculate installation progress in
# one of a few ways, as we have changed
# the mechanism a few times. The
# 'output/install' field in the manifest
# gives us information about how to
# report installation progress.
progparams = build.get('output', {}).get(params_key, None)
# The first method (version 1) involves
# progress reporting by monitoring number of
# lines of standard output produced by
# "conda env update". This is set to None,
# as it is the default behaviour of the
# Progress.monitor_progress function.
progress_v1 = None
# The remaining methods involve counting
# files and sizes in $FSLDIR/pkgs/
# The second method involves progress
# reporting by monitoring the number of
# package files created in $FSLDIR/pkgs/
# This coarsely reflects download
# progress - when conda downloads a
# package, it is saved into this directory.
#
# The third method involves progress
# reporting by monitoring the number of
# files created in $FSLDIR/pkgs/,
# $FSLDIR/bin/ and $FSLDIR/lib/. Tracking
# these three directories will cause the
# progress to reflect both download and
# installation
#
# The fourth method monitors download
# progress in a more fine-grained manner,
# by calculating the size of all .conda
# and .tar.bz2 files in $FSLDIR/pkgs/.
# This is combined with the number of
# files saved to $FSLDIR/bin/ and
# $FSLDIR/lib/
pkgdir = op.join(ctx.basedir, 'pkgs')
pkgdir = op.join(ctx.basedir, 'pkgs')
bindir = op.join( destdir, 'bin')
libdir = op.join( destdir, 'lib')
def matchany(name, *filters):
return any([fnmatch.fnmatch(name, f) for f in filters])
def contents(dirname, *filters):
if not op.exists(dirname):
return []
contents = os.listdir(dirname)
contents = [f for f in contents if matchany(f, *filters)]
return [op.join(dirname, f) for f in contents]
start_pkgs = contents(pkgdir, '*.conda', '*.bz2')
start_sizes = sum([op.getsize(p) for p in start_pkgs])
start_pkgs = len(start_pkgs)
start_bins = len(contents(bindir))
start_libs = len(contents(libdir))
def progress_v234(v, _):
pkgs = contents(pkgdir, '*.conda', '*.bz2')
bins = contents(bindir)
libs = contents(libdir)
sizes = [op.getsize(p) for p in pkgs]
pkgs = len(pkgs) - start_pkgs
bins = len(bins) - start_bins
libs = len(libs) - start_libs
sizes = sum(sizes) - start_sizes
if v == 2: return pkgs
elif v == 3: return pkgs + bins + libs
elif v == 4: return sizes + bins + libs
else: return None
progresses = {}
progresses[1] = progress_v1
progresses[2] = ft.partial(progress_v234, 2)
progresses[3] = ft.partial(progress_v234, 3)
progresses[4] = ft.partial(progress_v234, 4)
progval = None
progfunc = None
# The output field may be either a
# string, in which case we assume
# version 2, or a dictionary containing
# the progress reporting version, and
# an integer value.
if isstr(progparams):
progval = int(progparams)
progfunc = progresses[2]
# output field is a dict - versioned
# progress reporting
elif isinstance(progparams, dict):
progver = int(progparams['version'])
progfunc = progresses[progver]
progval = progparams['value']
# unsupported progress reporting version
if progver > 4:
progval = None
progfunc = None
# version 4: progval is a dict
# containing various quantities
if progver == 4:
progval = sum([int(v) for v in progval.values()])
# older versions: progval is an integer
elif progver:
progval = int(progval)
return progval, progfunc
def install_fsl(ctx, **kwargs):
"""Install FSL into ctx.destdir (which is assumed to be a miniconda
installation.
This function assumes that it is run within a temporary/scratch directory.
Keyword arguments are passed through to the Progress bar constructor.
"""
progval, progfunc = get_install_fsl_progress_reporting_method(ctx)
# Generate .condarc which contains some default/
# fixed conda settings. We create $FSLDIR in
# advance, and copy .condarc into it. Conda seems
# to be ok with the directory already existing,
# although I am concerned that this behaviour may
# not be guaranteed.
#
# If this is a typical FSL installation (a self-
# contained base miniconda environment) we fix
# the package cache directory to isolate it from
# other conda installations that may be on the
# system.
if ctx.destdir == ctx.basedir: pkgsdir = op.join(ctx.destdir, 'pkgs')
else: pkgsdir = None
condarc_contents = generate_condarc(ctx.destdir,
ctx.environment_channels,
ctx.args.skip_ssl_verify,
ctx.args.throttle_downloads,
pkgsdir)
with open('.condarc', 'wt') as f:
f.write(condarc_contents)
cmds = ['mkdir -p {}'.format(ctx.destdir),
'cp -f .condarc {}'.format(ctx.destdir)]
for cmd in cmds:
ctx.run(Process.check_call, cmd)
# Are we updating an existing
# env or creating a new env?
if ctx.destdir == ctx.basedir: cmd = 'update'
else: cmd = 'create'
# We install FSL simply by running conda
# env [update|create] -f env.yml.
envfile = ctx.environment_file
cmd = (ctx.conda + ' env ' + cmd +
' -p ' + ctx.destdir +
' -f ' + envfile)
# Make conda/mamba super verbose if the
# hidden --debug option was specified.
if ctx.args.debug:
cmd += ' -v -v -v'
printmsg('Installing FSL into {}...'.format(ctx.destdir))
# Temporarily install a logging handler which
# records any stdout/stderr messages emitted
# by the conda command that contain phrases
# indicating that the installation failed due
# to a network error.
err_patterns = ['Connection broken',
'Download error',
'NewConnectionError',
'Downloaded bytes did not match Content-Length',
'CONNECTION FAILED']
with LogRecordingHandler(err_patterns) as hd:
# If the installation fails for what appears
# to have been a network error, retry it
# according to --num_retries. Conda>=23.11.0
# will resume failed package downloads, so
# we can just re-run e.g. conda command to
# resume.
#
# Tell the retry_on_error function to retry
# if conda emitted any messages matching the
# patterns above
err_message = 'Installation failed!'
def retry_install(e):
logmsgs = hd.records()
hd.clear()
return len(logmsgs) > 0
retry_on_error(ctx.run, ctx.args.num_retries, Process.monitor_progress,
cmd, timeout=2, total=progval, progfunc=progfunc,
proglabel='install_fsl', progfile=ctx.args.progress_file,
retry_error_message=err_message,
retry_condition=retry_install, **kwargs)
def install_extra(ctx, name, **kwargs):
"""Install an additional FSL component as a separate child environment into
<ctx.destdir>/envs/<name>/.
This function assumes that it is run within a temporary/scratch directory.
Keyword arguments are passed through to the Progress bar constructor.
"""
envfile = ctx.extra_environment_files[name]
destdir = op.join(ctx.extras_dir, name)
# directory already exists - try updating
if not op.exists(destdir): action = 'create'
else: action = 'update'
cmd = (ctx.conda + ' env ' + action +
' -p ' + destdir +
' -f ' + envfile)
if ctx.args.debug:
cmd += ' -v -v -v'
progval, progfunc = get_install_fsl_progress_reporting_method(
ctx, ctx.build['extras'][name], destdir)
printmsg('Installing {} into {}...'.format(name, destdir))
ctx.run(Process.monitor_progress, cmd,
timeout=2, total=progval, progfunc=progfunc,
proglabel='install_{}'.format(name),
progfile=ctx.args.progress_file,
**kwargs)
@warn_on_error('WARNING: The installation succeeded, but an error occurred '
'while creating $FSLDIR/etc/fslversion! There may be more '
'information in the log file.', WARNING, EMPHASIS)
def finalise_installation(ctx):
"""Performs some finalisation tasks. Includes:
- Saving the installed version to $FSLDIR/etc/fslversion
- Saving this installer script and the environment file to
$FSLDIR/etc/
"""
with open('fslversion', 'wt') as f:
f.write(ctx.build['version'])
etcdir = op.join(ctx.destdir, 'etc')
cmds = ['cp fslversion {}' .format(etcdir),
'cp {} {}' .format(ctx.environment_file, etcdir)]
for envfile in ctx.extra_environment_files.values():
cmds.append('cp {} {}'.format(envfile, etcdir))
for cmd in cmds:
ctx.run(Process.check_call, cmd)
@warn_on_error('WARNING: The installation succeeded, but an error occurred '
'while removing intermediate package files! There may be more '
'information in the log file.', WARNING, EMPHASIS)
def post_install_cleanup(ctx, tmpdir):
"""Cleans up the FSL directory after installation. """
cmds = [ctx.conda + ' clean -y --all']
if tmpdir is not None:
cmds.append('rm -rf ' + tmpdir)
for cmd in cmds:
ctx.run(Process.check_call, cmd)
@warn_on_error('WARNING: ', WARNING, EMPHASIS, toscreen=False)
def register_installation(ctx):
"""Gathers and sends some basic system details to the FSL registration
website.
"""
if ctx.args.skip_registration:
return
regurl = ctx.registration_url
if regurl is None:
return
# Exclude hostname from uname output, as
# it may contain identifying information
uname = Process.check_output('uname -msrv', check=False)
system = platform.system().lower()
osinfo = ''
# macOS
if system == 'darwin':
osinfo = Process.check_output('sw_vers', check=False)
# Linux
else:
if op.exists('/etc/os-release'):
with open('/etc/os-release', 'rt') as f:
osinfo = f.read().strip()
else:
osinfo = 'Unknown'
# WSL
if 'microsoft' in uname.lower():
osinfo += '\n\n' + Process.check_output('wsl.exe -v', check=False)
info = {
'architecture' : platform.machine(),
'os' : system,
'os_info' : osinfo,
'uname' : uname,
'python_version' : platform.python_version(),
'python_info' : sys.version,
'fsl_version' : ctx.build['version'],
'fsl_platform' : ctx.build['platform'],
'locale' : getlocale(),
}
printmsg('Registering installation with {}'.format(regurl))
send_registration_info(regurl, data=info)
def patch_file(filename, searchline, numlines, content):
"""Used by configure_shell and configure_matlab. Adds to, modifies,
or creates the specified file.
If a line matching searchline is found in the file, numlines (starting
from searchline) are replaced with content.
Otherwise, content is appended to the end of the file.
"""
content = content.split('\n')
if op.isfile(filename):
with open(filename) as f:
lines = [l.strip() for l in f.readlines()]
else:
lines = []
# replace block
try:
idx = lines.index(searchline)
lines = lines[:idx] + content + lines[idx + numlines:]
# append to end
except ValueError:
lines = lines + [''] + content + ['']
with open(filename, 'wt') as f:
f.write('\n'.join(lines))
def configure_shell(shell, homedir, fsldir):
"""Configures the user's shell environment (e.g. ~/.bash_profile).
:arg shell: User's shell (taken from the $SHELL environment variable
:arg homedir: User's home directory, presumed to contain shell profile
file(s).
:arg fsldir: FSL installation directory
"""
bourne_shells = ['sh', 'bash', 'zsh', 'dash']
csh_shells = ['csh', 'tcsh']
# we edit the first file that exists in
# the list of candidate profile files.
# They are attached as an attribute of
# this function just for testing purposes
# (see after function definition)
shell_profiles = configure_shell.shell_profiles
# DO NOT CHANGE the format of these configurations -
# they are kept exactly as-is for compatibility with
# legacy FSL installations, i.e. so we can modify
# profiles with an existing configuration from older
# FSL versions
bourne_cfg = tw.dedent("""
# FSL Setup
FSLDIR={fsldir}
PATH=${{FSLDIR}}/share/fsl/bin:${{PATH}}
export FSLDIR PATH
. ${{FSLDIR}}/etc/fslconf/fsl.sh
""").format(fsldir=fsldir).strip()
csh_cfg = tw.dedent("""
# FSL Setup
setenv FSLDIR {fsldir}
setenv PATH ${{FSLDIR}}/share/fsl/bin:${{PATH}}
source ${{FSLDIR}}/etc/fslconf/fsl.csh
""").format(fsldir=fsldir).strip()
if shell not in bourne_shells + csh_shells:
printmsg('Shell {} not recognised - skipping environment '
'setup'.format(shell), WARNING, EMPHASIS)
return
if shell in bourne_shells: cfg = bourne_cfg
else: cfg = csh_cfg
# find the profile file to edit
profile = None
candidates = [op.join(homedir, p)
for p in shell_profiles[shell]]
for candidate in candidates:
if op.isfile(candidate):
profile = candidate
break
# if no candidate profile files
# exist, fall back to the first one
if profile is None:
profile = candidates[0]
printmsg('Adding FSL configuration to {}'.format(profile))
patch_file(profile, '# FSL Setup', len(cfg.split('\n')), cfg)
configure_shell.shell_profiles = {'sh' : ['.profile'],
'ksh' : ['.profile'],
'bash' : ['.bash_profile', '.profile'],
'dash' : ['.bash_profile', '.profile'],
'zsh' : ['.zprofile'],
'csh' : ['.cshrc'],
'tcsh' : ['.tcshrc']}
def configure_matlab(homedir, fsldir):
"""Creates/appends FSL configuration code to ~/Documents/MATLAB/startup.m.
"""
# DO NOT CHANGE the format of this configuration -
# see in-line comments in configure_shell.
cfg = tw.dedent("""
% FSL Setup
setenv( 'FSLDIR', '{fsldir}' );
setenv('FSLOUTPUTTYPE', 'NIFTI_GZ');
fsldir = getenv('FSLDIR');
fsldirmpath = sprintf('%s/etc/matlab',fsldir);
path(path, fsldirmpath);
clear fsldir fsldirmpath;
""").format(fsldir=fsldir).strip()
matlab_dir = op.expanduser(op.join(homedir, 'Documents', 'MATLAB'))
startup_m = op.join(matlab_dir, 'startup.m')
if not op.exists(matlab_dir):
os.makedirs(matlab_dir)
printmsg('Adding FSL configuration to {}'.format(startup_m))
patch_file(startup_m, '% FSL Setup', len(cfg.split('\n')), cfg)
def self_update(manifest, workdir, checksum, **kwargs):
"""Checks to see if a newer version of the installer (this script) is
available and if so, downloads it to a temporary file, and runs it in
place of this script.
"""
thisver = Version(__version__)
latestver = Version(manifest['installer']['version'])
if latestver <= thisver:
log.debug('Installer is up to date (this version: %s, '
'latest version: %s)', thisver, latestver)
return
log.debug('New version of installer is available '
'(%s) - self-updating', latestver)
tmpf = tempfile.NamedTemporaryFile(
prefix='new_fslinstaller', delete=False, dir=workdir)
tmpf.close()
tmpf = tmpf.name
download_file(manifest['installer']['url'], tmpf, **kwargs)
if checksum:
try:
sha256(tmpf, manifest['installer']['sha256'])
except Exception as e:
printmsg('New installer file does not match expected '
'checksum! Skipping update.', WARNING)
return
# Don't try and update again - if for some
# reason the online manifest reports a newer
# version than what is available, we would
# otherwise enter into an infinite loop.
cmd = [sys.executable, tmpf] + sys.argv[1:] + ['--no_self_update']
log.debug('Running new installer: %s', cmd)
os.execv(sys.executable, cmd)
def overwrite_destdir(ctx):
"""Called by main to handle when the destination directory already exists.
Asks the user if they want to overwrite it. If they do, or if the
--overwrite option was specified, the directory is moved, and then deleted
after the installation succeeds.
This function assumes that it is run within a temporary/scratch directory.
"""
# there is no existing installation,
# so there is nothing to worry about
if not op.exists(ctx.destdir):
return
# We have been instructed to install
# into an existing [mini]conda environment
if ctx.use_existing_base and (ctx.basedir == ctx.destdir):
return
if not ctx.args.overwrite:
printmsg('\nDestination directory [{}] already exists!\n'
.format(ctx.destdir), WARNING, EMPHASIS)
response = prompt('Do you want to overwrite it [y/N]?',
QUESTION, EMPHASIS)
if response.lower() not in ('y', 'yes'):
printmsg('Aborting installation', ERROR, EMPHASIS)
sys.exit(1)
# generate a unique name for the old
# destination directory (to avoid
# collisions if using the same workdir
# repeatedly)
i = 0
while True:
ctx.old_destdir = op.abspath('old_destdir{}'.format(i))
i += 1
if not op.exists(ctx.old_destdir):
break
printmsg('Deleting directory {}'.format(ctx.destdir), IMPORTANT)
ctx.run(Process.check_call,
'mv {} {}'.format(ctx.destdir, ctx.old_destdir))
def parse_args(argv=None, include=None, parser=None):
"""Parse command-line arguments, returns an argparse.Namespace object.
:arg argv: Command-line arguments.
:arg include: List of arguments to parse. May be used by other scripts
which re-use some of the routines defined in this script.
The resulting argparse.Namespace object will contain values
of None for all arguments that are not included.
:arg parser: `argparse.ArgumentParser` to configure. If not provided,
one is created.
"""
if parser is None:
parser = argparse.ArgumentParser()
uid = os.getuid()
if uid != 0: destdir = DEFAULT_INSTALLATION_DIRECTORY
else: destdir = DEFAULT_ROOT_INSTALLATION_DIRECTORY
# on macOS, when Python is run with sudo,
# op.expanduser('~') will return the
# calling user's home directory, and not
# the root home directory. This doesn't
# really matter, as homedir is only used
# for modifying the shell/matlab profile,
# and this is automatically disabled via
# the --no_env option when run as root. But
# in case the user wants the root shell
# profile modified (via the hidden
# --root_env option), we use getpwuid to
# determine the appropriate home directory.
homedir = pwd.getpwuid(uid).pw_dir
username = os.environ.get('FSLCONDA_USERNAME', None)
password = os.environ.get('FSLCONDA_PASSWORD', None)
options = {
# regular options
'version' : ('-v', {'action' : 'version',
'version' : __version__}),
'dest' : ('-d', {'metavar' : 'DESTDIR'}),
'overwrite' : ('-o', {'action' : 'store_true'}),
'listversions' : ('-l', {'action' : 'store_true'}),
'no_env' : ('-n', {'action' : 'store_true'}),
'no_shell' : ('-s', {'action' : 'store_true'}),
'no_matlab' : ('-m', {'action' : 'store_true'}),
'skip_registration' : ('-r', {'action' : 'store_true'}),
'extra' : ('-e', {'action' : 'append'}),
'fslversion' : ('-V', {'default' : 'latest'}),
'cuda' : ('-c', {'metavar' : 'X.Y'}),
# hidden options
'skip_ssl_verify' : (None, {'action' : 'store_true'}),
'throttle_downloads' : (None, {'action' : 'store_true'}),
'num_retries' : (None, {'type' : int,
'default' : 3}),
'debug' : (None, {'action' : 'store_true'}),
'logfile' : (None, {}),
'username' : (None, {'default' : username}),
'password' : (None, {'default' : password}),
'no_checksum' : (None, {'action' : 'store_true'}),
'workdir' : (None, {}),
'homedir' : (None, {'default' : homedir}),
'devrelease' : (None, {'action' : 'store_true'}),
'devlatest' : (None, {'action' : 'store_true'}),
'manifest' : (None, {}),
'channel' : (None, {'action' : 'append'}),
'miniconda' : (None, {}),
'extras_dir' : (None, {}),
'conda' : (None, {'action' : 'store_true'}),
'no_self_update' : (None, {'action' : 'store_true'}),
'exclude_package' : (None, {'action' : 'append'}),
'root_env' : (None, {'action' : 'store_true'}),
'progress_file' : (None, {}),
}
if include is None:
include = list(options.keys())
helps = {
'version' : 'Print installer version number and exit.',
'listversions' : 'List available FSL versions and exit.',
'dest' : 'Install FSL into this folder (default: '
'{}).'.format(destdir),
'overwrite' : 'Delete existing destination directory if it '
'exists, without asking.',
'no_env' : 'Do not modify your shell or MATLAB configuration '
'(implies --no_shell and --no_matlab). When '
'running the installer script as the root user, '
'the root shell profile is never modified.',
'no_shell' : 'Do not modify your shell configuration.',
'no_matlab' : 'Do not modify your MATLAB configuration.',
'skip_registration' : 'Do not register this installation with the '
'FSL development team.',
'extra' : 'Install optional FSL components',
'fslversion' : 'Install this specific version of FSL.',
'cuda' : 'Install CUDA libraries which are compatible '
'with this CUDA version (default: install '
'versions of CUDA libraries that are compatible '
'with the GPU on the system, or do not install '
'CUDA libraries on systems without a GPU). Set '
'to "none" to disable installation of CUDA '
'libraries.',
# Configure conda to skip SSL verification.
# Not recommended.
'skip_ssl_verify' : argparse.SUPPRESS,
# Limit the number of simultaneous package
# downloads - may be needed when installing
# over unreliable network connection.
'throttle_downloads' : argparse.SUPPRESS,
# Number of times to re-try a failed
# installation, if it appears that
# the installation failed due to a
# download error.
'num_retries' : argparse.SUPPRESS,
# Enable verbose output when calling
# mamba/conda.
'debug' : argparse.SUPPRESS,
# Direct the installer log to this file
# (default: file in $TMPDIR)
'logfile' : argparse.SUPPRESS,
# Username / password for accessing
# internal FSL conda channel, if an
# internal/development release is being
# installed. If not set, will be read from
# FSLCONDA_USERNAME/FSLCONDA_PASSWORD
# environment variables.
'username' : argparse.SUPPRESS,
'password' : argparse.SUPPRESS,
# Do not automatically update the installer script,
'no_self_update' : argparse.SUPPRESS,
# Install a development release. This
# option will cause the installer to
# download the devrelreases.txt file,
# which contains a list of available
# internal/development manifests. The
# user will be prompted to choose one,
# which will be propagated on to the
# --manifest option. If --devlatest
# is used, the most recent developmet
# release is automatically selected.
'devrelease' : argparse.SUPPRESS,
'devlatest' : argparse.SUPPRESS,
# Path/URL to alternative FSL release
# manifest.
'manifest' : argparse.SUPPRESS,
# Source packages from additional conda
# channels. Can be used multiple times.
# Channels specified with this argument
# are pre-pended to the channel list,
# e.g.:
#
# fslinstaller.py --channel A --channel B
#
# will result in a channel list such as:
#
# - A
# - B
# - https://fsl.fmrib..../fslconda/public
# - conda-forge
'channel' : argparse.SUPPRESS,
# Install miniconda from this path/URL,
# instead of the one specified in the
# FSL release manifest.
#
# For example - to download/install a
# conda base environment and install FSL
# packages into the base environment,
# pass a URL or path to a miniconda
# installer:
#
# fslinstaller.py --miniconda https://path/to/miniconda.sh
# fslinstaller.py --miniconda ~/Downloads/miniconda.sh
#
# Alternatively, pass the directory of
# an existing [mini]conda installation
# to use that - for example, if a conda
# base environment has already been
# created at ~/fsl/, to install FSL into
# that base environment:
#
# fslinstaller.py --miniconda ~/fsl/
#
# Or to use an existing [mini]conda
# installation, and create FSL as a
# child environment, just set the
# destination directory to a
# different path, e.g.:
#
# fslinstaller.py --miniconda ~/miniconda3/ -d ~/fsl/
'miniconda' : argparse.SUPPRESS,
# Directory in which to create child
# environments for additional FSL
# modules. Defaults to destdir/envs/
# for typical installations where
# destdir is a base miniconda environment.
# Must be specified when destdir is an
# existing miniconda installation.
'extras_dir' : argparse.SUPPRESS,
# Use conda and not mamba
'conda' : argparse.SUPPRESS,
# Disable SHA256 checksum validation
# of downloaded files
'no_checksum' : argparse.SUPPRESS,
# Store temp files in this directory
# rather than in a temporary directory
'workdir' : argparse.SUPPRESS,
# Treat this directory as user's home
# directory, for the purposes of shell
# configuration. Must already exist.
'homedir' : argparse.SUPPRESS,
# Do not install packages matching this
# fnmatch-style wildcard pattern. Can
# be used multiple times.
'exclude_package' : argparse.SUPPRESS,
# If the installer is run as root, the
# --no_env flag is automatically enabled
# UNLESS this flag is also provided.
'root_env' : argparse.SUPPRESS,
# File to send progress information to.
'progress_file' : argparse.SUPPRESS,
}
# parse args
for option in include:
shortflag, kwargs = options[option]
flags = ['--{}'.format(option)]
if shortflag is not None:
flags.insert(0, shortflag)
parser.add_argument(*flags, help=helps[option], **kwargs)
# parse_known_args so that newly added
# args are ignored by older versions,
# but will be parsed after self_update
args = parser.parse_known_args(argv)[0]
if getattr(args, 'fslversion', 'latest') != 'latest':
if Version(args.fslversion) < Version('6.0.6'):
printmsg(
'This script can only be used to install FSL 6.0.6 or newer. '
'Visit https://fsl.fmrib.ox.ac.uk/fsl/fslwiki/FslInstallation '
'for information on installing older versions.', ERROR,
EMPHASIS)
sys.exit(1)
# add placeholder values for excluded args
for option in options.keys():
if option not in include:
setattr(args, option, None)
# alternate home dir (for debugging)
if args.homedir is not None:
args.homedir = op.abspath(args.homedir)
if not op.isdir(args.homedir):
printmsg('Home directory {} does not exist!'.format(args.homedir),
ERROR, EMPHASIS)
sys.exit(1)
# convert --cuda X.Y into
# a tuple of (X, Y) ints
if args.cuda is not None:
# User does not want CUDA
if args.cuda.lower() == 'none':
args.cuda = 'none'
else:
try:
major, minor = args.cuda.split('.')
major = int(major)
minor = int(minor)
args.cuda = (major, minor)
except Exception:
printmsg('Invalid CUDA version specified: '
'{}'.format(args.cuda),
ERROR, EMPHASIS)
sys.exit(1)
# --no-env is automatically enabled
# when installer is run as root
if os.getuid() == 0 and not args.root_env:
args.no_env = True
# don't modify shell profile
if args.no_env:
args.no_shell = True
args.no_matlab = True
# use workdir rather than a tempdir
if args.workdir is not None:
args.workdir = op.abspath(args.workdir)
if not op.exists(args.workdir):
os.mkdir(args.workdir)
if args.extra is None:
args.extra = []
if args.extras_dir is not None:
args.extras_dir = op.abspath(args.extras_dir)
# manifest takes priority over devrelease/devlatest
if args.manifest is not None:
args.devrelease = False
args.devlatest = False
if args.manifest is None:
args.manifest = FSL_RELEASE_MANIFEST
if args.channel is None:
args.channel = []
for i, channel in enumerate(args.channel):
if op.exists(channel):
args.channel[i] = op.abspath(channel)
if args.devlatest:
args.devrelease = True
if args.exclude_package is None:
args.exclude_package = []
if args.logfile is not None:
args.logfile = op.abspath(args.logfile)
if args.progress_file is not None:
args.progress_file = op.abspath(args.progress_file)
# accept local path for manifest and environment
if args.manifest is not None:
args.manifest = op.expanduser(args.manifest)
if op.exists(args.manifest):
args.manifest = op.abspath(args.manifest)
# accept local path for miniconda installer, or
# path to existing miniconda installation
if args.miniconda is not None:
args.miniconda = op.expanduser(args.miniconda)
if op.exists(args.miniconda):
args.miniconda = op.abspath(args.miniconda)
return args
def config_logging(prefix='fslinstaller_', logdir=None, logfile=None):
"""Configures logging. If a logfile is not specified, log messages are
directed to $TMPDIR/fslinstaller_<unique_token>.log, or
logdir/fslinstaller_<unique_token>.log
"""
if logfile is None:
if logdir is None:
logdir = tempfile.gettempdir()
# Use a unique name for the log file
# (important for multi-user systems)
logfilef, logfile = tempfile.mkstemp(prefix=prefix,
suffix='.log',
dir=logdir)
os.close(logfilef)
handler = logging.FileHandler(logfile)
formatter = logging.Formatter(
'%(asctime)s %(filename)s:%(lineno)4d: %(message)s', '%H:%M:%S')
handler.setFormatter(formatter)
log.addHandler(handler)
log.setLevel(logging.DEBUG)
return logfile
@contextlib.contextmanager
def handle_error(ctx):
"""Used by main as a context manager around the main installation steps.
If an error occurs, prints some messages, performs some clean-up/
restoration tasks, and exits.
"""
try:
yield
except Exception as e:
printmsg('\nERROR occurred during installation!', ERROR, EMPHASIS)
printmsg(' {}\n'.format(e), INFO)
# send traceback to log file
tb = traceback.format_tb(sys.exc_info()[2])
log.debug(''.join(tb))
# send env to logfile
log.debug('Environment variables:')
for k in sorted(os.environ.keys()):
log.debug('{}={}'.format(k, os.environ[k]))
if op.exists(ctx.destdir):
printmsg('Removing failed installation directory '
'{}'.format(ctx.destdir), WARNING)
ctx.run(Process.check_call, 'rm -r ' + ctx.destdir)
# overwrite_destdir moves the existing
# destdir to a temp location, so we can
# restore it if the installation fails
if not op.exists(ctx.destdir) and (ctx.old_destdir is not None):
printmsg('Restoring contents of {}'.format(ctx.destdir),
WARNING)
ctx.run(Process.check_call,
'mv {} {}'.format(ctx.old_destdir, ctx.destdir))
# copy log file to ~/ so it is
# easier for the user to access
date = datetime.datetime.today().strftime('%Y%m%d%H%M%S')
logfile = 'fsl_installation_{}.log'.format(date)
logfile = op.join(op.expanduser('~'), logfile)
shutil.copy(ctx.logfile, logfile)
printmsg('\nFSL installation failed!\n', ERROR, EMPHASIS)
printmsg('Please check the log file - it may contain some '
'more information to help you diagnose the problem: '
'{}\n'.format(logfile), WARNING, EMPHASIS)
sys.exit(1)
def main(argv=None):
"""Installer entry point. Downloads and installs miniconda and FSL, and
configures the user's environment.
"""
printmsg('FSL installer version:', EMPHASIS, UNDERLINE, end='')
printmsg(' {}'.format(__version__))
printmsg('Press CTRL+C at any time to cancel installation', INFO)
if os.getuid() == 0:
printmsg('Running the installer script as root user is discouraged! '
'You should run this script as a regular user - you will be '
'asked for your administrator password if required.',
WARNING, EMPHASIS)
args = parse_args(argv)
logfile = config_logging(logdir=args.workdir, logfile=args.logfile)
log.debug(' '.join(sys.argv))
log.debug('Python: %s %s', sys.executable, str(PYVER))
printmsg('Installation log file: {}\n'.format(logfile), INFO)
ctx = Context(args)
ctx.logfile = logfile
if not args.no_self_update:
self_update(ctx.manifest, args.workdir, not args.no_checksum,
ssl_verify=(not args.skip_ssl_verify))
if args.listversions:
list_available_versions(ctx.manifest)
sys.exit(0)
agree_to_license(ctx)
if (not args.skip_registration) and (ctx.registration_url is not None):
printmsg('During the installation process, please note that some '
'system details will be automatically sent to the FSL '
'development team. These details are extremely basic and '
'cannot be used in any way to identify individual users. If '
'you do not want any information to be sent, please cancel '
'this installation by pressing CTRL+C, and re-run the '
'installer with the --skip_registration option.\n', INFO)
try:
ctx.finalise_settings()
except Exception as e:
printmsg('An error has occurred: {}'.format(e), ERROR)
sys.exit(1)
# Check if using x86 emulation on an Apple
# arm64 machine
check_rosetta_status(ctx)
# Do everything in a temporary directory,
# but don't delete it, as some operations
# may be run as root. The tempdir is
# deleted within the post_install_cleanup
# function.
with tempdir(args.workdir, delete=False) as tmpdir:
if args.workdir is not None:
tmpdir = None
# Ask the user if they want to overwrite
# an existing installation
overwrite_destdir(ctx)
download_fsl_environment_files(ctx)
printmsg('\nInstalling FSL in {}\n'.format(ctx.destdir), EMPHASIS)
with handle_error(ctx):
# These are the main steps of the installation,
# which perform downloading and/or installing.
# We iterate over them so we can show the user
# a step number and a total, e.g. "Step 2 of 4".
steps = [
(download_miniconda, ctx),
(install_miniconda, ctx),
(install_fsl, ctx)]
for name in args.extra:
if name not in ctx.extra_environment_files:
printmsg('There is no extra FSL component called {} - '
'ignoring'.format(name), WARNING, EMPHASIS)
continue
steps.append((install_extra, ctx, name))
for i, step in enumerate(steps):
func = step[0]
funcargs = step[1:]
prefix = '{} / {}'.format(i + 1, len(steps))
func(*funcargs, prefix=prefix)
finalise_installation(ctx)
post_install_cleanup(ctx, tmpdir)
register_installation(ctx)
if not args.no_shell:
configure_shell(ctx.shell, args.homedir, ctx.destdir)
if not args.no_matlab:
configure_matlab(args.homedir, ctx.destdir)
printmsg('\nFSL successfully installed\n', IMPORTANT)
if not args.no_shell:
printmsg('Open a new terminal, or log out and log back in, '
'for the environment changes to take effect.', INFO)
if __name__ == '__main__':
sys.exit(main())
|