summaryrefslogtreecommitdiff
path: root/cloudinit/util.py
blob: 6a6415506f818b95a44e7cb8fc0ab75b6cbffdc2 (plain)
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
# Copyright (C) 2012 Canonical Ltd.
# Copyright (C) 2012, 2013 Hewlett-Packard Development Company, L.P.
# Copyright (C) 2012 Yahoo! Inc.
#
# Author: Scott Moser <scott.moser@canonical.com>
# Author: Juerg Haefliger <juerg.haefliger@hp.com>
# Author: Joshua Harlow <harlowja@yahoo-inc.com>
#
# This file is part of cloud-init. See LICENSE file for license information.

import contextlib
import copy as obj_copy
import email
import glob
import grp
import gzip
import hashlib
import io
import json
import os
import os.path
import platform
import pwd
import random
import re
import shlex
import shutil
import socket
import stat
import string
import subprocess
import sys
import time
from urllib import parse

from errno import ENOENT, ENOEXEC

from base64 import b64decode, b64encode

from cloudinit import importer
from cloudinit import log as logging
from cloudinit import mergers
from cloudinit import safeyaml
from cloudinit import temp_utils
from cloudinit import type_utils
from cloudinit import url_helper
from cloudinit import version

from cloudinit.settings import (CFG_BUILTIN)

try:
    from functools import lru_cache
except ImportError:
    def lru_cache():
        """pass-thru replace for Python3's lru_cache()"""
        def wrapper(f):
            return f
        return wrapper


_DNS_REDIRECT_IP = None
LOG = logging.getLogger(__name__)

# Helps cleanup filenames to ensure they aren't FS incompatible
FN_REPLACEMENTS = {
    os.sep: '_',
}
FN_ALLOWED = ('_-.()' + string.digits + string.ascii_letters)

TRUE_STRINGS = ('true', '1', 'on', 'yes')
FALSE_STRINGS = ('off', '0', 'no', 'false')


# Helper utils to see if running in a container
CONTAINER_TESTS = (['systemd-detect-virt', '--quiet', '--container'],
                   ['running-in-container'],
                   ['lxc-is-container'])


@lru_cache()
def get_dpkg_architecture(target=None):
    """Return the sanitized string output by `dpkg --print-architecture`.

    N.B. This function is wrapped in functools.lru_cache, so repeated calls
    won't shell out every time.
    """
    out, _ = subp(['dpkg', '--print-architecture'], capture=True,
                  target=target)
    return out.strip()


@lru_cache()
def lsb_release(target=None):
    fmap = {'Codename': 'codename', 'Description': 'description',
            'Distributor ID': 'id', 'Release': 'release'}

    data = {}
    try:
        out, _ = subp(['lsb_release', '--all'], capture=True, target=target)
        for line in out.splitlines():
            fname, _, val = line.partition(":")
            if fname in fmap:
                data[fmap[fname]] = val.strip()
        missing = [k for k in fmap.values() if k not in data]
        if len(missing):
            LOG.warning("Missing fields in lsb_release --all output: %s",
                        ','.join(missing))

    except ProcessExecutionError as err:
        LOG.warning("Unable to get lsb_release --all: %s", err)
        data = dict((v, "UNAVAILABLE") for v in fmap.values())

    return data


def target_path(target, path=None):
    # return 'path' inside target, accepting target as None
    if target in (None, ""):
        target = "/"
    elif not isinstance(target, str):
        raise ValueError("Unexpected input for target: %s" % target)
    else:
        target = os.path.abspath(target)
        # abspath("//") returns "//" specifically for 2 slashes.
        if target.startswith("//"):
            target = target[1:]

    if not path:
        return target

    # os.path.join("/etc", "/foo") returns "/foo". Chomp all leading /.
    while len(path) and path[0] == "/":
        path = path[1:]

    return os.path.join(target, path)


def decode_binary(blob, encoding='utf-8'):
    # Converts a binary type into a text type using given encoding.
    if isinstance(blob, str):
        return blob
    return blob.decode(encoding)


def encode_text(text, encoding='utf-8'):
    # Converts a text string into a binary type using given encoding.
    if isinstance(text, bytes):
        return text
    return text.encode(encoding)


def b64d(source):
    # Base64 decode some data, accepting bytes or unicode/str, and returning
    # str/unicode if the result is utf-8 compatible, otherwise returning bytes.
    decoded = b64decode(source)
    try:
        return decoded.decode('utf-8')
    except UnicodeDecodeError:
        return decoded


def b64e(source):
    # Base64 encode some data, accepting bytes or unicode/str, and returning
    # str/unicode if the result is utf-8 compatible, otherwise returning bytes.
    if not isinstance(source, bytes):
        source = source.encode('utf-8')
    return b64encode(source).decode('utf-8')


def fully_decoded_payload(part):
    # In Python 3, decoding the payload will ironically hand us a bytes object.
    # 'decode' means to decode according to Content-Transfer-Encoding, not
    # according to any charset in the Content-Type.  So, if we end up with
    # bytes, first try to decode to str via CT charset, and failing that, try
    # utf-8 using surrogate escapes.
    cte_payload = part.get_payload(decode=True)
    if (part.get_content_maintype() == 'text' and
            isinstance(cte_payload, bytes)):
        charset = part.get_charset()
        if charset and charset.input_codec:
            encoding = charset.input_codec
        else:
            encoding = 'utf-8'
        return cte_payload.decode(encoding, 'surrogateescape')
    return cte_payload


# Path for DMI Data
DMI_SYS_PATH = "/sys/class/dmi/id"

# dmidecode and /sys/class/dmi/id/* use different names for the same value,
# this allows us to refer to them by one canonical name
DMIDECODE_TO_DMI_SYS_MAPPING = {
    'baseboard-asset-tag': 'board_asset_tag',
    'baseboard-manufacturer': 'board_vendor',
    'baseboard-product-name': 'board_name',
    'baseboard-serial-number': 'board_serial',
    'baseboard-version': 'board_version',
    'bios-release-date': 'bios_date',
    'bios-vendor': 'bios_vendor',
    'bios-version': 'bios_version',
    'chassis-asset-tag': 'chassis_asset_tag',
    'chassis-manufacturer': 'chassis_vendor',
    'chassis-serial-number': 'chassis_serial',
    'chassis-version': 'chassis_version',
    'system-manufacturer': 'sys_vendor',
    'system-product-name': 'product_name',
    'system-serial-number': 'product_serial',
    'system-uuid': 'product_uuid',
    'system-version': 'product_version',
}


class ProcessExecutionError(IOError):

    MESSAGE_TMPL = ('%(description)s\n'
                    'Command: %(cmd)s\n'
                    'Exit code: %(exit_code)s\n'
                    'Reason: %(reason)s\n'
                    'Stdout: %(stdout)s\n'
                    'Stderr: %(stderr)s')
    empty_attr = '-'

    def __init__(self, stdout=None, stderr=None,
                 exit_code=None, cmd=None,
                 description=None, reason=None,
                 errno=None):
        if not cmd:
            self.cmd = self.empty_attr
        else:
            self.cmd = cmd

        if not description:
            if not exit_code and errno == ENOEXEC:
                self.description = 'Exec format error. Missing #! in script?'
            else:
                self.description = 'Unexpected error while running command.'
        else:
            self.description = description

        if not isinstance(exit_code, int):
            self.exit_code = self.empty_attr
        else:
            self.exit_code = exit_code

        if not stderr:
            if stderr is None:
                self.stderr = self.empty_attr
            else:
                self.stderr = stderr
        else:
            self.stderr = self._indent_text(stderr)

        if not stdout:
            if stdout is None:
                self.stdout = self.empty_attr
            else:
                self.stdout = stdout
        else:
            self.stdout = self._indent_text(stdout)

        if reason:
            self.reason = reason
        else:
            self.reason = self.empty_attr

        self.errno = errno
        message = self.MESSAGE_TMPL % {
            'description': self._ensure_string(self.description),
            'cmd': self._ensure_string(self.cmd),
            'exit_code': self._ensure_string(self.exit_code),
            'stdout': self._ensure_string(self.stdout),
            'stderr': self._ensure_string(self.stderr),
            'reason': self._ensure_string(self.reason),
        }
        IOError.__init__(self, message)

    def _ensure_string(self, text):
        """
        if data is bytes object, decode
        """
        return text.decode() if isinstance(text, bytes) else text

    def _indent_text(self, text, indent_level=8):
        """
        indent text on all but the first line, allowing for easy to read output
        """
        cr = '\n'
        indent = ' ' * indent_level
        # if input is bytes, return bytes
        if isinstance(text, bytes):
            cr = cr.encode()
            indent = indent.encode()
        # remove any newlines at end of text first to prevent unneeded blank
        # line in output
        return text.rstrip(cr).replace(cr, cr + indent)


class SeLinuxGuard(object):
    def __init__(self, path, recursive=False):
        # Late import since it might not always
        # be possible to use this
        try:
            self.selinux = importer.import_module('selinux')
        except ImportError:
            self.selinux = None
        self.path = path
        self.recursive = recursive

    def __enter__(self):
        if self.selinux and self.selinux.is_selinux_enabled():
            return True
        else:
            return False

    def __exit__(self, excp_type, excp_value, excp_traceback):
        if not self.selinux or not self.selinux.is_selinux_enabled():
            return
        if not os.path.lexists(self.path):
            return

        path = os.path.realpath(self.path)
        try:
            stats = os.lstat(path)
            self.selinux.matchpathcon(path, stats[stat.ST_MODE])
        except OSError:
            return

        LOG.debug("Restoring selinux mode for %s (recursive=%s)",
                  path, self.recursive)
        try:
            self.selinux.restorecon(path, recursive=self.recursive)
        except OSError as e:
            LOG.warning('restorecon failed on %s,%s maybe badness? %s',
                        path, self.recursive, e)


class MountFailedError(Exception):
    pass


class DecompressionError(Exception):
    pass


def fork_cb(child_cb, *args, **kwargs):
    fid = os.fork()
    if fid == 0:
        try:
            child_cb(*args, **kwargs)
            os._exit(0)
        except Exception:
            logexc(LOG, "Failed forking and calling callback %s",
                   type_utils.obj_name(child_cb))
            os._exit(1)
    else:
        LOG.debug("Forked child %s who will run callback %s",
                  fid, type_utils.obj_name(child_cb))


def is_true(val, addons=None):
    if isinstance(val, (bool)):
        return val is True
    check_set = TRUE_STRINGS
    if addons:
        check_set = list(check_set) + addons
    if str(val).lower().strip() in check_set:
        return True
    return False


def is_false(val, addons=None):
    if isinstance(val, (bool)):
        return val is False
    check_set = FALSE_STRINGS
    if addons:
        check_set = list(check_set) + addons
    if str(val).lower().strip() in check_set:
        return True
    return False


