summaryrefslogtreecommitdiff
path: root/tests/unittests/test_net.py
blob: 0f45dc388b2e891c69f984a8c107b805d3a62219 (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
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
# This file is part of cloud-init. See LICENSE file for license information.

from cloudinit import net
from cloudinit import distros
from cloudinit.net import cmdline
from cloudinit.net import (
    eni, interface_has_own_mac, natural_sort_key, netplan, network_state,
    renderers, sysconfig)
from cloudinit.sources.helpers import openstack
from cloudinit import temp_utils
from cloudinit import util
from cloudinit import safeyaml as yaml

from cloudinit.tests.helpers import (
    CiTestCase, FilesystemMockingTestCase, dir2dict, mock, populate_dir)

import base64
import copy
import gzip
import io
import json
import os
import re
import textwrap
from yaml.serializer import Serializer


DHCP_CONTENT_1 = """
DEVICE='eth0'
PROTO='dhcp'
IPV4ADDR='192.168.122.89'
IPV4BROADCAST='192.168.122.255'
IPV4NETMASK='255.255.255.0'
IPV4GATEWAY='192.168.122.1'
IPV4DNS0='192.168.122.1'
IPV4DNS1='0.0.0.0'
HOSTNAME='foohost'
DNSDOMAIN=''
NISDOMAIN=''
ROOTSERVER='192.168.122.1'
ROOTPATH=''
filename=''
UPTIME='21'
DHCPLEASETIME='3600'
DOMAINSEARCH='foo.com'
"""

DHCP_EXPECTED_1 = {
    'name': 'eth0',
    'type': 'physical',
    'subnets': [{'broadcast': '192.168.122.255',
                 'control': 'manual',
                 'gateway': '192.168.122.1',
                 'dns_search': ['foo.com'],
                 'type': 'dhcp',
                 'netmask': '255.255.255.0',
                 'dns_nameservers': ['192.168.122.1']}],
}

DHCP6_CONTENT_1 = """
DEVICE6=eno1
HOSTNAME=
DNSDOMAIN=
IPV6PROTO=dhcp6
IPV6ADDR=2001:67c:1562:8010:0:1::
IPV6NETMASK=64
IPV6DNS0=2001:67c:1562:8010::2:1
IPV6DOMAINSEARCH=
HOSTNAME=
DNSDOMAIN=
"""

DHCP6_EXPECTED_1 = {
    'name': 'eno1',
    'type': 'physical',
    'subnets': [{'control': 'manual',
                 'dns_nameservers': ['2001:67c:1562:8010::2:1'],
                 'netmask': '64',
                 'type': 'dhcp6'}]}


STATIC_CONTENT_1 = """
DEVICE='eth1'
PROTO='static'
IPV4ADDR='10.0.0.2'
IPV4BROADCAST='10.0.0.255'
IPV4NETMASK='255.255.255.0'
IPV4GATEWAY='10.0.0.1'
IPV4DNS0='10.0.1.1'
IPV4DNS1='0.0.0.0'
HOSTNAME='foohost'
UPTIME='21'
DHCPLEASETIME='3600'
DOMAINSEARCH='foo.com'
"""

STATIC_EXPECTED_1 = {
    'name': 'eth1',
    'type': 'physical',
    'subnets': [{'broadcast': '10.0.0.255', 'control': 'manual',
                 'gateway': '10.0.0.1',
                 'dns_search': ['foo.com'], 'type': 'static',
                 'netmask': '255.255.255.0',
                 'dns_nameservers': ['10.0.1.1'],
                 'address': '10.0.0.2'}],
}

V1_NAMESERVER_ALIAS = """
config:
-   id: eno1
    mac_address: 08:94:ef:51:ae:e0
    mtu: 1500
    name: eno1
    subnets:
    -   type: manual
    type: physical
-   id: eno2
    mac_address: 08:94:ef:51:ae:e1
    mtu: 1500
    name: eno2
    subnets:
    -   type: manual
    type: physical
-   id: eno3
    mac_address: 08:94:ef:51:ae:de
    mtu: 1500
    name: eno3
    subnets:
    -   type: manual
    type: physical
-   bond_interfaces:
    - eno1
    - eno3
    id: bondM
    mac_address: 08:94:ef:51:ae:e0
    mtu: 1500
    name: bondM
    params:
        bond-downdelay: 0
        bond-lacp-rate: fast
        bond-miimon: 100
        bond-mode: 802.3ad
        bond-updelay: 0
        bond-xmit-hash-policy: layer3+4
    subnets:
    -   address: 10.101.10.47/23
        gateway: 10.101.11.254
        type: static
    type: bond
-   id: eno4
    mac_address: 08:94:ef:51:ae:df
    mtu: 1500
    name: eno4
    subnets:
    -   type: manual
    type: physical
-   id: enp0s20f0u1u6
    mac_address: 0a:94:ef:51:a4:b9
    mtu: 1500
    name: enp0s20f0u1u6
    subnets:
    -   type: manual
    type: physical
-   id: enp216s0f0
    mac_address: 68:05:ca:81:7c:e8
    mtu: 9000
    name: enp216s0f0
    subnets:
    -   type: manual
    type: physical
-   id: enp216s0f1
    mac_address: 68:05:ca:81:7c:e9
    mtu: 9000
    name: enp216s0f1
    subnets:
    -   type: manual
    type: physical
-   id: enp47s0f0
    mac_address: 68:05:ca:64:d3:6c
    mtu: 9000
    name: enp47s0f0
    subnets:
    -   type: manual
    type: physical
-   bond_interfaces:
    - enp216s0f0
    - enp47s0f0
    id: bond0
    mac_address: 68:05:ca:64:d3:6c
    mtu: 9000
    name: bond0
    params:
        bond-downdelay: 0
        bond-lacp-rate: fast
        bond-miimon: 100
        bond-mode: 802.3ad
        bond-updelay: 0
        bond-xmit-hash-policy: layer3+4
    subnets:
    -   type: manual
    type: bond
-   id: bond0.3502
    mtu: 9000
    name: bond0.3502
    subnets:
    -   address: 172.20.80.4/25
        type: static
    type: vlan
    vlan_id: 3502
    vlan_link: bond0
-   id: bond0.3503
    mtu: 9000
    name: bond0.3503
    subnets:
    -   address: 172.20.80.129/25
        type: static
    type: vlan
    vlan_id: 3503
    vlan_link: bond0
-   id: enp47s0f1
    mac_address: 68:05:ca:64:d3:6d
    mtu: 9000
    name: enp47s0f1
    subnets:
    -   type: manual
    type: physical
-   bond_interfaces:
    - enp216s0f1
    - enp47s0f1
    id: bond1
    mac_address: 68:05:ca:64:d3:6d
    mtu: 9000
    name: bond1
    params:
        bond-downdelay: 0
        bond-lacp-rate: fast
        bond-miimon: 100
        bond-mode: 802.3ad
        bond-updelay: 0
        bond-xmit-hash-policy: layer3+4
    subnets:
    -   address: 10.101.8.65/26
        routes:
        -   destination: 213.119.192.0/24
            gateway: 10.101.8.126
            metric: 0
        type: static
    type: bond
-   address:
    - 10.101.10.1
    - 10.101.10.2
    - 10.101.10.3
    - 10.101.10.5
    search:
    - foo.bar
    - maas
    type: nameserver
version: 1
"""

NETPLAN_NO_ALIAS = """
network:
    version: 2
    ethernets:
        eno1:
            match:
                macaddress: 08:94:ef:51:ae:e0
            mtu: 1500
            set-name: eno1
        eno2:
            match:
                macaddress: 08:94:ef:51:ae:e1
            mtu: 1500
            set-name: eno2
        eno3:
            match:
                macaddress: 08:94:ef:51:ae:de
            mtu: 1500
            set-name: eno3
        eno4:
            match:
                macaddress: 08:94:ef:51:ae:df
            mtu: 1500
            set-name: eno4
        enp0s20f0u1u6:
            match:
                macaddress: 0a:94:ef:51:a4:b9
            mtu: 1500
            set-name: enp0s20f0u1u6
        enp216s0f0:
            match:
                macaddress: 68:05:ca:81:7c:e8
            mtu: 9000
            set-name: enp216s0f0
        enp216s0f1:
            match:
                macaddress: 68:05:ca:81:7c:e9
            mtu: 9000
            set-name: enp216s0f1
        enp47s0f0:
            match:
                macaddress: 68:05:ca:64:d3:6c
            mtu: 9000
            set-name: enp47s0f0
        enp47s0f1:
            match:
                macaddress: 68:05:ca:64:d3:6d
            mtu: 9000
            set-name: enp47s0f1
    bonds:
        bond0:
            interfaces:
            - enp216s0f0
            - enp47s0f0
            macaddress: 68:05:ca:64:d3:6c
            mtu: 9000
            parameters:
                down-delay: 0
                lacp-rate: fast
                mii-monitor-interval: 100
                mode: 802.3ad
                transmit-hash-policy: layer3+4
                up-delay: 0
        bond1:
            addresses:
            - 10.101.8.65/26
            interfaces:
            - enp216s0f1
            - enp47s0f1
            macaddress: 68:05:ca:64:d3:6d
            mtu: 9000
            nameservers:
                addresses:
                - 10.101.10.1
                - 10.101.10.2
                - 10.101.10.3
                - 10.101.10.5
                search:
                - foo.bar
                - maas
            parameters:
                down-delay: 0
                lacp-rate: fast
                mii-monitor-interval: 100
                mode: 802.3ad
                transmit-hash-policy: layer3+4
                up-delay: 0
            routes:
            -   metric: 0
                to: 213.119.192.0/24
                via: 10.101.8.126
        bondM:
            addresses:
            - 10.101.10.47/23
            gateway4: 10.101.11.254
            interfaces:
            - eno1
            - eno3
            macaddress: 08:94:ef:51:ae:e0
            mtu: 1500
            nameservers:
                addresses:
                - 10.101.10.1
                - 10.101.10.2
                - 10.101.10.3
                - 10.101.10.5
                search:
                - foo.bar
                - maas
            parameters:
                down-delay: 0
                lacp-rate: fast
                mii-monitor-interval: 100
                mode: 802.3ad
                transmit-hash-policy: layer3+4
                up-delay: 0
    vlans:
        bond0.3502:
            addresses:
            - 172.20.80.4/25
            id: 3502
            link: bond0
            mtu: 9000
            nameservers:
                addresses:
                - 10.101.10.1
                - 10.101.10.2
                - 10.101.10.3
                - 10.101.10.5
                search:
                - foo.bar
                - maas
        bond0.3503:
            addresses:
            - 172.20.80.129/25
            id: 3503
            link: bond0
            mtu: 9000
            nameservers:
                addresses:
                - 10.101.10.1
                - 10.101.10.2
                - 10.101.10.3
                - 10.101.10.5
                search:
                - foo.bar
                - maas
"""

NETPLAN_BOND_GRAT_ARP = """
network:
    bonds:
        bond0:
            interfaces:
            - ens3
            macaddress: 68:05:ca:64:d3:6c
            mtu: 9000
            parameters:
                gratuitious-arp: 1
        bond1:
            interfaces:
            - ens4
            macaddress: 68:05:ca:64:d3:6d
            mtu: 9000
            parameters:
                gratuitous-arp: 2
    ethernets:
        ens3:
            dhcp4: false
            dhcp6: false
            match:
                macaddress: 52:54:00:ab:cd:ef
        ens4:
            dhcp4: false
            dhcp6: false
            match:
                macaddress: 52:54:00:11:22:ff
    version: 2
"""

NETPLAN_DHCP_FALSE = """
version: 2
ethernets:
  ens3:
    match:
      macaddress: 52:54:00:ab:cd:ef
    dhcp4: false
    dhcp6: false
    addresses:
      - 192.168.42.100/24
      - 2001:db8::100/32
    gateway4: 192.168.42.1
    gateway6: 2001:db8::1
    nameservers:
      search: [example.com]
      addresses: [192.168.42.53, 1.1.1.1]
"""

# Examples (and expected outputs for various renderers).
OS_SAMPLES = [
    {
        'in_data': {
            "services": [{"type": "dns", "address": "172.19.0.12"}],
            "networks": [{
                "network_id": "dacd568d-5be6-4786-91fe-750c374b78b4",
                "type": "ipv4", "netmask": "255.255.252.0",
                "link": "tap1a81968a-79",
                "routes": [{
                    "netmask": "0.0.0.0",
                    "network": "0.0.0.0",
                    "gateway": "172.19.3.254",
                }],
                "ip_address": "172.19.1.34", "id": "network0"
            }],
            "links": [
                {
                    "ethernet_mac_address": "fa:16:3e:ed:9a:59",
                    "mtu": None, "type": "bridge", "id":
                    "tap1a81968a-79",
                    "vif_id": "1a81968a-797a-400f-8a80-567f997eb93f"
                },
            ],
        },
        'in_macs': {
            'fa:16:3e:ed:9a:59': 'eth0',
        },
        'out_sysconfig_opensuse': [
            ('etc/sysconfig/network/ifcfg-eth0',
             """
# Created by cloud-init on instance boot automatically, do not edit.
#
BOOTPROTO=none
DEFROUTE=yes
DEVICE=eth0
GATEWAY=172.19.3.254
HWADDR=fa:16:3e:ed:9a:59
IPADDR=172.19.1.34
NETMASK=255.255.252.0
NM_CONTROLLED=no
ONBOOT=yes
STARTMODE=auto
TYPE=Ethernet
USERCTL=no
""".lstrip()),
            ('etc/resolv.conf',
             """
; Created by cloud-init on instance boot automatically, do not edit.
;
nameserver 172.19.0.12
""".lstrip()),
            ('etc/NetworkManager/conf.d/99-cloud-init.conf',
             """
# Created by cloud-init on instance boot automatically, do not edit.
#
[main]
dns = none
""".lstrip()),
            ('etc/udev/rules.d/85-persistent-net-cloud-init.rules',
             "".join(['SUBSYSTEM=="net", ACTION=="add", DRIVERS=="?*", ',
                      'ATTR{address}=="fa:16:3e:ed:9a:59", NAME="eth0"\n']))],
        'out_sysconfig_rhel': [
            ('etc/sysconfig/network-scripts/ifcfg-eth0',
             """
# Created by cloud-init on instance boot automatically, do not edit.
#
BOOTPROTO=none
DEFROUTE=yes
DEVICE=eth0
GATEWAY=172.19.3.254
HWADDR=fa:16:3e:ed:9a:59
IPADDR=172.19.1.34
NETMASK=255.255.252.0
NM_CONTROLLED=no
ONBOOT=yes
STARTMODE=auto
TYPE=Ethernet
USERCTL=no
""".lstrip()),
            ('etc/resolv.conf',
             """
; Created by cloud-init on instance boot automatically, do not edit.
;
nameserver 172.19.0.12
""".lstrip()),
            ('etc/NetworkManager/conf.d/99-cloud-init.conf',
             """
# Created by cloud-init on instance boot automatically, do not edit.
#
[main]
dns = none
""".lstrip()),
            ('etc/udev/rules.d/70-persistent-net.rules',
             "".join(['SUBSYSTEM=="net", ACTION=="add", DRIVERS=="?*", ',
                      'ATTR{address}=="fa:16:3e:ed:9a:59", NAME="eth0"\n']))]

    },
    {
        'in_data': {
            "services": [{"type": "dns", "address": "172.19.0.12"}],
            "networks": [{
                "network_id": "public-ipv4",
                "type": "ipv4", "netmask": "255.255.252.0",
                "link": "tap1a81968a-79",
                "routes": [{
                    "netmask": "0.0.0.0",
                    "network": "0.0.0.0",
                    "gateway": "172.19.3.254",
                }],
                "ip_address": "172.19.1.34", "id": "network0"
            }, {
                "network_id": "private-ipv4",
                "type": "ipv4", "netmask": "255.255.255.0",
                "link": "tap1a81968a-79",
                "routes": [],
                "ip_address": "10.0.0.10", "id": "network1"
            }],
            "links": [
                {
                    "ethernet_mac_address": "fa:16:3e:ed:9a:59",
                    "mtu": None, "type": "bridge", "id":
                    "tap1a81968a-79",
                    "vif_id": "1a81968a-797a-400f-8a80-567f997eb93f"
                },
            ],
        },
        'in_macs': {
            'fa:16:3e:ed:9a:59': 'eth0',
        },
        'out_sysconfig_opensuse': [
            ('etc/sysconfig/network/ifcfg-eth0',
             """
# Created by cloud-init on instance boot automatically, do not edit.
#
BOOTPROTO=none
DEFROUTE=yes
DEVICE=eth0
GATEWAY=172.19.3.254
HWADDR=fa:16:3e:ed:9a:59
IPADDR=172.19.1.34
IPADDR1=10.0.0.10
NETMASK=255.255.252.0
NETMASK1=255.255.255.0
NM_CONTROLLED=no
ONBOOT=yes
STARTMODE=auto
TYPE=Ethernet
USERCTL=no
""".lstrip()),
            ('etc/resolv.conf',
             """
; Created by cloud-init on instance boot automatically, do not edit.
;
nameserver 172.19.0.12
""".lstrip()),
            ('etc/NetworkManager/conf.d/99-cloud-init.conf',
             """
# Created by cloud-init on instance boot automatically, do not edit.
#
[main]
dns = none
""".lstrip()),
            ('etc/udev/rules.d/85-persistent-net-cloud-init.rules',
             "".join(['SUBSYSTEM=="net", ACTION=="add", DRIVERS=="?*", ',
                      'ATTR{address}=="fa:16:3e:ed:9a:59", NAME="eth0"\n']))],
        'out_sysconfig_rhel': [
            ('etc/sysconfig/network-scripts/ifcfg-eth0',
             """
# Created by cloud-init on instance boot automatically, do not edit.
#
BOOTPROTO=none
DEFROUTE=yes
DEVICE=eth0
GATEWAY=172.19.3.254
HWADDR=fa:16:3e:ed:9a:59
IPADDR=172.19.1.34
IPADDR1=10.0.0.10
NETMASK=255.255.252.0
NETMASK1=255.255.255.0
NM_CONTROLLED=no
ONBOOT=yes
STARTMODE=auto
TYPE=Ethernet
USERCTL=no
""".lstrip()),
            ('etc/resolv.conf',
             """
; Created by cloud-init on instance boot automatically, do not edit.
;
nameserver 172.19.0.12
""".lstrip()),
            ('etc/NetworkManager/conf.d/99-cloud-init.conf',
             """
# Created by cloud-init on instance boot automatically, do not edit.
#
[main]
dns = none
""".lstrip()),
            ('etc/udev/rules.d/70-persistent-net.rules',
             "".join(['SUBSYSTEM=="net", ACTION=="add", DRIVERS=="?*", ',
                      'ATTR{address}=="fa:16:3e:ed:9a:59", NAME="eth0"\n']))]

    },
    {
        'in_data': {
            "services": [{"type": "dns", "address": "172.19.0.12"}],
            "networks": [{
                "network_id": "public-ipv4",
                "type": "ipv4", "netmask": "255.255.252.0",
                "link": "tap1a81968a-79",
                "routes": [{
                    "netmask": "0.0.0.0",
                    "network": "0.0.0.0",
                    "gateway": "172.19.3.254",
                }],
                "ip_address": "172.19.1.34", "id": "network0"
            }, {
                "network_id": "public-ipv6-a",
                "type": "ipv6", "netmask": "",
                "link": "tap1a81968a-79",
                "routes": [
                    {
                        "gateway": "2001:DB8::1",
                        "netmask": "::",
                        "network": "::"
                    }
                ],
                "ip_address": "2001:DB8::10", "id": "network1"
            }, {
                "network_id": "public-ipv6-b",
                "type": "ipv6", "netmask": "64",
                "link": "tap1a81968a-79",
                "routes": [
                ],
                "ip_address": "2001:DB9::10", "id": "network2"
            }, {
                "network_id": "public-ipv6-c",
                "type": "ipv6", "netmask": "64",
                "link": "tap1a81968a-79",
                "routes": [
                ],
                "ip_address": "2001:DB10::10", "id": "network3"
            }],
            "links": [
                {
                    "ethernet_mac_address": "fa:16:3e:ed:9a:59",
                    "mtu": None, "type": "bridge", "id":
                    "tap1a81968a-79",
                    "vif_id": "1a81968a-797a-400f-8a80-567f997eb93f"
                },
            ],
        },
        'in_macs': {
            'fa:16:3e:ed:9a:59': 'eth0',
        },
        'out_sysconfig_opensuse': [
            ('etc/sysconfig/network/ifcfg-eth0',
             """
# Created by cloud-init on instance boot automatically, do not edit.
#
BOOTPROTO=none
DEFROUTE=yes
DEVICE=eth0
GATEWAY=172.19.3.254
HWADDR=fa:16:3e:ed:9a:59
IPADDR=172.19.1.34
IPADDR6=2001:DB8::10/64
IPADDR6_0=2001:DB9::10/64
IPADDR6_2=2001:DB10::10/64
IPV6ADDR=2001:DB8::10/64
IPV6ADDR_SECONDARIES="2001:DB9::10/64 2001:DB10::10/64"
IPV6INIT=yes
IPV6_DEFAULTGW=2001:DB8::1
NETMASK=255.255.252.0
NM_CONTROLLED=no
ONBOOT=yes
STARTMODE=auto
TYPE=Ethernet
USERCTL=no
""".lstrip()),
            ('etc/resolv.conf',
             """
; Created by cloud-init on instance boot automatically, do not edit.
;
nameserver 172.19.0.12
""".lstrip()),
            ('etc/NetworkManager/conf.d/99-cloud-init.conf',
             """
# Created by cloud-init on instance boot automatically, do not edit.
#
[main]
dns = none
""".lstrip()),
            ('etc/udev/rules.d/85-persistent-net-cloud-init.rules',
             "".join(['SUBSYSTEM=="net", ACTION=="add", DRIVERS=="?*", ',
                      'ATTR{address}=="fa:16:3e:ed:9a:59", NAME="eth0"\n']))],
        'out_sysconfig_rhel': [
            ('etc/sysconfig/network-scripts/ifcfg-eth0',
             """
# Created by cloud-init on instance boot automatically, do not edit.
#
BOOTPROTO=none
DEFROUTE=yes
DEVICE=eth0
GATEWAY=172.19.3.254
HWADDR=fa:16:3e:ed:9a:59
IPADDR=172.19.1.34
IPADDR6=2001:DB8::10/64
IPADDR6_0=2001:DB9::10/64
IPADDR6_2=2001:DB10::10/64
IPV6ADDR=2001:DB8::10/64
IPV6ADDR_SECONDARIES="2001:DB9::10/64 2001:DB10::10/64"
IPV6INIT=yes
IPV6_DEFAULTGW=2001:DB8::1
NETMASK=255.255.252.0
NM_CONTROLLED=no
ONBOOT=yes
STARTMODE=auto
TYPE=Ethernet
USERCTL=no
""".lstrip()),
            ('etc/resolv.conf',
             """
; Created by cloud-init on instance boot automatically, do not edit.
;
nameserver 172.19.0.12
""".lstrip()),
            ('etc/NetworkManager/conf.d/99-cloud-init.conf',
             """
# Created by cloud-init on instance boot automatically, do not edit.
#
[main]
dns = none
""".lstrip()),
            ('etc/udev/rules.d/70-persistent-net.rules',
             "".join(['SUBSYSTEM=="net", ACTION=="add", DRIVERS=="?*", ',
                      'ATTR{address}=="fa:16:3e:ed:9a:59", NAME="eth0"\n']))]
    }
]

EXAMPLE_ENI = """
auto lo
iface lo inet loopback
   dns-nameservers 10.0.0.1
   dns-search foo.com

auto eth0
iface eth0 inet static
        address 1.2.3.12
        netmask 255.255.255.248
        broadcast 1.2.3.15
        gateway 1.2.3.9
        dns-nameservers 69.9.160.191 69.9.191.4
auto eth1
iface eth1 inet static
        address 10.248.2.4
        netmask 255.255.255.248
        broadcast 10.248.2.7
"""

RENDERED_ENI = """
auto lo
iface lo inet loopback
    dns-nameservers 10.0.0.1
    dns-search foo.com

auto eth0
iface eth0 inet static
    address 1.2.3.12/29
    broadcast 1.2.3.15
    dns-nameservers 69.9.160.191 69.9.191.4
    gateway 1.2.3.9

auto eth1
iface eth1 inet static
    address 10.248.2.4/29
    broadcast 10.248.2.7
""".lstrip()

NETWORK_CONFIGS = {
    'small': {
        'expected_eni': textwrap.dedent("""\
            auto lo
            iface lo inet loopback
                dns-nameservers 1.2.3.4 5.6.7.8
                dns-search wark.maas

            iface eth1 inet manual

            auto eth99
            iface eth99 inet dhcp

            # control-alias eth99
            iface eth99 inet static
                address 192.168.21.3/24
                dns-nameservers 8.8.8.8 8.8.4.4
                dns-search barley.maas sach.maas
                post-up route add default gw 65.61.151.37 metric 10000 || true
                pre-down route del default gw 65.61.151.37 metric 10000 || true
        """).rstrip(' '),
        'expected_netplan': textwrap.dedent("""
            network:
                version: 2
                ethernets:
                    eth1:
                        match:
                            macaddress: cf:d6:af:48:e8:80
                        set-name: eth1
                    eth99:
                        addresses:
                        - 192.168.21.3/24
                        dhcp4: true
                        match:
                            macaddress: c0:d6:9f:2c:e8:80
                        nameservers:
                            addresses:
                            - 8.8.8.8
                            - 8.8.4.4
                            search:
                            - barley.maas
                            - sach.maas
                        routes:
                        -   metric: 10000
                            to: 0.0.0.0/0
                            via: 65.61.151.37
                        set-name: eth99
        """).rstrip(' '),
        'expected_sysconfig': {
            'ifcfg-eth1': textwrap.dedent("""\
                BOOTPROTO=none
                DEVICE=eth1
                HWADDR=cf:d6:af:48:e8:80
                NM_CONTROLLED=no
                ONBOOT=yes
                STARTMODE=auto
                TYPE=Ethernet
                USERCTL=no"""),
            'ifcfg-eth99': textwrap.dedent("""\
                BOOTPROTO=dhcp
                DEFROUTE=yes
                DEVICE=eth99
                DHCLIENT_SET_DEFAULT_ROUTE=yes
                DNS1=8.8.8.8
                DNS2=8.8.4.4
                DOMAIN="barley.maas sach.maas"
                GATEWAY=65.61.151.37
                HWADDR=c0:d6:9f:2c:e8:80
                IPADDR=192.168.21.3
                NETMASK=255.255.255.0
                METRIC=10000
                NM_CONTROLLED=no
                ONBOOT=yes
                STARTMODE=auto
                TYPE=Ethernet
                USERCTL=no"""),
        },
        'yaml': textwrap.dedent("""
            version: 1
            config:
                # Physical interfaces.
                - type: physical
                  name: eth99
                  mac_address: "c0:d6:9f:2c:e8:80"
                  subnets:
                      - type: dhcp4
                      - type: static
                        address: 192.168.21.3/24
                        dns_nameservers:
                          - 8.8.8.8
                          - 8.8.4.4
                        dns_search: barley.maas sach.maas
                        routes:
                          - gateway: 65.61.151.37
                            netmask: 0.0.0.0
                            network: 0.0.0.0
                            metric: 10000
                - type: physical
                  name: eth1
                  mac_address: "cf:d6:af:48:e8:80"
                - type: nameserver
                  address:
                    - 1.2.3.4
                    - 5.6.7.8
                  search:
                    - wark.maas
        """),
    },
    'v4_and_v6': {
        'expected_eni': textwrap.dedent("""\
            auto lo
            iface lo inet loopback

            auto iface0
            iface iface0 inet dhcp

            # control-alias iface0
            iface iface0 inet6 dhcp
        """).rstrip(' '),
        'expected_netplan': textwrap.dedent("""
            network:
                version: 2
                ethernets:
                    iface0:
                        dhcp4: true
                        dhcp6: true
        """).rstrip(' '),
        'yaml': textwrap.dedent("""\
            version: 1
            config:
              - type: 'physical'
                name: 'iface0'
                subnets:
                - {'type': 'dhcp4'}
                - {'type': 'dhcp6'}
        """).rstrip(' '),
    },
    'v4_and_v6_static': {
        'expected_eni': textwrap.dedent("""\
            auto lo
            iface lo inet loopback

            auto iface0
            iface iface0 inet static
                address 192.168.14.2/24
                mtu 9000

            # control-alias iface0
            iface iface0 inet6 static
                address 2001:1::1/64
                mtu 1500
        """).rstrip(' '),
        'expected_netplan': textwrap.dedent("""
            network:
                version: 2
                ethernets:
                    iface0:
                        addresses:
                        - 192.168.14.2/24
                        - 2001:1::1/64
                        ipv6-mtu: 1500
                        mtu: 9000
        """).rstrip(' '),
        'yaml': textwrap.dedent("""\
            version: 1
            config:
              - type: 'physical'
                name: 'iface0'
                mtu: 8999
                subnets:
                  - type: static
                    address: 192.168.14.2/24
                    mtu: 9000
                  - type: static
                    address: 2001:1::1/64
                    mtu: 1500
        """).rstrip(' '),
        'expected_sysconfig': {
            'ifcfg-iface0': textwrap.dedent("""\
                BOOTPROTO=none
                DEVICE=iface0
                IPADDR=192.168.14.2
                IPADDR6=2001:1::1/64
                IPV6ADDR=2001:1::1/64
                IPV6INIT=yes
                NETMASK=255.255.255.0
                NM_CONTROLLED=no
                ONBOOT=yes
                STARTMODE=auto
                TYPE=Ethernet
                USERCTL=no
                MTU=9000
                IPV6_MTU=1500
                """),
        },
    },
    'dhcpv6_only': {
        'expected_eni': textwrap.dedent("""\
            auto lo
            iface lo inet loopback

            auto iface0
            iface iface0 inet6 dhcp
        """).rstrip(' '),
        'expected_netplan': textwrap.dedent("""
            network:
                version: 2
                ethernets:
                    iface0:
                        dhcp6: true
        """).rstrip(' '),
        'yaml': textwrap.dedent("""\
            version: 1
            config:
              - type: 'physical'
                name: 'iface0'
                subnets:
                - {'type': 'dhcp6'}
        """).rstrip(' '),
        'expected_sysconfig': {
            'ifcfg-iface0': textwrap.dedent("""\
                BOOTPROTO=none
                DEVICE=iface0
                DHCPV6C=yes
                IPV6INIT=yes
                DEVICE=iface0
                NM_CONTROLLED=no
                ONBOOT=yes
                STARTMODE=auto
                TYPE=Ethernet
                USERCTL=no
                """),
        },
    },
    'dhcpv6_accept_ra': {
        'expected_eni': textwrap.dedent("""\
            auto lo
            iface lo inet loopback

            auto iface0
            iface iface0 inet6 dhcp
                accept_ra 1
        """).rstrip(' '),
        'expected_netplan': textwrap.dedent("""
            network:
                version: 2
                ethernets:
                    iface0:
                        accept-ra: true
                        dhcp6: true
        """).rstrip(' '),
        'yaml_v1': textwrap.dedent("""\
            version: 1
            config:
              - type: 'physical'
                name: 'iface0'
                subnets:
                - {'type': 'dhcp6'}
                accept-ra: true
        """).rstrip(' '),
        'yaml_v2': textwrap.dedent("""\
            version: 2
            ethernets:
                iface0:
                    dhcp6: true
                    accept-ra: true
        """).rstrip(' '),
        'expected_sysconfig': {
            'ifcfg-iface0': textwrap.dedent("""\
                BOOTPROTO=none
                DEVICE=iface0
                DHCPV6C=yes
                IPV6INIT=yes
                IPV6_FORCE_ACCEPT_RA=yes
                DEVICE=iface0
                NM_CONTROLLED=no
                ONBOOT=yes
                STARTMODE=auto
                TYPE=Ethernet
                USERCTL=no
            """),
        },
    },
    'dhcpv6_reject_ra': {
        'expected_eni': textwrap.dedent("""\
            auto lo
            iface lo inet loopback

            auto iface0
            iface iface0 inet6 dhcp
                accept_ra 0
        """).rstrip(' '),
        'expected_netplan': textwrap.dedent("""
            network:
                version: 2
                ethernets:
                    iface0:
                        accept-ra: false
                        dhcp6: true
        """).rstrip(' '),
        'yaml_v1': textwrap.dedent("""\
            version: 1
            config:
            - type: 'physical'
              name: 'iface0'
              subnets:
              - {'type': 'dhcp6'}
              accept-ra: false
        """).rstrip(' '),
        'yaml_v2': textwrap.dedent("""\
            version: 2
            ethernets:
                iface0:
                    dhcp6: true
                    accept-ra: false
        """).rstrip(' '),
        'expected_sysconfig': {
            'ifcfg-iface0': textwrap.dedent("""\
                BOOTPROTO=none
                DEVICE=iface0
                DHCPV6C=yes
                IPV6INIT=yes
                IPV6_FORCE_ACCEPT_RA=no
                DEVICE=iface0
                NM_CONTROLLED=no
                ONBOOT=yes
                STARTMODE=auto
                TYPE=Ethernet
                USERCTL=no
            """),
        },
    },
    'ipv6_slaac': {
        'expected_eni': textwrap.dedent("""\
            auto lo
            iface lo inet loopback

            auto iface0
            iface iface0 inet6 auto
                dhcp 0
        """).rstrip(' '),
        'expected_netplan': textwrap.dedent("""
            network:
                version: 2
                ethernets:
                    iface0:
                        dhcp6: true
        """).rstrip(' '),
        'yaml': textwrap.dedent("""\
            version: 1
            config:
            - type: 'physical'
              name: 'iface0'
              subnets:
              - {'type': 'ipv6_slaac'}
        """).rstrip(' '),
        'expected_sysconfig': {
            'ifcfg-iface0': textwrap.dedent("""\
                BOOTPROTO=none
                DEVICE=iface0
                IPV6_AUTOCONF=yes
                IPV6INIT=yes
                DEVICE=iface0
                NM_CONTROLLED=no
                ONBOOT=yes
                STARTMODE=auto
                TYPE=Ethernet
                USERCTL=no
            """),
        },
    },
    'dhcpv6_stateless': {
        'expected_eni': textwrap.dedent("""\
        auto lo
        iface lo inet loopback

        auto iface0
        iface iface0 inet6 auto
            dhcp 1
    """).rstrip(' '),
        'expected_netplan': textwrap.dedent("""
        network:
            version: 2
            ethernets:
                iface0:
                    dhcp6: true
    """).rstrip(' '),
        'yaml': textwrap.dedent("""\
        version: 1
        config:
          - type: 'physical'
            name: 'iface0'
            subnets:
            - {'type': 'ipv6_dhcpv6-stateless'}
    """).rstrip(' '),
        'expected_sysconfig': {
            'ifcfg-iface0': textwrap.dedent("""\
            BOOTPROTO=none
            DEVICE=iface0
            DHCPV6C=yes
            DHCPV6C_OPTIONS=-S
            IPV6_AUTOCONF=yes
            IPV6INIT=yes
            DEVICE=iface0
            NM_CONTROLLED=no
            ONBOOT=yes
            STARTMODE=auto
            TYPE=Ethernet
            USERCTL=no
            """),
        },
    },
    'dhcpv6_stateful': {
        'expected_eni': textwrap.dedent("""\
        auto lo
        iface lo inet loopback

        auto iface0
        iface iface0 inet6 dhcp
    """).rstrip(' '),
        'expected_netplan': textwrap.dedent("""
        network:
            version: 2
            ethernets:
                iface0:
                    accept-ra: true
                    dhcp6: true
    """).rstrip(' '),
        'yaml': textwrap.dedent("""\
        version: 1
        config:
          - type: 'physical'
            name: 'iface0'
            subnets:
            - {'type': 'ipv6_dhcpv6-stateful'}
            accept-ra: true
    """).rstrip(' '),
        'expected_sysconfig': {
            'ifcfg-iface0': textwrap.dedent("""\
            BOOTPROTO=none
            DEVICE=iface0
            DHCPV6C=yes
            IPV6INIT=yes
            IPV6_FORCE_ACCEPT_RA=yes
            DEVICE=iface0
            NM_CONTROLLED=no
            ONBOOT=yes
            STARTMODE=auto
            TYPE=Ethernet
            USERCTL=no
            """),
        },
    },
    'all': {
        'expected_eni': ("""\
auto lo
iface lo inet loopback
    dns-nameservers 8.8.8.8 4.4.4.4 8.8.4.4
    dns-search barley.maas wark.maas foobar.maas

iface eth0 inet manual

auto eth1
iface eth1 inet manual
    bond-master bond0
    bond-mode active-backup
    bond-xmit-hash-policy layer3+4
    bond_miimon 100

auto eth2
iface eth2 inet manual
    bond-master bond0
    bond-mode active-backup
    bond-xmit-hash-policy layer3+4
    bond_miimon 100

iface eth3 inet manual

iface eth4 inet manual

# control-manual eth5
iface eth5 inet dhcp

auto ib0
iface ib0 inet static
    address 192.168.200.7/24
    mtu 9000
    hwaddress a0:00:02:20:fe:80:00:00:00:00:00:00:ec:0d:9a:03:00:15:e2:c1

auto bond0
iface bond0 inet6 dhcp
    bond-mode active-backup
    bond-slaves none
    bond-xmit-hash-policy layer3+4
    bond_miimon 100
    hwaddress aa:bb:cc:dd:ee:ff

auto br0
iface br0 inet static
    address 192.168.14.2/24
    bridge_ageing 250
    bridge_bridgeprio 22
    bridge_fd 1
    bridge_gcint 2
    bridge_hello 1
    bridge_maxage 10
    bridge_pathcost eth3 50
    bridge_pathcost eth4 75
    bridge_portprio eth3 28
    bridge_portprio eth4 14
    bridge_ports eth3 eth4
    bridge_stp off
    bridge_waitport 1 eth3
    bridge_waitport 2 eth4
    hwaddress bb:bb:bb:bb:bb:aa

# control-alias br0
iface br0 inet6 static
    address 2001:1::1/64
    post-up route add -A inet6 default gw 2001:4800:78ff:1b::1 || true
    pre-down route del -A inet6 default gw 2001:4800:78ff:1b::1 || true

auto bond0.200
iface bond0.200 inet dhcp
    vlan-raw-device bond0
    vlan_id 200

auto eth0.101
iface eth0.101 inet static
    address 192.168.0.2/24
    dns-nameservers 192.168.0.10 10.23.23.134
    dns-search barley.maas sacchromyces.maas brettanomyces.maas
    gateway 192.168.0.1
    mtu 1500
    hwaddress aa:bb:cc:dd:ee:11
    vlan-raw-device eth0
    vlan_id 101

# control-alias eth0.101
iface eth0.101 inet static
    address 192.168.2.10/24

post-up route add -net 10.0.0.0/8 gw 11.0.0.1 metric 3 || true
pre-down route del -net 10.0.0.0/8 gw 11.0.0.1 metric 3 || true
"""),
        'expected_netplan': textwrap.dedent("""
            network:
                version: 2
                ethernets:
                    eth0:
                        match:
                            macaddress: c0:d6:9f:2c:e8:80
                        set-name: eth0
                    eth1:
                        match:
                            macaddress: aa:d6:9f:2c:e8:80
                        set-name: eth1
                    eth2:
                        match:
                            macaddress: c0:bb:9f:2c:e8:80
                        set-name: eth2
                    eth3:
                        match:
                            macaddress: 66:bb:9f:2c:e8:80
                        set-name: eth3
                    eth4:
                        match:
                            macaddress: 98:bb:9f:2c:e8:80
                        set-name: eth4
                    eth5:
                        dhcp4: true
                        match:
                            macaddress: 98:bb:9f:2c:e8:8a
                        set-name: eth5
                bonds:
                    bond0:
                        dhcp6: true
                        interfaces:
                        - eth1
                        - eth2
                        macaddress: aa:bb:cc:dd:ee:ff
                        parameters:
                            mii-monitor-interval: 100
                            mode: active-backup
                            transmit-hash-policy: layer3+4
                bridges:
                    br0:
                        addresses:
                        - 192.168.14.2/24
                        - 2001:1::1/64
                        interfaces:
                        - eth3
                        - eth4
                        macaddress: bb:bb:bb:bb:bb:aa
                        nameservers:
                            addresses:
                            - 8.8.8.8
                            - 4.4.4.4
                            - 8.8.4.4
                            search:
                            - barley.maas
                            - wark.maas
                            - foobar.maas
                        parameters:
                            ageing-time: 250
                            forward-delay: 1
                            hello-time: 1
                            max-age: 10
                            path-cost:
                                eth3: 50
                                eth4: 75
                            port-priority:
                                eth3: 28
                                eth4: 14
                            priority: 22
                            stp: false
                        routes:
                        -   to: ::/0
                            via: 2001:4800:78ff:1b::1
                vlans:
                    bond0.200:
                        dhcp4: true
                        id: 200
                        link: bond0
                    eth0.101:
                        addresses:
                        - 192.168.0.2/24
                        - 192.168.2.10/24
                        gateway4: 192.168.0.1
                        id: 101
                        link: eth0
                        macaddress: aa:bb:cc:dd:ee:11
                        mtu: 1500
                        nameservers:
                            addresses:
                            - 192.168.0.10
                            - 10.23.23.134
                            search:
                            - barley.maas
                            - sacchromyces.maas
                            - brettanomyces.maas
        """).rstrip(' '),
        'expected_sysconfig': {
            'ifcfg-bond0': textwrap.dedent("""\
                BONDING_MASTER=yes
                BONDING_OPTS="mode=active-backup """
                                           """xmit_hash_policy=layer3+4 """
                                           """miimon=100"
                BONDING_SLAVE0=eth1
                BONDING_SLAVE1=eth2
                BOOTPROTO=none
                DEVICE=bond0
                DHCPV6C=yes
                IPV6INIT=yes
                MACADDR=aa:bb:cc:dd:ee:ff
                NM_CONTROLLED=no
                ONBOOT=yes
                STARTMODE=auto
                TYPE=Bond
                USERCTL=no"""),
            'ifcfg-bond0.200': textwrap.dedent("""\
                BOOTPROTO=dhcp
                DEVICE=bond0.200
                DHCLIENT_SET_DEFAULT_ROUTE=no
                NM_CONTROLLED=no
                ONBOOT=yes
                PHYSDEV=bond0
                STARTMODE=auto
                TYPE=Ethernet
                USERCTL=no
                VLAN=yes"""),
            'ifcfg-br0': textwrap.dedent("""\
                AGEING=250
                BOOTPROTO=none
                DEFROUTE=yes
                DEVICE=br0
                IPADDR=192.168.14.2
                IPADDR6=2001:1::1/64
                IPV6ADDR=2001:1::1/64
                IPV6INIT=yes
                IPV6_DEFAULTGW=2001:4800:78ff:1b::1
                MACADDR=bb:bb:bb:bb:bb:aa
                NETMASK=255.255.255.0
                NM_CONTROLLED=no
                ONBOOT=yes
                PRIO=22
                STARTMODE=auto
                STP=no
                TYPE=Bridge
                USERCTL=no"""),
            'ifcfg-eth0': textwrap.dedent("""\
                BOOTPROTO=none
                DEVICE=eth0
                HWADDR=c0:d6:9f:2c:e8:80
                NM_CONTROLLED=no
                ONBOOT=yes
                STARTMODE=auto
                TYPE=Ethernet
                USERCTL=no"""),
            'ifcfg-eth0.101': textwrap.dedent("""\
                BOOTPROTO=none
                DEFROUTE=yes
                DEVICE=eth0.101
                DNS1=192.168.0.10
                DNS2=10.23.23.134
                DOMAIN="barley.maas sacchromyces.maas brettanomyces.maas"
                GATEWAY=192.168.0.1
                IPADDR=192.168.0.2
                IPADDR1=192.168.2.10
                MTU=1500
                NETMASK=255.255.255.0
                NETMASK1=255.255.255.0
                NM_CONTROLLED=no
                ONBOOT=yes
                PHYSDEV=eth0
                STARTMODE=auto
                TYPE=Ethernet
                USERCTL=no
                VLAN=yes"""),
            'ifcfg-eth1': textwrap.dedent("""\
                BOOTPROTO=none
                DEVICE=eth1
                HWADDR=aa:d6:9f:2c:e8:80
                MASTER=bond0
                NM_CONTROLLED=no
                ONBOOT=yes
                STARTMODE=auto
                SLAVE=yes
                TYPE=Ethernet
                USERCTL=no"""),
            'ifcfg-eth2': textwrap.dedent("""\
                BOOTPROTO=none
                DEVICE=eth2
                HWADDR=c0:bb:9f:2c:e8:80
                MASTER=bond0
                NM_CONTROLLED=no
                ONBOOT=yes
                STARTMODE=auto
                SLAVE=yes
                TYPE=Ethernet
                USERCTL=no"""),
            'ifcfg-eth3': textwrap.dedent("""\
                BOOTPROTO=none
                BRIDGE=br0
                DEVICE=eth3
                HWADDR=66:bb:9f:2c:e8:80
                NM_CONTROLLED=no
                ONBOOT=yes
                STARTMODE=auto
                TYPE=Ethernet
                USERCTL=no"""),
            'ifcfg-eth4': textwrap.dedent("""\
                BOOTPROTO=none
                BRIDGE=br0
                DEVICE=eth4
                HWADDR=98:bb:9f:2c:e8:80
                NM_CONTROLLED=no
                ONBOOT=yes
                STARTMODE=auto
                TYPE=Ethernet
                USERCTL=no"""),
            'ifcfg-eth5': textwrap.dedent("""\
                BOOTPROTO=dhcp
                DEVICE=eth5
                DHCLIENT_SET_DEFAULT_ROUTE=no
                HWADDR=98:bb:9f:2c:e8:8a
                NM_CONTROLLED=no
                ONBOOT=no
                STARTMODE=manual
                TYPE=Ethernet
                USERCTL=no"""),
            'ifcfg-ib0': textwrap.dedent("""\
                BOOTPROTO=none
                DEVICE=ib0
                HWADDR=a0:00:02:20:fe:80:00:00:00:00:00:00:ec:0d:9a:03:00:15:e2:c1
                IPADDR=192.168.200.7
                MTU=9000
                NETMASK=255.255.255.0
                NM_CONTROLLED=no
                ONBOOT=yes
                STARTMODE=auto
                TYPE=InfiniBand
                USERCTL=no"""),
        },
        'yaml': textwrap.dedent("""
            version: 1
            config:
                # Physical interfaces.
                - type: physical
                  name: eth0
                  mac_address: "c0:d6:9f:2c:e8:80"
                - type: physical
                  name: eth1
                  mac_address: "aa:d6:9f:2c:e8:80"
                - type: physical
                  name: eth2
                  mac_address: "c0:bb:9f:2c:e8:80"
                - type: physical
                  name: eth3
                  mac_address: "66:bb:9f:2c:e8:80"
                - type: physical
                  name: eth4
                  mac_address: "98:bb:9f:2c:e8:80"
                # specify how ifupdown should treat iface
                # control is one of ['auto', 'hotplug', 'manual']
                # with manual meaning ifup/ifdown should not affect the iface
                # useful for things like iscsi root + dhcp
                - type: physical
                  name: eth5
                  mac_address: "98:bb:9f:2c:e8:8a"
                  subnets:
                    - type: dhcp
                      control: manual
                # VLAN interface.
                - type: vlan
                  name: eth0.101
                  vlan_link: eth0
                  vlan_id: 101
                  mac_address: aa:bb:cc:dd:ee:11
                  mtu: 1500
                  subnets:
                    - type: static
                      # When 'mtu' matches device-level mtu, no warnings
                      mtu: 1500
                      address: 192.168.0.2/24
                      gateway: 192.168.0.1
                      dns_nameservers:
                        - 192.168.0.10
                        - 10.23.23.134
                      dns_search:
                        - barley.maas
                        - sacchromyces.maas
                        - brettanomyces.maas
                    - type: static
                      address: 192.168.2.10/24
                # Bond.
                - type: bond
                  name: bond0
                  # if 'mac_address' is omitted, the MAC is taken from
                  # the first slave.
                  mac_address: "aa:bb:cc:dd:ee:ff"
                  bond_interfaces:
                    - eth1
                    - eth2
                  params:
                    bond-mode: active-backup
                    bond_miimon: 100
                    bond-xmit-hash-policy: "layer3+4"
                  subnets:
                    - type: dhcp6
                # A Bond VLAN.
                - type: vlan
                  name: bond0.200
                  vlan_link: bond0
                  vlan_id: 200
                  subnets:
                      - type: dhcp4
                # An infiniband
                - type: infiniband
                  name: ib0
                  mac_address: >-
                    a0:00:02:20:fe:80:00:00:00:00:00:00:ec:0d:9a:03:00:15:e2:c1
                  subnets:
                      - type: static
                        address: 192.168.200.7/24
                        mtu: 9000
                # A bridge.
                - type: bridge
                  name: br0
                  bridge_interfaces:
                      - eth3
                      - eth4
                  ipv4_conf:
                      rp_filter: 1
                      proxy_arp: 0
                      forwarding: 1
                  ipv6_conf:
                      autoconf: 1
                      disable_ipv6: 1
                      use_tempaddr: 1
                      forwarding: 1
                      # basically anything in /proc/sys/net/ipv6/conf/.../
                  mac_address: bb:bb:bb:bb:bb:aa
                  params:
                      bridge_ageing: 250
                      bridge_bridgeprio: 22
                      bridge_fd: 1
                      bridge_gcint: 2
                      bridge_hello: 1
                      bridge_maxage: 10
                      bridge_maxwait: 0
                      bridge_pathcost:
                        - eth3 50
                        - eth4 75
                      bridge_portprio:
                        - eth3 28
                        - eth4 14
                      bridge_stp: 'off'
                      bridge_waitport:
                        - 1 eth3
                        - 2 eth4
                  subnets:
                      - type: static
                        address: 192.168.14.2/24
                      - type: static
                        address: 2001:1::1/64 # default to /64
                        routes:
                          - gateway: 2001:4800:78ff:1b::1
                            netmask: '::'
                            network: '::'
                # A global nameserver.
                - type: nameserver
                  address: 8.8.8.8
                  search: barley.maas
                # global nameservers and search in list form
                - type: nameserver
                  address:
                    - 4.4.4.4
                    - 8.8.4.4
                  search:
                    - wark.maas
                    - foobar.maas
                # A global route.
                - type: route
                  destination: 10.0.0.0/8
                  gateway: 11.0.0.1
                  metric: 3
        """).lstrip(),
    },
    'bond': {
        'yaml': textwrap.dedent("""
            version: 1
            config:
              - type: physical
                name: bond0s0
                mac_address: "aa:bb:cc:dd:e8:00"
              - type: physical
                name: bond0s1
                mac_address: "aa:bb:cc:dd:e8:01"
              - type: bond
                name: bond0
                mac_address: "aa:bb:cc:dd:e8:ff"
                mtu: 9000
                bond_interfaces:
                  - bond0s0
                  - bond0s1
                params:
                  bond-mode: active-backup
                  bond_miimon: 100
                  bond-xmit-hash-policy: "layer3+4"
                  bond-num-grat-arp: 5
                  bond-downdelay: 10
                  bond-updelay: 20
                  bond-fail-over-mac: active
                  bond-primary: bond0s0
                  bond-primary-reselect: always
                subnets:
                  - type: static
                    address: 192.168.0.2/24
                    gateway: 192.168.0.1
                    routes:
                     - gateway: 192.168.0.3
                       netmask: 255.255.255.0
                       network: 10.1.3.0
                  - type: static
                    address: 192.168.1.2/24
                  - type: static
                    address: 2001:1::1/92
                    routes:
                        - gateway: 2001:67c:1562:1
                          network: 2001:67c:1
                          netmask: ffff:ffff:0
                        - gateway: 3001:67c:1562:1
                          network: 3001:67c:1
                          netmask: ffff:ffff:0
                          metric: 10000
            """),
        'expected_netplan': textwrap.dedent("""
         network:
             version: 2
             ethernets:
                 bond0s0:
                     match:
                         macaddress: aa:bb:cc:dd:e8:00
                     set-name: bond0s0
                 bond0s1:
                     match:
                         macaddress: aa:bb:cc:dd:e8:01
                     set-name: bond0s1
             bonds:
                 bond0:
                     addresses:
                     - 192.168.0.2/24
                     - 192.168.1.2/24
                     - 2001:1::1/92
                     gateway4: 192.168.0.1
                     interfaces:
                     - bond0s0
                     - bond0s1
                     macaddress: aa:bb:cc:dd:e8:ff
                     mtu: 9000
                     parameters:
                         down-delay: 10
                         fail-over-mac-policy: active
                         gratuitious-arp: 5
                         mii-monitor-interval: 100
                         mode: active-backup
                         primary: bond0s0
                         primary-reselect-policy: always
                         transmit-hash-policy: layer3+4
                         up-delay: 20
                     routes:
                     -   to: 10.1.3.0/24
                         via: 192.168.0.3
                     -   to: 2001:67c:1/32
                         via: 2001:67c:1562:1
                     -   metric: 10000
                         to: 3001:67c:1/32
                         via: 3001:67c:1562:1
        """),
        'expected_eni': textwrap.dedent("""\
auto lo
iface lo inet loopback

auto bond0s0
iface bond0s0 inet manual
    bond-downdelay 10
    bond-fail-over-mac active
    bond-master bond0
    bond-mode active-backup
    bond-num-grat-arp 5
    bond-primary bond0s0
    bond-primary-reselect always
    bond-updelay 20
    bond-xmit-hash-policy layer3+4
    bond_miimon 100

auto bond0s1
iface bond0s1 inet manual
    bond-downdelay 10
    bond-fail-over-mac active
    bond-master bond0
    bond-mode active-backup
    bond-num-grat-arp 5
    bond-primary bond0s0
    bond-primary-reselect always
    bond-updelay 20
    bond-xmit-hash-policy layer3+4
    bond_miimon 100

auto bond0
iface bond0 inet static
    address 192.168.0.2/24
    gateway 192.168.0.1
    bond-downdelay 10
    bond-fail-over-mac active
    bond-mode active-backup
    bond-num-grat-arp 5
    bond-primary bond0s0
    bond-primary-reselect always
    bond-slaves none
    bond-updelay 20
    bond-xmit-hash-policy layer3+4
    bond_miimon 100
    hwaddress aa:bb:cc:dd:e8:ff
    mtu 9000
    post-up route add -net 10.1.3.0/24 gw 192.168.0.3 || true
    pre-down route del -net 10.1.3.0/24 gw 192.168.0.3 || true

# control-alias bond0
iface bond0 inet static
    address 192.168.1.2/24

# control-alias bond0
iface bond0 inet6 static
    address 2001:1::1/92
    post-up route add -A inet6 2001:67c:1/32 gw 2001:67c:1562:1 || true
    pre-down route del -A inet6 2001:67c:1/32 gw 2001:67c:1562:1 || true
    post-up route add -A inet6 3001:67c:1/32 gw 3001:67c:1562:1 metric 10000 \
|| true
    pre-down route del -A inet6 3001:67c:1/32 gw 3001:67c:1562:1 metric 10000 \
|| true
        """),
        'yaml-v2': textwrap.dedent("""
            version: 2
            ethernets:
              eth0:
                match:
                    driver: "virtio_net"
                    macaddress: "aa:bb:cc:dd:e8:00"
              vf0:
                set-name: vf0
                match:
                    driver: "e1000"
                    macaddress: "aa:bb:cc:dd:e8:01"
            bonds:
              bond0:
                addresses:
                - 192.168.0.2/24
                - 192.168.1.2/24
                - 2001:1::1/92
                gateway4: 192.168.0.1
                interfaces:
                - eth0
                - vf0
                parameters:
                    down-delay: 10
                    fail-over-mac-policy: active
                    gratuitious-arp: 5
                    mii-monitor-interval: 100
                    mode: active-backup
                    primary: bond0s0
                    primary-reselect-policy: always
                    transmit-hash-policy: layer3+4
                    up-delay: 20
                routes:
                -   to: 10.1.3.0/24
                    via: 192.168.0.3
                -   to: 2001:67c:1562:8007::1/64
                    via: 2001:67c:1562:8007::aac:40b2
                -   metric: 10000
                    to: 3001:67c:1562:8007::1/64
                    via: 3001:67c:1562:8007::aac:40b2
            """),
        'expected_netplan-v2': textwrap.dedent("""
         network:
             bonds:
                 bond0:
                     addresses:
                     - 192.168.0.2/24
                     - 192.168.1.2/24
                     - 2001:1::1/92
                     gateway4: 192.168.0.1
                     interfaces:
                     - eth0
                     - vf0
                     parameters:
                         down-delay: 10
                         fail-over-mac-policy: active
                         gratuitious-arp: 5
                         mii-monitor-interval: 100
                         mode: active-backup
                         primary: bond0s0
                         primary-reselect-policy: always
                         transmit-hash-policy: layer3+4
                         up-delay: 20
                     routes:
                     -   to: 10.1.3.0/24
                         via: 192.168.0.3
                     -   to: 2001:67c:1562:8007::1/64
                         via: 2001:67c:1562:8007::aac:40b2
                     -   metric: 10000
                         to: 3001:67c:1562:8007::1/64
                         via: 3001:67c:1562:8007::aac:40b2
             ethernets:
                 eth0:
                     match:
                         driver: virtio_net
                         macaddress: aa:bb:cc:dd:e8:00
                 vf0:
                     match:
                         driver: e1000
                         macaddress: aa:bb:cc:dd:e8:01
                     set-name: vf0
             version: 2
        """),

        'expected_sysconfig_opensuse': {
            'ifcfg-bond0': textwrap.dedent("""\
        BONDING_MASTER=yes
        BONDING_OPTS="mode=active-backup xmit_hash_policy=layer3+4 """
                                           """miimon=100 num_grat_arp=5 """
                                           """downdelay=10 updelay=20 """
                                           """fail_over_mac=active """
                                           """primary=bond0s0 """
                                           """primary_reselect=always"
        BONDING_SLAVE0=bond0s0
        BONDING_SLAVE1=bond0s1
        BOOTPROTO=none
        DEFROUTE=yes
        DEVICE=bond0
        GATEWAY=192.168.0.1
        MACADDR=aa:bb:cc:dd:e8:ff
        IPADDR=192.168.0.2
        IPADDR1=192.168.1.2
        IPADDR6=2001:1::1/92
        IPV6ADDR=2001:1::1/92
        IPV6INIT=yes
        MTU=9000
        NETMASK=255.255.255.0
        NETMASK1=255.255.255.0
        NM_CONTROLLED=no
        ONBOOT=yes
        STARTMODE=auto
        TYPE=Bond
        USERCTL=no
        """),
            'ifcfg-bond0s0': textwrap.dedent("""\
        BOOTPROTO=none
        DEVICE=bond0s0
        HWADDR=aa:bb:cc:dd:e8:00
        MASTER=bond0
        NM_CONTROLLED=no
        ONBOOT=yes
        SLAVE=yes
        STARTMODE=auto
        TYPE=Ethernet
        USERCTL=no
        """),
            'ifroute-bond0': textwrap.dedent("""\
        ADDRESS0=10.1.3.0
        GATEWAY0=192.168.0.3
        NETMASK0=255.255.255.0
        """),
            'ifcfg-bond0s1': textwrap.dedent("""\
        BOOTPROTO=none
        DEVICE=bond0s1
        HWADDR=aa:bb:cc:dd:e8:01
        MASTER=bond0
        NM_CONTROLLED=no
        ONBOOT=yes
        SLAVE=yes
        STARTMODE=auto
        TYPE=Ethernet
        USERCTL=no
        """),
        },

        'expected_sysconfig_rhel': {
            'ifcfg-bond0': textwrap.dedent("""\
        BONDING_MASTER=yes
        BONDING_OPTS="mode=active-backup xmit_hash_policy=layer3+4 """
                                           """miimon=100 num_grat_arp=5 """
                                           """downdelay=10 updelay=20 """
                                           """fail_over_mac=active """
                                           """primary=bond0s0 """
                                           """primary_reselect=always"
        BONDING_SLAVE0=bond0s0
        BONDING_SLAVE1=bond0s1
        BOOTPROTO=none
        DEFROUTE=yes
        DEVICE=bond0
        GATEWAY=192.168.0.1
        MACADDR=aa:bb:cc:dd:e8:ff
        IPADDR=192.168.0.2
        IPADDR1=192.168.1.2
        IPADDR6=2001:1::1/92
        IPV6ADDR=2001:1::1/92
        IPV6INIT=yes
        MTU=9000
        NETMASK=255.255.255.0
        NETMASK1=255.255.255.0
        NM_CONTROLLED=no
        ONBOOT=yes
        STARTMODE=auto
        TYPE=Bond
        USERCTL=no
        """),
            'ifcfg-bond0s0': textwrap.dedent("""\
        BOOTPROTO=none
        DEVICE=bond0s0
        HWADDR=aa:bb:cc:dd:e8:00
        MASTER=bond0
        NM_CONTROLLED=no
        ONBOOT=yes
        SLAVE=yes
        STARTMODE=auto
        TYPE=Ethernet
        USERCTL=no
        """),
            'route6-bond0': textwrap.dedent("""\
        # Created by cloud-init on instance boot automatically, do not edit.
        #
        2001:67c:1/ffff:ffff:0 via 2001:67c:1562:1  dev bond0
        3001:67c:1/ffff:ffff:0 via 3001:67c:1562:1 metric 10000 dev bond0
            """),
            'route-bond0': textwrap.dedent("""\
        ADDRESS0=10.1.3.0
        GATEWAY0=192.168.0.3
        NETMASK0=255.255.255.0
        """),
            'ifcfg-bond0s1': textwrap.dedent("""\
        BOOTPROTO=none
        DEVICE=bond0s1
        HWADDR=aa:bb:cc:dd:e8:01
        MASTER=bond0
        NM_CONTROLLED=no
        ONBOOT=yes
        SLAVE=yes
        STARTMODE=auto
        TYPE=Ethernet
        USERCTL=no
        """),
        },
    },
    'vlan': {
        'yaml': textwrap.dedent("""
            version: 1
            config:
              - type: physical
                name: en0
                mac_address: "aa:bb:cc:dd:e8:00"
              - type: vlan
                mtu: 2222
                name: en0.99
                vlan_link: en0
                vlan_id: 99
                subnets:
                  - type: static
                    address: '192.168.2.2/24'
                  - type: static
                    address: '192.168.1.2/24'
                    gateway: 192.168.1.1
                  - type: static
                    address: 2001:1::bbbb/96
                    routes:
                     - gateway: 2001:1::1
                       netmask: '::'
                       network: '::'
            """),
        'expected_sysconfig': {
            'ifcfg-en0': textwrap.dedent("""\
                BOOTPROTO=none
                DEVICE=en0
                HWADDR=aa:bb:cc:dd:e8:00
                NM_CONTROLLED=no
                ONBOOT=yes
                STARTMODE=auto
                TYPE=Ethernet
                USERCTL=no"""),
            'ifcfg-en0.99': textwrap.dedent("""\
                BOOTPROTO=none
                DEFROUTE=yes
                DEVICE=en0.99
                GATEWAY=192.168.1.1
                IPADDR=192.168.2.2
                IPADDR1=192.168.1.2
                IPADDR6=2001:1::bbbb/96
                IPV6ADDR=2001:1::bbbb/96
                IPV6INIT=yes
                IPV6_DEFAULTGW=2001:1::1
                MTU=2222
                NETMASK=255.255.255.0
                NETMASK1=255.255.255.0
                NM_CONTROLLED=no
                ONBOOT=yes
                PHYSDEV=en0
                STARTMODE=auto
                TYPE=Ethernet
                USERCTL=no
                VLAN=yes"""),
        },
    },
    'bridge': {
        'yaml': textwrap.dedent("""
            version: 1
            config:
              - type: physical
                name: eth0
                mac_address: "52:54:00:12:34:00"
                subnets:
                  - type: static
                    address: 2001:1::100/96
              - type: physical
                name: eth1
                mac_address: "52:54:00:12:34:01"
                subnets:
                  - type: static
                    address: 2001:1::101/96
              - type: bridge
                name: br0
                bridge_interfaces:
                  - eth0
                  - eth1
                params:
                  bridge_stp: 0
                  bridge_bridgeprio: 22
                subnets:
                  - type: static
                    address: 192.168.2.2/24"""),
        'expected_sysconfig': {
            'ifcfg-br0': textwrap.dedent("""\
                BOOTPROTO=none
                DEVICE=br0
                IPADDR=192.168.2.2
                NETMASK=255.255.255.0
                NM_CONTROLLED=no
                ONBOOT=yes
                PRIO=22
                STARTMODE=auto
                STP=no
                TYPE=Bridge
                USERCTL=no
                """),
            'ifcfg-eth0': textwrap.dedent("""\
                BOOTPROTO=none
                BRIDGE=br0
                DEVICE=eth0
                HWADDR=52:54:00:12:34:00
                IPADDR6=2001:1::100/96
                IPV6ADDR=2001:1::100/96
                IPV6INIT=yes
                NM_CONTROLLED=no
                ONBOOT=yes
                STARTMODE=auto
                TYPE=Ethernet
                USERCTL=no
                """),
            'ifcfg-eth1': textwrap.dedent("""\
                BOOTPROTO=none
                BRIDGE=br0
                DEVICE=eth1
                HWADDR=52:54:00:12:34:01
                IPADDR6=2001:1::101/96
                IPV6ADDR=2001:1::101/96
                IPV6INIT=yes
                NM_CONTROLLED=no
                ONBOOT=yes
                STARTMODE=auto
                TYPE=Ethernet
                USERCTL=no
                """),
        },
    },
    'manual': {
        'yaml': textwrap.dedent("""
            version: 1
            config:
              - type: physical
                name: eth0
                mac_address: "52:54:00:12:34:00"
                subnets:
                  - type: static
                    address: 192.168.1.2/24
                    control: manual
              - type: physical
                name: eth1
                mtu: 1480
                mac_address: "52:54:00:12:34:aa"
                subnets:
                  - type: manual
              - type: physical
                name: eth2
                mac_address: "52:54:00:12:34:ff"
                subnets:
                  - type: manual
                    control: manual
                  """),
        'expected_eni': textwrap.dedent("""\
            auto lo
            iface lo inet loopback

            # control-manual eth0
            iface eth0 inet static
                address 192.168.1.2/24

            auto eth1
            iface eth1 inet manual
                mtu 1480

            # control-manual eth2
            iface eth2 inet manual
            """),
        'expected_netplan': textwrap.dedent("""\

            network:
                version: 2
                ethernets:
                    eth0:
                        addresses:
                        - 192.168.1.2/24
                        match:
                            macaddress: '52:54:00:12:34:00'
                        set-name: eth0
                    eth1:
                        match:
                            macaddress: 52:54:00:12:34:aa
                        mtu: 1480
                        set-name: eth1
                    eth2:
                        match:
                            macaddress: 52:54:00:12:34:ff
                        set-name: eth2
            """),
        'expected_sysconfig': {
            'ifcfg-eth0': textwrap.dedent("""\
                BOOTPROTO=none
                DEVICE=eth0
                HWADDR=52:54:00:12:34:00
                IPADDR=192.168.1.2
                NETMASK=255.255.255.0
                NM_CONTROLLED=no
                ONBOOT=no
                STARTMODE=manual
                TYPE=Ethernet
                USERCTL=no
                """),
            'ifcfg-eth1': textwrap.dedent("""\
                BOOTPROTO=none
                DEVICE=eth1
                HWADDR=52:54:00:12:34:aa
                MTU=1480
                NM_CONTROLLED=no
                ONBOOT=yes
                STARTMODE=auto
                TYPE=Ethernet
                USERCTL=no
                """),
            'ifcfg-eth2': textwrap.dedent("""\
                BOOTPROTO=none
                DEVICE=eth2
                HWADDR=52:54:00:12:34:ff
                NM_CONTROLLED=no
                ONBOOT=no
                STARTMODE=manual
                TYPE=Ethernet
                USERCTL=no
                """),
        },
    },
}


CONFIG_V1_EXPLICIT_LOOPBACK = {
    'version': 1,
    'config': [{'name': 'eth0', 'type': 'physical',
               'subnets': [{'control': 'auto', 'type': 'dhcp'}]},
               {'name': 'lo', 'type': 'loopback',
                'subnets': [{'control': 'auto', 'type': 'loopback'}]},
               ]}


CONFIG_V1_SIMPLE_SUBNET = {
    'version': 1,
    'config': [{'mac_address': '52:54:00:12:34:00',
                'name': 'interface0',
                'subnets': [{'address': '10.0.2.15',
                             'gateway': '10.0.2.2',
                             'netmask': '255.255.255.0',
                             'type': 'static'}],
                'type': 'physical'}]}

CONFIG_V1_MULTI_IFACE = {
    'version': 1,
    'config': [{'type': 'physical',
                'mtu': 1500,
                'subnets': [{'type': 'static',
                             'netmask': '255.255.240.0',
                             'routes': [{'netmask': '0.0.0.0',
                                         'network': '0.0.0.0',
                                         'gateway': '51.68.80.1'}],
                             'address': '51.68.89.122',
                             'ipv4': True}],
                'mac_address': 'fa:16:3e:25:b4:59',
                'name': 'eth0'},
               {'type': 'physical',
                'mtu': 9000,
                'subnets': [{'type': 'dhcp4'}],
                'mac_address': 'fa:16:3e:b1:ca:29', 'name': 'eth1'}]}

DEFAULT_DEV_ATTRS = {
    'eth1000': {
        "bridge": False,
        "carrier": False,
        "dormant": False,
        "operstate": "down",
        "address": "07-1c-c6-75-a4-be",
        "device/driver": None,
        "device/device": None,
        "name_assign_type": "4",
    }
}


def _setup_test(tmp_dir, mock_get_devicelist, mock_read_sys_net,
                mock_sys_dev_path, dev_attrs=None):
    if not dev_attrs:
        dev_attrs = DEFAULT_DEV_ATTRS

    mock_get_devicelist.return_value = dev_attrs.keys()

    def fake_read(devname, path, translate=None,
                  on_enoent=None, on_keyerror=None,
                  on_einval=None):
        return dev_attrs[devname][path]

    mock_read_sys_net.side_effect = fake_read

    def sys_dev_path(devname, path=""):
        return tmp_dir + "/" + devname + "/" + path

    for dev in dev_attrs:
        os.makedirs(os.path.join(tmp_dir, dev))
        with open(os.path.join(tmp_dir, dev, 'operstate'), 'w') as fh:
            fh.write(dev_attrs[dev]['operstate'])
        os.makedirs(os.path.join(tmp_dir, dev, "device"))
        for key in ['device/driver']:
            if key in dev_attrs[dev] and dev_attrs[dev][key]:
                target = dev_attrs[dev][key]
                link = os.path.join(tmp_dir, dev, key)
                print('symlink %s -> %s' % (link, target))
                os.symlink(target, link)

    mock_sys_dev_path.side_effect = sys_dev_path


class TestGenerateFallbackConfig(CiTestCase):

    def setUp(self):
        super(TestGenerateFallbackConfig, self).setUp()
        self.add_patch(
            "cloudinit.util.get_cmdline", "m_get_cmdline",
            return_value="root=/dev/sda1")

    @mock.patch("cloudinit.net.sys_dev_path")
    @mock.patch("cloudinit.net.read_sys_net")
    @mock.patch("cloudinit.net.get_devicelist")
    def test_device_driver_v2(self, mock_get_devicelist, mock_read_sys_net,
                              mock_sys_dev_path):
        """Network configuration for generate_fallback_config is version 2."""
        devices = {
            'eth0': {
                'bridge': False, 'carrier': False, 'dormant': False,
                'operstate': 'down', 'address': '00:11:22:33:44:55',
                'device/driver': 'hv_netsvc', 'device/device': '0x3',
                'name_assign_type': '4'},
            'eth1': {
                'bridge': False, 'carrier': False, 'dormant': False,
                'operstate': 'down', 'address': '00:11:22:33:44:55',
                'device/driver': 'mlx4_core', 'device/device': '0x7',
                'name_assign_type': '4'},

        }

        tmp_dir = self.tmp_dir()
        _setup_test(tmp_dir, mock_get_devicelist,
                    mock_read_sys_net, mock_sys_dev_path,
                    dev_attrs=devices)

        network_cfg = net.generate_fallback_config(config_driver=True)
        expected = {
            'ethernets': {'eth0': {'dhcp4': True, 'set-name': 'eth0',
                                   'match': {'macaddress': '00:11:22:33:44:55',
                                             'driver': 'hv_netsvc'}}},
            'version': 2}
        self.assertEqual(expected, network_cfg)

    @mock.patch("cloudinit.net.sys_dev_path")
    @mock.patch("cloudinit.net.read_sys_net")
    @mock.patch("cloudinit.net.get_devicelist")
    def test_device_driver(self, mock_get_devicelist, mock_read_sys_net,
                           mock_sys_dev_path):
        devices = {
            'eth0': {
                'bridge': False, 'carrier': False, 'dormant': False,
                'operstate': 'down', 'address': '00:11:22:33:44:55',
                'device/driver': 'hv_netsvc', 'device/device': '0x3',
                'name_assign_type': '4'},
            'eth1': {
                'bridge': False, 'carrier': False, 'dormant': False,
                'operstate': 'down', 'address': '00:11:22:33:44:55',
                'device/driver': 'mlx4_core', 'device/device': '0x7',
                'name_assign_type': '4'},

        }

        tmp_dir = self.tmp_dir()
        _setup_test(tmp_dir, mock_get_devicelist,
                    mock_read_sys_net, mock_sys_dev_path,
                    dev_attrs=devices)

        network_cfg = net.generate_fallback_config(config_driver=True)
        ns = network_state.parse_net_config_data(network_cfg,
                                                 skip_broken=False)

        render_dir = os.path.join(tmp_dir, "render")
        os.makedirs(render_dir)

        # don't set rulepath so eni writes them
        renderer = eni.Renderer(
            {'eni_path': 'interfaces', 'netrules_path': 'netrules'})
        renderer.render_network_state(ns, target=render_dir)

        self.assertTrue(os.path.exists(os.path.join(render_dir,
                                                    'interfaces')))
        with open(os.path.join(render_dir, 'interfaces')) as fh:
            contents = fh.read()
        print(contents)
        expected = """
auto lo
iface lo inet loopback

auto eth0
iface eth0 inet dhcp
"""
        self.assertEqual(expected.lstrip(), contents.lstrip())

        self.assertTrue(os.path.exists(os.path.join(render_dir, 'netrules')))
        with open(os.path.join(render_dir, 'netrules')) as fh:
            contents = fh.read()
        print(contents)
        expected_rule = [
            'SUBSYSTEM=="net"',
            'ACTION=="add"',
            'DRIVERS=="hv_netsvc"',
            'ATTR{address}=="00:11:22:33:44:55"',
            'NAME="eth0"',
        ]
        self.assertEqual(", ".join(expected_rule) + '\n', contents.lstrip())

    @mock.patch("cloudinit.net.sys_dev_path")
    @mock.patch("cloudinit.net.read_sys_net")
    @mock.patch("cloudinit.net.get_devicelist")
    def test_device_driver_blacklist(self, mock_get_devicelist,
                                     mock_read_sys_net, mock_sys_dev_path):
        devices = {
            'eth1': {
                'bridge': False, 'carrier': False, 'dormant': False,
                'operstate': 'down', 'address': '00:11:22:33:44:55',
                'device/driver': 'hv_netsvc', 'device/device': '0x3',
                'name_assign_type': '4'},
            'eth0': {
                'bridge': False, 'carrier': False, 'dormant': False,
                'operstate': 'down', 'address': '00:11:22:33:44:55',
                'device/driver': 'mlx4_core', 'device/device': '0x7',
                'name_assign_type': '4'},
        }

        tmp_dir = self.tmp_dir()
        _setup_test(tmp_dir, mock_get_devicelist,
                    mock_read_sys_net, mock_sys_dev_path,
                    dev_attrs=devices)

        blacklist = ['mlx4_core']
        network_cfg = net.generate_fallback_config(blacklist_drivers=blacklist,
                                                   config_driver=True)
        ns = network_state.parse_net_config_data(network_cfg,
                                                 skip_broken=False)

        render_dir = os.path.join(tmp_dir, "render")
        os.makedirs(render_dir)

        # don't set rulepath so eni writes them
        renderer = eni.Renderer(
            {'eni_path': 'interfaces', 'netrules_path': 'netrules'})
        renderer.render_network_state(ns, target=render_dir)

        self.assertTrue(os.path.exists(os.path.join(render_dir,
                                                    'interfaces')))
        with open(os.path.join(render_dir, 'interfaces')) as fh:
            contents = fh.read()
        print(contents)
        expected = """
auto lo
iface lo inet loopback

auto eth1
iface eth1 inet dhcp
"""
        self.assertEqual(expected.lstrip(), contents.lstrip())

        self.assertTrue(os.path.exists(os.path.join(render_dir, 'netrules')))
        with open(os.path.join(render_dir, 'netrules')) as fh:
            contents = fh.read()
        print(contents)
        expected_rule = [
            'SUBSYSTEM=="net"',
            'ACTION=="add"',
            'DRIVERS=="hv_netsvc"',
            'ATTR{address}=="00:11:22:33:44:55"',
            'NAME="eth1"',
        ]
        self.assertEqual(", ".join(expected_rule) + '\n', contents.lstrip())

    @mock.patch("cloudinit.util.get_cmdline")
    @mock.patch("cloudinit.util.udevadm_settle")
    @mock.patch("cloudinit.net.sys_dev_path")
    @mock.patch("cloudinit.net.read_sys_net")
    @mock.patch("cloudinit.net.get_devicelist")
    def test_unstable_names(self, mock_get_devicelist, mock_read_sys_net,
                            mock_sys_dev_path, mock_settle, m_get_cmdline):
        """verify that udevadm settle is called when we find unstable names"""
        devices = {
            'eth0': {
                'bridge': False, 'carrier': False, 'dormant': False,
                'operstate': 'down', 'address': '00:11:22:33:44:55',
                'device/driver': 'hv_netsvc', 'device/device': '0x3',
                'name_assign_type': False},
            'ens4': {
                'bridge': False, 'carrier': False, 'dormant': False,
                'operstate': 'down', 'address': '00:11:22:33:44:55',
                'device/driver': 'mlx4_core', 'device/device': '0x7',
                'name_assign_type': '4'},

        }

        m_get_cmdline.return_value = ''
        tmp_dir = self.tmp_dir()
        _setup_test(tmp_dir, mock_get_devicelist,
                    mock_read_sys_net, mock_sys_dev_path,
                    dev_attrs=devices)
        net.generate_fallback_config(config_driver=True)
        self.assertEqual(1, mock_settle.call_count)

    @mock.patch("cloudinit.util.get_cmdline")
    @mock.patch("cloudinit.util.udevadm_settle")
    @mock.patch("cloudinit.net.sys_dev_path")
    @mock.patch("cloudinit.net.read_sys_net")
    @mock.patch("cloudinit.net.get_devicelist")
    def test_unstable_names_disabled(self, mock_get_devicelist,
                                     mock_read_sys_net, mock_sys_dev_path,
                                     mock_settle, m_get_cmdline):
        """verify udevadm settle not called when cmdline has net.ifnames=0"""
        devices = {
            'eth0': {
                'bridge': False, 'carrier': False, 'dormant': False,
                'operstate': 'down', 'address': '00:11:22:33:44:55',
                'device/driver': 'hv_netsvc', 'device/device': '0x3',
                'name_assign_type': False},
            'ens4': {
                'bridge': False, 'carrier': False, 'dormant': False,
                'operstate': 'down', 'address': '00:11:22:33:44:55',
                'device/driver': 'mlx4_core', 'device/device': '0x7',
                'name_assign_type': '4'},

        }

        m_get_cmdline.return_value = 'net.ifnames=0'
        tmp_dir = self.tmp_dir()
        _setup_test(tmp_dir, mock_get_devicelist,
                    mock_read_sys_net, mock_sys_dev_path,
                    dev_attrs=devices)
        net.generate_fallback_config(config_driver=True)
        self.assertEqual(0, mock_settle.call_count)


class TestRhelSysConfigRendering(CiTestCase):

    with_logs = True

    nm_cfg_file = "/etc/NetworkManager/NetworkManager.conf"
    scripts_dir = '/etc/sysconfig/network-scripts'
    header = ('# Created by cloud-init on instance boot automatically, '
              'do not edit.\n#\n')

    expected_name = 'expected_sysconfig'

    def _get_renderer(self):
        distro_cls = distros.fetch('rhel')
        return sysconfig.Renderer(
            config=distro_cls.renderer_configs.get('sysconfig'))

    def _render_and_read(self, network_config=None, state=None, dir=None):
        if dir is None:
            dir = self.tmp_dir()

        if network_config:
            ns = network_state.parse_net_config_data(network_config)
        elif state:
            ns = state
        else:
            raise ValueError("Expected data or state, got neither")

        renderer = self._get_renderer()
        renderer.render_network_state(ns, target=dir)
        return dir2dict(dir)

    def _compare_files_to_expected(self, expected, found):

        def _try_load(f):
            ''' Attempt to load shell content, otherwise return as-is '''
            try:
                return util.load_shell_content(f)
            except ValueError:
                pass
            # route6- * files aren't shell content, but iproute2 params
            return f

        orig_maxdiff = self.maxDiff
        expected_d = dict(
            (os.path.join(self.scripts_dir, k), _try_load(v))
            for k, v in expected.items())

        # only compare the files in scripts_dir
        scripts_found = dict(
            (k, _try_load(v)) for k, v in found.items()
            if k.startswith(self.scripts_dir))
        try:
            self.maxDiff = None
            self.assertEqual(expected_d, scripts_found)
        finally:
            self.maxDiff = orig_maxdiff

    def _assert_headers(self, found):
        missing = [f for f in found
                   if (f.startswith(self.scripts_dir) and
                       not found[f].startswith(self.header))]
        if missing:
            raise AssertionError("Missing headers in: %s" % missing)

    @mock.patch("cloudinit.net.util.get_cmdline", return_value="root=myroot")
    @mock.patch("cloudinit.net.sys_dev_path")
    @mock.patch("cloudinit.net.read_sys_net")
    @mock.patch("cloudinit.net.get_devicelist")
    def test_default_generation(self, mock_get_devicelist,
                                mock_read_sys_net,
                                mock_sys_dev_path, m_get_cmdline):
        tmp_dir = self.tmp_dir()
        _setup_test(tmp_dir, mock_get_devicelist,
                    mock_read_sys_net, mock_sys_dev_path)

        network_cfg = net.generate_fallback_config()
        ns = network_state.parse_net_config_data(network_cfg,
                                                 skip_broken=False)

        render_dir = os.path.join(tmp_dir, "render")
        os.makedirs(render_dir)

        renderer = self._get_renderer()
        renderer.render_network_state(ns, target=render_dir)

        render_file = 'etc/sysconfig/network-scripts/ifcfg-eth1000'
        with open(os.path.join(render_dir, render_file)) as fh:
            content = fh.read()
            expected_content = """
# Created by cloud-init on instance boot automatically, do not edit.
#
BOOTPROTO=dhcp
DEVICE=eth1000
HWADDR=07-1c-c6-75-a4-be
NM_CONTROLLED=no
ONBOOT=yes
STARTMODE=auto
TYPE=Ethernet
USERCTL=no
""".lstrip()
            self.assertEqual(expected_content, content)

    def test_multiple_ipv4_default_gateways(self):
        """ValueError is raised when duplicate ipv4 gateways exist."""
        net_json = {
            "services": [{"type": "dns", "address": "172.19.0.12"}],
            "networks": [{
                "network_id": "dacd568d-5be6-4786-91fe-750c374b78b4",
                "type": "ipv4", "netmask": "255.255.252.0",
                "link": "tap1a81968a-79",
                "routes": [{
                    "netmask": "0.0.0.0",
                    "network": "0.0.0.0",
                    "gateway": "172.19.3.254",
                }, {
                    "netmask": "0.0.0.0",  # A second default gateway
                    "network": "0.0.0.0",
                    "gateway": "172.20.3.254",
                }],
                "ip_address": "172.19.1.34", "id": "network0"
            }],
            "links": [
                {
                    "ethernet_mac_address": "fa:16:3e:ed:9a:59",
                    "mtu": None, "type": "bridge", "id":
                    "tap1a81968a-79",
                    "vif_id": "1a81968a-797a-400f-8a80-567f997eb93f"
                },
            ],
        }
        macs = {'fa:16:3e:ed:9a:59': 'eth0'}
        render_dir = self.tmp_dir()
        network_cfg = openstack.convert_net_json(net_json, known_macs=macs)
        ns = network_state.parse_net_config_data(network_cfg,
                                                 skip_broken=False)
        renderer = self._get_renderer()
        with self.assertRaises(ValueError):
            renderer.render_network_state(ns, target=render_dir)
        self.assertEqual([], os.listdir(render_dir))

    def test_multiple_ipv6_default_gateways(self):
        """ValueError is raised when duplicate ipv6 gateways exist."""
        net_json = {
            "services": [{"type": "dns", "address": "172.19.0.12"}],
            "networks": [{
                "network_id": "public-ipv6",
                "type": "ipv6", "netmask": "",
                "link": "tap1a81968a-79",
                "routes": [{
                    "gateway": "2001:DB8::1",
                    "netmask": "::",
                    "network": "::"
                }, {
                    "gateway": "2001:DB9::1",
                    "netmask": "::",
                    "network": "::"
                }],
                "ip_address": "2001:DB8::10", "id": "network1"
            }],
            "links": [
                {
                    "ethernet_mac_address": "fa:16:3e:ed:9a:59",
                    "mtu": None, "type": "bridge", "id":
                    "tap1a81968a-79",
                    "vif_id": "1a81968a-797a-400f-8a80-567f997eb93f"
                },
            ],
        }
        macs = {'fa:16:3e:ed:9a:59': 'eth0'}
        render_dir = self.tmp_dir()
        network_cfg = openstack.convert_net_json(net_json, known_macs=macs)
        ns = network_state.parse_net_config_data(network_cfg,
                                                 skip_broken=False)
        renderer = self._get_renderer()
        with self.assertRaises(ValueError):
            renderer.render_network_state(ns, target=render_dir)
        self.assertEqual([], os.listdir(render_dir))

    def test_openstack_rendering_samples(self):
        for os_sample in OS_SAMPLES:
            render_dir = self.tmp_dir()
            ex_input = os_sample['in_data']
            ex_mac_addrs = os_sample['in_macs']
            network_cfg = openstack.convert_net_json(
                ex_input, known_macs=ex_mac_addrs)
            ns = network_state.parse_net_config_data(network_cfg,
                                                     skip_broken=False)
            renderer = self._get_renderer()
            # render a multiple times to simulate reboots
            renderer.render_network_state(ns, target=render_dir)
            renderer.render_network_state(ns, target=render_dir)
            renderer.render_network_state(ns, target=render_dir)
            for fn, expected_content in os_sample.get('out_sysconfig_rhel',
                                                      []):
                with open(os.path.join(render_dir, fn)) as fh:
                    self.assertEqual(expected_content, fh.read())

    def test_network_config_v1_samples(self):
        ns = network_state.parse_net_config_data(CONFIG_V1_SIMPLE_SUBNET)
        render_dir = self.tmp_path("render")
        os.makedirs(render_dir)
        renderer = self._get_renderer()
        renderer.render_network_state(ns, target=render_dir)
        found = dir2dict(render_dir)
        nspath = '/etc/sysconfig/network-scripts/'
        self.assertNotIn(nspath + 'ifcfg-lo', found.keys())
        expected = """\
# Created by cloud-init on instance boot automatically, do not edit.
#
BOOTPROTO=none
DEFROUTE=yes
DEVICE=interface0
GATEWAY=10.0.2.2
HWADDR=52:54:00:12:34:00
IPADDR=10.0.2.15
NETMASK=255.255.255.0
NM_CONTROLLED=no
ONBOOT=yes
STARTMODE=auto
TYPE=Ethernet
USERCTL=no
"""
        self.assertEqual(expected, found[nspath + 'ifcfg-interface0'])
        # The configuration has no nameserver information make sure we
        # do not write the resolv.conf file
        respath = '/etc/resolv.conf'
        self.assertNotIn(respath, found.keys())

    def test_network_config_v1_multi_iface_samples(self):
        ns = network_state.parse_net_config_data(CONFIG_V1_MULTI_IFACE)
        render_dir = self.tmp_path("render")
        os.makedirs(render_dir)
        renderer = self._get_renderer()
        renderer.render_network_state(ns, target=render_dir)
        found = dir2dict(render_dir)
        nspath = '/etc/sysconfig/network-scripts/'
        self.assertNotIn(nspath + 'ifcfg-lo', found.keys())
        expected_i1 = """\
# Created by cloud-init on instance boot automatically, do not edit.
#
BOOTPROTO=none
DEFROUTE=yes
DEVICE=eth0
GATEWAY=51.68.80.1
HWADDR=fa:16:3e:25:b4:59
IPADDR=51.68.89.122
MTU=1500
NETMASK=255.255.240.0
NM_CONTROLLED=no
ONBOOT=yes
STARTMODE=auto
TYPE=Ethernet
USERCTL=no
"""
        self.assertEqual(expected_i1, found[nspath + 'ifcfg-eth0'])
        expected_i2 = """\
# Created by cloud-init on instance boot automatically, do not edit.
#
BOOTPROTO=dhcp
DEVICE=eth1
DHCLIENT_SET_DEFAULT_ROUTE=no
HWADDR=fa:16:3e:b1:ca:29
MTU=9000
NM_CONTROLLED=no
ONBOOT=yes
STARTMODE=auto
TYPE=Ethernet
USERCTL=no
"""
        self.assertEqual(expected_i2, found[nspath + 'ifcfg-eth1'])

    def test_config_with_explicit_loopback(self):
        ns = network_state.parse_net_config_data(CONFIG_V1_EXPLICIT_LOOPBACK)
        render_dir = self.tmp_path("render")
        os.makedirs(render_dir)
        # write an etc/resolv.conf and expect it to not be modified
        resolvconf = os.path.join(render_dir, 'etc/resolv.conf')
        resolvconf_content = "# Original Content"
        util.write_file(resolvconf, resolvconf_content)
        renderer = self._get_renderer()
        renderer.render_network_state(ns, target=render_dir)
        found = dir2dict(render_dir)
        nspath = '/etc/sysconfig/network-scripts/'
        self.assertNotIn(nspath + 'ifcfg-lo', found.keys())
        expected = """\
# Created by cloud-init on instance boot automatically, do not edit.
#
BOOTPROTO=dhcp
DEVICE=eth0
NM_CONTROLLED=no
ONBOOT=yes
STARTMODE=auto
TYPE=Ethernet
USERCTL=no
"""
        self.assertEqual(expected, found[nspath + 'ifcfg-eth0'])
        # a dhcp only config should not modify resolv.conf
        self.assertEqual(resolvconf_content, found['/etc/resolv.conf'])

    def test_bond_config(self):
        expected_name = 'expected_sysconfig_rhel'
        entry = NETWORK_CONFIGS['bond']
        found = self._render_and_read(network_config=yaml.load(entry['yaml']))
        self._compare_files_to_expected(entry[expected_name], found)
        self._assert_headers(found)

    def test_vlan_config(self):
        entry = NETWORK_CONFIGS['vlan']
        found = self._render_and_read(network_config=yaml.load(entry['yaml']))
        self._compare_files_to_expected(entry[self.expected_name], found)
        self._assert_headers(found)

    def test_bridge_config(self):
        entry = NETWORK_CONFIGS['bridge']
        found = self._render_and_read(network_config=yaml.load(entry['yaml']))
        self._compare_files_to_expected(entry[self.expected_name], found)
        self._assert_headers(found)

    def test_manual_config(self):
        entry = NETWORK_CONFIGS['manual']
        found = self._render_and_read(network_config=yaml.load(entry['yaml']))
        self._compare_files_to_expected(entry[self.expected_name], found)
        self._assert_headers(found)

    def test_all_config(self):
        entry = NETWORK_CONFIGS['all']
        found = self._render_and_read(network_config=yaml.load(entry['yaml']))
        self._compare_files_to_expected(entry[self.expected_name], found)
        self._assert_headers(found)
        self.assertNotIn(
            'WARNING: Network config: ignoring eth0.101 device-level mtu',
            self.logs.getvalue())

    def test_small_config(self):
        entry = NETWORK_CONFIGS['small']
        found = self._render_and_read(network_config=yaml.load(entry['yaml']))
        self._compare_files_to_expected(entry[self.expected_name], found)
        self._assert_headers(found)

    def test_v4_and_v6_static_config(self):
        entry = NETWORK_CONFIGS['v4_and_v6_static']
        found = self._render_and_read(network_config=yaml.load(entry['yaml']))
        self._compare_files_to_expected(entry[self.expected_name], found)
        self._assert_headers(found)
        expected_msg = (
            'WARNING: Network config: ignoring iface0 device-level mtu:8999'
            ' because ipv4 subnet-level mtu:9000 provided.')
        self.assertIn(expected_msg, self.logs.getvalue())

    def test_dhcpv6_only_config(self):
        entry = NETWORK_CONFIGS['dhcpv6_only']
        found = self._render_and_read(network_config=yaml.load(entry['yaml']))
        self._compare_files_to_expected(entry[self.expected_name], found)
        self._assert_headers(found)

    def test_dhcpv6_accept_ra_config_v1(self):
        entry = NETWORK_CONFIGS['dhcpv6_accept_ra']
        found = self._render_and_read(network_config=yaml.load(
            entry['yaml_v1']))
        self._compare_files_to_expected(entry[self.expected_name], found)
        self._assert_headers(found)

    def test_dhcpv6_accept_ra_config_v2(self):
        entry = NETWORK_CONFIGS['dhcpv6_accept_ra']
        found = self._render_and_read(network_config=yaml.load(
            entry['yaml_v2']))
        self._compare_files_to_expected(entry[self.expected_name], found)
        self._assert_headers(found)

    def test_dhcpv6_reject_ra_config_v1(self):
        entry = NETWORK_CONFIGS['dhcpv6_reject_ra']
        found = self._render_and_read(network_config=yaml.load(
            entry['yaml_v1']))
        self._compare_files_to_expected(entry[self.expected_name], found)
        self._assert_headers(found)

    def test_dhcpv6_reject_ra_config_v2(self):
        entry = NETWORK_CONFIGS['dhcpv6_reject_ra']
        found = self._render_and_read(network_config=yaml.load(
            entry['yaml_v2']))
        self._compare_files_to_expected(entry[self.expected_name], found)
        self._assert_headers(found)

    def test_dhcpv6_stateless_config(self):
        entry = NETWORK_CONFIGS['dhcpv6_stateless']
        found = self._render_and_read(network_config=yaml.load(entry['yaml']))
        self._compare_files_to_expected(entry[self.expected_name], found)
        self._assert_headers(found)

    def test_dhcpv6_stateful_config(self):
        entry = NETWORK_CONFIGS['dhcpv6_stateful']
        found = self._render_and_read(network_config=yaml.load(entry['yaml']))
        self._compare_files_to_expected(entry[self.expected_name], found)
        self._assert_headers(found)

    def test_check_ifcfg_rh(self):
        """ifcfg-rh plugin is added NetworkManager.conf if conf present."""
        render_dir = self.tmp_dir()
        nm_cfg = util.target_path(render_dir, path=self.nm_cfg_file)
        util.ensure_dir(os.path.dirname(nm_cfg))

        # write a template nm.conf, note plugins is a list here
        with open(nm_cfg, 'w') as fh:
            fh.write('# test_check_ifcfg_rh\n[main]\nplugins=foo,bar\n')
        self.assertTrue(os.path.exists(nm_cfg))

        # render and read
        entry = NETWORK_CONFIGS['small']
        found = self._render_and_read(network_config=yaml.load(entry['yaml']),
                                      dir=render_dir)
        self._compare_files_to_expected(entry[self.expected_name], found)
        self._assert_headers(found)

        # check ifcfg-rh is in the 'plugins' list
        config = sysconfig.ConfigObj(nm_cfg)
        self.assertIn('ifcfg-rh', config['main']['plugins'])

    def test_check_ifcfg_rh_plugins_string(self):
        """ifcfg-rh plugin is append when plugins is a string."""
        render_dir = self.tmp_path("render")
        os.makedirs(render_dir)
        nm_cfg = util.target_path(render_dir, path=self.nm_cfg_file)
        util.ensure_dir(os.path.dirname(nm_cfg))

        # write a template nm.conf, note plugins is a value here
        util.write_file(nm_cfg, '# test_check_ifcfg_rh\n[main]\nplugins=foo\n')

        # render and read
        entry = NETWORK_CONFIGS['small']
        found = self._render_and_read(network_config=yaml.load(entry['yaml']),
                                      dir=render_dir)
        self._compare_files_to_expected(entry[self.expected_name], found)
        self._assert_headers(found)

        # check raw content has plugin
        nm_file_content = util.load_file(nm_cfg)
        self.assertIn('ifcfg-rh', nm_file_content)

        # check ifcfg-rh is in the 'plugins' list
        config = sysconfig.ConfigObj(nm_cfg)
        self.assertIn('ifcfg-rh', config['main']['plugins'])

    def test_check_ifcfg_rh_plugins_no_plugins(self):
        """enable_ifcfg_plugin creates plugins value if missing."""
        render_dir = self.tmp_path("render")
        os.makedirs(render_dir)
        nm_cfg = util.target_path(render_dir, path=self.nm_cfg_file)
        util.ensure_dir(os.path.dirname(nm_cfg))

        # write a template nm.conf, note plugins is missing
        util.write_file(nm_cfg, '# test_check_ifcfg_rh\n[main]\n')
        self.assertTrue(os.path.exists(nm_cfg))

        # render and read
        entry = NETWORK_CONFIGS['small']
        found = self._render_and_read(network_config=yaml.load(entry['yaml']),
                                      dir=render_dir)
        self._compare_files_to_expected(entry[self.expected_name], found)
        self._assert_headers(found)

        # check ifcfg-rh is in the 'plugins' list
        config = sysconfig.ConfigObj(nm_cfg)
        self.assertIn('ifcfg-rh', config['main']['plugins'])

    def test_netplan_dhcp_false_disable_dhcp_in_state(self):
        """netplan config with dhcp[46]: False should not add dhcp in state"""
        net_config = yaml.load(NETPLAN_DHCP_FALSE)
        ns = network_state.parse_net_config_data(net_config,
                                                 skip_broken=False)

        dhcp_found = [snet for iface in ns.iter_interfaces()
                      for snet in iface['subnets'] if 'dhcp' in snet['type']]

        self.assertEqual([], dhcp_found)

    def test_netplan_dhcp_false_no_dhcp_in_sysconfig(self):
        """netplan cfg with dhcp[46]: False should not have bootproto=dhcp"""

        entry = {
            'yaml': NETPLAN_DHCP_FALSE,
            'expected_sysconfig': {
                'ifcfg-ens3': textwrap.dedent("""\
                   BOOTPROTO=none
                   DEFROUTE=yes
                   DEVICE=ens3
                   DNS1=192.168.42.53
                   DNS2=1.1.1.1
                   DOMAIN=example.com
                   GATEWAY=192.168.42.1
                   HWADDR=52:54:00:ab:cd:ef
                   IPADDR=192.168.42.100
                   IPADDR6=2001:db8::100/32
                   IPV6ADDR=2001:db8::100/32
                   IPV6INIT=yes
                   IPV6_DEFAULTGW=2001:db8::1
                   NETMASK=255.255.255.0
                   NM_CONTROLLED=no
                   ONBOOT=yes
                   STARTMODE=auto
                   TYPE=Ethernet
                   USERCTL=no
                   """),
            }
        }

        found = self._render_and_read(network_config=yaml.load(entry['yaml']))
        self._compare_files_to_expected(entry['expected_sysconfig'], found)
        self._assert_headers(found)

    def test_from_v2_vlan_mtu(self):
        """verify mtu gets rendered on bond when source is netplan."""
        v2data = {
            'version': 2,
            'ethernets': {'eno1': {}},
            'vlans': {
                'eno1.1000': {
                    'addresses': ["192.6.1.9/24"],
                    'id': 1000, 'link': 'eno1', 'mtu': 1495}}}
        expected = {
            'ifcfg-eno1': textwrap.dedent("""\
                BOOTPROTO=none
                DEVICE=eno1
                NM_CONTROLLED=no
                ONBOOT=yes
                STARTMODE=auto
                TYPE=Ethernet
                USERCTL=no
                """),
            'ifcfg-eno1.1000': textwrap.dedent("""\
                BOOTPROTO=none
                DEVICE=eno1.1000
                IPADDR=192.6.1.9
                MTU=1495
                NETMASK=255.255.255.0
                NM_CONTROLLED=no
                ONBOOT=yes
                PHYSDEV=eno1
                STARTMODE=auto
                TYPE=Ethernet
                USERCTL=no
                VLAN=yes
                """)
            }
        self._compare_files_to_expected(
            expected, self._render_and_read(network_config=v2data))

    def test_from_v2_bond_mtu(self):
        """verify mtu gets rendered on bond when source is netplan."""
        v2data = {
            'version': 2,
            'bonds': {
                'bond0': {'addresses': ['10.101.8.65/26'],
                          'interfaces': ['enp0s0', 'enp0s1'],
                          'mtu': 1334,
                          'parameters': {}}}
        }
        expected = {
            'ifcfg-bond0': textwrap.dedent("""\
                BONDING_MASTER=yes
                BONDING_SLAVE0=enp0s0
                BONDING_SLAVE1=enp0s1
                BOOTPROTO=none
                DEVICE=bond0
                IPADDR=10.101.8.65
                MTU=1334
                NETMASK=255.255.255.192
                NM_CONTROLLED=no
                ONBOOT=yes
                STARTMODE=auto
                TYPE=Bond
                USERCTL=no
                """),
            'ifcfg-enp0s0': textwrap.dedent("""\
                BONDING_MASTER=yes
                BOOTPROTO=none
                DEVICE=enp0s0
                MASTER=bond0
                NM_CONTROLLED=no
                ONBOOT=yes
                SLAVE=yes
                STARTMODE=auto
                TYPE=Bond
                USERCTL=no
                """),
            'ifcfg-enp0s1': textwrap.dedent("""\
                BONDING_MASTER=yes
                BOOTPROTO=none
                DEVICE=enp0s1
                MASTER=bond0
                NM_CONTROLLED=no
                ONBOOT=yes
                SLAVE=yes
                STARTMODE=auto
                TYPE=Bond
                USERCTL=no
                """)
        }
        self._compare_files_to_expected(
            expected, self._render_and_read(network_config=v2data))

    def test_from_v2_route_metric(self):
        """verify route-metric gets rendered on nic when source is netplan."""
        overrides = {'route-metric': 100}
        v2base = {
            'version': 2,
            'ethernets': {
                'eno1': {'dhcp4': True,
                         'match': {'macaddress': '07-1c-c6-75-a4-be'}}}}
        expected = {
            'ifcfg-eno1': textwrap.dedent("""\
                BOOTPROTO=dhcp
                DEVICE=eno1
                HWADDR=07-1c-c6-75-a4-be
                METRIC=100
                NM_CONTROLLED=no
                ONBOOT=yes
                STARTMODE=auto
                TYPE=Ethernet
                USERCTL=no
                """),
            }
        for dhcp_ver in ('dhcp4', 'dhcp6'):
            v2data = copy.deepcopy(v2base)
            if dhcp_ver == 'dhcp6':
                expected['ifcfg-eno1'] += "IPV6INIT=yes\nDHCPV6C=yes\n"
            v2data['ethernets']['eno1'].update(
                {dhcp_ver: True, '{0}-overrides'.format(dhcp_ver): overrides})
            self._compare_files_to_expected(
                expected, self._render_and_read(network_config=v2data))


class TestOpenSuseSysConfigRendering(CiTestCase):

    with_logs = True

    scripts_dir = '/etc/sysconfig/network'
    header = ('# Created by cloud-init on instance boot automatically, '
              'do not edit.\n#\n')

    expected_name = 'expected_sysconfig'

    def _get_renderer(self):
        distro_cls = distros.fetch('opensuse')
        return sysconfig.Renderer(
            config=distro_cls.renderer_configs.get('sysconfig'))

    def _render_and_read(self, network_config=None, state=None, dir=None):
        if dir is None:
            dir = self.tmp_dir()

        if network_config:
            ns = network_state.parse_net_config_data(network_config)
        elif state:
            ns = state
        else:
            raise ValueError("Expected data or state, got neither")

        renderer = self._get_renderer()
        renderer.render_network_state(ns, target=dir)
        return dir2dict(dir)

    def _compare_files_to_expected(self, expected, found):
        orig_maxdiff = self.maxDiff
        expected_d = dict(
            (os.path.join(self.scripts_dir, k), util.load_shell_content(v))
            for k, v in expected.items())

        # only compare the files in scripts_dir
        scripts_found = dict(
            (k, util.load_shell_content(v)) for k, v in found.items()
            if k.startswith(self.scripts_dir))
        try:
            self.maxDiff = None
            self.assertEqual(expected_d, scripts_found)
        finally:
            self.maxDiff = orig_maxdiff

    def _assert_headers(self, found):
        missing = [f for f in found
                   if (f.startswith(self.scripts_dir) and
                       not found[f].startswith(self.header))]
        if missing:
            raise AssertionError("Missing headers in: %s" % missing)

    @mock.patch("cloudinit.net.util.get_cmdline", return_value="root=myroot")
    @mock.patch("cloudinit.net.sys_dev_path")
    @mock.patch("cloudinit.net.read_sys_net")
    @mock.patch("cloudinit.net.get_devicelist")
    def test_default_generation(self, mock_get_devicelist,
                                mock_read_sys_net,
                                mock_sys_dev_path, m_get_cmdline):
        tmp_dir = self.tmp_dir()
        _setup_test(tmp_dir, mock_get_devicelist,
                    mock_read_sys_net, mock_sys_dev_path)

        network_cfg = net.generate_fallback_config()
        ns = network_state.parse_net_config_data(network_cfg,
                                                 skip_broken=False)

        render_dir = os.path.join(tmp_dir, "render")
        os.makedirs(render_dir)

        renderer = self._get_renderer()
        renderer.render_network_state(ns, target=render_dir)

        render_file = 'etc/sysconfig/network/ifcfg-eth1000'
        with open(os.path.join(render_dir, render_file)) as fh:
            content = fh.read()
            expected_content = """
# Created by cloud-init on instance boot automatically, do not edit.
#
BOOTPROTO=dhcp
DEVICE=eth1000
HWADDR=07-1c-c6-75-a4-be
NM_CONTROLLED=no
ONBOOT=yes
STARTMODE=auto
TYPE=Ethernet
USERCTL=no
""".lstrip()
            self.assertEqual(expected_content, content)

    def test_multiple_ipv4_default_gateways(self):
        """ValueError is raised when duplicate ipv4 gateways exist."""
        net_json = {
            "services": [{"type": "dns", "address": "172.19.0.12"}],
            "networks": [{
                "network_id": "dacd568d-5be6-4786-91fe-750c374b78b4",
                "type": "ipv4", "netmask": "255.255.252.0",
                "link": "tap1a81968a-79",
                "routes": [{
                    "netmask": "0.0.0.0",
                    "network": "0.0.0.0",
                    "gateway": "172.19.3.254",
                }, {
                    "netmask": "0.0.0.0",  # A second default gateway
                    "network": "0.0.0.0",
                    "gateway": "172.20.3.254",
                }],
                "ip_address": "172.19.1.34", "id": "network0"
            }],
            "links": [
                {
                    "ethernet_mac_address": "fa:16:3e:ed:9a:59",
                    "mtu": None, "type": "bridge", "id":
                    "tap1a81968a-79",
                    "vif_id": "1a81968a-797a-400f-8a80-567f997eb93f"
                },
            ],
        }
        macs = {'fa:16:3e:ed:9a:59': 'eth0'}
        render_dir = self.tmp_dir()
        network_cfg = openstack.convert_net_json(net_json, known_macs=macs)
        ns = network_state.parse_net_config_data(network_cfg,
                                                 skip_broken=False)
        renderer = self._get_renderer()
        with self.assertRaises(ValueError):
            renderer.render_network_state(ns, target=render_dir)
        self.assertEqual([], os.listdir(render_dir))

    def test_multiple_ipv6_default_gateways(self):
        """ValueError is raised when duplicate ipv6 gateways exist."""
        net_json = {
            "services": [{"type": "dns", "address": "172.19.0.12"}],
            "networks": [{
                "network_id": "public-ipv6",
                "type": "ipv6", "netmask": "",
                "link": "tap1a81968a-79",
                "routes": [{
                    "gateway": "2001:DB8::1",
                    "netmask": "::",
                    "network": "::"
                }, {
                    "gateway": "2001:DB9::1",
                    "netmask": "::",
                    "network": "::"
                }],
                "ip_address": "2001:DB8::10", "id": "network1"
            }],
            "links": [
                {
                    "ethernet_mac_address": "fa:16:3e:ed:9a:59",
                    "mtu": None, "type": "bridge", "id":
                    "tap1a81968a-79",
                    "vif_id": "1a81968a-797a-400f-8a80-567f997eb93f"
                },
            ],
        }
        macs = {'fa:16:3e:ed:9a:59': 'eth0'}
        render_dir = self.tmp_dir()
        network_cfg = openstack.convert_net_json(net_json, known_macs=macs)
        ns = network_state.parse_net_config_data(network_cfg,
                                                 skip_broken=False)
        renderer = self._get_renderer()
        with self.assertRaises(ValueError):
            renderer.render_network_state(ns, target=render_dir)
        self.assertEqual([], os.listdir(render_dir))

    def test_openstack_rendering_samples(self):
        for os_sample in OS_SAMPLES:
            render_dir = self.tmp_dir()
            ex_input = os_sample['in_data']
            ex_mac_addrs = os_sample['in_macs']
            network_cfg = openstack.convert_net_json(
                ex_input, known_macs=ex_mac_addrs)
            ns = network_state.parse_net_config_data(network_cfg,
                                                     skip_broken=False)
            renderer = self._get_renderer()
            # render a multiple times to simulate reboots
            renderer.render_network_state(ns, target=render_dir)
            renderer.render_network_state(ns, target=render_dir)
            renderer.render_network_state(ns, target=render_dir)
            for fn, expected_content in os_sample.get('out_sysconfig_opensuse',
                                                      []):
                with open(os.path.join(render_dir, fn)) as fh:
                    self.assertEqual(expected_content, fh.read())

    def test_network_config_v1_samples(self):
        ns = network_state.parse_net_config_data(CONFIG_V1_SIMPLE_SUBNET)
        render_dir = self.tmp_path("render")
        os.makedirs(render_dir)
        renderer = self._get_renderer()
        renderer.render_network_state(ns, target=render_dir)
        found = dir2dict(render_dir)
        nspath = '/etc/sysconfig/network/'
        self.assertNotIn(nspath + 'ifcfg-lo', found.keys())
        expected = """\
# Created by cloud-init on instance boot automatically, do not edit.
#
BOOTPROTO=none
DEFROUTE=yes
DEVICE=interface0
GATEWAY=10.0.2.2
HWADDR=52:54:00:12:34:00
IPADDR=10.0.2.15
NETMASK=255.255.255.0
NM_CONTROLLED=no
ONBOOT=yes
STARTMODE=auto
TYPE=Ethernet
USERCTL=no
"""
        self.assertEqual(expected, found[nspath + 'ifcfg-interface0'])
        # The configuration has no nameserver information make sure we
        # do not write the resolv.conf file
        respath = '/etc/resolv.conf'
        self.assertNotIn(respath, found.keys())

    def test_config_with_explicit_loopback(self):
        ns = network_state.parse_net_config_data(CONFIG_V1_EXPLICIT_LOOPBACK)
        render_dir = self.tmp_path("render")
        os.makedirs(render_dir)
        # write an etc/resolv.conf and expect it to not be modified
        resolvconf = os.path.join(render_dir, 'etc/resolv.conf')
        resolvconf_content = "# Original Content"
        util.write_file(resolvconf, resolvconf_content)
        renderer = self._get_renderer()
        renderer.render_network_state(ns, target=render_dir)
        found = dir2dict(render_dir)
        nspath = '/etc/sysconfig/network/'
        self.assertNotIn(nspath + 'ifcfg-lo', found.keys())
        expected = """\
# Created by cloud-init on instance boot automatically, do not edit.
#
BOOTPROTO=dhcp
DEVICE=eth0
NM_CONTROLLED=no
ONBOOT=yes
STARTMODE=auto
TYPE=Ethernet
USERCTL=no
"""
        self.assertEqual(expected, found[nspath + 'ifcfg-eth0'])
        # a dhcp only config should not modify resolv.conf
        self.assertEqual(resolvconf_content, found['/etc/resolv.conf'])

    def test_bond_config(self):
        expected_name = 'expected_sysconfig_opensuse'
        entry = NETWORK_CONFIGS['bond']
        found = self._render_and_read(network_config=yaml.load(entry['yaml']))
        for fname, contents in entry[expected_name].items():
            print(fname)
            print(contents)
            print()
        print('-- expected ^ | v rendered --')
        for fname, contents in found.items():
            print(fname)
            print(contents)
            print()
        self._compare_files_to_expected(entry[expected_name], found)
        self._assert_headers(found)

    def test_vlan_config(self):
        entry = NETWORK_CONFIGS['vlan']
        found = self._render_and_read(network_config=yaml.load(entry['yaml']))
        self._compare_files_to_expected(entry[self.expected_name], found)
        self._assert_headers(found)

    def test_bridge_config(self):
        entry = NETWORK_CONFIGS['bridge']
        found = self._render_and_read(network_config=yaml.load(entry['yaml']))
        self._compare_files_to_expected(entry[self.expected_name], found)
        self._assert_headers(found)

    def test_manual_config(self):
        entry = NETWORK_CONFIGS['manual']
        found = self._render_and_read(network_config=yaml.load(entry['yaml']))
        self._compare_files_to_expected(entry[self.expected_name], found)
        self._assert_headers(found)

    def test_all_config(self):
        entry = NETWORK_CONFIGS['all']
        found = self._render_and_read(network_config=yaml.load(entry['yaml']))
        self._compare_files_to_expected(entry[self.expected_name], found)
        self._assert_headers(found)
        self.assertNotIn(
            'WARNING: Network config: ignoring eth0.101 device-level mtu',
            self.logs.getvalue())

    def test_small_config(self):
        entry = NETWORK_CONFIGS['small']
        found = self._render_and_read(network_config=yaml.load(entry['yaml']))
        self._compare_files_to_expected(entry[self.expected_name], found)
        self._assert_headers(found)

    def test_v4_and_v6_static_config(self):
        entry = NETWORK_CONFIGS['v4_and_v6_static']
        found = self._render_and_read(network_config=yaml.load(entry['yaml']))
        self._compare_files_to_expected(entry[self.expected_name], found)
        self._assert_headers(found)
        expected_msg = (
            'WARNING: Network config: ignoring iface0 device-level mtu:8999'
            ' because ipv4 subnet-level mtu:9000 provided.')
        self.assertIn(expected_msg, self.logs.getvalue())

    def test_dhcpv6_only_config(self):
        entry = NETWORK_CONFIGS['dhcpv6_only']
        found = self._render_and_read(network_config=yaml.load(entry['yaml']))
        self._compare_files_to_expected(entry[self.expected_name], found)
        self._assert_headers(found)


class TestEniNetRendering(CiTestCase):

    @mock.patch("cloudinit.net.util.get_cmdline", return_value="root=myroot")
    @mock.patch("cloudinit.net.sys_dev_path")
    @mock.patch("cloudinit.net.read_sys_net")
    @mock.patch("cloudinit.net.get_devicelist")
    def test_default_generation(self, mock_get_devicelist,
                                mock_read_sys_net,
                                mock_sys_dev_path, m_get_cmdline):
        tmp_dir = self.tmp_dir()
        _setup_test(tmp_dir, mock_get_devicelist,
                    mock_read_sys_net, mock_sys_dev_path)

        network_cfg = net.generate_fallback_config()
        ns = network_state.parse_net_config_data(network_cfg,
                                                 skip_broken=False)

        render_dir = os.path.join(tmp_dir, "render")
        os.makedirs(render_dir)

        renderer = eni.Renderer(
            {'eni_path': 'interfaces', 'netrules_path': None})
        renderer.render_network_state(ns, target=render_dir)

        self.assertTrue(os.path.exists(os.path.join(render_dir,
                                                    'interfaces')))
        with open(os.path.join(render_dir, 'interfaces')) as fh:
            contents = fh.read()

        expected = """
auto lo
iface lo inet loopback

auto eth1000
iface eth1000 inet dhcp
"""
        self.assertEqual(expected.lstrip(), contents.lstrip())

    def test_config_with_explicit_loopback(self):
        tmp_dir = self.tmp_dir()
        ns = network_state.parse_net_config_data(CONFIG_V1_EXPLICIT_LOOPBACK)
        renderer = eni.Renderer()
        renderer.render_network_state(ns, target=tmp_dir)
        expected = """\
auto lo
iface lo inet loopback

auto eth0
iface eth0 inet dhcp
"""
        self.assertEqual(
            expected, dir2dict(tmp_dir)['/etc/network/interfaces'])

    def test_v2_route_metric_to_eni(self):
        """Network v2 route-metric overrides are preserved in eni output"""
        tmp_dir = self.tmp_dir()
        renderer = eni.Renderer()
        expected_tmpl = textwrap.dedent("""\
            auto lo
            iface lo inet loopback

            auto eth0
            iface eth0 inet{suffix} dhcp
                metric 100
            """)
        for dhcp_ver in ('dhcp4', 'dhcp6'):
            suffix = '6' if dhcp_ver == 'dhcp6' else ''
            dhcp_cfg = {
                dhcp_ver: True,
                '{ver}-overrides'.format(ver=dhcp_ver): {'route-metric': 100}}
            v2_input = {'version': 2, 'ethernets': {'eth0': dhcp_cfg}}
            ns = network_state.parse_net_config_data(v2_input)
            renderer.render_network_state(ns, target=tmp_dir)
            self.assertEqual(
                expected_tmpl.format(suffix=suffix),
                dir2dict(tmp_dir)['/etc/network/interfaces'])


class TestNetplanNetRendering(CiTestCase):

    @mock.patch("cloudinit.net.util.get_cmdline", return_value="root=myroot")
    @mock.patch("cloudinit.net.netplan._clean_default")
    @mock.patch("cloudinit.net.sys_dev_path")
    @mock.patch("cloudinit.net.read_sys_net")
    @mock.patch("cloudinit.net.get_devicelist")
    def test_default_generation(self, mock_get_devicelist,
                                mock_read_sys_net,
                                mock_sys_dev_path,
                                mock_clean_default, m_get_cmdline):
        tmp_dir = self.tmp_dir()
        _setup_test(tmp_dir, mock_get_devicelist,
                    mock_read_sys_net, mock_sys_dev_path)

        network_cfg = net.generate_fallback_config()
        ns = network_state.parse_net_config_data(network_cfg,
                                                 skip_broken=False)

        render_dir = os.path.join(tmp_dir, "render")
        os.makedirs(render_dir)

        render_target = 'netplan.yaml'
        renderer = netplan.Renderer(
            {'netplan_path': render_target, 'postcmds': False})
        renderer.render_network_state(ns, target=render_dir)

        self.assertTrue(os.path.exists(os.path.join(render_dir,
                                                    render_target)))
        with open(os.path.join(render_dir, render_target)) as fh:
            contents = fh.read()
            print(contents)

        expected = """
network:
    ethernets:
        eth1000:
            dhcp4: true
            match:
                macaddress: 07-1c-c6-75-a4-be
            set-name: eth1000
    version: 2
"""
        self.assertEqual(expected.lstrip(), contents.lstrip())
        self.assertEqual(1, mock_clean_default.call_count)


class TestNetplanCleanDefault(CiTestCase):
    snapd_known_path = 'etc/netplan/00-snapd-config.yaml'
    snapd_known_content = textwrap.dedent("""\
        # This is the initial network config.
        # It can be overwritten by cloud-init or console-conf.
        network:
            version: 2
            ethernets:
                all-en:
                    match:
                        name: "en*"
                    dhcp4: true
                all-eth:
                    match:
                        name: "eth*"
                    dhcp4: true
        """)
    stub_known = {
        'run/systemd/network/10-netplan-all-en.network': 'foo-en',
        'run/systemd/network/10-netplan-all-eth.network': 'foo-eth',
        'run/systemd/generator/netplan.stamp': 'stamp',
    }

    def test_clean_known_config_cleaned(self):
        content = {self.snapd_known_path: self.snapd_known_content, }
        content.update(self.stub_known)
        tmpd = self.tmp_dir()
        files = sorted(populate_dir(tmpd, content))
        netplan._clean_default(target=tmpd)
        found = [t for t in files if os.path.exists(t)]
        self.assertEqual([], found)

    def test_clean_unknown_config_not_cleaned(self):
        content = {self.snapd_known_path: self.snapd_known_content, }
        content.update(self.stub_known)
        content[self.snapd_known_path] += "# user put a comment\n"
        tmpd = self.tmp_dir()
        files = sorted(populate_dir(tmpd, content))
        netplan._clean_default(target=tmpd)
        found = [t for t in files if os.path.exists(t)]
        self.assertEqual(files, found)

    def test_clean_known_config_cleans_only_expected(self):
        astamp = "run/systemd/generator/another.stamp"
        anet = "run/systemd/network/10-netplan-all-lo.network"
        ayaml = "etc/netplan/01-foo-config.yaml"
        content = {
            self.snapd_known_path: self.snapd_known_content,
            astamp: "stamp",
            anet: "network",
            ayaml: "yaml",
        }
        content.update(self.stub_known)

        tmpd = self.tmp_dir()
        files = sorted(populate_dir(tmpd, content))
        netplan._clean_default(target=tmpd)
        found = [t for t in files if os.path.exists(t)]
        expected = [util.target_path(tmpd, f) for f in (astamp, anet, ayaml)]
        self.assertEqual(sorted(expected), found)


class TestNetplanPostcommands(CiTestCase):
    mycfg = {
        'config': [{"type": "physical", "name": "eth0",
                    "mac_address": "c0:d6:9f:2c:e8:80",
                    "subnets": [{"type": "dhcp"}]}],
        'version': 1}

    @mock.patch.object(netplan.Renderer, '_netplan_generate')
    @mock.patch.object(netplan.Renderer, '_net_setup_link')
    @mock.patch('cloudinit.util.subp')
    def test_netplan_render_calls_postcmds(self, mock_subp,
                                           mock_netplan_generate,
                                           mock_net_setup_link):
        tmp_dir = self.tmp_dir()
        ns = network_state.parse_net_config_data(self.mycfg,
                                                 skip_broken=False)

        render_dir = os.path.join(tmp_dir, "render")
        os.makedirs(render_dir)

        render_target = 'netplan.yaml'
        renderer = netplan.Renderer(
            {'netplan_path': render_target, 'postcmds': True})
        mock_subp.side_effect = iter([util.ProcessExecutionError])
        renderer.render_network_state(ns, target=render_dir)

        mock_netplan_generate.assert_called_with(run=True)
        mock_net_setup_link.assert_called_with(run=True)

    @mock.patch('cloudinit.util.SeLinuxGuard')
    @mock.patch.object(netplan, "get_devicelist")
    @mock.patch('cloudinit.util.subp')
    def test_netplan_postcmds(self, mock_subp, mock_devlist, mock_sel):
        mock_sel.__enter__ = mock.Mock(return_value=False)
        mock_sel.__exit__ = mock.Mock()
        mock_devlist.side_effect = [['lo']]
        tmp_dir = self.tmp_dir()
        ns = network_state.parse_net_config_data(self.mycfg,
                                                 skip_broken=False)

        render_dir = os.path.join(tmp_dir, "render")
        os.makedirs(render_dir)

        render_target = 'netplan.yaml'
        renderer = netplan.Renderer(
            {'netplan_path': render_target, 'postcmds': True})
        mock_subp.side_effect = iter([
            util.ProcessExecutionError,
            ('', ''),
            ('', ''),
        ])
        expected = [
            mock.call(['netplan', 'info'], capture=True),
            mock.call(['netplan', 'generate'], capture=True),
            mock.call(['udevadm', 'test-builtin', 'net_setup_link',
                       '/sys/class/net/lo'], capture=True),
        ]
        with mock.patch.object(os.path, 'islink', return_value=True):
            renderer.render_network_state(ns, target=render_dir)
            mock_subp.assert_has_calls(expected)


class TestEniNetworkStateToEni(CiTestCase):
    mycfg = {
        'config': [{"type": "physical", "name": "eth0",
                    "mac_address": "c0:d6:9f:2c:e8:80",
                    "subnets": [{"type": "dhcp"}]}],
        'version': 1}
    my_mac = 'c0:d6:9f:2c:e8:80'

    def test_no_header(self):
        rendered = eni.network_state_to_eni(
            network_state=network_state.parse_net_config_data(self.mycfg),
            render_hwaddress=True)
        self.assertIn(self.my_mac, rendered)
        self.assertIn("hwaddress", rendered)

    def test_with_header(self):
        header = "# hello world\n"
        rendered = eni.network_state_to_eni(
            network_state=network_state.parse_net_config_data(self.mycfg),
            header=header, render_hwaddress=True)
        self.assertIn(header, rendered)
        self.assertIn(self.my_mac, rendered)

    def test_no_hwaddress(self):
        rendered = eni.network_state_to_eni(
            network_state=network_state.parse_net_config_data(self.mycfg),
            render_hwaddress=False)
        self.assertNotIn(self.my_mac, rendered)
        self.assertNotIn("hwaddress", rendered)


class TestCmdlineConfigParsing(CiTestCase):
    simple_cfg = {
        'config': [{"type": "physical", "name": "eth0",
                    "mac_address": "c0:d6:9f:2c:e8:80",
                    "subnets": [{"type": "dhcp"}]}]}

    def test_cmdline_convert_dhcp(self):
        found = cmdline._klibc_to_config_entry(DHCP_CONTENT_1)
        self.assertEqual(found, ('eth0', DHCP_EXPECTED_1))

    def test_cmdline_convert_dhcp6(self):
        found = cmdline._klibc_to_config_entry(DHCP6_CONTENT_1)
        self.assertEqual(found, ('eno1', DHCP6_EXPECTED_1))

    def test_cmdline_convert_static(self):
        found = cmdline._klibc_to_config_entry(STATIC_CONTENT_1)
        self.assertEqual(found, ('eth1', STATIC_EXPECTED_1))

    def test_config_from_cmdline_net_cfg(self):
        files = []
        pairs = (('net-eth0.cfg', DHCP_CONTENT_1),
                 ('net-eth1.cfg', STATIC_CONTENT_1))

        macs = {'eth1': 'b8:ae:ed:75:ff:2b',
                'eth0': 'b8:ae:ed:75:ff:2a'}

        dhcp = copy.deepcopy(DHCP_EXPECTED_1)
        dhcp['mac_address'] = macs['eth0']

        static = copy.deepcopy(STATIC_EXPECTED_1)
        static['mac_address'] = macs['eth1']

        expected = {'version': 1, 'config': [dhcp, static]}
        with temp_utils.tempdir() as tmpd:
            for fname, content in pairs:
                fp = os.path.join(tmpd, fname)
                files.append(fp)
                util.write_file(fp, content)

            found = cmdline.config_from_klibc_net_cfg(files=files,
                                                      mac_addrs=macs)
            self.assertEqual(found, expected)

    def test_cmdline_with_b64(self):
        data = base64.b64encode(json.dumps(self.simple_cfg).encode())
        encoded_text = data.decode()
        raw_cmdline = 'ro network-config=' + encoded_text + ' root=foo'
        found = cmdline.read_kernel_cmdline_config(cmdline=raw_cmdline)
        self.assertEqual(found, self.simple_cfg)

    def test_cmdline_with_b64_gz(self):
        data = _gzip_data(json.dumps(self.simple_cfg).encode())
        encoded_text = base64.b64encode(data).decode()
        raw_cmdline = 'ro network-config=' + encoded_text + ' root=foo'
        found = cmdline.read_kernel_cmdline_config(cmdline=raw_cmdline)
        self.assertEqual(found, self.simple_cfg)


class TestCmdlineKlibcNetworkConfigSource(FilesystemMockingTestCase):
    macs = {
        'eth0': '14:02:ec:42:48:00',
        'eno1': '14:02:ec:42:48:01',
    }

    def test_without_ip(self):
        content = {'/run/net-eth0.conf': DHCP_CONTENT_1,
                   cmdline._OPEN_ISCSI_INTERFACE_FILE: "eth0\n"}
        exp1 = copy.deepcopy(DHCP_EXPECTED_1)
        exp1['mac_address'] = self.macs['eth0']

        root = self.tmp_dir()
        populate_dir(root, content)
        self.reRoot(root)

        src = cmdline.KlibcNetworkConfigSource(
            _cmdline='foo root=/root/bar', _mac_addrs=self.macs,
        )
        self.assertTrue(src.is_applicable())
        found = src.render_config()
        self.assertEqual(found['version'], 1)
        self.assertEqual(found['config'], [exp1])

    def test_with_ip(self):
        content = {'/run/net-eth0.conf': DHCP_CONTENT_1}
        exp1 = copy.deepcopy(DHCP_EXPECTED_1)
        exp1['mac_address'] = self.macs['eth0']

        root = self.tmp_dir()
        populate_dir(root, content)
        self.reRoot(root)

        src = cmdline.KlibcNetworkConfigSource(
            _cmdline='foo ip=dhcp', _mac_addrs=self.macs,
        )
        self.assertTrue(src.is_applicable())
        found = src.render_config()
        self.assertEqual(found['version'], 1)
        self.assertEqual(found['config'], [exp1])

    def test_with_ip6(self):
        content = {'/run/net6-eno1.conf': DHCP6_CONTENT_1}
        root = self.tmp_dir()
        populate_dir(root, content)
        self.reRoot(root)

        src = cmdline.KlibcNetworkConfigSource(
            _cmdline='foo ip6=dhcp root=/dev/sda', _mac_addrs=self.macs,
        )
        self.assertTrue(src.is_applicable())
        found = src.render_config()
        self.assertEqual(
            found,
            {'version': 1, 'config': [
             {'type': 'physical', 'name': 'eno1',
              'mac_address': self.macs['eno1'],
              'subnets': [
                  {'dns_nameservers': ['2001:67c:1562:8010::2:1'],
                   'control': 'manual', 'type': 'dhcp6', 'netmask': '64'}]}]})

    def test_with_no_ip_or_ip6(self):
        # if there is no ip= or ip6= on cmdline, return value should be None
        content = {'net6-eno1.conf': DHCP6_CONTENT_1}
        files = sorted(populate_dir(self.tmp_dir(), content))
        src = cmdline.KlibcNetworkConfigSource(
            _files=files, _cmdline='foo root=/dev/sda', _mac_addrs=self.macs,
        )
        self.assertFalse(src.is_applicable())

    def test_with_both_ip_ip6(self):
        content = {
            '/run/net-eth0.conf': DHCP_CONTENT_1,
            '/run/net6-eth0.conf': DHCP6_CONTENT_1.replace('eno1', 'eth0')}
        eth0 = copy.deepcopy(DHCP_EXPECTED_1)
        eth0['mac_address'] = self.macs['eth0']
        eth0['subnets'].append(
            {'control': 'manual', 'type': 'dhcp6',
             'netmask': '64', 'dns_nameservers': ['2001:67c:1562:8010::2:1']})
        expected = [eth0]

        root = self.tmp_dir()
        populate_dir(root, content)
        self.reRoot(root)

        src = cmdline.KlibcNetworkConfigSource(
            _cmdline='foo ip=dhcp ip6=dhcp', _mac_addrs=self.macs,
        )

        self.assertTrue(src.is_applicable())
        found = src.render_config()
        self.assertEqual(found['version'], 1)
        self.assertEqual(found['config'], expected)


class TestReadInitramfsConfig(CiTestCase):

    def _config_source_cls_mock(self, is_applicable, render_config=None):
        return lambda: mock.Mock(
            is_applicable=lambda: is_applicable,
            render_config=lambda: render_config,
        )

    def test_no_sources(self):
        with mock.patch('cloudinit.net.cmdline._INITRAMFS_CONFIG_SOURCES', []):
            self.assertIsNone(cmdline.read_initramfs_config())

    def test_no_applicable_sources(self):
        sources = [
            self._config_source_cls_mock(is_applicable=False),
            self._config_source_cls_mock(is_applicable=False),
            self._config_source_cls_mock(is_applicable=False),
        ]
        with mock.patch('cloudinit.net.cmdline._INITRAMFS_CONFIG_SOURCES',
                        sources):
            self.assertIsNone(cmdline.read_initramfs_config())

    def test_one_applicable_source(self):
        expected_config = object()
        sources = [
            self._config_source_cls_mock(
                is_applicable=True, render_config=expected_config,
            ),
        ]
        with mock.patch('cloudinit.net.cmdline._INITRAMFS_CONFIG_SOURCES',
                        sources):
            self.assertEqual(expected_config, cmdline.read_initramfs_config())

    def test_one_applicable_source_after_inapplicable_sources(self):
        expected_config = object()
        sources = [
            self._config_source_cls_mock(is_applicable=False),
            self._config_source_cls_mock(is_applicable=False),
            self._config_source_cls_mock(
                is_applicable=True, render_config=expected_config,
            ),
        ]
        with mock.patch('cloudinit.net.cmdline._INITRAMFS_CONFIG_SOURCES',
                        sources):
            self.assertEqual(expected_config, cmdline.read_initramfs_config())

    def test_first_applicable_source_is_used(self):
        first_config, second_config = object(), object()
        sources = [
            self._config_source_cls_mock(
                is_applicable=True, render_config=first_config,
            ),
            self._config_source_cls_mock(
                is_applicable=True, render_config=second_config,
            ),
        ]
        with mock.patch('cloudinit.net.cmdline._INITRAMFS_CONFIG_SOURCES',
                        sources):
            self.assertEqual(first_config, cmdline.read_initramfs_config())


class TestNetplanRoundTrip(CiTestCase):

    NETPLAN_INFO_OUT = textwrap.dedent("""
    netplan.io:
      features:
        - dhcp-use-domains
        - ipv6-mtu
      website: https://netplan.io/
    """)

    def setUp(self):
        super(TestNetplanRoundTrip, self).setUp()
        self.add_patch('cloudinit.net.netplan.util.subp', 'm_subp')
        self.m_subp.return_value = (self.NETPLAN_INFO_OUT, '')

    def _render_and_read(self, network_config=None, state=None,
                         netplan_path=None, target=None):
        if target is None:
            target = self.tmp_dir()

        if network_config:
            ns = network_state.parse_net_config_data(network_config)
        elif state:
            ns = state
        else:
            raise ValueError("Expected data or state, got neither")

        if netplan_path is None:
            netplan_path = 'etc/netplan/50-cloud-init.yaml'

        renderer = netplan.Renderer(
            config={'netplan_path': netplan_path})

        renderer.render_network_state(ns, target=target)
        return dir2dict(target)

    def testsimple_render_bond_netplan(self):
        entry = NETWORK_CONFIGS['bond']
        files = self._render_and_read(network_config=yaml.load(entry['yaml']))
        print(entry['expected_netplan'])
        print('-- expected ^ | v rendered --')
        print(files['/etc/netplan/50-cloud-init.yaml'])
        self.assertEqual(
            entry['expected_netplan'].splitlines(),
            files['/etc/netplan/50-cloud-init.yaml'].splitlines())

    def testsimple_render_bond_v2_input_netplan(self):
        entry = NETWORK_CONFIGS['bond']
        files = self._render_and_read(
            network_config=yaml.load(entry['yaml-v2']))
        print(entry['expected_netplan-v2'])
        print('-- expected ^ | v rendered --')
        print(files['/etc/netplan/50-cloud-init.yaml'])
        self.assertEqual(
            entry['expected_netplan-v2'].splitlines(),
            files['/etc/netplan/50-cloud-init.yaml'].splitlines())

    def testsimple_render_small_netplan(self):
        entry = NETWORK_CONFIGS['small']
        files = self._render_and_read(network_config=yaml.load(entry['yaml']))
        self.assertEqual(
            entry['expected_netplan'].splitlines(),
            files['/etc/netplan/50-cloud-init.yaml'].splitlines())

    def testsimple_render_v4_and_v6(self):
        entry = NETWORK_CONFIGS['v4_and_v6']
        files = self._render_and_read(network_config=yaml.load(entry['yaml']))
        self.assertEqual(
            entry['expected_netplan'].splitlines(),
            files['/etc/netplan/50-cloud-init.yaml'].splitlines())

    def testsimple_render_v4_and_v6_static(self):
        entry = NETWORK_CONFIGS['v4_and_v6_static']
        files = self._render_and_read(network_config=yaml.load(entry['yaml']))
        self.assertEqual(
            entry['expected_netplan'].splitlines(),
            files['/etc/netplan/50-cloud-init.yaml'].splitlines())

    def testsimple_render_dhcpv6_only(self):
        entry = NETWORK_CONFIGS['dhcpv6_only']
        files = self._render_and_read(network_config=yaml.load(entry['yaml']))
        self.assertEqual(
            entry['expected_netplan'].splitlines(),
            files['/etc/netplan/50-cloud-init.yaml'].splitlines())

    def testsimple_render_dhcpv6_accept_ra(self):
        entry = NETWORK_CONFIGS['dhcpv6_accept_ra']
        files = self._render_and_read(network_config=yaml.load(
            entry['yaml_v1']))
        self.assertEqual(
            entry['expected_netplan'].splitlines(),
            files['/etc/netplan/50-cloud-init.yaml'].splitlines())

    def testsimple_render_dhcpv6_reject_ra(self):
        entry = NETWORK_CONFIGS['dhcpv6_reject_ra']
        files = self._render_and_read(network_config=yaml.load(
            entry['yaml_v1']))
        self.assertEqual(
            entry['expected_netplan'].splitlines(),
            files['/etc/netplan/50-cloud-init.yaml'].splitlines())

    def testsimple_render_ipv6_slaac(self):
        entry = NETWORK_CONFIGS['ipv6_slaac']
        files = self._render_and_read(network_config=yaml.load(
            entry['yaml']))
        self.assertEqual(
            entry['expected_netplan'].splitlines(),
            files['/etc/netplan/50-cloud-init.yaml'].splitlines())

    def testsimple_render_dhcpv6_stateless(self):
        entry = NETWORK_CONFIGS['dhcpv6_stateless']
        files = self._render_and_read(network_config=yaml.load(
            entry['yaml']))
        self.assertEqual(
            entry['expected_netplan'].splitlines(),
            files['/etc/netplan/50-cloud-init.yaml'].splitlines())

    def testsimple_render_dhcpv6_stateful(self):
        entry = NETWORK_CONFIGS['dhcpv6_stateful']
        files = self._render_and_read(network_config=yaml.load(
            entry['yaml']))
        self.assertEqual(
            entry['expected_netplan'].splitlines(),
            files['/etc/netplan/50-cloud-init.yaml'].splitlines())

    def testsimple_render_all(self):
        entry = NETWORK_CONFIGS['all']
        files = self._render_and_read(network_config=yaml.load(entry['yaml']))
        print(entry['expected_netplan'])
        print('-- expected ^ | v rendered --')
        print(files['/etc/netplan/50-cloud-init.yaml'])
        self.assertEqual(
            entry['expected_netplan'].splitlines(),
            files['/etc/netplan/50-cloud-init.yaml'].splitlines())

    def testsimple_render_manual(self):
        entry = NETWORK_CONFIGS['manual']
        files = self._render_and_read(network_config=yaml.load(entry['yaml']))
        self.assertEqual(
            entry['expected_netplan'].splitlines(),
            files['/etc/netplan/50-cloud-init.yaml'].splitlines())

    def test_render_output_has_yaml_no_aliases(self):
        entry = {
            'yaml': V1_NAMESERVER_ALIAS,
            'expected_netplan': NETPLAN_NO_ALIAS,
        }
        network_config = yaml.load(entry['yaml'])
        ns = network_state.parse_net_config_data(network_config)
        files = self._render_and_read(state=ns)
        # check for alias
        content = files['/etc/netplan/50-cloud-init.yaml']

        # test load the yaml to ensure we don't render something not loadable
        # this allows single aliases, but not duplicate ones
        parsed = yaml.load(files['/etc/netplan/50-cloud-init.yaml'])
        self.assertNotEqual(None, parsed)

        # now look for any alias, avoid rendering them entirely
        # generate the first anchor string using the template
        # as of this writing, looks like "&id001"
        anchor = r'&' + Serializer.ANCHOR_TEMPLATE % 1
        found_alias = re.search(anchor, content, re.MULTILINE)
        if found_alias:
            msg = "Error at: %s\nContent:\n%s" % (found_alias, content)
            raise ValueError('Found yaml alias in rendered netplan: ' + msg)

        print(entry['expected_netplan'])
        print('-- expected ^ | v rendered --')
        print(files['/etc/netplan/50-cloud-init.yaml'])
        self.assertEqual(
            entry['expected_netplan'].splitlines(),
            files['/etc/netplan/50-cloud-init.yaml'].splitlines())

    def test_render_output_supports_both_grat_arp_spelling(self):
        entry = {
            'yaml': NETPLAN_BOND_GRAT_ARP,
            'expected_netplan': NETPLAN_BOND_GRAT_ARP.replace('gratuitous',
                                                              'gratuitious'),
        }
        network_config = yaml.load(entry['yaml']).get('network')
        files = self._render_and_read(network_config=network_config)
        print(entry['expected_netplan'])
        print('-- expected ^ | v rendered --')
        print(files['/etc/netplan/50-cloud-init.yaml'])
        self.assertEqual(
            entry['expected_netplan'].splitlines(),
            files['/etc/netplan/50-cloud-init.yaml'].splitlines())


class TestEniRoundTrip(CiTestCase):

    def _render_and_read(self, network_config=None, state=None, eni_path=None,
                         netrules_path=None, dir=None):
        if dir is None:
            dir = self.tmp_dir()

        if network_config:
            ns = network_state.parse_net_config_data(network_config)
        elif state:
            ns = state
        else:
            raise ValueError("Expected data or state, got neither")

        if eni_path is None:
            eni_path = 'etc/network/interfaces'

        renderer = eni.Renderer(
            config={'eni_path': eni_path, 'netrules_path': netrules_path})

        renderer.render_network_state(ns, target=dir)
        return dir2dict(dir)

    def testsimple_convert_and_render(self):
        network_config = eni.convert_eni_data(EXAMPLE_ENI)
        files = self._render_and_read(network_config=network_config)
        self.assertEqual(
            RENDERED_ENI.splitlines(),
            files['/etc/network/interfaces'].splitlines())

    def testsimple_render_all(self):
        entry = NETWORK_CONFIGS['all']
        files = self._render_and_read(network_config=yaml.load(entry['yaml']))
        self.assertEqual(
            entry['expected_eni'].splitlines(),
            files['/etc/network/interfaces'].splitlines())

    def testsimple_render_small(self):
        entry = NETWORK_CONFIGS['small']
        files = self._render_and_read(network_config=yaml.load(entry['yaml']))
        self.assertEqual(
            entry['expected_eni'].splitlines(),
            files['/etc/network/interfaces'].splitlines())

    def testsimple_render_v4_and_v6(self):
        entry = NETWORK_CONFIGS['v4_and_v6']
        files = self._render_and_read(network_config=yaml.load(entry['yaml']))
        self.assertEqual(
            entry['expected_eni'].splitlines(),
            files['/etc/network/interfaces'].splitlines())

    def testsimple_render_dhcpv6_only(self):
        entry = NETWORK_CONFIGS['dhcpv6_only']
        files = self._render_and_read(network_config=yaml.load(entry['yaml']))
        self.assertEqual(
            entry['expected_eni'].splitlines(),
            files['/etc/network/interfaces'].splitlines())

    def testsimple_render_v4_and_v6_static(self):
        entry = NETWORK_CONFIGS['v4_and_v6_static']
        files = self._render_and_read(network_config=yaml.load(entry['yaml']))
        self.assertEqual(
            entry['expected_eni'].splitlines(),
            files['/etc/network/interfaces'].splitlines())

    def testsimple_render_dhcpv6_stateless(self):
        entry = NETWORK_CONFIGS['dhcpv6_stateless']
        files = self._render_and_read(network_config=yaml.load(entry['yaml']))
        self.assertEqual(
            entry['expected_eni'].splitlines(),
            files['/etc/network/interfaces'].splitlines())

    def testsimple_render_ipv6_slaac(self):
        entry = NETWORK_CONFIGS['ipv6_slaac']
        files = self._render_and_read(network_config=yaml.load(entry['yaml']))
        self.assertEqual(
            entry['expected_eni'].splitlines(),
            files['/etc/network/interfaces'].splitlines())

    def testsimple_render_dhcpv6_stateful(self):
        entry = NETWORK_CONFIGS['dhcpv6_stateless']
        files = self._render_and_read(network_config=yaml.load(entry['yaml']))
        self.assertEqual(
            entry['expected_eni'].splitlines(),
            files['/etc/network/interfaces'].splitlines())

    def testsimple_render_dhcpv6_accept_ra(self):
        entry = NETWORK_CONFIGS['dhcpv6_accept_ra']
        files = self._render_and_read(network_config=yaml.load(
            entry['yaml_v1']))
        self.assertEqual(
            entry['expected_eni'].splitlines(),
            files['/etc/network/interfaces'].splitlines())

    def testsimple_render_dhcpv6_reject_ra(self):
        entry = NETWORK_CONFIGS['dhcpv6_reject_ra']
        files = self._render_and_read(network_config=yaml.load(
            entry['yaml_v1']))
        self.assertEqual(
            entry['expected_eni'].splitlines(),
            files['/etc/network/interfaces'].splitlines())

    def testsimple_render_manual(self):
        """Test rendering of 'manual' for 'type' and 'control'.

        'type: manual' in a subnet is odd, but it is the way that was used
        to declare that a network device should get a mtu set on it even
        if there were no addresses to configure.  Also strange is the fact
        that in order to apply that MTU the ifupdown device must be set
        to 'auto', or the MTU would not be set."""
        entry = NETWORK_CONFIGS['manual']
        files = self._render_and_read(network_config=yaml.load(entry['yaml']))
        self.assertEqual(
            entry['expected_eni'].splitlines(),
            files['/etc/network/interfaces'].splitlines())

    def test_routes_rendered(self):
        # as reported in bug 1649652
        conf = [
            {'name': 'eth0', 'type': 'physical',
             'subnets': [{
                 'address': '172.23.31.42/26',
                 'dns_nameservers': [], 'gateway': '172.23.31.2',
                 'type': 'static'}]},
            {'type': 'route', 'id': 4,
             'metric': 0, 'destination': '10.0.0.0/12',
             'gateway': '172.23.31.1'},
            {'type': 'route', 'id': 5,
             'metric': 0, 'destination': '192.168.2.0/16',
             'gateway': '172.23.31.1'},
            {'type': 'route', 'id': 6,
             'metric': 1, 'destination': '10.0.200.0/16',
             'gateway': '172.23.31.1'},
        ]

        files = self._render_and_read(
            network_config={'config': conf, 'version': 1})
        expected = [
            'auto lo',
            'iface lo inet loopback',
            'auto eth0',
            'iface eth0 inet static',
            '    address 172.23.31.42/26',
            '    gateway 172.23.31.2',
            ('post-up route add -net 10.0.0.0/12 gw '
             '172.23.31.1 metric 0 || true'),
            ('pre-down route del -net 10.0.0.0/12 gw '
             '172.23.31.1 metric 0 || true'),
            ('post-up route add -net 192.168.2.0/16 gw '
             '172.23.31.1 metric 0 || true'),
            ('pre-down route del -net 192.168.2.0/16 gw '
             '172.23.31.1 metric 0 || true'),
            ('post-up route add -net 10.0.200.0/16 gw '
             '172.23.31.1 metric 1 || true'),
            ('pre-down route del -net 10.0.200.0/16 gw '
             '172.23.31.1 metric 1 || true'),
        ]
        found = files['/etc/network/interfaces'].splitlines()

        self.assertEqual(
            expected, [line for line in found if line])

    def test_ipv6_static_routes(self):
        # as reported in bug 1818669
        conf = [
            {'name': 'eno3', 'type': 'physical',
             'subnets': [{
                 'address': 'fd00::12/64',
                 'dns_nameservers': ['fd00:2::15'],
                 'gateway': 'fd00::1',
                 'ipv6': True,
                 'type': 'static',
                 'routes': [{'netmask': '32',
                             'network': 'fd00:12::',
                             'gateway': 'fd00::2'},
                            {'network': 'fd00:14::',
                             'gateway': 'fd00::3'},
                            {'destination': 'fe00:14::/48',
                             'gateway': 'fe00::4',
                             'metric': 500},
                            {'gateway': '192.168.23.1',
                             'metric': 999,
                             'netmask': 24,
                             'network': '192.168.23.0'},
                            {'destination': '10.23.23.0/24',
                             'gateway': '10.23.23.2',
                             'metric': 300}]}]},
        ]

        files = self._render_and_read(
            network_config={'config': conf, 'version': 1})
        expected = [
            'auto lo',
            'iface lo inet loopback',
            'auto eno3',
            'iface eno3 inet6 static',
            '    address fd00::12/64',
            '    dns-nameservers fd00:2::15',
            '    gateway fd00::1',
            ('    post-up route add -A inet6 fd00:12::/32 gw '
             'fd00::2 || true'),
            ('    pre-down route del -A inet6 fd00:12::/32 gw '
             'fd00::2 || true'),
            ('    post-up route add -A inet6 fd00:14::/64 gw '
             'fd00::3 || true'),
            ('    pre-down route del -A inet6 fd00:14::/64 gw '
             'fd00::3 || true'),
            ('    post-up route add -A inet6 fe00:14::/48 gw '
             'fe00::4 metric 500 || true'),
            ('    pre-down route del -A inet6 fe00:14::/48 gw '
             'fe00::4 metric 500 || true'),
            ('    post-up route add -net 192.168.23.0/24 gw '
             '192.168.23.1 metric 999 || true'),
            ('    pre-down route del -net 192.168.23.0/24 gw '
             '192.168.23.1 metric 999 || true'),
            ('    post-up route add -net 10.23.23.0/24 gw '
             '10.23.23.2 metric 300 || true'),
            ('    pre-down route del -net 10.23.23.0/24 gw '
             '10.23.23.2 metric 300 || true'),

        ]
        found = files['/etc/network/interfaces'].splitlines()

        self.assertEqual(
            expected, [line for line in found if line])

    def testsimple_render_bond(self):
        entry = NETWORK_CONFIGS['bond']
        files = self._render_and_read(network_config=yaml.load(entry['yaml']))
        self.assertEqual(
            entry['expected_eni'].splitlines(),
            files['/etc/network/interfaces'].splitlines())


class TestNetRenderers(CiTestCase):
    @mock.patch("cloudinit.net.renderers.sysconfig.available")
    @mock.patch("cloudinit.net.renderers.eni.available")
    def test_eni_and_sysconfig_available(self, m_eni_avail, m_sysc_avail):
        m_eni_avail.return_value = True
        m_sysc_avail.return_value = True
        found = renderers.search(priority=['sysconfig', 'eni'], first=False)
        names = [f[0] for f in found]
        self.assertEqual(['sysconfig', 'eni'], names)

    @mock.patch("cloudinit.net.renderers.eni.available")
    def test_search_returns_empty_on_none(self, m_eni_avail):
        m_eni_avail.return_value = False
        found = renderers.search(priority=['eni'], first=False)
        self.assertEqual([], found)

    @mock.patch("cloudinit.net.renderers.sysconfig.available")
    @mock.patch("cloudinit.net.renderers.eni.available")
    def test_first_in_priority(self, m_eni_avail, m_sysc_avail):
        # available should only be called until one is found.
        m_eni_avail.return_value = True
        m_sysc_avail.side_effect = Exception("Should not call me")
        found = renderers.search(priority=['eni', 'sysconfig'], first=True)
        self.assertEqual(['eni'], [found[0]])

    @mock.patch("cloudinit.net.renderers.sysconfig.available")
    @mock.patch("cloudinit.net.renderers.eni.available")
    def test_select_positive(self, m_eni_avail, m_sysc_avail):
        m_eni_avail.return_value = True
        m_sysc_avail.return_value = False
        found = renderers.select(priority=['sysconfig', 'eni'])
        self.assertEqual('eni', found[0])

    @mock.patch("cloudinit.net.renderers.sysconfig.available")
    @mock.patch("cloudinit.net.renderers.eni.available")
    def test_select_none_found_raises(self, m_eni_avail, m_sysc_avail):
        # if select finds nothing, should raise exception.
        m_eni_avail.return_value = False
        m_sysc_avail.return_value = False

        self.assertRaises(net.RendererNotFoundError, renderers.select,
                          priority=['sysconfig', 'eni'])

    @mock.patch("cloudinit.net.renderers.netplan.available")
    @mock.patch("cloudinit.net.renderers.sysconfig.available_sysconfig")
    @mock.patch("cloudinit.net.renderers.sysconfig.available_nm")
    @mock.patch("cloudinit.net.renderers.eni.available")
    @mock.patch("cloudinit.net.renderers.sysconfig.util.get_linux_distro")
    def test_sysconfig_selected_on_sysconfig_enabled_distros(self, m_distro,
                                                             m_eni, m_sys_nm,
                                                             m_sys_scfg,
                                                             m_netplan):
        """sysconfig only selected on specific distros (rhel/sles)."""

        # Ubuntu with Network-Manager installed
        m_eni.return_value = False       # no ifupdown (ifquery)
        m_sys_scfg.return_value = False  # no sysconfig/ifup/ifdown
        m_sys_nm.return_value = True     # network-manager is installed
        m_netplan.return_value = True    # netplan is installed
        m_distro.return_value = ('ubuntu', None, None)
        self.assertEqual('netplan', renderers.select(priority=None)[0])

        # Centos with Network-Manager installed
        m_eni.return_value = False       # no ifupdown (ifquery)
        m_sys_scfg.return_value = False  # no sysconfig/ifup/ifdown
        m_sys_nm.return_value = True     # network-manager is installed
        m_netplan.return_value = False    # netplan is not installed
        m_distro.return_value = ('centos', None, None)
        self.assertEqual('sysconfig', renderers.select(priority=None)[0])

        # OpenSuse with Network-Manager installed
        m_eni.return_value = False       # no ifupdown (ifquery)
        m_sys_scfg.return_value = False  # no sysconfig/ifup/ifdown
        m_sys_nm.return_value = True     # network-manager is installed
        m_netplan.return_value = False    # netplan is not installed
        m_distro.return_value = ('opensuse', None, None)
        self.assertEqual('sysconfig', renderers.select(priority=None)[0])

    @mock.patch("cloudinit.net.sysconfig.available_sysconfig")
    @mock.patch("cloudinit.util.get_linux_distro")
    def test_sysconfig_available_uses_variant_mapping(self, m_distro, m_avail):
        m_avail.return_value = True
        distro_values = [
           ('opensuse', '', ''),
           ('opensuse-leap', '', ''),
           ('opensuse-tumbleweed', '', ''),
           ('sles', '', ''),
           ('centos', '', ''),
           ('fedora', '', ''),
           ('redhat', '', ''),
        ]
        for (distro_name, distro_version, flavor) in distro_values:
            m_distro.return_value = (distro_name, distro_version, flavor)
            result = sysconfig.available()
            self.assertTrue(result)


class TestGetInterfaces(CiTestCase):
    _data = {'bonds': ['bond1'],
             'bridges': ['bridge1'],
             'vlans': ['bond1.101'],
             'own_macs': ['enp0s1', 'enp0s2', 'bridge1-nic', 'bridge1',
                          'bond1.101', 'lo', 'eth1'],
             'macs': {'enp0s1': 'aa:aa:aa:aa:aa:01',
                      'enp0s2': 'aa:aa:aa:aa:aa:02',
                      'bond1': 'aa:aa:aa:aa:aa:01',
                      'bond1.101': 'aa:aa:aa:aa:aa:01',
                      'bridge1': 'aa:aa:aa:aa:aa:03',
                      'bridge1-nic': 'aa:aa:aa:aa:aa:03',
                      'lo': '00:00:00:00:00:00',
                      'greptap0': '00:00:00:00:00:00',
                      'eth1': 'aa:aa:aa:aa:aa:01',
                      'tun0': None},
             'drivers': {'enp0s1': 'virtio_net',
                         'enp0s2': 'e1000',
                         'bond1': None,
                         'bond1.101': None,
                         'bridge1': None,
                         'bridge1-nic': None,
                         'lo': None,
                         'greptap0': None,
                         'eth1': 'mlx4_core',
                         'tun0': None}}
    data = {}

    def _se_get_devicelist(self):
        return list(self.data['devices'])

    def _se_device_driver(self, name):
        return self.data['drivers'][name]

    def _se_device_devid(self, name):
        return '0x%s' % sorted(list(self.data['drivers'].keys())).index(name)

    def _se_get_interface_mac(self, name):
        return self.data['macs'][name]

    def _se_is_bridge(self, name):
        return name in self.data['bridges']

    def _se_is_vlan(self, name):
        return name in self.data['vlans']

    def _se_interface_has_own_mac(self, name):
        return name in self.data['own_macs']

    def _mock_setup(self):
        self.data = copy.deepcopy(self._data)
        self.data['devices'] = set(list(self.data['macs'].keys()))
        mocks = ('get_devicelist', 'get_interface_mac', 'is_bridge',
                 'interface_has_own_mac', 'is_vlan', 'device_driver',
                 'device_devid')
        self.mocks = {}
        for n in mocks:
            m = mock.patch('cloudinit.net.' + n,
                           side_effect=getattr(self, '_se_' + n))
            self.addCleanup(m.stop)
            self.mocks[n] = m.start()

    def test_gi_includes_duplicate_macs(self):
        self._mock_setup()
        ret = net.get_interfaces()

        self.assertIn('enp0s1', self._se_get_devicelist())
        self.assertIn('eth1', self._se_get_devicelist())
        found = [ent for ent in ret if 'aa:aa:aa:aa:aa:01' in ent]
        self.assertEqual(len(found), 2)

    def test_gi_excludes_any_without_mac_address(self):
        self._mock_setup()
        ret = net.get_interfaces()

        self.assertIn('tun0', self._se_get_devicelist())
        found = [ent for ent in ret if 'tun0' in ent]
        self.assertEqual(len(found), 0)

    def test_gi_excludes_stolen_macs(self):
        self._mock_setup()
        ret = net.get_interfaces()
        self.mocks['interface_has_own_mac'].assert_has_calls(
            [mock.call('enp0s1'), mock.call('bond1')], any_order=True)
        expected = [
            ('enp0s2', 'aa:aa:aa:aa:aa:02', 'e1000', '0x5'),
            ('enp0s1', 'aa:aa:aa:aa:aa:01', 'virtio_net', '0x4'),
            ('eth1', 'aa:aa:aa:aa:aa:01', 'mlx4_core', '0x6'),
            ('lo', '00:00:00:00:00:00', None, '0x8'),
            ('bridge1-nic', 'aa:aa:aa:aa:aa:03', None, '0x3'),
        ]
        self.assertEqual(sorted(expected), sorted(ret))

    def test_gi_excludes_bridges(self):
        self._mock_setup()
        # add a device 'b1', make all return they have their "own mac",
        # set everything other than 'b1' to be a bridge.
        # then expect b1 is the only thing left.
        self.data['macs']['b1'] = 'aa:aa:aa:aa:aa:b1'
        self.data['drivers']['b1'] = None
        self.data['devices'].add('b1')
        self.data['bonds'] = []
        self.data['own_macs'] = self.data['devices']
        self.data['bridges'] = [f for f in self.data['devices'] if f != "b1"]
        ret = net.get_interfaces()
        self.assertEqual([('b1', 'aa:aa:aa:aa:aa:b1', None, '0x0')], ret)
        self.mocks['is_bridge'].assert_has_calls(
            [mock.call('bridge1'), mock.call('enp0s1'), mock.call('bond1'),
             mock.call('b1')],
            any_order=True)


class TestInterfaceHasOwnMac(CiTestCase):
    """Test interface_has_own_mac.  This is admittedly a bit whitebox."""

    @mock.patch('cloudinit.net.read_sys_net_int', return_value=None)
    def test_non_strict_with_no_addr_assign_type(self, m_read_sys_net_int):
        """If nic does not have addr_assign_type, it is not "stolen".

        SmartOS containers do not provide the addr_assign_type in /sys.

            $ ( cd /sys/class/net/eth0/ && grep -r . *)
            address:90:b8:d0:20:e1:b0
            addr_len:6
            flags:0x1043
            ifindex:2
            mtu:1500
            tx_queue_len:1
            type:1
        """
        self.assertTrue(interface_has_own_mac("eth0"))

    @mock.patch('cloudinit.net.read_sys_net_int', return_value=None)
    def test_strict_with_no_addr_assign_type_raises(self, m_read_sys_net_int):
        with self.assertRaises(ValueError):
            interface_has_own_mac("eth0", True)

    @mock.patch('cloudinit.net.read_sys_net_int')
    def test_expected_values(self, m_read_sys_net_int):
        msg = "address_assign_type=%d said to not have own mac"
        for address_assign_type in (0, 1, 3):
            m_read_sys_net_int.return_value = address_assign_type
            self.assertTrue(
                interface_has_own_mac("eth0", msg % address_assign_type))

        m_read_sys_net_int.return_value = 2
        self.assertFalse(interface_has_own_mac("eth0"))


class TestGetInterfacesByMac(CiTestCase):
    _data = {'bonds': ['bond1'],
             'bridges': ['bridge1'],
             'vlans': ['bond1.101'],
             'own_macs': ['enp0s1', 'enp0s2', 'bridge1-nic', 'bridge1',
                          'bond1.101', 'lo'],
             'macs': {'enp0s1': 'aa:aa:aa:aa:aa:01',
                      'enp0s2': 'aa:aa:aa:aa:aa:02',
                      'bond1': 'aa:aa:aa:aa:aa:01',
                      'bond1.101': 'aa:aa:aa:aa:aa:01',
                      'bridge1': 'aa:aa:aa:aa:aa:03',
                      'bridge1-nic': 'aa:aa:aa:aa:aa:03',
                      'lo': '00:00:00:00:00:00',
                      'greptap0': '00:00:00:00:00:00',
                      'tun0': None}}
    data = {}

    def _se_get_devicelist(self):
        return list(self.data['devices'])

    def _se_get_interface_mac(self, name):
        return self.data['macs'][name]

    def _se_is_bridge(self, name):
        return name in self.data['bridges']

    def _se_is_vlan(self, name):
        return name in self.data['vlans']

    def _se_interface_has_own_mac(self, name):
        return name in self.data['own_macs']

    def _se_get_ib_interface_hwaddr(self, name, ethernet_format):
        ib_hwaddr = self.data.get('ib_hwaddr', {})
        return ib_hwaddr.get(name, {}).get(ethernet_format)

    def _mock_setup(self):
        self.data = copy.deepcopy(self._data)
        self.data['devices'] = set(list(self.data['macs'].keys()))
        mocks = ('get_devicelist', 'get_interface_mac', 'is_bridge',
                 'interface_has_own_mac', 'is_vlan', 'get_ib_interface_hwaddr')
        self.mocks = {}
        for n in mocks:
            m = mock.patch('cloudinit.net.' + n,
                           side_effect=getattr(self, '_se_' + n))
            self.addCleanup(m.stop)
            self.mocks[n] = m.start()

    def test_raise_exception_on_duplicate_macs(self):
        self._mock_setup()
        self.data['macs']['bridge1-nic'] = self.data['macs']['enp0s1']
        self.assertRaises(RuntimeError, net.get_interfaces_by_mac)

    def test_excludes_any_without_mac_address(self):
        self._mock_setup()
        ret = net.get_interfaces_by_mac()
        self.assertIn('tun0', self._se_get_devicelist())
        self.assertNotIn('tun0', ret.values())

    def test_excludes_stolen_macs(self):
        self._mock_setup()
        ret = net.get_interfaces_by_mac()
        self.mocks['interface_has_own_mac'].assert_has_calls(
            [mock.call('enp0s1'), mock.call('bond1')], any_order=True)
        self.assertEqual(
            {'aa:aa:aa:aa:aa:01': 'enp0s1', 'aa:aa:aa:aa:aa:02': 'enp0s2',
             'aa:aa:aa:aa:aa:03': 'bridge1-nic', '00:00:00:00:00:00': 'lo'},
            ret)

    def test_excludes_bridges(self):
        self._mock_setup()
        # add a device 'b1', make all return they have their "own mac",
        # set everything other than 'b1' to be a bridge.
        # then expect b1 is the only thing left.
        self.data['macs']['b1'] = 'aa:aa:aa:aa:aa:b1'
        self.data['devices'].add('b1')
        self.data['bonds'] = []
        self.data['own_macs'] = self.data['devices']
        self.data['bridges'] = [f for f in self.data['devices'] if f != "b1"]
        ret = net.get_interfaces_by_mac()
        self.assertEqual({'aa:aa:aa:aa:aa:b1': 'b1'}, ret)
        self.mocks['is_bridge'].assert_has_calls(
            [mock.call('bridge1'), mock.call('enp0s1'), mock.call('bond1'),
             mock.call('b1')],
            any_order=True)

    def test_excludes_vlans(self):
        self._mock_setup()
        # add a device 'b1', make all return they have their "own mac",
        # set everything other than 'b1' to be a vlan.
        # then expect b1 is the only thing left.
        self.data['macs']['b1'] = 'aa:aa:aa:aa:aa:b1'
        self.data['devices'].add('b1')
        self.data['bonds'] = []
        self.data['bridges'] = []
        self.data['own_macs'] = self.data['devices']
        self.data['vlans'] = [f for f in self.data['devices'] if f != "b1"]
        ret = net.get_interfaces_by_mac()
        self.assertEqual({'aa:aa:aa:aa:aa:b1': 'b1'}, ret)
        self.mocks['is_vlan'].assert_has_calls(
            [mock.call('bridge1'), mock.call('enp0s1'), mock.call('bond1'),
             mock.call('b1')],
            any_order=True)

    def test_duplicates_of_empty_mac_are_ok(self):
        """Duplicate macs of 00:00:00:00:00:00 should be skipped."""
        self._mock_setup()
        empty_mac = "00:00:00:00:00:00"
        addnics = ('greptap1', 'lo', 'greptap2')
        self.data['macs'].update(dict((k, empty_mac) for k in addnics))
        self.data['devices'].update(set(addnics))
        self.data['own_macs'].extend(list(addnics))
        ret = net.get_interfaces_by_mac()
        self.assertEqual('lo', ret[empty_mac])

    def test_skip_all_zeros(self):
        """Any mac of 00:... should be skipped."""
        self._mock_setup()
        emac1, emac2, emac4, emac6 = (
            '00', '00:00', '00:00:00:00', '00:00:00:00:00:00')
        addnics = {'empty1': emac1, 'emac2a': emac2, 'emac2b': emac2,
                   'emac4': emac4, 'emac6': emac6}
        self.data['macs'].update(addnics)
        self.data['devices'].update(set(addnics))
        self.data['own_macs'].extend(addnics.keys())
        ret = net.get_interfaces_by_mac()
        self.assertEqual('lo', ret['00:00:00:00:00:00'])

    def test_ib(self):
        ib_addr = '80:00:00:28:fe:80:00:00:00:00:00:00:00:11:22:03:00:33:44:56'
        ib_addr_eth_format = '00:11:22:33:44:56'
        self._mock_setup()
        self.data['devices'] = ['enp0s1', 'ib0']
        self.data['own_macs'].append('ib0')
        self.data['macs']['ib0'] = ib_addr
        self.data['ib_hwaddr'] = {'ib0': {True: ib_addr_eth_format,
                                          False: ib_addr}}
        result = net.get_interfaces_by_mac()
        expected = {'aa:aa:aa:aa:aa:01': 'enp0s1',
                    ib_addr_eth_format: 'ib0', ib_addr: 'ib0'}
        self.assertEqual(expected, result)


class TestInterfacesSorting(CiTestCase):

    def test_natural_order(self):
        data = ['ens5', 'ens6', 'ens3', 'ens20', 'ens13', 'ens2']
        self.assertEqual(
            sorted(data, key=natural_sort_key),
            ['ens2', 'ens3', 'ens5', 'ens6', 'ens13', 'ens20'])
        data2 = ['enp2s0', 'enp2s3', 'enp0s3', 'enp0s13', 'enp0s8', 'enp1s2']
        self.assertEqual(
            sorted(data2, key=natural_sort_key),
            ['enp0s3', 'enp0s8', 'enp0s13', 'enp1s2', 'enp2s0', 'enp2s3'])


class TestGetIBHwaddrsByInterface(CiTestCase):

    _ib_addr = '80:00:00:28:fe:80:00:00:00:00:00:00:00:11:22:03:00:33:44:56'
    _ib_addr_eth_format = '00:11:22:33:44:56'
    _data = {'devices': ['enp0s1', 'enp0s2', 'bond1', 'bridge1',
                         'bridge1-nic', 'tun0', 'ib0'],
             'bonds': ['bond1'],
             'bridges': ['bridge1'],
             'own_macs': ['enp0s1', 'enp0s2', 'bridge1-nic', 'bridge1', 'ib0'],
             'macs': {'enp0s1': 'aa:aa:aa:aa:aa:01',
                      'enp0s2': 'aa:aa:aa:aa:aa:02',
                      'bond1': 'aa:aa:aa:aa:aa:01',
                      'bridge1': 'aa:aa:aa:aa:aa:03',
                      'bridge1-nic': 'aa:aa:aa:aa:aa:03',
                      'tun0': None,
                      'ib0': _ib_addr},
             'ib_hwaddr': {'ib0': {True: _ib_addr_eth_format,
                                   False: _ib_addr}}}
    data = {}

    def _mock_setup(self):
        self.data = copy.deepcopy(self._data)
        mocks = ('get_devicelist', 'get_interface_mac', 'is_bridge',
                 'interface_has_own_mac', 'get_ib_interface_hwaddr')
        self.mocks = {}
        for n in mocks:
            m = mock.patch('cloudinit.net.' + n,
                           side_effect=getattr(self, '_se_' + n))
            self.addCleanup(m.stop)
            self.mocks[n] = m.start()

    def _se_get_devicelist(self):
        return self.data['devices']

    def _se_get_interface_mac(self, name):
        return self.data['macs'][name]

    def _se_is_bridge(self, name):
        return name in self.data['bridges']

    def _se_interface_has_own_mac(self, name):
        return name in self.data['own_macs']

    def _se_get_ib_interface_hwaddr(self, name, ethernet_format):
        ib_hwaddr = self.data.get('ib_hwaddr', {})
        return ib_hwaddr.get(name, {}).get(ethernet_format)

    def test_ethernet(self):
        self._mock_setup()
        self.data['devices'].remove('ib0')
        result = net.get_ib_hwaddrs_by_interface()
        expected = {}
        self.assertEqual(expected, result)

    def test_ib(self):
        self._mock_setup()
        result = net.get_ib_hwaddrs_by_interface()
        expected = {'ib0': self._ib_addr}
        self.assertEqual(expected, result)


def _gzip_data(data):
    with io.BytesIO() as iobuf:
        gzfp = gzip.GzipFile(mode="wb", fileobj=iobuf)
        gzfp.write(data)
        gzfp.close()
        return iobuf.getvalue()


class TestRenameInterfaces(CiTestCase):

    @mock.patch('cloudinit.util.subp')
    def test_rename_all(self, mock_subp):
        renames = [
            ('00:11:22:33:44:55', 'interface0', 'virtio_net', '0x3'),
            ('00:11:22:33:44:aa', 'interface2', 'virtio_net', '0x5'),
        ]
        current_info = {
            'ens3': {
                'downable': True,
                'device_id': '0x3',
                'driver': 'virtio_net',
                'mac': '00:11:22:33:44:55',
                'name': 'ens3',
                'up': False},
            'ens5': {
                'downable': True,
                'device_id': '0x5',
                'driver': 'virtio_net',
                'mac': '00:11:22:33:44:aa',
                'name': 'ens5',
                'up': False},
        }
        net._rename_interfaces(renames, current_info=current_info)
        print(mock_subp.call_args_list)
        mock_subp.assert_has_calls([
            mock.call(['ip', 'link', 'set', 'ens3', 'name', 'interface0'],
                      capture=True),
            mock.call(['ip', 'link', 'set', 'ens5', 'name', 'interface2'],
                      capture=True),
        ])

    @mock.patch('cloudinit.util.subp')
    def test_rename_no_driver_no_device_id(self, mock_subp):
        renames = [
            ('00:11:22:33:44:55', 'interface0', None, None),
            ('00:11:22:33:44:aa', 'interface1', None, None),
        ]
        current_info = {
            'eth0': {
                'downable': True,
                'device_id': None,
                'driver': None,
                'mac': '00:11:22:33:44:55',
                'name': 'eth0',
                'up': False},
            'eth1': {
                'downable': True,
                'device_id': None,
                'driver': None,
                'mac': '00:11:22:33:44:aa',
                'name': 'eth1',
                'up': False},
        }
        net._rename_interfaces(renames, current_info=current_info)
        print(mock_subp.call_args_list)
        mock_subp.assert_has_calls([
            mock.call(['ip', 'link', 'set', 'eth0', 'name', 'interface0'],
                      capture=True),
            mock.call(['ip', 'link', 'set', 'eth1', 'name', 'interface1'],
                      capture=True),
        ])

    @mock.patch('cloudinit.util.subp')
    def test_rename_all_bounce(self, mock_subp):
        renames = [
            ('00:11:22:33:44:55', 'interface0', 'virtio_net', '0x3'),
            ('00:11:22:33:44:aa', 'interface2', 'virtio_net', '0x5'),
        ]
        current_info = {
            'ens3': {
                'downable': True,
                'device_id': '0x3',
                'driver': 'virtio_net',
                'mac': '00:11:22:33:44:55',
                'name': 'ens3',
                'up': True},
            'ens5': {
                'downable': True,
                'device_id': '0x5',
                'driver': 'virtio_net',
                'mac': '00:11:22:33:44:aa',
                'name': 'ens5',
                'up': True},
        }
        net._rename_interfaces(renames, current_info=current_info)
        print(mock_subp.call_args_list)
        mock_subp.assert_has_calls([
            mock.call(['ip', 'link', 'set', 'ens3', 'down'], capture=True),
            mock.call(['ip', 'link', 'set', 'ens3', 'name', 'interface0'],
                      capture=True),
            mock.call(['ip', 'link', 'set', 'ens5', 'down'], capture=True),
            mock.call(['ip', 'link', 'set', 'ens5', 'name', 'interface2'],
                      capture=True),
            mock.call(['ip', 'link', 'set', 'interface0', 'up'], capture=True),
            mock.call(['ip', 'link', 'set', 'interface2', 'up'], capture=True)
        ])

    @mock.patch('cloudinit.util.subp')
    def test_rename_duplicate_macs(self, mock_subp):
        renames = [
            ('00:11:22:33:44:55', 'eth0', 'hv_netsvc', '0x3'),
            ('00:11:22:33:44:55', 'vf1', 'mlx4_core', '0x5'),
        ]
        current_info = {
            'eth0': {
                'downable': True,
                'device_id': '0x3',
                'driver': 'hv_netsvc',
                'mac': '00:11:22:33:44:55',
                'name': 'eth0',
                'up': False},
            'eth1': {
                'downable': True,
                'device_id': '0x5',
                'driver': 'mlx4_core',
                'mac': '00:11:22:33:44:55',
                'name': 'eth1',
                'up': False},
        }
        net._rename_interfaces(renames, current_info=current_info)
        print(mock_subp.call_args_list)
        mock_subp.assert_has_calls([
            mock.call(['ip', 'link', 'set', 'eth1', 'name', 'vf1'],
                      capture=True),
        ])

    @mock.patch('cloudinit.util.subp')
    def test_rename_duplicate_macs_driver_no_devid(self, mock_subp):
        renames = [
            ('00:11:22:33:44:55', 'eth0', 'hv_netsvc', None),
            ('00:11:22:33:44:55', 'vf1', 'mlx4_core', None),
        ]
        current_info = {
            'eth0': {
                'downable': True,
                'device_id': '0x3',
                'driver': 'hv_netsvc',
                'mac': '00:11:22:33:44:55',
                'name': 'eth0',
                'up': False},
            'eth1': {
                'downable': True,
                'device_id': '0x5',
                'driver': 'mlx4_core',
                'mac': '00:11:22:33:44:55',
                'name': 'eth1',
                'up': False},
        }
        net._rename_interfaces(renames, current_info=current_info)
        print(mock_subp.call_args_list)
        mock_subp.assert_has_calls([
            mock.call(['ip', 'link', 'set', 'eth1', 'name', 'vf1'],
                      capture=True),
        ])

    @mock.patch('cloudinit.util.subp')
    def test_rename_multi_mac_dups(self, mock_subp):
        renames = [
            ('00:11:22:33:44:55', 'eth0', 'hv_netsvc', '0x3'),
            ('00:11:22:33:44:55', 'vf1', 'mlx4_core', '0x5'),
            ('00:11:22:33:44:55', 'vf2', 'mlx4_core', '0x7'),
        ]
        current_info = {
            'eth0': {
                'downable': True,
                'device_id': '0x3',
                'driver': 'hv_netsvc',
                'mac': '00:11:22:33:44:55',
                'name': 'eth0',
                'up': False},
            'eth1': {
                'downable': True,
                'device_id': '0x5',
                'driver': 'mlx4_core',
                'mac': '00:11:22:33:44:55',
                'name': 'eth1',
                'up': False},
            'eth2': {
                'downable': True,
                'device_id': '0x7',
                'driver': 'mlx4_core',
                'mac': '00:11:22:33:44:55',
                'name': 'eth2',
                'up': False},
        }
        net._rename_interfaces(renames, current_info=current_info)
        print(mock_subp.call_args_list)
        mock_subp.assert_has_calls([
            mock.call(['ip', 'link', 'set', 'eth1', 'name', 'vf1'],
                      capture=True),
            mock.call(['ip', 'link', 'set', 'eth2', 'name', 'vf2'],
                      capture=True),
        ])

    @mock.patch('cloudinit.util.subp')
    def test_rename_macs_case_insensitive(self, mock_subp):
        """_rename_interfaces must support upper or lower case macs."""
        renames = [
            ('aa:aa:aa:aa:aa:aa', 'en0', None, None),
            ('BB:BB:BB:BB:BB:BB', 'en1', None, None),
            ('cc:cc:cc:cc:cc:cc', 'en2', None, None),
            ('DD:DD:DD:DD:DD:DD', 'en3', None, None),
        ]
        current_info = {
            'eth0': {'downable': True, 'mac': 'AA:AA:AA:AA:AA:AA',
                     'name': 'eth0', 'up': False},
            'eth1': {'downable': True, 'mac': 'bb:bb:bb:bb:bb:bb',
                     'name': 'eth1', 'up': False},
            'eth2': {'downable': True, 'mac': 'cc:cc:cc:cc:cc:cc',
                     'name': 'eth2', 'up': False},
            'eth3': {'downable': True, 'mac': 'DD:DD:DD:DD:DD:DD',
                     'name': 'eth3', 'up': False},
        }
        net._rename_interfaces(renames, current_info=current_info)

        expected = [
            mock.call(['ip', 'link', 'set', 'eth%d' % i, 'name', 'en%d' % i],
                      capture=True)
            for i in range(len(renames))]
        mock_subp.assert_has_calls(expected)


class TestNetworkState(CiTestCase):

    def test_bcast_addr(self):
        """Test mask_and_ipv4_to_bcast_addr proper execution."""
        bcast_addr = network_state.mask_and_ipv4_to_bcast_addr
        self.assertEqual("192.168.1.255",
                         bcast_addr("255.255.255.0", "192.168.1.1"))
        self.assertEqual("128.42.7.255",
                         bcast_addr("255.255.248.0", "128.42.5.4"))
        self.assertEqual("10.1.21.255",
                         bcast_addr("255.255.255.0", "10.1.21.4"))

# vi: ts=4 expandtab