def translate_bool(val, addons=None):
    if not val:
        # This handles empty lists and false and
        # other things that python believes are false
        return False
    # If its already a boolean skip
    if isinstance(val, (bool)):
        return val
    return is_true(val, addons)


def rand_str(strlen=32, select_from=None):
    r = random.SystemRandom()
    if not select_from:
        select_from = string.ascii_letters + string.digits
    return "".join([r.choice(select_from) for _x in range(0, strlen)])


def rand_dict_key(dictionary, postfix=None):
    if not postfix:
        postfix = ""
    while True:
        newkey = rand_str(strlen=8) + "_" + postfix
        if newkey not in dictionary:
            break
    return newkey


def read_conf(fname):
    try:
        return load_yaml(load_file(fname), default={})
    except IOError as e:
        if e.errno == ENOENT:
            return {}
        else:
            raise


# Merges X lists, and then keeps the
# unique ones, but orders by sort order
# instead of by the original order
def uniq_merge_sorted(*lists):
    return sorted(uniq_merge(*lists))


# Merges X lists and then iterates over those
# and only keeps the unique items (order preserving)
# and returns that merged and uniqued list as the
# final result.
#
# Note: if any entry is a string it will be
# split on commas and empty entries will be
# evicted and merged in accordingly.
def uniq_merge(*lists):
    combined_list = []
    for a_list in lists:
        if isinstance(a_list, str):
            a_list = a_list.strip().split(",")
            # Kickout the empty ones
            a_list = [a for a in a_list if len(a)]
        combined_list.extend(a_list)
    return uniq_list(combined_list)


def clean_filename(fn):
    for (k, v) in FN_REPLACEMENTS.items():
        fn = fn.replace(k, v)
    removals = []
    for k in fn:
        if k not in FN_ALLOWED:
            removals.append(k)
    for k in removals:
        fn = fn.replace(k, '')
    fn = fn.strip()
    return fn


def decomp_gzip(data, quiet=True, decode=True):
    try:
        buf = io.BytesIO(encode_text(data))
        with contextlib.closing(gzip.GzipFile(None, "rb", 1, buf)) as gh:
            # E1101 is https://github.com/PyCQA/pylint/issues/1444
            if decode:
                return decode_binary(gh.read())  # pylint: disable=E1101
            else:
                return gh.read()  # pylint: disable=E1101
    except Exception as e:
        if quiet:
            return data
        else:
            raise DecompressionError(str(e))


def extract_usergroup(ug_pair):
    if not ug_pair:
        return (None, None)
    ug_parted = ug_pair.split(':', 1)
    u = ug_parted[0].strip()
    if len(ug_parted) == 2:
        g = ug_parted[1].strip()
    else:
        g = None
    if not u or u == "-1" or u.lower() == "none":
        u = None
    if not g or g == "-1" or g.lower() == "none":
        g = None
    return (u, g)


def find_modules(root_dir):
    entries = dict()
    for fname in glob.glob(os.path.join(root_dir, "*.py")):
        if not os.path.isfile(fname):
            continue
        modname = os.path.basename(fname)[0:-3]
        modname = modname.strip()
        if modname and modname.find(".") == -1:
            entries[fname] = modname
    return entries


def multi_log(text, console=True, stderr=True,
              log=None, log_level=logging.DEBUG):
    if stderr:
        sys.stderr.write(text)
    if console:
        conpath = "/dev/console"
        if os.path.exists(conpath):
            with open(conpath, 'w') as wfh:
                wfh.write(text)
                wfh.flush()
        else:
            # A container may lack /dev/console (arguably a container bug).  If
            # it does not exist, then write output to stdout.  this will result
            # in duplicate stderr and stdout messages if stderr was True.
            #
            # even though upstart or systemd might have set up output to go to
            # /dev/console, the user may have configured elsewhere via
            # cloud-config 'output'.  If there is /dev/console, messages will
            # still get there.
            sys.stdout.write(text)
    if log:
        if text[-1] == "\n":
            log.log(log_level, text[:-1])
        else:
            log.log(log_level, text)


def is_ipv4(instr):
    """determine if input string is a ipv4 address. return boolean."""
    toks = instr.split('.')
    if len(toks) != 4:
        return False

    try:
        toks = [x for x in toks if 0 <= int(x) < 256]
    except Exception:
        return False

    return len(toks) == 4


@lru_cache()
def is_FreeBSD():
    return system_info()['variant'] == "freebsd"


@lru_cache()
def is_NetBSD():
    return system_info()['variant'] == "netbsd"


def get_cfg_option_bool(yobj, key, default=False):
    if key not in yobj:
        return default
    return translate_bool(yobj[key])


def get_cfg_option_str(yobj, key, default=None):
    if key not in yobj:
        return default
    val = yobj[key]
    if not isinstance(val, str):
        val = str(val)
    return val


def get_cfg_option_int(yobj, key, default=0):
    return int(get_cfg_option_str(yobj, key, default=default))


def _parse_redhat_release(release_file=None):
    """Return a dictionary of distro info fields from /etc/redhat-release.

    Dict keys will align with /etc/os-release keys:
        ID, VERSION_ID, VERSION_CODENAME
    """

    if not release_file:
        release_file = '/etc/redhat-release'
    if not os.path.exists(release_file):
        return {}
    redhat_release = load_file(release_file)
    redhat_regex = (
        r'(?P<name>.+) release (?P<version>[\d\.]+) '
        r'\((?P<codename>[^)]+)\)')
    match = re.match(redhat_regex, redhat_release)
    if match:
        group = match.groupdict()
        group['name'] = group['name'].lower().partition(' linux')[0]
        if group['name'] == 'red hat enterprise':
            group['name'] = 'redhat'
        return {'ID': group['name'], 'VERSION_ID': group['version'],
                'VERSION_CODENAME': group['codename']}
    return {}


@lru_cache()
def get_linux_distro():
    distro_name = ''
    distro_version = ''
    flavor = ''
    os_release = {}
    if os.path.exists('/etc/os-release'):
        os_release = load_shell_content(load_file('/etc/os-release'))
    if not os_release:
        os_release = _parse_redhat_release()
    if os_release:
        distro_name = os_release.get('ID', '')
        distro_version = os_release.get('VERSION_ID', '')
        if 'sles' in distro_name or 'suse' in distro_name:
            # RELEASE_BLOCKER: We will drop this sles divergent behavior in
            # the future so that get_linux_distro returns a named tuple
            # which will include both version codename and architecture
            # on all distributions.
            flavor = platform.machine()
        else:
            flavor = os_release.get('VERSION_CODENAME', '')
            if not flavor:
                match = re.match(r'[^ ]+ \((?P<codename>[^)]+)\)',
                                 os_release.get('VERSION', ''))
                if match:
                    flavor = match.groupdict()['codename']
        if distro_name == 'rhel':
            distro_name = 'redhat'
    elif 'BSD' in platform.system():
        distro_name = platform.system().lower()
        distro_version = platform.release()
    else:
        dist = ('', '', '')
        try:
            # Was removed in 3.8
            dist = platform.dist()  # pylint: disable=W1505,E1101
        except Exception:
            pass
        finally:
            found = None
            for entry in dist:
                if entry:
                    found = 1
            if not found:
                LOG.warning('Unable to determine distribution, template '
                            'expansion may have unexpected results')
        return dist

    return (distro_name, distro_version, flavor)


@lru_cache()
def system_info():
    info = {
        'platform': platform.platform(),
        'system': platform.system(),
        'release': platform.release(),
        'python': platform.python_version(),
        'uname': list(platform.uname()),
        'dist': get_linux_distro()
    }
    system = info['system'].lower()
    var = 'unknown'
    if system == "linux":
        linux_dist = info['dist'][0].lower()
        if linux_dist in (
                'arch', 'centos', 'debian', 'fedora', 'rhel', 'suse'):
            var = linux_dist
        elif linux_dist in ('ubuntu', 'linuxmint', 'mint'):
            var = 'ubuntu'
        elif linux_dist == 'redhat':
            var = 'rhel'
        elif linux_dist in (
                'opensuse', 'opensuse-tumbleweed', 'opensuse-leap', 'sles'):
            var = 'suse'
        else:
            var = 'linux'
    elif system in ('windows', 'darwin', "freebsd", "netbsd"):
        var = system

    info['variant'] = var

    return info


def get_cfg_option_list(yobj, key, default=None):
    """
    Gets the C{key} config option from C{yobj} as a list of strings. If the
    key is present as a single string it will be returned as a list with one
    string arg.

    @param yobj: The configuration object.
    @param key: The configuration key to get.
    @param default: The default to return if key is not found.
    @return: The configuration option as a list of strings or default if key
        is not found.
    """
    if key not in yobj:
        return default
    if yobj[key] is None:
        return []
    val = yobj[key]
    if isinstance(val, (list)):
        cval = [v for v in val]
        return cval
    if not isinstance(val, str):
        val = str(val)
    return [val]


# get a cfg entry by its path array
# for f['a']['b']: get_cfg_by_path(mycfg,('a','b'))
def get_cfg_by_path(yobj, keyp, default=None):
    """Return the value of the item at path C{keyp} in C{yobj}.

    example:
      get_cfg_by_path({'a': {'b': {'num': 4}}}, 'a/b/num') == 4
      get_cfg_by_path({'a': {'b': {'num': 4}}}, 'c/d') == None

    @param yobj: A dictionary.
    @param keyp: A path inside yobj.  it can be a '/' delimited string,
                 or an iterable.
    @param default: The default to return if the path does not exist.
    @return: The value of the item at keyp."
        is not found."""

    if isinstance(keyp, str):
        keyp = keyp.split("/")
    cur = yobj
    for tok in keyp:
        if tok not in cur:
            return default
        cur = cur[tok]
    return cur


def fixup_output(cfg, mode):
    (outfmt, errfmt) = get_output_cfg(cfg, mode)
    redirect_output(outfmt, errfmt)
    return (outfmt, errfmt)


# redirect_output(outfmt, errfmt, orig_out, orig_err)
#  replace orig_out and orig_err with filehandles specified in outfmt or errfmt
#  fmt can be:
#   > FILEPATH
#   >> FILEPATH
#   | program [ arg1 [ arg2 [ ... ] ] ]
#
#   with a '|', arguments are passed to shell, so one level of
#   shell escape is required.
#
#   if _CLOUD_INIT_SAVE_STDOUT is set in environment to a non empty and true
#   value then output input will not be closed (useful for debugging).
#
def redirect_output(outfmt, errfmt, o_out=None, o_err=None):

    if is_true(os.environ.get("_CLOUD_INIT_SAVE_STDOUT")):
        LOG.debug("Not redirecting output due to _CLOUD_INIT_SAVE_STDOUT")
        return

    if not o_out:
        o_out = sys.stdout
    if not o_err:
        o_err = sys.stderr

    if outfmt:
        LOG.debug("Redirecting %s to %s", o_out, outfmt)
        (mode, arg) = outfmt.split(" ", 1)
        if mode == ">" or mode == ">>":
            owith = "ab"
            if mode == ">":
                owith = "wb"
            new_fp = open(arg, owith)
        elif mode == "|":
            proc = subprocess.Popen(arg, shell=True, stdin=subprocess.PIPE)
            new_fp = proc.stdin
        else:
            raise TypeError("Invalid type for output format: %s" % outfmt)

        if o_out:
            os.dup2(new_fp.fileno(), o_out.fileno())

        if errfmt == outfmt:
            LOG.debug("Redirecting %s to %s", o_err, outfmt)
            os.dup2(new_fp.fileno(), o_err.fileno())
            return

    if errfmt:
        LOG.debug("Redirecting %s to %s", o_err, errfmt)
        (mode, arg) = errfmt.split(" ", 1)
        if mode == ">" or mode == ">>":
            owith = "ab"
            if mode == ">":
                owith = "wb"
            new_fp = open(arg, owith)
        elif mode == "|":
            proc = subprocess.Popen(arg, shell=True, stdin=subprocess.PIPE)
            new_fp = proc.stdin
        else:
            raise TypeError("Invalid type for error format: %s" % errfmt)

        if o_err:
            os.dup2(new_fp.fileno(), o_err.fileno())


def make_url(scheme, host, port=None,
             path='', params='', query='', fragment=''):

    pieces = [scheme or '']

    netloc = ''
    if host:
        netloc = str(host)

    if port is not None:
        netloc += ":" + "%s" % (port)

    pieces.append(netloc or '')
    pieces.append(path or '')
    pieces.append(params or '')
    pieces.append(query or '')
    pieces.append(fragment or '')

    return parse.urlunparse(pieces)


def mergemanydict(srcs, reverse=False):
    if reverse:
        srcs = reversed(srcs)
    merged_cfg = {}
    for cfg in srcs:
        if cfg:
            # Figure out which mergers to apply...
            mergers_to_apply = mergers.dict_extract_mergers(cfg)
            if not mergers_to_apply:
                mergers_to_apply = mergers.default_mergers()
            merger = mergers.construct(mergers_to_apply)
            merged_cfg = merger.merge(merged_cfg, cfg)
    return merged_cfg


@contextlib.contextmanager
def chdir(ndir):
    curr = os.getcwd()
    try:
        os.chdir(ndir)
        yield ndir
    finally:
        os.chdir(curr)


@contextlib.contextmanager
def umask(n_msk):
    old = os.umask(n_msk)
    try:
        yield old
    finally:
        os.umask(old)


def center(text, fill, max_len):
    return '{0:{fill}{align}{size}}'.format(text, fill=fill,
                                            align="^", size=max_len)


def del_dir(path):
    LOG.debug("Recursively deleting %s", path)
    shutil.rmtree(path)


def runparts(dirp, skip_no_exist=True, exe_prefix=None):
    if skip_no_exist and not os.path.isdir(dirp):
        return

    failed = []
    attempted = []

    if exe_prefix is None:
        prefix = []
    elif isinstance(exe_prefix, str):
        prefix = [str(exe_prefix)]
    elif isinstance(exe_prefix, list):
        prefix = exe_prefix
    else:
        raise TypeError("exe_prefix must be None, str, or list")

    for exe_name in sorted(os.listdir(dirp)):
        exe_path = os.path.join(dirp, exe_name)
        if os.path.isfile(exe_path) and os.access(exe_path, os.X_OK):
            attempted.append(exe_path)
            try:
                subp(prefix + [exe_path], capture=False)
            except ProcessExecutionError as e:
                logexc(LOG, "Failed running %s [%s]", exe_path, e.exit_code)
                failed.append(e)

    if failed and attempted:
        raise RuntimeError('Runparts: %s failures in %s attempted commands'
                           % (len(failed), len(attempted)))


# read_optional_seed
# returns boolean indicating success or failure (presense of files)
# if files are present, populates 'fill' dictionary with 'user-data' and
# 'meta-data' entries
def read_optional_seed(fill, base="", ext="", timeout=5):
    try:
        (md, ud) = read_seeded(base, ext, timeout)
        fill['user-data'] = ud
        fill['meta-data'] = md
        return True
    except url_helper.UrlError as e:
        if e.code == url_helper.NOT_FOUND:
            return False
        raise


def fetch_ssl_details(paths=None):
    ssl_details = {}
    # Lookup in these locations for ssl key/cert files
    ssl_cert_paths = [
        '/var/lib/cloud/data/ssl',
        '/var/lib/cloud/instance/data/ssl',
    ]
    if paths:
        ssl_cert_paths.extend([
            os.path.join(paths.get_ipath_cur('data'), 'ssl'),
            os.path.join(paths.get_cpath('data'), 'ssl'),
        ])
    ssl_cert_paths = uniq_merge(ssl_cert_paths)
    ssl_cert_paths = [d for d in ssl_cert_paths if d and os.path.isdir(d)]
    cert_file = None
    for d in ssl_cert_paths:
        if os.path.isfile(os.path.join(d, 'cert.pem')):
            cert_file = os.path.join(d, 'cert.pem')
            break
    key_file = None
    for d in ssl_cert_paths:
        if os.path.isfile(os.path.join(d, 'key.pem')):
            key_file = os.path.join(d, 'key.pem')
            break
    if cert_file and key_file:
        ssl_details['cert_file'] = cert_file
        ssl_details['key_file'] = key_file
    elif cert_file:
        ssl_details['cert_file'] = cert_file
    return ssl_details


def load_yaml(blob, default=None, allowed=(dict,)):
    loaded = default
    blob = decode_binary(blob)
    try:
        LOG.debug("Attempting to load yaml from string "
                  "of length %s with allowed root types %s",
                  len(blob), allowed)
        converted = safeyaml.load(blob)
        if converted is None:
            LOG.debug("loaded blob returned None, returning default.")
            converted = default
        elif not isinstance(converted, allowed):
            # Yes this will just be caught, but thats ok for now...
            raise TypeError(("Yaml load allows %s root types,"
                             " but got %s instead") %
                            (allowed, type_utils.obj_name(converted)))
        loaded = converted
    except (safeyaml.YAMLError, TypeError, ValueError) as e:
        msg = 'Failed loading yaml blob'
        mark = None
        if hasattr(e, 'context_mark') and getattr(e, 'context_mark'):
            mark = getattr(e, 'context_mark')
        elif hasattr(e, 'problem_mark') and getattr(e, 'problem_mark'):
            mark = getattr(e, 'problem_mark')
        if mark:
            msg += (
                '. Invalid format at line {line} column {col}: "{err}"'.format(
                    line=mark.line + 1, col=mark.column + 1, err=e))
        else:
            msg += '. {err}'.format(err=e)
        LOG.warning(msg)
    return loaded


def read_seeded(base="", ext="", timeout=5, retries=10, file_retries=0):
    if base.find("%s") >= 0:
        ud_url = base % ("user-data" + ext)
        md_url = base % ("meta-data" + ext)
    else:
        ud_url = "%s%s%s" % (base, "user-data", ext)
        md_url = "%s%s%s" % (base, "meta-data", ext)

    md_resp = url_helper.read_file_or_url(md_url, timeout=timeout,
                                          retries=retries)
    md = None
    if md_resp.ok():
        md = load_yaml(decode_binary(md_resp.contents), default={})

    ud_resp = url_helper.read_file_or_url(ud_url, timeout=timeout,
                                          retries=retries)
    ud = None
    if ud_resp.ok():
        ud = ud_resp.contents

    return (md, ud)


def read_conf_d(confd):
    # Get reverse sorted list (later trumps newer)
    confs = sorted(os.listdir(confd), reverse=True)

    # Remove anything not ending in '.cfg'
    confs = [f for f in confs if f.endswith(".cfg")]

    # Remove anything not a file
    confs = [f for f in confs
             if os.path.isfile(os.path.join(confd, f))]

    # Load them all so that they can be merged
    cfgs = []
    for fn in confs:
        cfgs.append(read_conf(os.path.join(confd, fn)))

    return mergemanydict(cfgs)


def read_conf_with_confd(cfgfile):
    cfg = read_conf(cfgfile)

    confd = False
    if "conf_d" in cfg:
        confd = cfg['conf_d']
        if confd:
            if not isinstance(confd, str):
                raise TypeError(("Config file %s contains 'conf_d' "
                                 "with non-string type %s") %
                                (cfgfile, type_utils.obj_name(confd)))
            else:
                confd = str(confd).strip()
    elif os.path.isdir("%s.d" % cfgfile):
        confd = "%s.d" % cfgfile

    if not confd or not os.path.isdir(confd):
        return cfg

    # Conf.d settings override input configuration
    confd_cfg = read_conf_d(confd)
    return mergemanydict([confd_cfg, cfg])


def read_conf_from_cmdline(cmdline=None):
    # return a dictionary or config on the cmdline or None
    return load_yaml(read_cc_from_cmdline(cmdline=cmdline))


def read_cc_from_cmdline(cmdline=None):
    # this should support reading cloud-config information from
    # the kernel command line.  It is intended to support content of the
    # format:
    #  cc: <yaml content here> [end_cc]
    # this would include:
    # cc: ssh_import_id: [smoser, kirkland]\\n
    # cc: ssh_import_id: [smoser, bob]\\nruncmd: [ [ ls, -l ], echo hi ] end_cc
    # cc:ssh_import_id: [smoser] end_cc cc:runcmd: [ [ ls, -l ] ] end_cc
    if cmdline is None:
        cmdline = get_cmdline()

    tag_begin = "cc:"
    tag_end = "end_cc"
    begin_l = len(tag_begin)
    end_l = len(tag_end)
    clen = len(cmdline)
    tokens = []
    begin = cmdline.find(tag_begin)
    while begin >= 0:
        end = cmdline.find(tag_end, begin + begin_l)
        if end < 0:
            end = clen
        tokens.append(cmdline[begin + begin_l:end].lstrip().replace("\\n",
                                                                    "\n"))

        begin = cmdline.find(tag_begin, end + end_l)

    return '\n'.join(tokens)


def dos2unix(contents):
    # find first end of line
    pos = contents.find('\n')
    if pos <= 0 or contents[pos - 1] != '\r':
        return contents
    return contents.replace('\r\n', '\n')


def get_hostname_fqdn(cfg, cloud, metadata_only=False):
    """Get hostname and fqdn from config if present and fallback to cloud.

    @param cfg: Dictionary of merged user-data configuration (from init.cfg).
    @param cloud: Cloud instance from init.cloudify().
    @param metadata_only: Boolean, set True to only query cloud meta-data,
        returning None if not present in meta-data.
    @return: a Tuple of strings <hostname>, <fqdn>. Values can be none when
        metadata_only is True and no cfg or metadata provides hostname info.
    """
    if "fqdn" in cfg:
        # user specified a fqdn.  Default hostname then is based off that
        fqdn = cfg['fqdn']
        hostname = get_cfg_option_str(cfg, "hostname", fqdn.split('.')[0])
    else:
        if "hostname" in cfg and cfg['hostname'].find('.') > 0:
            # user specified hostname, and it had '.' in it
            # be nice to them.  set fqdn and hostname from that
            fqdn = cfg['hostname']
            hostname = cfg['hostname'][:fqdn.find('.')]
        else:
            # no fqdn set, get fqdn from cloud.
            # get hostname from cfg if available otherwise cloud
            fqdn = cloud.get_hostname(fqdn=True, metadata_only=metadata_only)
            if "hostname" in cfg:
                hostname = cfg['hostname']
            else:
                hostname = cloud.get_hostname(metadata_only=metadata_only)
    return (hostname, fqdn)


def get_fqdn_from_hosts(hostname, filename="/etc/hosts"):
    """
    For each host a single line should be present with
      the following information:

        IP_address canonical_hostname [aliases...]

      Fields of the entry are separated by any number of  blanks  and/or  tab
      characters.  Text  from a "#" character until the end of the line is a
      comment, and is ignored. Host  names  may  contain  only  alphanumeric
      characters, minus signs ("-"), and periods (".").  They must begin with
      an  alphabetic  character  and  end  with  an  alphanumeric  character.
      Optional aliases provide for name changes, alternate spellings, shorter
      hostnames, or generic hostnames (for example, localhost).
    """
    fqdn = None
    try:
        for line in load_file(filename).splitlines():
            hashpos = line.find("#")
            if hashpos >= 0:
                line = line[0:hashpos]
            line = line.strip()
            if not line:
                continue

            # If there there is less than 3 entries
            # (IP_address, canonical_hostname, alias)
            # then ignore this line
            toks = line.split()
            if len(toks) < 3:
                continue

            if hostname in toks[2:]:
                fqdn = toks[1]
                break
    except IOError:
        pass
    return fqdn


def is_resolvable(name):
    """determine if a url is resolvable, return a boolean
    This also attempts to be resilent against dns redirection.

    Note, that normal nsswitch resolution is used here.  So in order
    to avoid any utilization of 'search' entries in /etc/resolv.conf
    we have to append '.'.

    The top level 'invalid' domain is invalid per RFC.  And example.com
    should also not exist.  The '__cloud_init_expected_not_found__' entry will
    be resolved inside the search list.
    """
    global _DNS_REDIRECT_IP
    if _DNS_REDIRECT_IP is None:
        badips = set()
        badnames = ("does-not-exist.example.com.", "example.invalid.",
                    "__cloud_init_expected_not_found__")
        badresults = {}
        for iname in badnames:
            try:
                result = socket.getaddrinfo(iname, None, 0, 0,
                                            socket.SOCK_STREAM,
                                            socket.AI_CANONNAME)
                badresults[iname] = []
                for (_fam, _stype, _proto, cname, sockaddr) in result:
                    badresults[iname].append("%s: %s" % (cname, sockaddr[0]))
                    badips.add(sockaddr[0])
            except (socket.gaierror, socket.error):
                pass
        _DNS_REDIRECT_IP = badips
        if badresults:
            LOG.debug("detected dns redirection: %s", badresults)

    try:
        result = socket.getaddrinfo(name, None)
        # check first result's sockaddr field
        addr = result[0][4][0]
        if addr in _DNS_REDIRECT_IP:
            return False
        return True
    except (socket.gaierror, socket.error):
        return False


def get_hostname():
    hostname = socket.gethostname()
    return hostname


def gethostbyaddr(ip):
    try:
        return socket.gethostbyaddr(ip)[0]
    except socket.herror:
        return None


def is_resolvable_url(url):
    """determine if this url is resolvable (existing or ip)."""
    return log_time(logfunc=LOG.debug, msg="Resolving URL: " + url,
                    func=is_resolvable,
                    args=(parse.urlparse(url).hostname,))


def search_for_mirror(candidates):
    """
    Search through a list of mirror urls for one that works
    This needs to return quickly.
    """
    for cand in candidates:
        try:
            if is_resolvable_url(cand):
                return cand
        except Exception:
            pass
    return None


def close_stdin():
    """
    reopen stdin as /dev/null so even subprocesses or other os level things get
    /dev/null as input.

    if _CLOUD_INIT_SAVE_STDIN is set in environment to a non empty and true
    value then input will not be closed (useful for debugging).
    """
    if is_true(os.environ.get("_CLOUD_INIT_SAVE_STDIN")):
        return
    with open(os.devnull) as fp:
        os.dup2(fp.fileno(), sys.stdin.fileno())


def find_devs_with_netbsd(criteria=None, oformat='device',
                          tag=None, no_cache=False, path=None):
    if not path:
        path = "/dev/cd0"
    cmd = ["mscdlabel", path]
    out, _ = subp(cmd, capture=True, decode="replace", rcs=[0, 1])
    result = out.split()
    if result and len(result) > 2:
        if criteria == "TYPE=iso9660" and "ISO" in result:
            return [path]
        if criteria == "LABEL=CONFIG-2" and '"config-2"' in result:
            return [path]
    return []


def find_devs_with(criteria=None, oformat='device',
                   tag=None, no_cache=False, path=None):
    """
    find devices matching given criteria (via blkid)
    criteria can be *one* of:
      TYPE=<filesystem>
      LABEL=<label>
      UUID=<uuid>
    """
    if is_NetBSD():
        return find_devs_with_netbsd(criteria, oformat,
                                     tag, no_cache, path)

    blk_id_cmd = ['blkid']
    options = []
    if criteria:
        # Search for block devices with tokens named NAME that
        # have the value 'value' and display any devices which are found.
        # Common values for NAME include  TYPE, LABEL, and UUID.
        # If there are no devices specified on the command line,
        # all block devices will be searched; otherwise,
        # only search the devices specified by the user.
        options.append("-t%s" % (criteria))
    if tag:
        # For each (specified) device, show only the tags that match tag.
        options.append("-s%s" % (tag))
    if no_cache:
        # If you want to start with a clean cache
        # (i.e. don't report devices previously scanned
        # but not necessarily available at this time), specify /dev/null.
        options.extend(["-c", "/dev/null"])
    if oformat:
        # Display blkid's output using the specified format.
        # The format parameter may be:
        # full, value, list, device, udev, export
        options.append('-o%s' % (oformat))
    if path:
        options.append(path)
    cmd = blk_id_cmd + options
    # See man blkid for why 2 is added
    try:
        (out, _err) = subp(cmd, rcs=[0, 2])
    except ProcessExecutionError as e:
        if e.errno == ENOENT:
            # blkid not found...
            out = ""
        else:
            raise
    entries = []
    for line in out.splitlines():
        line = line.strip()
        if line:
            entries.append(line)
    return entries


def blkid(devs=None, disable_cache=False):
    """Get all device tags details from blkid.

    @param devs: Optional list of device paths you wish to query.
    @param disable_cache: Bool, set True to start with clean cache.

    @return: Dict of key value pairs of info for the device.
    """
    if devs is None:
        devs = []
    else:
        devs = list(devs)

    cmd = ['blkid', '-o', 'full']
    if disable_cache:
        cmd.extend(['-c', '/dev/null'])
    cmd.extend(devs)

    # we have to decode with 'replace' as shelx.split (called by
    # load_shell_content) can't take bytes.  So this is potentially
    # lossy of non-utf-8 chars in blkid output.
    out, _ = subp(cmd, capture=True, decode="replace")
    ret = {}
    for line in out.splitlines():
        dev, _, data = line.partition(":")
        ret[dev] = load_shell_content(data)
        ret[dev]["DEVNAME"] = dev

    return ret


def peek_file(fname, max_bytes):
    LOG.debug("Peeking at %s (max_bytes=%s)", fname, max_bytes)
    with open(fname, 'rb') as ifh:
        return ifh.read(max_bytes)


def uniq_list(in_list):
    out_list = []
    for i in in_list:
        if i in out_list:
            continue
        else:
            out_list.append(i)
    return out_list


def load_file(fname, read_cb=None, quiet=False, decode=True):
    LOG.debug("Reading from %s (quiet=%s)", fname, quiet)
    ofh = io.BytesIO()
    try:
        with open(fname, 'rb') as ifh:
            pipe_in_out(ifh, ofh, chunk_cb=read_cb)
    except IOError as e:
        if not quiet:
            raise
        if e.errno != ENOENT:
            raise
    contents = ofh.getvalue()
    LOG.debug("Read %s bytes from %s", len(contents), fname)
    if decode:
        return decode_binary(contents)
    else:
        return contents


@lru_cache()
def _get_cmdline():
    if is_container():
        try:
            contents = load_file("/proc/1/cmdline")
            # replace nulls with space and drop trailing null
            cmdline = contents.replace("\x00", " ")[:-1]
        except Exception as e:
            LOG.warning("failed reading /proc/1/cmdline: %s", e)
            cmdline = ""
    else:
        try:
            cmdline = load_file("/proc/cmdline").strip()
        except Exception:
            cmdline = ""

    return cmdline


def get_cmdline():
    if 'DEBUG_PROC_CMDLINE' in os.environ:
        return os.environ["DEBUG_PROC_CMDLINE"]

    return _get_cmdline()


def pipe_in_out(in_fh, out_fh, chunk_size=1024, chunk_cb=None):
    bytes_piped = 0
    while True:
        data = in_fh.read(chunk_size)
        if len(data) == 0:
            break
        else:
            out_fh.write(data)
            bytes_piped += len(data)
            if chunk_cb:
                chunk_cb(bytes_piped)
    out_fh.flush()
    return bytes_piped


def chownbyid(fname, uid=None, gid=None):
    if uid in [None, -1] and gid in [None, -1]:
        # Nothing to do
        return
    LOG.debug("Changing the ownership of %s to %s:%s", fname, uid, gid)
    os.chown(fname, uid, gid)


def chownbyname(fname, user=None, group=None):
    uid = -1
    gid = -1
    try:
        if user:
            uid = pwd.getpwnam(user).pw_uid
        if group:
            gid = grp.getgrnam(group).gr_gid
    except KeyError as e:
        raise OSError("Unknown user or group: %s" % (e))
    chownbyid(fname, uid, gid)


# Always returns well formated values
# cfg is expected to have an entry 'output' in it, which is a dictionary
# that includes entries for 'init', 'config', 'final' or 'all'
#   init: /var/log/cloud.out
#   config: [ ">> /var/log/cloud-config.out", /var/log/cloud-config.err ]
#   final:
#     output: "| logger -p"
#     error: "> /dev/null"
# this returns the specific 'mode' entry, cleanly formatted, with value
def get_output_cfg(cfg, mode):
    ret = [None, None]
    if not cfg or 'output' not in cfg:
        return ret

    outcfg = cfg['output']
    if mode in outcfg:
        modecfg = outcfg[mode]
    else:
        if 'all' not in outcfg:
            return ret
        # if there is a 'all' item in the output list
        # then it applies to all users of this (init, config, final)
        modecfg = outcfg['all']

    # if value is a string, it specifies stdout and stderr
    if isinstance(modecfg, str):
        ret = [modecfg, modecfg]

    # if its a list, then we expect (stdout, stderr)
    if isinstance(modecfg, list):
        if len(modecfg) > 0:
            ret[0] = modecfg[0]
        if len(modecfg) > 1:
            ret[1] = modecfg[1]

    # if it is a dictionary, expect 'out' and 'error'
    # items, which indicate out and error
    if isinstance(modecfg, dict):
        if 'output' in modecfg:
            ret[0] = modecfg['output']
        if 'error' in modecfg:
            ret[1] = modecfg['error']

    # if err's entry == "&1", then make it same as stdout
    # as in shell syntax of "echo foo >/dev/null 2>&1"
    if ret[1] == "&1":
        ret[1] = ret[0]

    swlist = [">>", ">", "|"]
    for i in range(len(ret)):
        if not ret[i]:
            continue
        val = ret[i].lstrip()
        found = False
        for s in swlist:
            if val.startswith(s):
                val = "%s %s" % (s, val[len(s):].strip())
                found = True
                break
        if not found:
            # default behavior is append
            val = "%s %s" % (">>", val.strip())
        ret[i] = val

    return ret


def get_config_logfiles(cfg):
    """Return a list of log file paths from the configuration dictionary.

    @param cfg: The cloud-init merged configuration dictionary.
    """
    logs = []
    if not cfg or not isinstance(cfg, dict):
        return logs
    default_log = cfg.get('def_log_file')
    if default_log:
        logs.append(default_log)
    for fmt in get_output_cfg(cfg, None):
        if not fmt:
            continue
        match = re.match(r'(?P<type>\||>+)\s*(?P<target>.*)', fmt)
        if not match:
            continue
        target = match.group('target')
        parts = target.split()
        if len(parts) == 1:
            logs.append(target)
        elif ['tee', '-a'] == parts[:2]:
            logs.append(parts[2])
    return list(set(logs))


def logexc(log, msg, *args):
    # Setting this here allows this to change
    # levels easily (not always error level)
    # or even desirable to have that much junk
    # coming out to a non-debug stream
    if msg:
        log.warning(msg, *args)
    # Debug gets the full trace.  However, nose has a bug whereby its
    # logcapture plugin doesn't properly handle the case where there is no
    # actual exception.  To avoid tracebacks during the test suite then, we'll
    # do the actual exc_info extraction here, and if there is no exception in
    # flight, we'll just pass in None.
    exc_info = sys.exc_info()
    if exc_info == (None, None, None):
        exc_info = None
    log.debug(msg, exc_info=exc_info, *args)


def hash_blob(blob, routine, mlen=None):
    hasher = hashlib.new(routine)
    hasher.update(encode_text(blob))
    digest = hasher.hexdigest()
    # Don't get to long now
    if mlen is not None:
        return digest[0:mlen]
    else:
        return digest


def is_user(name):
    try:
        if pwd.getpwnam(name):
            return True
    except KeyError:
        return False


def is_group(name):
    try:
        if grp.getgrnam(name):
            return True
    except KeyError:
        return False


def rename(src, dest):
    LOG.debug("Renaming %s to %s", src, dest)
    # TODO(harlowja) use a se guard here??
    os.rename(src, dest)


def ensure_dirs(dirlist, mode=0o755):
    for d in dirlist:
        ensure_dir(d, mode)


def load_json(text, root_types=(dict,)):
    decoded = json.loads(decode_binary(text))
    if not isinstance(decoded, tuple(root_types)):
        expected_types = ", ".join([str(t) for t in root_types])
        raise TypeError("(%s) root types expected, got %s instead"
                        % (expected_types, type(decoded)))
    return decoded


def json_serialize_default(_obj):
    """Handler for types which aren't json serializable."""
    try:
        return 'ci-b64:{0}'.format(b64e(_obj))
    except AttributeError:
        return 'Warning: redacted unserializable type {0}'.format(type(_obj))


def json_preserialize_binary(data):
    """Preserialize any discovered binary values to avoid json.dumps issues.

    Used only on python 2.7 where default type handling is not honored for
    failure to encode binary data. LP: #1801364.
    TODO(Drop this function when py2.7 support is dropped from cloud-init)
    """
    data = obj_copy.deepcopy(data)
    for key, value in data.items():
        if isinstance(value, (dict)):
            data[key] = json_preserialize_binary(value)
        if isinstance(value, bytes):
            data[key] = 'ci-b64:{0}'.format(b64e(value))
    return data


def json_dumps(data):
    """Return data in nicely formatted json."""
    try:
        return json.dumps(
            data, indent=1, sort_keys=True, separators=(',', ': '),
            default=json_serialize_default)
    except UnicodeDecodeError:
        if sys.version_info[:2] == (2, 7):
            data = json_preserialize_binary(data)
            return json.dumps(data)
        raise


def ensure_dir(path, mode=None):
    if not os.path.isdir(path):
        # Make the dir and adjust the mode
        with SeLinuxGuard(os.path.dirname(path), recursive=True):
            os.makedirs(path)
        chmod(path, mode)
    else:
        # Just adjust the mode
        chmod(path, mode)


@contextlib.contextmanager
def unmounter(umount):
    try:
        yield umount
    finally:
        if umount:
            umount_cmd = ["umount", umount]
            subp(umount_cmd)


def mounts():
    mounted = {}
    try:
        # Go through mounts to see what is already mounted
        if os.path.exists("/proc/mounts"):
            mount_locs = load_file("/proc/mounts").splitlines()
            method = 'proc'
        else:
            (mountoutput, _err) = subp("mount")
            mount_locs = mountoutput.splitlines()
            method = 'mount'
        mountre = r'^(/dev/[\S]+) on (/.*) \((.+), .+, (.+)\)$'
        for mpline in mount_locs:
            # Linux: /dev/sda1 on /boot type ext4 (rw,relatime,data=ordered)
            # FreeBSD: /dev/vtbd0p2 on / (ufs, local, journaled soft-updates)
            try:
                if method == 'proc':
                    (dev, mp, fstype, opts, _freq, _passno) = mpline.split()
                else:
                    m = re.search(mountre, mpline)
                    dev = m.group(1)
                    mp = m.group(2)
                    fstype = m.group(3)
                    opts = m.group(4)
            except Exception:
                continue
            # If the name of the mount point contains spaces these
            # can be escaped as '\040', so undo that..
            mp = mp.replace("\\040", " ")
            mounted[dev] = {
                'fstype': fstype,
                'mountpoint': mp,
                'opts': opts,
            }
        LOG.debug("Fetched %s mounts from %s", mounted, method)
    except (IOError, OSError):
        logexc(LOG, "Failed fetching mount points")
    return mounted


def mount_cb(device, callback, data=None, mtype=None,
             update_env_for_mount=None):
    """
    Mount the device, call method 'callback' passing the directory
    in which it was mounted, then unmount.  Return whatever 'callback'
    returned.  If data != None, also pass data to callback.

    mtype is a filesystem type.  it may be a list, string (a single fsname)
    or a list of fsnames.
    """

    if isinstance(mtype, str):
        mtypes = [mtype]
    elif isinstance(mtype, (list, tuple)):
        mtypes = list(mtype)
    elif mtype is None:
        mtypes = None
    else:
        raise TypeError(
            'Unsupported type provided for mtype parameter: {_type}'.format(
                _type=type(mtype)))

    # clean up 'mtype' input a bit based on platform.
    platsys = platform.system().lower()
    if platsys == "linux":
        if mtypes is None:
            mtypes = ["auto"]
    elif platsys.endswith("bsd"):
        if mtypes is None:
            mtypes = ['ufs', 'cd9660', 'vfat']
        for index, mtype in enumerate(mtypes):
            if mtype == "iso9660":
                mtypes[index] = "cd9660"
    else:
        # we cannot do a smart "auto", so just call 'mount' once with no -t
        mtypes = ['']

    mounted = mounts()
    with temp_utils.tempdir() as tmpd:
        umount = False
        if os.path.realpath(device) in mounted:
            mountpoint = mounted[os.path.realpath(device)]['mountpoint']
        else:
            failure_reason = None
            for mtype in mtypes:
                mountpoint = None
                try:
                    mountcmd = ['mount', '-o', 'ro']
                    if mtype:
                        mountcmd.extend(['-t', mtype])
                    mountcmd.append(device)
                    mountcmd.append(tmpd)
                    subp(mountcmd, update_env=update_env_for_mount)
                    umount = tmpd  # This forces it to be unmounted (when set)
                    mountpoint = tmpd
                    break
                except (IOError, OSError) as exc:
                    LOG.debug("Failed mount of '%s' as '%s': %s",
                              device, mtype, exc)
                    failure_reason = exc
            if not mountpoint:
                raise MountFailedError("Failed mounting %s to %s due to: %s" %
                                       (device, tmpd, failure_reason))

        # Be nice and ensure it ends with a slash
        if not mountpoint.endswith("/"):
            mountpoint += "/"
        with unmounter(umount):
            if data is None:
                ret = callback(mountpoint)
            else:
                ret = callback(mountpoint, data)
            return ret


def get_builtin_cfg():
    # Deep copy so that others can't modify
    return obj_copy.deepcopy(CFG_BUILTIN)


def is_link(path):
    LOG.debug("Testing if a link exists for %s", path)
    return os.path.islink(path)


def sym_link(source, link, force=False):
    LOG.debug("Creating symbolic link from %r => %r", link, source)
    if force and os.path.exists(link):
        del_file(link)
    os.symlink(source, link)


def del_file(path):
    LOG.debug("Attempting to remove %s", path)
    try:
        os.unlink(path)
    except OSError as e:
        if e.errno != ENOENT:
            raise e


def copy(src, dest):
    LOG.debug("Copying %s to %s", src, dest)
    shutil.copy(src, dest)


def time_rfc2822():
    try:
        ts = time.strftime("%a, %d %b %Y %H:%M:%S %z", time.gmtime())
    except Exception:
        ts = "??"
    return ts


def boottime():
    """Use sysctlbyname(3) via ctypes to find kern.boottime

    kern.boottime is of type struct timeval. Here we create a
    private class to easier unpack it.

    @return boottime: float to be compatible with linux
    """
    import ctypes

    NULL_BYTES = b"\x00"

    class timeval(ctypes.Structure):
        _fields_ = [
            ("tv_sec", ctypes.c_int64),
            ("tv_usec", ctypes.c_int64)
        ]
    libc = ctypes.CDLL('libc.so')
    size = ctypes.c_size_t()
    size.value = ctypes.sizeof(timeval)
    buf = timeval()
    if libc.sysctlbyname(b"kern.boottime" + NULL_BYTES, ctypes.byref(buf),
                         ctypes.byref(size), None, 0) != -1:
        return buf.tv_sec + buf.tv_usec / 1000000.0
    raise RuntimeError("Unable to retrieve kern.boottime on this system")


def uptime():
    uptime_str = '??'
    method = 'unknown'
    try:
        if os.path.exists("/proc/uptime"):
            method = '/proc/uptime'
            contents = load_file("/proc/uptime")
            if contents:
                uptime_str = contents.split()[0]
        else:
            method = 'ctypes'
            # This is the *BSD codepath
            uptime_str = str(time.time() - boottime())

    except Exception:
        logexc(LOG, "Unable to read uptime using method: %s" % method)
    return uptime_str


def append_file(path, content):
    write_file(path, content, omode="ab", mode=None)


def ensure_file(path, mode=0o644):
    write_file(path, content='', omode="ab", mode=mode)


def safe_int(possible_int):
    try:
        return int(possible_int)
    except (ValueError, TypeError):
        return None


def chmod(path, mode):
    real_mode = safe_int(mode)
    if path and real_mode:
        with SeLinuxGuard(path):
            os.chmod(path, real_mode)


def write_file(filename, content, mode=0o644, omode="wb", copy_mode=False):
    """
    Writes a file with the given content and sets the file mode as specified.
    Restores the SELinux context if possible.

    @param filename: The full path of the file to write.
    @param content: The content to write to the file.
    @param mode: The filesystem mode to set on the file.
    @param omode: The open mode used when opening the file (w, wb, a, etc.)
    """

    if copy_mode:
        try:
            file_stat = os.stat(filename)
            mode = stat.S_IMODE(file_stat.st_mode)
        except OSError:
            pass

    ensure_dir(os.path.dirname(filename))
    if 'b' in omode.lower():
        content = encode_text(content)
        write_type = 'bytes'
    else:
        content = decode_binary(content)
        write_type = 'characters'
    try:
        mode_r = "%o" % mode
    except TypeError:
        mode_r = "%r" % mode
    LOG.debug("Writing to %s - %s: [%s] %s %s",
              filename, omode, mode_r, len(content), write_type)
    with SeLinuxGuard(path=filename):
        with open(filename, omode) as fh:
            fh.write(content)
            fh.flush()
    chmod(filename, mode)


def delete_dir_contents(dirname):
    """
    Deletes all contents of a directory without deleting the directory itself.

    @param dirname: The directory whose contents should be deleted.
    """
    for node in os.listdir(dirname):
        node_fullpath = os.path.join(dirname, node)
        if os.path.isdir(node_fullpath):
            del_dir(node_fullpath)
        else:
            del_file(node_fullpath)


def subp_blob_in_tempfile(blob, *args, **kwargs):
    """Write blob to a tempfile, and call subp with args, kwargs. Then cleanup.

    'basename' as a kwarg allows providing the basename for the file.
    The 'args' argument to subp will be updated with the full path to the
    filename as the first argument.
    """
    basename = kwargs.pop('basename', "subp_blob")

    if len(args) == 0 and 'args' not in kwargs:
        args = [tuple()]

    # Use tmpdir over tmpfile to avoid 'text file busy' on execute
    with temp_utils.tempdir(needs_exe=True) as tmpd:
        tmpf = os.path.join(tmpd, basename)
        if 'args' in kwargs:
            kwargs['args'] = [tmpf] + list(kwargs['args'])
        else:
            args = list(args)
            args[0] = [tmpf] + args[0]

        write_file(tmpf, blob, mode=0o700)
        return subp(*args, **kwargs)


def subp(args, data=None, rcs=None, env=None, capture=True,
         combine_capture=False, shell=False,
         logstring=False, decode="replace", target=None, update_env=None,
         status_cb=None):
    """Run a subprocess.

    :param args: command to run in a list. [cmd, arg1, arg2...]
    :param data: input to the command, made available on its stdin.
    :param rcs:
        a list of allowed return codes.  If subprocess exits with a value not
        in this list, a ProcessExecutionError will be raised.  By default,
        data is returned as a string.  See 'decode' parameter.
    :param env: a dictionary for the command's environment.
    :param capture:
        boolean indicating if output should be captured.  If True, then stderr
        and stdout will be returned.  If False, they will not be redirected.
    :param combine_capture:
        boolean indicating if stderr should be redirected to stdout. When True,
        interleaved stderr and stdout will be returned as the first element of
        a tuple, the second will be empty string or bytes (per decode).
        if combine_capture is True, then output is captured independent of
        the value of capture.
    :param shell: boolean indicating if this should be run with a shell.
    :param logstring:
        the command will be logged to DEBUG.  If it contains info that should
        not be logged, then logstring will be logged instead.
    :param decode:
        if False, no decoding will be done and returned stdout and stderr will
        be bytes.  Other allowed values are 'strict', 'ignore', and 'replace'.
        These values are passed through to bytes().decode() as the 'errors'
        parameter.  There is no support for decoding to other than utf-8.
    :param target:
        not supported, kwarg present only to make function signature similar
        to curtin's subp.
    :param update_env:
        update the enviornment for this command with this dictionary.
        this will not affect the current processes os.environ.
    :param status_cb:
        call this fuction with a single string argument before starting
        and after finishing.

    :return
        if not capturing, return is (None, None)
        if capturing, stdout and stderr are returned.
            if decode:
                entries in tuple will be python2 unicode or python3 string
            if not decode:
                entries in tuple will be python2 string or python3 bytes
    """

    # not supported in cloud-init (yet), for now kept in the call signature
    # to ease maintaining code shared between cloud-init and curtin
    if target is not None:
        raise ValueError("target arg not supported by cloud-init")

    if rcs is None:
        rcs = [0]

    devnull_fp = None

    if update_env:
        if env is None:
            env = os.environ
        env = env.copy()
        env.update(update_env)

    if target_path(target) != "/":
        args = ['chroot', target] + list(args)

    if status_cb:
        command = ' '.join(args) if isinstance(args, list) else args
        status_cb('Begin run command: {command}\n'.format(command=command))
    if not logstring:
        LOG.debug(("Running command %s with allowed return codes %s"
                   " (shell=%s, capture=%s)"),
                  args, rcs, shell, 'combine' if combine_capture else capture)
    else:
        LOG.debug(("Running hidden command to protect sensitive "
                   "input/output logstring: %s"), logstring)

    stdin = None
    stdout = None
    stderr = None
    if capture:
        stdout = subprocess.PIPE
        stderr = subprocess.PIPE
    if combine_capture:
        stdout = subprocess.PIPE
        stderr = subprocess.STDOUT
    if data is None:
        # using devnull assures any reads get null, rather
        # than possibly waiting on input.
        devnull_fp = open(os.devnull)
        stdin = devnull_fp
    else:
        stdin = subprocess.PIPE
        if not isinstance(data, bytes):
            data = data.encode()

    # Popen converts entries in the arguments array from non-bytes to bytes.
    # When locale is unset it may use ascii for that encoding which can
    # cause UnicodeDecodeErrors. (LP: #1751051)
    if isinstance(args, bytes):
        bytes_args = args
    elif isinstance(args, str):
        bytes_args = args.encode("utf-8")
    else:
        bytes_args = [
            x if isinstance(x, bytes) else x.encode("utf-8")
            for x in args]
    try:
        sp = subprocess.Popen(bytes_args, stdout=stdout,
                              stderr=stderr, stdin=stdin,
                              env=env, shell=shell)
        (out, err) = sp.communicate(data)
    except OSError as e:
        if status_cb:
            status_cb('ERROR: End run command: invalid command provided\n')
        raise ProcessExecutionError(
            cmd=args, reason=e, errno=e.errno,
            stdout="-" if decode else b"-",
            stderr="-" if decode else b"-")
    finally:
        if devnull_fp:
            devnull_fp.close()

    # Just ensure blank instead of none.
    if capture or combine_capture:
        if not out:
            out = b''
        if not err:
            err = b''
    if decode:
        def ldecode(data, m='utf-8'):
            if not isinstance(data, bytes):
                return data
            return data.decode(m, decode)

        out = ldecode(out)
        err = ldecode(err)

    rc = sp.returncode
    if rc not in rcs:
        if status_cb:
            status_cb(
                'ERROR: End run command: exit({code})\n'.format(code=rc))
        raise ProcessExecutionError(stdout=out, stderr=err,
                                    exit_code=rc,
                                    cmd=args)
    if status_cb:
        status_cb('End run command: exit({code})\n'.format(code=rc))
    return (out, err)


def make_header(comment_char="#", base='created'):
    ci_ver = version.version_string()
    header = str(comment_char)
    header += " %s by cloud-init v. %s" % (base.title(), ci_ver)
    header += " on %s" % time_rfc2822()
    return header


def abs_join(*paths):
    return os.path.abspath(os.path.join(*paths))


# shellify, takes a list of commands
#  for each entry in the list
#    if it is an array, shell protect it (with single ticks)
#    if it is a string, do nothing
def shellify(cmdlist, add_header=True):
    if not isinstance(cmdlist, (tuple, list)):
        raise TypeError(
            "Input to shellify was type '%s'. Expected list or tuple." %
            (type_utils.obj_name(cmdlist)))

    content = ''
    if add_header:
        content += "#!/bin/sh\n"
    escaped = "%s%s%s%s" % ("'", '\\', "'", "'")
    cmds_made = 0
    for args in cmdlist:
        # If the item is a list, wrap all items in single tick.
        # If its not, then just write it directly.
        if isinstance(args, (list, tuple)):
            fixed = []
            for f in args:
                fixed.append("'%s'" % (str(f).replace("'", escaped)))
            content = "%s%s\n" % (content, ' '.join(fixed))
            cmds_made += 1
        elif isinstance(args, str):
            content = "%s%s\n" % (content, args)
            cmds_made += 1
        else:
            raise TypeError(
                "Unable to shellify type '%s'. Expected list, string, tuple. "
                "Got: %s" % (type_utils.obj_name(args), args))

    LOG.debug("Shellified %s commands.", cmds_made)
    return content


def strip_prefix_suffix(line, prefix=None, suffix=None):
    if prefix and line.startswith(prefix):
        line = line[len(prefix):]
    if suffix and line.endswith(suffix):
        line = line[:-len(suffix)]
    return line


def is_container():
    """
    Checks to see if this code running in a container of some sort
    """

    for helper in CONTAINER_TESTS:
        try:
            # try to run a helper program. if it returns true/zero
            # then we're inside a container. otherwise, no
            subp(helper)
            return True
        except (IOError, OSError):
            pass

    # this code is largely from the logic in
    # ubuntu's /etc/init/container-detect.conf
    try:
        # Detect old-style libvirt
        # Detect OpenVZ containers
        pid1env = get_proc_env(1)
        if "container" in pid1env:
            return True
        if "LIBVIRT_LXC_UUID" in pid1env:
            return True
    except (IOError, OSError):
        pass

    # Detect OpenVZ containers
    if os.path.isdir("/proc/vz") and not os.path.isdir("/proc/bc"):
        return True

    try:
        # Detect Vserver containers
        lines = load_file("/proc/self/status").splitlines()
        for line in lines:
            if line.startswith("VxID:"):
                (_key, val) = line.strip().split(":", 1)
                if val != "0":
                    return True
    except (IOError, OSError):
        pass

    return False


def is_lxd():
    """Check to see if we are running in a lxd container."""
    return os.path.exists('/dev/lxd/sock')


def get_proc_env(pid, encoding='utf-8', errors='replace'):
    """
    Return the environment in a dict that a given process id was started with.

    @param encoding: if true, then decoding will be done with
                     .decode(encoding, errors) and text will be returned.
                     if false then binary will be returned.
    @param errors:   only used if encoding is true."""
    fn = os.path.join("/proc", str(pid), "environ")

    try:
        contents = load_file(fn, decode=False)
    except (IOError, OSError):
        return {}

    env = {}
    null, equal = (b"\x00", b"=")
    if encoding:
        null, equal = ("\x00", "=")
        contents = contents.decode(encoding, errors)

    for tok in contents.split(null):
        if not tok:
            continue
        (name, val) = tok.split(equal, 1)
        if name:
            env[name] = val
    return env


def keyval_str_to_dict(kvstring):
    ret = {}
    for tok in kvstring.split():
        try:
            (key, val) = tok.split("=", 1)
        except ValueError:
            key = tok
            val = True
        ret[key] = val
    return ret


def is_partition(device):
    if device.startswith("/dev/"):
        device = device[5:]

    return os.path.isfile("/sys/class/block/%s/partition" % device)


def expand_package_list(version_fmt, pkgs):
    # we will accept tuples, lists of tuples, or just plain lists
    if not isinstance(pkgs, list):
        pkgs = [pkgs]

    pkglist = []
    for pkg in pkgs:
        if isinstance(pkg, str):
            pkglist.append(pkg)
            continue

        if isinstance(pkg, (tuple, list)):
            if len(pkg) < 1 or len(pkg) > 2:
                raise RuntimeError("Invalid package & version tuple.")

            if len(pkg) == 2 and pkg[1]:
                pkglist.append(version_fmt % tuple(pkg))
                continue

            pkglist.append(pkg[0])

        else:
            raise RuntimeError("Invalid package type.")

    return pkglist


def parse_mount_info(path, mountinfo_lines, log=LOG, get_mnt_opts=False):
    """Return the mount information for PATH given the lines from
    /proc/$$/mountinfo."""

    path_elements = [e for e in path.split('/') if e]
    devpth = None
    fs_type = None
    match_mount_point = None
    match_mount_point_elements = None
    for i, line in enumerate(mountinfo_lines):
        parts = line.split()

        # Completely fail if there is anything in any line that is
        # unexpected, as continuing to parse past a bad line could
        # cause an incorrect result to be returned, so it's better
        # return nothing than an incorrect result.

        # The minimum number of elements in a valid line is 10.
        if len(parts) < 10:
            log.debug("Line %d has two few columns (%d): %s",
                      i + 1, len(parts), line)
            return None

        mount_point = parts[4]
        mount_point_elements = [e for e in mount_point.split('/') if e]

        # Ignore mounts deeper than the path in question.
        if len(mount_point_elements) > len(path_elements):
            continue

        # Ignore mounts where the common path is not the same.
        x = min(len(mount_point_elements), len(path_elements))
        if mount_point_elements[0:x] != path_elements[0:x]:
            continue

        # Ignore mount points higher than an already seen mount
        # point.
        if (match_mount_point_elements is not None and
                len(match_mount_point_elements) > len(mount_point_elements)):
            continue

        # Find the '-' which terminates a list of optional columns to
        # find the filesystem type and the path to the device.  See
        # man 5 proc for the format of this file.
        try:
            i = parts.index('-')
        except ValueError:
            log.debug("Did not find column named '-' in line %d: %s",
                      i + 1, line)
            return None

        # Get the path to the device.
        try:
            fs_type = parts[i + 1]
            devpth = parts[i + 2]
        except IndexError:
            log.debug("Too few columns after '-' column in line %d: %s",
                      i + 1, line)
            return None

        match_mount_point = mount_point
        match_mount_point_elements = mount_point_elements
        mount_options = parts[5]

    if get_mnt_opts:
        if devpth and fs_type and match_mount_point and mount_options:
            return (devpth, fs_type, match_mount_point, mount_options)
    else:
        if devpth and fs_type and match_mount_point:
            return (devpth, fs_type, match_mount_point)

    return None


def parse_mtab(path):
    """On older kernels there's no /proc/$$/mountinfo, so use mtab."""
    for line in load_file("/etc/mtab").splitlines():
        devpth, mount_point, fs_type = line.split()[:3]
        if mount_point == path:
            return devpth, fs_type, mount_point
    return None


def find_freebsd_part(fs):
    splitted = fs.split('/')
    if len(splitted) == 3:
        return splitted[2]
    elif splitted[2] in ['label', 'gpt', 'ufs']:
        target_label = fs[5:]
        (part, _err) = subp(['glabel', 'status', '-s'])
        for labels in part.split("\n"):
            items = labels.split()
            if len(items) > 0 and items[0] == target_label:
                part = items[2]
                break
        return str(part)
    else:
        LOG.warning("Unexpected input in find_freebsd_part: %s", fs)


def get_path_dev_freebsd(path, mnt_list):
    path_found = None
    for line in mnt_list.split("\n"):
        items = line.split()
        if (len(items) > 2 and os.path.exists(items[1] + path)):
            path_found = line
            break
    return path_found


def get_mount_info_freebsd(path):
    (result, err) = subp(['mount', '-p', path], rcs=[0, 1])
    if len(err):
        # find a path if the input is not a mounting point
        (mnt_list, err) = subp(['mount', '-p'])
        path_found = get_path_dev_freebsd(path, mnt_list)
        if (path_found is None):
            return None
        result = path_found
    ret = result.split()
    label_part = find_freebsd_part(ret[0])
    return "/dev/" + label_part, ret[2], ret[1]


def get_device_info_from_zpool(zpool):
    # zpool has 10 second timeout waiting for /dev/zfs LP: #1760173
    if not os.path.exists('/dev/zfs'):
        LOG.debug('Cannot get zpool info, no /dev/zfs')
        return None
    try:
        (zpoolstatus, err) = subp(['zpool', 'status', zpool])
    except ProcessExecutionError as err:
        LOG.warning("Unable to get zpool status of %s: %s", zpool, err)
        return None
    if len(err):
        return None
    r = r'.*(ONLINE).*'
    for line in zpoolstatus.split("\n"):
        if re.search(r, line) and zpool not in line and "state" not in line:
            disk = line.split()[0]
            LOG.debug('found zpool "%s" on disk %s', zpool, disk)
            return disk


def parse_mount(path):
    (mountoutput, _err) = subp(['mount'])
    mount_locs = mountoutput.splitlines()
    # there are 2 types of mount outputs we have to parse therefore
    # the regex is a bit complex. to better understand this regex see:
    # https://regex101.com/r/2F6c1k/1
    # https://regex101.com/r/T2en7a/1
    regex = (r'^(/dev/[\S]+|.*zroot\S*?) on (/[\S]*) '
             r'(?=(?:type)[\s]+([\S]+)|\(([^,]*))')
    for line in mount_locs:
        m = re.search(regex, line)
        if not m:
            continue
        devpth = m.group(1)
        mount_point = m.group(2)
        # above regex will either fill the fs_type in group(3)
        # or group(4) depending on the format we have.
        fs_type = m.group(3)
        if fs_type is None:
            fs_type = m.group(4)
        LOG.debug('found line in mount -> devpth: %s, mount_point: %s, '
                  'fs_type: %s', devpth, mount_point, fs_type)
        # check whether the dev refers to a label on FreeBSD
        # for example, if dev is '/dev/label/rootfs', we should
        # continue finding the real device like '/dev/da0'.
        # this is only valid for non zfs file systems as a zpool
        # can have gpt labels as disk.
        devm = re.search('^(/dev/.+)p([0-9])$', devpth)
        if not devm and is_FreeBSD() and fs_type != 'zfs':
            return get_mount_info_freebsd(path)
        elif mount_point == path:
            return devpth, fs_type, mount_point
    return None


def get_mount_info(path, log=LOG, get_mnt_opts=False):
    # Use /proc/$$/mountinfo to find the device where path is mounted.
    # This is done because with a btrfs filesystem using os.stat(path)
    # does not return the ID of the device.
    #
    # Here, / has a device of 18 (decimal).
    #
    # $ stat /
    #   File: '/'
    #   Size: 234               Blocks: 0          IO Block: 4096   directory
    # Device: 12h/18d   Inode: 256         Links: 1
    # Access: (0755/drwxr-xr-x)  Uid: (    0/    root)   Gid: (    0/    root)
    # Access: 2013-01-13 07:31:04.358011255 +0000
    # Modify: 2013-01-13 18:48:25.930011255 +0000
    # Change: 2013-01-13 18:48:25.930011255 +0000
    #  Birth: -
    #
    # Find where / is mounted:
    #
    # $ mount | grep ' / '
    # /dev/vda1 on / type btrfs (rw,subvol=@,compress=lzo)
    #
    # And the device ID for /dev/vda1 is not 18:
    #
    # $ ls -l /dev/vda1
    # brw-rw---- 1 root disk 253, 1 Jan 13 08:29 /dev/vda1
    #
    # So use /proc/$$/mountinfo to find the device underlying the
    # input path.
    mountinfo_path = '/proc/%s/mountinfo' % os.getpid()
    if os.path.exists(mountinfo_path):
        lines = load_file(mountinfo_path).splitlines()
        return parse_mount_info(path, lines, log, get_mnt_opts)
    elif os.path.exists("/etc/mtab"):
        return parse_mtab(path)
    else:
        return parse_mount(path)


def is_exe(fpath):
    # return boolean indicating if fpath exists and is executable.
    return os.path.isfile(fpath) and os.access(fpath, os.X_OK)


def which(program, search=None, target=None):
    target = target_path(target)

    if os.path.sep in program:
        # if program had a '/' in it, then do not search PATH
        # 'which' does consider cwd here. (cd / && which bin/ls) = bin/ls
        # so effectively we set cwd to / (or target)
        if is_exe(target_path(target, program)):
            return program

    if search is None:
        paths = [p.strip('"') for p in
                 os.environ.get("PATH", "").split(os.pathsep)]
        if target == "/":
            search = paths
        else:
            search = [p for p in paths if p.startswith("/")]

    # normalize path input
    search = [os.path.abspath(p) for p in search]

    for path in search:
        ppath = os.path.sep.join((path, program))
        if is_exe(target_path(target, ppath)):
            return ppath

    return None


def log_time(logfunc, msg, func, args=None, kwargs=None, get_uptime=False):
    if args is None:
        args = []
    if kwargs is None:
        kwargs = {}

    start = time.time()

    ustart = None
    if get_uptime:
        try:
            ustart = float(uptime())
        except ValueError:
            pass

    try:
        ret = func(*args, **kwargs)
    finally:
        delta = time.time() - start
        udelta = None
        if ustart is not None:
            try:
                udelta = float(uptime()) - ustart
            except ValueError:
                pass

        tmsg = " took %0.3f seconds" % delta
        if get_uptime:
            if isinstance(udelta, (float)):
                tmsg += " (%0.2f)" % udelta
            else:
                tmsg += " (N/A)"
        try:
            logfunc(msg + tmsg)
        except Exception:
            pass
    return ret


def expand_dotted_devname(dotted):
    toks = dotted.rsplit(".", 1)
    if len(toks) > 1:
        return toks
    else:
        return (dotted, None)


def pathprefix2dict(base, required=None, optional=None, delim=os.path.sep):
    # return a dictionary populated with keys in 'required' and 'optional'
    # by reading files in prefix + delim + entry
    if required is None:
        required = []
    if optional is None:
        optional = []

    missing = []
    ret = {}
    for f in required + optional:
        try:
            ret[f] = load_file(base + delim + f, quiet=False, decode=False)
        except IOError as e:
            if e.errno != ENOENT:
                raise
            if f in required:
                missing.append(f)

    if len(missing):
        raise ValueError(
            'Missing required files: {files}'.format(files=','.join(missing)))

    return ret


def read_meminfo(meminfo="/proc/meminfo", raw=False):
    # read a /proc/meminfo style file and return
    # a dict with 'total', 'free', and 'available'
    mpliers = {'kB': 2 ** 10, 'mB': 2 ** 20, 'B': 1, 'gB': 2 ** 30}
    kmap = {'MemTotal:': 'total', 'MemFree:': 'free',
            'MemAvailable:': 'available'}
    ret = {}
    for line in load_file(meminfo).splitlines():
        try:
            key, value, unit = line.split()
        except ValueError:
            key, value = line.split()
            unit = 'B'
        if raw:
            ret[key] = int(value) * mpliers[unit]
        elif key in kmap:
            ret[kmap[key]] = int(value) * mpliers[unit]

    return ret


def human2bytes(size):
    """Convert human string or integer to size in bytes
      10M => 10485760
      .5G => 536870912
    """
    size_in = size
    if size.endswith("B"):
        size = size[:-1]

    mpliers = {'B': 1, 'K': 2 ** 10, 'M': 2 ** 20, 'G': 2 ** 30, 'T': 2 ** 40}

    num = size
    mplier = 'B'
    for m in mpliers:
        if size.endswith(m):
            mplier = m
            num = size[0:-len(m)]

    try:
        num = float(num)
    except ValueError:
        raise ValueError("'%s' is not valid input." % size_in)

    if num < 0:
        raise ValueError("'%s': cannot be negative" % size_in)

    return int(num * mpliers[mplier])


def _read_dmi_syspath(key):
    """
    Reads dmi data with from /sys/class/dmi/id
    """
    if key not in DMIDECODE_TO_DMI_SYS_MAPPING:
        return None
    mapped_key = DMIDECODE_TO_DMI_SYS_MAPPING[key]
    dmi_key_path = "{0}/{1}".format(DMI_SYS_PATH, mapped_key)
    LOG.debug("querying dmi data %s", dmi_key_path)
    try:
        if not os.path.exists(dmi_key_path):
            LOG.debug("did not find %s", dmi_key_path)
            return None

        key_data = load_file(dmi_key_path, decode=False)
        if not key_data:
            LOG.debug("%s did not return any data", dmi_key_path)
            return None

        # uninitialized dmi values show as all \xff and /sys appends a '\n'.
        # in that event, return a string of '.' in the same length.
        if key_data == b'\xff' * (len(key_data) - 1) + b'\n':
            key_data = b""

        str_data = key_data.decode('utf8').strip()
        LOG.debug("dmi data %s returned %s", dmi_key_path, str_data)
        return str_data

    except Exception:
        logexc(LOG, "failed read of %s", dmi_key_path)
        return None


def _call_dmidecode(key, dmidecode_path):
    """
    Calls out to dmidecode to get the data out. This is mostly for supporting
    OS's without /sys/class/dmi/id support.
    """
    try:
        cmd = [dmidecode_path, "--string", key]
        (result, _err) = subp(cmd)
        result = result.strip()
        LOG.debug("dmidecode returned '%s' for '%s'", result, key)
        if result.replace(".", "") == "":
            return ""
        return result
    except (IOError, OSError) as e:
        LOG.debug('failed dmidecode cmd: %s\n%s', cmd, e)
        return None


def is_x86(uname_arch=None):
    """Return True if platform is x86-based"""
    if uname_arch is None:
        uname_arch = os.uname()[4]
    x86_arch_match = (
        uname_arch == 'x86_64' or
        (uname_arch[0] == 'i' and uname_arch[2:] == '86'))
    return x86_arch_match


def read_dmi_data(key):
    """
    Wrapper for reading DMI data.

    If running in a container return None.  This is because DMI data is
    assumed to be not useful in a container as it does not represent the
    container but rather the host.

    This will do the following (returning the first that produces a
    result):
        1) Use a mapping to translate `key` from dmidecode naming to
           sysfs naming and look in /sys/class/dmi/... for a value.
        2) Use `key` as a sysfs key directly and look in /sys/class/dmi/...
        3) Fall-back to passing `key` to `dmidecode --string`.

    If all of the above fail to find a value, None will be returned.
    """

    if is_container():
        return None

    syspath_value = _read_dmi_syspath(key)
    if syspath_value is not None:
        return syspath_value

    # running dmidecode can be problematic on some arches (LP: #1243287)
    uname_arch = os.uname()[4]
    if not (is_x86(uname_arch) or
            uname_arch == 'aarch64' or
            uname_arch == 'amd64'):
        LOG.debug("dmidata is not supported on %s", uname_arch)
        return None

    dmidecode_path = which('dmidecode')
    if dmidecode_path:
        return _call_dmidecode(key, dmidecode_path)

    LOG.warning("did not find either path %s or dmidecode command",
                DMI_SYS_PATH)
    return None


def message_from_string(string):
    if sys.version_info[:2] < (2, 7):
        return email.message_from_file(io.StringIO(string))
    return email.message_from_string(string)


def get_installed_packages(target=None):
    (out, _) = subp(['dpkg-query', '--list'], target=target, capture=True)

    pkgs_inst = set()
    for line in out.splitlines():
        try:
            (state, pkg, _) = line.split(None, 2)
        except ValueError:
            continue
        if state.startswith("hi") or state.startswith("ii"):
            pkgs_inst.add(re.sub(":.*", "", pkg))

    return pkgs_inst


def system_is_snappy():
    # channel.ini is configparser loadable.
    # snappy will move to using /etc/system-image/config.d/*.ini
    # this is certainly not a perfect test, but good enough for now.
    orpath = "/etc/os-release"
    try:
        orinfo = load_shell_content(load_file(orpath, quiet=True))
        if orinfo.get('ID', '').lower() == "ubuntu-core":
            return True
    except ValueError as e:
        LOG.warning("Unexpected error loading '%s': %s", orpath, e)

    cmdline = get_cmdline()
    if 'snap_core=' in cmdline:
        return True

    content = load_file("/etc/system-image/channel.ini", quiet=True)
    if 'ubuntu-core' in content.lower():
        return True
    if os.path.isdir("/etc/system-image/config.d/"):
        return True
    return False


def indent(text, prefix):
    """replacement for indent from textwrap that is not available in 2.7."""
    lines = []
    for line in text.splitlines(True):
        lines.append(prefix + line)
    return ''.join(lines)


def rootdev_from_cmdline(cmdline):
    found = None
    for tok in cmdline.split():
        if tok.startswith("root="):
            found = tok[5:]
            break
    if found is None:
        return None

    if found.startswith("/dev/"):
        return found
    if found.startswith("LABEL="):
        return "/dev/disk/by-label/" + found[len("LABEL="):]
    if found.startswith("UUID="):
        return "/dev/disk/by-uuid/" + found[len("UUID="):].lower()
    if found.startswith("PARTUUID="):
        disks_path = ("/dev/disk/by-partuuid/" +
                      found[len("PARTUUID="):].lower())
        if os.path.exists(disks_path):
            return disks_path
        results = find_devs_with(found)
        if results:
            return results[0]
        # we know this doesn't exist, but for consistency return the path as
        # it /would/ exist
        return disks_path

    return "/dev/" + found


def load_shell_content(content, add_empty=False, empty_val=None):
    """Given shell like syntax (key=value\nkey2=value2\n) in content
       return the data in dictionary form.  If 'add_empty' is True
       then add entries in to the returned dictionary for 'VAR='
       variables.  Set their value to empty_val."""

    def _shlex_split(blob):
        return shlex.split(blob, comments=True)

    data = {}
    for line in _shlex_split(content):
        key, value = line.split("=", 1)
        if not value:
            value = empty_val
        if add_empty or value:
            data[key] = value

    return data


def wait_for_files(flist, maxwait, naplen=.5, log_pre=""):
    need = set(flist)
    waited = 0
    while True:
        need -= set([f for f in need if os.path.exists(f)])
        if len(need) == 0:
            LOG.debug("%sAll files appeared after %s seconds: %s",
                      log_pre, waited, flist)
            return []
        if waited == 0:
            LOG.debug("%sWaiting up to %s seconds for the following files: %s",
                      log_pre, maxwait, flist)
        if waited + naplen > maxwait:
            break
        time.sleep(naplen)
        waited += naplen

    LOG.debug("%sStill missing files after %s seconds: %s",
              log_pre, maxwait, need)
    return need


def mount_is_read_write(mount_point):
    """Check whether the given mount point is mounted rw"""
    result = get_mount_info(mount_point, get_mnt_opts=True)
    mount_opts = result[-1].split(',')
    return mount_opts[0] == 'rw'


def udevadm_settle(exists=None, timeout=None):
    """Invoke udevadm settle with optional exists and timeout parameters"""
    settle_cmd = ["udevadm", "settle"]
    if exists:
        # skip the settle if the requested path already exists
        if os.path.exists(exists):
            return
        settle_cmd.extend(['--exit-if-exists=%s' % exists])
    if timeout:
        settle_cmd.extend(['--timeout=%s' % timeout])

    return subp(settle_cmd)


def get_proc_ppid(pid):
    """
    Return the parent pid of a process.
    """
    ppid = 0
    try:
        contents = load_file("/proc/%s/stat" % pid, quiet=True)
    except IOError as e:
        LOG.warning('Failed to load /proc/%s/stat. %s', pid, e)
    if contents:
        parts = contents.split(" ", 4)
        # man proc says
        #  ppid %d     (4) The PID of the parent.
        ppid = int(parts[3])
    return ppid

# vi: ts=4 expandtab