summaryrefslogtreecommitdiff
path: root/scripts/check-qemu-install
blob: b8ab3f61002343b0c93b507d2d4f6bd6ad9abfce (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
#!/usr/bin/env python3
#
# Copyright VyOS maintainers and contributors <maintainers@vyos.io>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 or later as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
# File: check-qemu-install
# Purpose:
#  This script installs a system on a emulated qemu host to verify
#  that the iso produced is installable and boots.
#  after the iso is booted from disk it also tries to execute the
#  vyos-smoketest script to verify checks there.
#
#  For now it will not fail on failed smoketest but will fail on
#  install and boot errors.
#  Arguments:
#    iso            iso image to install
#    [disk]         disk filename to use, if none is provided it
#                   is autogenerated
#    [--keep]       Keep the disk image after completion
#    [--logfile]    name of logfile to save, defaulting to stdout
#    [--silent]     only print on errors
#    [--debug]      print all communication with the device

import sys
import os
import time
import argparse
import subprocess
import random
import traceback
import logging
import re
import shutil
import json
import platform

from io import BytesIO
from datetime import datetime
from glob import glob

import tomli
import pexpect

EXCEPTION = 0
DISK_IMAGE_EXTENSION = '.raw'

# T3871: interface names are resolved from this store, so dump it on every
# testrun - it is what makes a naming failure reproducible after the fact
IFNAME_MAPPING_FILE = '/config/interface-mapping.json'

# Nested installer-ISO QEMU test: mkisofs payload (see --nested-installer-iso-test)
NESTED_ISO_DATA_DIR = 'nested_iso_data'
NESTED_INSTALLER_PAYLOAD_ISO = 'nested_installer_payload.iso'
NESTED_INNER_ISO_NAME = 'vyos-installer.iso'

# Local-only HTTP nested-ISO upgrade test: default VRF (main RIB) then named VRF purple
NESTED_HTTP_SERV_PORT = 18088
NESTED_HTTP_IMAGE_NAME = 'test-image-update'
NESTED_HTTP_VRF_NAME = 'purple'
NESTED_HTTP_VRF_DUMMY = 'dum8000'
NESTED_HTTP_VRF_TABLE = '42042'
NESTED_HTTP_VRF_ADDR = '198.51.100.99'  # RFC 5737 TEST-NET-3: bind address for http.server inside VRF
NESTED_HTTP_MOUNT_POINT = '/mnt/nested_installer_iso'

# RFC7042 section 2.1.2 MAC addresses used for documentation
macbase = '00:00:5E:00:53'

# Cloud-Init data
CI_CONFIG_ARGS = {
    'hostname': 'vyos-CLOUD-INIT',
    'eth0_mac': f'{macbase}:02'.lower(),
    'eth1_mac': f'{macbase}:00'.lower(),
    'eth2_mac': f'{macbase}:01'.lower(),
    'eth0_ipv4': '192.0.2.1/25',
    'eth0_ipv6': '2001:db8::1/64',
    'eth2_ipv4': '198.51.100.1/24',
    'default_nexthop' : '192.0.2.126',
    'default_nexthop6' : '2001:db8::ffff',
    }

tpm_folder = '/tmp/vyos_tpm_test'
tpm_sock = f'{tpm_folder}/swtpm-sock'
qemu_name = 'VyOS-QEMU'

# NICs wired up at boot by get_qemu_cmd() - the VMware variant labels
# every one of them
VMWARE_PORT_LABEL_COUNT = 8

test_timeout = 5 *3600 # 5 hours (in seconds) to complete individual testcases

# Terminal control/escape sequences (e.g. bash bracketed-paste \x1b[?2004h)
# emitted on the serial console - must be filtered before parsing command output
ansi_escape = re.compile(r'\x1B[@-_][0-?]*[ -/]*[@-~]')

op_mode_prompt = r'vyos@vyos:~\$'
cfg_mode_prompt = r'vyos@vyos#'
default_user = 'vyos'
default_password = 'vyos'

# getch.py
KEY_F2 = chr(27) + chr(91) + chr(49) + chr(50) + chr(126)
KEY_F10 = chr(27) + chr(91) + chr(50) + chr(49) + chr(126)
KEY_UP = chr(27) + chr(91) + chr(65)
KEY_DOWN = chr(27) + chr(91) + chr(66)
KEY_SPACE = chr(32)
KEY_RETURN = chr(13)
KEY_ESC = chr(27)
KEY_Y = chr(121)

mok_password = '1234'

# Custom Secure Boot signing material (see docs.vyos.io installation/secure-boot).
# If present, the image was signed with a custom CA and the MOK must be enrolled.
# If absent, the image is expected to be signed by the VyOS CA and boots as-is.
SB_CERT_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'data', 'certificates')
SB_DEV_YEAR = time.strftime('%Y')
SB_CUSTOM_KEY = os.path.join(SB_CERT_DIR, f'vyos-dev-{SB_DEV_YEAR}-linux.key')
SB_CUSTOM_CERT = os.path.join(SB_CERT_DIR, f'vyos-dev-{SB_DEV_YEAR}-linux.pem')
# Development shim root certificate, placed in the image by build-vyos-image
SB_MOK_DER = f'/var/lib/shim-signed/mok/vyos-dev-{SB_DEV_YEAR}-shim.der'
# Expected Linux Kernel signature certificate of a VyOS CA signed image
SB_VYOS_ISSUER = '/CN=VyOS Networks Secure Boot CA'
SB_VYOS_SUBJECT = '/CN=VyOS Networks Secure Boot Signer 2025 - linux'

# Map QEMU arch
QEMU_CONFIG = {
    'amd64': {
        'bin' : 'qemu-system-x86_64',
        'machine' : 'pc',
        'bios' : '/usr/share/OVMF/OVMF_CODE.fd',
    },
    "arm64": {
        'bin': 'qemu-system-aarch64',
        'machine': 'virt,highmem=on',
        'bios': '/usr/share/qemu-efi-aarch64/QEMU_EFI.fd',
    },
}

parser = argparse.ArgumentParser(description='Install and start a test VyOS vm.')
parser.add_argument('--iso', help='ISO file to install')
parser.add_argument('--disk', help='name of disk image file', nargs='?')
parser.add_argument('--keep', help='Do not remove disk-image after installation',
                              action='store_true', default=False)
parser.add_argument('--silent', help='Do not show output on stdout unless an error has occurred',
                              action='store_true', default=False)
parser.add_argument('--debug', help='Send all debug output to stdout',
                               action='store_true', default=False)
parser.add_argument('--logfile', help='Log to file')
parser.add_argument('--match', help='Smoketests to run')
parser.add_argument('--uefi', help='Boot using UEFI', action='store_true', default=False)
parser.add_argument('--vnc', help='Enable VNC', action='store_true', default=False)
parser.add_argument('--raid', help='Perform a RAID-1 install', action='store_true', default=False)
parser.add_argument('--no-interfaces', help='Execute testsuite without interface tests to save time',
                action='store_true', default=False)
parser.add_argument('--smoketest', help='Execute script based CLI smoketests',
                action='store_true', default=False)
parser.add_argument('--configtest', help='Execute load/commit config tests',
				action='store_true', default=False)
parser.add_argument('--tpmtest', help='Execute TPM encrypted config tests',
                action='store_true', default=False)
parser.add_argument('--ifnametest', help='Execute interface naming persistence tests',
                action='store_true', default=False)
parser.add_argument('--vmware', help='Present the VM as VMware hardware (DMI vendor and '
                                     'firmware port labels)',
                action='store_true', default=False)
parser.add_argument('--secure-boot-test', help='Execute Secure Boot tests (enrolls MOK only if custom '
                                     'signing certificates exist in data/certificates)',
                action='store_true', default=False)
parser.add_argument('--cloud-init', help='Execute cloud-init tests',
                action='store_true', default=False)
parser.add_argument('--test-image-update', help='Test ISO image update in default VRF and custom VRF',
                action='store_true', default=False)
parser.add_argument('--qemu-cmd', help='Only generate QEMU launch command',
                action='store_true', default=False)
parser.add_argument('--cpu', help='Set QEMU CPU', type=int, default=2)
parser.add_argument('--cpu-type', help='Set QEMU CPU type', type=str, default='host')
parser.add_argument('--memory', help='Set QEMU memory', type=int, default=4)
parser.add_argument('--vyconf', help='Execute testsuite with vyconfd', action='store_true',
                    default=False)
parser.add_argument('--no-vpp', help='Execute testsuite without VPP tests',
                action='store_true', default=False)
parser.add_argument('--huge-page-size', help='Huge page size (e.g., 2M, 1G)', type=str)
parser.add_argument('--huge-page-count', help='Number of huge pages to allocate', type=int)
parser.add_argument('--isolate-cpus', help='CPU cores to isolate (e.g., 1,3-4', type=str)

args = parser.parse_args()

if os.geteuid() != 0:
    exit('You need to have root privileges to run this script.')

if platform.machine() not in ['amd64', 'x86_64', 'arm64', 'aarch64']:
    exit(f'Unsupported host architecture "{platform.machine()}" - this script '
         'only runs on amd64 or arm64 hosts.')

if platform.machine() in ['arm64', 'aarch64'] and not args.uefi:
    exit('--uefi is mandatory when running on arm64 hosts.')

if args.cloud_init:
    hostname = CI_CONFIG_ARGS['hostname']
    op_mode_prompt = rf'vyos@{hostname}:~\$'
    cfg_mode_prompt = rf'vyos@{hostname}#'

# This is what we requested the build to contain
with open('data/defaults.toml', 'rb') as f:
    vyos_defaults = tomli.load(f)

# This is what we got from the build
manifest_file = 'build/manifest.json'
if os.path.isfile(manifest_file):
    with open('build/manifest.json', 'rb') as f:
        manifest = json.load(f)

    vyos_version = manifest['build_config']['version']
    vyos_codename = manifest['build_config']['release_train']

class StreamToLogger(object):
    """
    Fake file-like stream object that redirects writes to a logger instance.
    """
    def __init__(self, logger, log_level=logging.INFO):
        self.logger = logger
        self.log_level = log_level
        self.linebuf = b''

    def write(self, buf):
        self.linebuf += buf
        while b'\n' in self.linebuf:
            f = self.linebuf.split(b'\n', 1)
            if len(f) == 2:
                self.logger.debug(ansi_escape.sub('', f[0].decode(errors="replace").rstrip()))
                self.linebuf = f[1]

    def flush(self):
        pass

class EarlyExit(Exception):
    pass

def _kvm_exists():
    return os.path.exists("/dev/kvm")

def get_qemu_cmd(name, enable_uefi, disk_img, raid=None, iso_img=None, tpm=False,
                 vnc_enabled=False, secure_boot=False, nested_cdrom_iso=None,
                 vmware=False):
    uefi = ""
    uuid = "f48b60b2-e6ad-49ef-9d09-4245d0585e52"
    accel = ',accel=kvm' if _kvm_exists() else ''

    if platform.machine() in ['amd64', 'x86_64']:
        architecture = 'amd64'
    elif platform.machine() in ['arm64', 'aarch64']:
        architecture = 'arm64'
    else:
        raise ValueError('Unsupported architecture!')

    qemu_arch_config = QEMU_CONFIG[architecture]
    qemu_bin = qemu_arch_config['bin']
    bios = qemu_arch_config['bios']

    cpu_type = args.cpu_type
    enable_kvm = '-enable-kvm' if _kvm_exists() else ''
    machine = qemu_arch_config['machine']
    vga = '-vga none'
    vnc = ''
    if vnc_enabled:
        vga = '-vga virtio'
        vnc = '-vnc :0'

    if enable_uefi:
        uefi = f'-bios {bios}'
        name = f'{name}-UEFI'

        if secure_boot:
            name = f'{name}-SECURE-BOOT'
            machine = 'q35,smm=on'

            uefi = f'-drive "if=pflash,unit=0,format=raw,readonly=on,file={OVMF_CODE}" ' \
                   f'-drive "if=pflash,unit=1,format=raw,file={OVMF_VARS_TMP}"'
            # Changing UEFI settings require a display
            vga = '-vga virtio'

    # Only i440fx calls its root bus pci.0 - q35 and arm64 virt use pcie.0
    pci_bus = 'pci.0' if machine == 'pc' else 'pcie.0'

    cdrom = ""
    nested_cdrom = ""
    if iso_img:
        bootindex = '10'
        cdrom = f' -drive file={iso_img},format=raw,if=none,media=cdrom,id=drive-cd1,readonly=on'
        if architecture == 'arm64':
            cdrom = f' {cdrom} -device scsi-cd,bus=scsi0.0,drive=drive-cd1,id=cd1,bootindex={bootindex}'
        else:
            cdrom = f' {cdrom} -device ahci,id=achi0 -device ide-cd,bus=achi0.0,drive=drive-cd1,id=cd1,bootindex={bootindex}'

    if nested_cdrom_iso:
        drive_settings = 'drive=drive-cd2,id=cd2,bootindex=11'
        nested_cdrom = f' -drive file={nested_cdrom_iso},format=raw,if=none,media=cdrom,id=drive-cd2,readonly=on'
        if architecture == 'arm64':
            nested_cdrom = f' {nested_cdrom} -device scsi-cd,bus=scsi0.0,{drive_settings}'
        else:
            if not iso_img:
                # Second IDE CD on its own AHCI controller (no installer CD in this command)
                nested_cdrom = f'{nested_cdrom} -device ahci,id=nestedahci' \
                               f' -device ide-cd,bus=nestedahci.0,{drive_settings}'
            else:
                nested_cdrom = f'{nested_cdrom} -device ide-cd,bus=achi0.1,{drive_settings}'

    # Set QEmu disk image format - this differs if VyOS was installed via smoketest
    # or we use an already ewxisting image
    disk_format = 'qcow2' if args.disk.endswith('.qcow2') else 'raw'

    # A virtio NIC cannot carry a firmware port label: its sysfs device is the
    # virtio bus device, not the PCI function the label hangs off. ESXi has no
    # virtio anyway, so the VMware variant uses the adapters it does present.
    # host_mtu is a virtio option and goes with them.
    nic_model = 'vmxnet3' if vmware else 'virtio-net-pci'
    nic_opts = '' if vmware else ',host_mtu=1500'
    cmd = f'{qemu_bin} \
        -name "{name}" \
        -smp {args.cpu},sockets=1,cores={args.cpu},threads=1 \
        -cpu {cpu_type} \
        -machine {machine}{accel} \
        {uefi} \
        -m {args.memory}G \
        -nographic \
        {vga} {vnc}\
        -uuid {uuid} \
        {enable_kvm} \
        -monitor unix:/tmp/qemu-monitor-socket-{disk_img},server,nowait \
        -netdev user,id=n0,net=192.0.2.0/24,dhcpstart=192.0.2.101,dns=192.0.2.10 -device {nic_model},id=nic0,netdev=n0,mac={macbase}:00,romfile="",bus={pci_bus},addr=0x4{nic_opts} \
        -netdev user,id=n1 -device {nic_model},id=nic1,netdev=n1,mac={macbase}:01,romfile="",bus={pci_bus},addr=0x5{nic_opts} \
        -netdev user,id=n2 -device {nic_model},id=nic2,netdev=n2,mac={macbase}:02,romfile="",bus={pci_bus},addr=0x6{nic_opts} \
        -netdev user,id=n3 -device {nic_model},id=nic3,netdev=n3,mac={macbase}:03,romfile="",bus={pci_bus},addr=0x7{nic_opts} \
        -netdev user,id=n4 -device e1000e,id=nic4,netdev=n4,mac={macbase}:04,romfile="",bus={pci_bus},addr=0xa \
        -netdev user,id=n5 -device e1000e,id=nic5,netdev=n5,mac={macbase}:05,romfile="",bus={pci_bus},addr=0xb \
        -netdev user,id=n6 -device vmxnet3,id=nic6,netdev=n6,mac={macbase}:06,romfile="",bus={pci_bus},addr=0xe \
        -netdev user,id=n7 -device vmxnet3,id=nic7,netdev=n7,mac={macbase}:07,romfile="",bus={pci_bus},addr=0xf \
        -device virtio-scsi-pci,id=scsi0 \
        {cdrom}{nested_cdrom} \
        -drive format={disk_format},file={disk_img},if=none,media=disk,id=drive-hd1,readonly=off \
        -device scsi-hd,bus=scsi0.0,drive=drive-hd1,id=hd1,bootindex=1'

    if raid:
        # RAID member disks each get their own virtio-scsi-pci controller.
        # OVMF only appears to honor QEMU's per-device "bootindex" when disks
        # sit behind separate PCI controllers - sharing one controller via
        # SCSI LUN makes it always boot LUN 0 regardless of bootindex, which
        # breaks the RAID-failure simulation's boot-priority swap under UEFI.
        cmd += f' -device virtio-scsi-pci,id=scsi1' \
               f' -drive format={disk_format},file={raid},if=none,media=disk,id=drive-hd2,readonly=off' \
               f' -device scsi-hd,bus=scsi1.0,drive=drive-hd2,id=hd2,bootindex=2'

    if tpm:
        # The ISA "tpm-tis" device only exists on x86 machines - the arm64
        # "virt" machine exposes the TPM via MMIO and a device-tree node,
        # which QEMU models as "tpm-tis-device" instead.
        tpm_device = 'tpm-tis-device' if architecture == 'arm64' else 'tpm-tis'
        cmd += f' -chardev socket,id=chrtpm,path={tpm_sock}' \
               ' -tpmdev emulator,id=tpm0,chardev=chrtpm' \
               f' -device {tpm_device},tpmdev=tpm0'

    if vmware:
        # ESXi is the one platform where the firmware, not the PCI topology,
        # decides which adapter the operator calls the first one. Two SMBIOS
        # tables reproduce that: type 1 is what /sys/class/dmi/id/sys_vendor
        # reports, type 41 is where the kernel gets <device>/label from, which
        # is the "Network adapter N" order as vSphere shows it. The comma in
        # the vendor string has to reach QEMU doubled or its option parser
        # treats it as a separator.
        cmd += ' -smbios "type=1,manufacturer=VMware,, Inc.,product=VMware Virtual Platform"'
        for index in range(VMWARE_PORT_LABEL_COUNT):
            cmd += (f' -smbios type=41,designation=Ethernet{index},kind=ethernet,'
                    f'instance={index + 1},pcidev=nic{index}')

    return cmd

def shutdownVM(c, log, message=''):
    #################################################
    # Powering off system
    #################################################
    if message:
        log.info(message)

    c.sendline('poweroff now')
    log.info('Shutting down virtual machine')
    for i in range(30):
        log.info('Waiting for shutdown...')
        # Shutdown in qemu doesnt work first time
        # Use this workaround
        # https://vyos.dev/T5024
        c.sendline('poweroff now')
        if not c.isalive():
            log.info('VM is shut down!')
            break
        time.sleep(10)
    else:
        tmp = 'VM Did not shut down after 300sec'
        log.error(tmp)
        raise Exception(tmp)
    c.close()

def waitForLogin(child, log, timeout=20) -> None:
    try:
        child.expect('The highlighted entry will be executed automatically in',
                     timeout=timeout)
        child.sendline('')
    except pexpect.TIMEOUT:
        log.warning('Did not find GRUB countdown window, ignoring')

def loginVM(c, log):
    log.info('Waiting for login prompt')
    c.expect('[Ll]ogin:', timeout=600)
    c.sendline(default_user)
    c.expect('[Pp]assword:')
    c.sendline(default_password)
    c.expect(op_mode_prompt)
    log.info('Logged in!')
    c.sendline('set terminal width 160')
    c.expect(op_mode_prompt)
    c.sendline('set terminal length 60')
    c.expect(op_mode_prompt)

def clearTPM():
    for f in glob(f'{tpm_folder}/*'):
        os.remove(f)

# Setting up logger
log = logging.getLogger()
log.setLevel(logging.DEBUG)

stl = StreamToLogger(log)
formatter = logging.Formatter('%(levelname)5s - %(message)s')

handler = logging.StreamHandler(sys.stdout)
if args.silent:
    handler.setLevel(logging.ERROR)
elif args.debug:
    handler.setLevel(logging.DEBUG)
else:
    handler.setLevel(logging.INFO)

handler.setFormatter(formatter)
log.addHandler(handler)

# Mutually exclusive primary testcase selectors (--no-interfaces is a
# smoketest modifier).
_primary_modes = []
if args.cloud_init:
    _primary_modes.append('--cloud-init')
if args.test_image_update:
    _primary_modes.append('--test-image-update')
if args.tpmtest:
    _primary_modes.append('--tpmtest')
if args.ifnametest:
    _primary_modes.append('--ifnametest')
if args.raid:
    _primary_modes.append('--raid')
if args.smoketest:
    _primary_modes.append('--smoketest')
if args.configtest:
    _primary_modes.append('--configtest')
if args.secure_boot_test:
    _primary_modes.append('--secure-boot-test')
if len(_primary_modes) > 1:
    log.error('Incompatible combination of testcase flags (%s): only one of '
        '--cloud-init, --test-image-update, --tpmtest, --ifnametest, --raid, '
        '--smoketest, --configtest, --secure-boot-test may be set.', ', '.join(_primary_modes))
    sys.exit(1)

if args.no_interfaces and not args.smoketest:
    log.error('--no-interfaces requires --smoketest')
    sys.exit(1)

if args.secure_boot_test and not args.uefi:
    log.error('--secure-boot-test requires --uefi')
    sys.exit(1)

if args.logfile:
    filehandler = logging.FileHandler(args.logfile)
    filehandler.setLevel(logging.DEBUG)
    filehandler.setFormatter(formatter)
    log.addHandler(filehandler)

if args.silent:
    output = BytesIO()
else:
    output = sys.stdout.buffer

if not os.path.exists('/dev/kvm'):
    log.error('KVM not enabled on host, proceeding with software emulation')

if not args.iso and not args.disk:
    log.error('Neither ISO not QCOW2 disk image supplied - error!')
    sys.exit(1)

if not args.disk:
    tmp_disk_time = datetime.now().strftime('%Y%m%d-%H%M%S')
    tmp_disk_random = "%04x" % random.randint(0,65535)
    args.disk = f'testinstall-{tmp_disk_time}-{tmp_disk_random}{DISK_IMAGE_EXTENSION}'

if args.iso and not os.path.isfile(args.iso):
    log.error('Unable to find VyOS ISO image needed by testcases!')
    sys.exit(1)

if args.test_image_update and not args.iso:
    log.error('--test-image-update requires --iso file!')
    sys.exit(1)

OVMF_CODE = '/usr/share/OVMF/OVMF_CODE_4M.secboot.fd'
OVMF_VARS_TMP = args.disk.replace(DISK_IMAGE_EXTENSION, '.efivars')
if args.secure_boot_test:
    shutil.copy('/usr/share/OVMF/OVMF_VARS_4M.ms.fd', OVMF_VARS_TMP)

sb_custom_ca = args.secure_boot_test and os.path.isfile(SB_CUSTOM_KEY) and os.path.isfile(SB_CUSTOM_CERT)
if args.secure_boot_test:
    if sb_custom_ca:
        log.info('Secure Boot test: custom signing certificate found - enrolling MOK')
    else:
        log.info('Secure Boot test: no custom signing certificate - expecting VyOS CA signed image')

# Creating diskimage!!
diskname_raid = None
def gen_disk(name):
    if not os.path.isfile(name):
        log.info(f'Creating Disk image {name}')
        c = subprocess.check_output(['qemu-img', 'create', name, '5G'])
        log.debug(c.decode())
    else:
        log.info(f'Re-using already existing disk image "{name}".')

if args.raid:
    filename, ext = os.path.splitext(args.disk)
    diskname_raid = f'{filename}_disk1{ext}'
    # change primary diskname, too
    args.disk = f'{filename}_disk0{ext}'
    gen_disk(diskname_raid)

# must be called after the raid disk as args.disk name is altered in the RAID path
gen_disk(args.disk)

nested_payload_iso_path = None
if args.test_image_update:
    if os.path.isdir(NESTED_ISO_DATA_DIR):
        shutil.rmtree(NESTED_ISO_DATA_DIR)
    os.makedirs(NESTED_ISO_DATA_DIR)
    shutil.copy2(args.iso, os.path.join(NESTED_ISO_DATA_DIR, NESTED_INNER_ISO_NAME))
    if os.path.isfile(NESTED_INSTALLER_PAYLOAD_ISO):
        os.unlink(NESTED_INSTALLER_PAYLOAD_ISO)
    log.info('Assembling nested installer payload ISO (second CD-ROM, drive-cd2)')
    subprocess.check_call([
        'mkisofs', '-joliet', '-rock', '-volid', 'VYOSNESTED',
        '-output', NESTED_INSTALLER_PAYLOAD_ISO, NESTED_ISO_DATA_DIR,
    ])
    nested_payload_iso_path = os.path.abspath(NESTED_INSTALLER_PAYLOAD_ISO)
    log.info('Removing nested ISO staging directory %s', NESTED_ISO_DATA_DIR)
    shutil.rmtree(NESTED_ISO_DATA_DIR)

# Create software emulated TPM - clear existing TPM data first - might be a
# leftover from a previous run
clearTPM()

def start_swtpm():
    if not os.path.exists(tpm_folder):
        os.mkdir(tpm_folder)

    def swtpm_thread():
        subprocess.check_output([
            'swtpm', 'socket', '--tpmstate', f'dir={tpm_folder}',
            '--ctrl', f'type=unixio,path={tpm_sock}', '--tpm2', '--log', 'level=1'
        ])

    from multiprocessing import Process
    tpm_process = Process(target=swtpm_thread)
    tpm_process.start()
    return tpm_process

def toggleUEFISecureBoot(c):
    def UEFIKeyPress(c, key):
        UEFI_SLEEP = 1
        c.send(key)
        time.sleep(UEFI_SLEEP)

    # Enter UEFI
    for ii in range(1, 10):
        c.send(KEY_F2)
        time.sleep(0.250)

    # Wait for the firmware to start the setup application - the time this
    # takes differs between hosts, a fixed delay would lose the key presses
    c.expect(r'BdsDxe: starting Boot0000 "UiApp"', timeout=120)
    time.sleep(5)

    # Device Manager
    UEFIKeyPress(c, KEY_DOWN)
    UEFIKeyPress(c, KEY_RETURN)

    # Secure Boot Configuration
    UEFIKeyPress(c, KEY_DOWN)
    UEFIKeyPress(c, KEY_DOWN)
    UEFIKeyPress(c, KEY_RETURN)

    # Attempt Secure Boot Toggle
    UEFIKeyPress(c, KEY_DOWN)
    UEFIKeyPress(c, KEY_RETURN)
    UEFIKeyPress(c, KEY_RETURN)

    # Save Secure Boot
    UEFIKeyPress(c, KEY_F10)
    UEFIKeyPress(c, KEY_Y)

    # Go Back to Menu
    UEFIKeyPress(c, KEY_ESC)
    UEFIKeyPress(c, KEY_ESC)

    # Go Down for reset
    UEFIKeyPress(c, KEY_DOWN)
    UEFIKeyPress(c, KEY_DOWN)
    UEFIKeyPress(c, KEY_DOWN)
    UEFIKeyPress(c, KEY_DOWN)
    UEFIKeyPress(c, KEY_RETURN)

def BOOTLOADERchooseSerialConsole(child, live: bool) -> None:
    """ Select the boot entry that uses the serial console on a LIVE ISO image.
        An already installed system boots its default entry, which already
        uses the serial console. """
    BOOTLOADER_TMO = 40
    BOOTLOADER_SLEEP = 1.5
    BOOTLOADER_LOAD_TMO = 5 # let GRUB screen load

    UEFI_STRING = r'BdsDxe.*'
    GRUB_STRING = r'GNU GRUB.*'
    ISOLINUX_STRING = r'ISOLINUX.*'

    # XXX: UEFI systems directly load GRUB, BIOS systems fallback to ISOLINUX
    if live and args.uefi:
        def expectSelected(title, timeout=15) -> bool:
            try:
                child.expect_exact(b'*' + title, timeout=timeout)
            except (pexpect.TIMEOUT, pexpect.EOF):
                recent = child.before[-1500:]
                log.warning(
                    f'GRUB did not confirm selection of {title!r}; '
                    f'recent output: {recent!r}'
                )
                return False
            return True

        # The countdown is printed after all menu entries have been drawn.
        child.expect(
            rb'The highlighted entry will be executed automatically in (\d+)s\.',
            timeout=120,
        )
        # Until a key is confirmed, an unacknowledged Home is resent without
        # using up an attempt, as long as the countdown may still be running.
        autoboot = time.monotonic() + int(child.match.group(1)) - 2

        # A missing acknowledgement does not tell us whether the key was received.
        # Restart from Home instead of repeating Down from an unknown selection.
        attempts = 3
        while attempts:
            if child.eof():
                raise RuntimeError('QEMU exited during GRUB menu selection')

            # Ctrl-A is Home without the EFI console's escape-sequence parsing.
            child.sendcontrol('a')
            if not expectSelected(b'Live system (vyos) - KVM console', timeout=1):
                if time.monotonic() >= autoboot:
                    attempts -= 1
                continue
            # A received key stops the countdown
            autoboot = 0

            for title in (
                b'Live system (vyos fail-safe mode)',
                b'Live system (vyos) - Serial console',
            ):
                # Ctrl-N is Down without the escape-sequence parsing of arrow keys.
                child.sendcontrol('n')
                if not expectSelected(title):
                    break
            else:
                child.send(b'\r')
                return
            attempts -= 1

        raise RuntimeError('Failed to confirm GRUB serial console boot selection after 3 attempts')
    elif live and not args.uefi:
        # Wait for ISOLINUX
        child.expect(ISOLINUX_STRING, timeout=BOOTLOADER_TMO)
        time.sleep(BOOTLOADER_LOAD_TMO)

        # Boot Menu starts at Live system (vyos) - KVM console
        child.send(KEY_DOWN)
        time.sleep(BOOTLOADER_SLEEP)
        # Live system (vyos fail-safe mode)
        child.send(KEY_DOWN)
        time.sleep(BOOTLOADER_SLEEP)
        # Live system (vyos) - Serial console - boot it up
        child.send(KEY_RETURN)
    else:
        # Let UEFI start before GRUB
        if args.uefi:
            child.expect(UEFI_STRING, timeout=BOOTLOADER_TMO)

        # Wait for GRUB
        child.expect(GRUB_STRING, timeout=BOOTLOADER_TMO)

        # Do not navigate the installed system's GRUB menu. The installer
        # already made the serial console the default (we answer 'S' to
        # "What console should be used by default?", raw images get it from
        # the build flavor), so the default entry boots the right console.
        # Steering the menu with timed keypresses raced GRUB's auto-boot
        # countdown and lost keypresses under host load (T8147, T9099,
        # T9214). basic_cli_tests() verifies the console settings.

    return None

def get_cmd_output(c, cmd, prompt=op_mode_prompt):
    """ Run cmd on the console and return its last line of output, stripped of
        any terminal control sequences. """
    c.sendline(cmd)
    c.expect(prompt)
    text = ansi_escape.sub('', c.before.decode(errors='replace'))
    # Drop empty lines and the echoed command itself
    lines = [l.strip() for l in text.splitlines() if l.strip() and l.strip() != cmd]
    return lines[-1] if lines else ''

def basic_cli_tests(c):
    # Repeating / shared basic CLI test between installed images and the
    # cloud-init test-case
    c.sendline('configure')
    c.expect(cfg_mode_prompt)
    c.sendline('exit')
    c.expect(op_mode_prompt)
    c.sendline('show version')
    c.expect(op_mode_prompt)
    c.sendline('show version kernel')
    c.expect(f'{vyos_defaults["kernel_version"]}-{vyos_defaults["kernel_revision"]}-{vyos_defaults["kernel_flavor"]}')
    c.expect(op_mode_prompt)
    c.sendline('show version frr')
    c.expect(op_mode_prompt)
    c.sendline('show interfaces')
    c.expect(op_mode_prompt)
    # 2>&1 so a missing store is visible rather than an empty result
    c.sendline(f'cat {IFNAME_MAPPING_FILE} 2>&1 || true')
    c.expect(op_mode_prompt)
    # c.sendline('systemd-detect-virt')
    # c.expect('kvm')
    # c.expect(op_mode_prompt)
    c.sendline('show system cpu')
    c.expect(op_mode_prompt)
    c.sendline('show system memory')
    c.expect(op_mode_prompt)
    c.sendline('show system memory detail | no-more')
    c.expect(op_mode_prompt)
    c.sendline('show configuration commands | match "option kernel"')
    c.expect(op_mode_prompt)
    c.sendline('cat /proc/cmdline')
    c.expect(op_mode_prompt)
    c.sendline('show version all | grep -e "vpp" -e "vyos-1x"')
    c.expect(op_mode_prompt)

    # Get serial console interface name from flavor definition
    flavor_json = '/usr/share/vyos/flavor.json'
    console_type = get_cmd_output(c, f'jq -r ".console_type" {flavor_json}') # e.g. ttyS

    # We do only care for ttyS or ttyAMA console types, exit early
    # for VGA consoles
    if console_type == 'tty':
        return

    console_num = get_cmd_output(c, f'jq -r ".console_num" {flavor_json}') # e.g. 0

    # Get serial console speed from flavor definition
    console_speed = get_cmd_output(c, f'jq -r ".console_speed" {flavor_json}') # e.g. 115200

    # Values are interpolated into regular expressions below - bail out with a
    # meaningful error instead of a confusing re.error traceback if the console
    # returned something unexpected
    for name, value, pattern in [('console_type', console_type, r'tty[A-Za-z0-9]*'),
                                 ('console_num', console_num, r'\d+'),
                                 ('console_speed', console_speed, r'\d+')]:
        if not re.fullmatch(pattern, value):
            raise Exception(f'Invalid {name} "{value}" read from {flavor_json}')

    # These are scraped off a serial console, so they can pick up stray
    # control characters. Escape them: they are literal values, never
    # patterns, and an unescaped '[' makes re.compile() raise before the
    # expect even runs - which reads as a mysterious harness crash rather
    # than the scrape problem it actually is.
    console_dev = re.escape(f'{console_type}{console_num}')
    log.debug(f'console from flavor.json: {console_dev!r},{console_speed!r}')

    # Ensure serial console with kernel option is set in CLI, done automatically by image installer
    c.sendline('show configuration commands | match "system console"')
    c.expect(rf'set system console device {console_dev} kernel\r\r\nset system console device {console_dev} speed \'{re.escape(console_speed)}\'')
    c.expect(op_mode_prompt)

    # Validate GRUB has the right console_type defined. The GRUB configuration
    # lives on the persistence partition, which is not the running image's
    # /boot - resolve it the way vyos.system.grub does.
    persistence = get_cmd_output(
        c,
        'python3 -c "from vyos.system.disk import find_persistence;'
        ' print(find_persistence())"',
    )
    c.sendline(f'grep "set console_type" '
               f'{persistence}/boot/grub/grub.cfg.d/20-vyos-defaults-autoload.cfg')
    c.expect(rf'set console_type="{re.escape(console_type)}"')
    c.expect(op_mode_prompt)

def qemu_monitor(commands):
    """ Feed commands to the QEMU monitor of the running VM. """
    os.system(f"printf '{commands}' | "
              f'socat - unix-connect:/tmp/qemu-monitor-socket-{args.disk}')


def hotplug_nic(log, index, pci_addr, mac=None):
    """ Plug a NIC into the running VM through the QEMU monitor. The slot is
        deliberately one that sits between the slots already in use, so
        canonical hardware order would place the card in the middle of the
        existing interfaces - it must still be named after them. """
    netdev = f'hotplug{index}'
    mac = mac or f'{macbase}:{index:02x}'.lower()
    log.info(f'Hot-plugging a NIC with MAC {mac} into PCI slot {pci_addr}')
    qemu_monitor(f'netdev_add user,id={netdev}\n'
                 f'device_add virtio-net-pci,id=nic{index},netdev={netdev},'
                 f'mac={mac},bus=pci.0,addr={pci_addr}\n')
    return mac


def unplug_nic(log, index, settle=10):
    """ Pull a card out of the running VM. PCI removal is asynchronous - the
        guest has to acknowledge it - so give it a moment to complete, then
        drop the backend too or its id cannot be reused. The boot-time cards
        are wired to netdev n0..n7, anything plugged in later to hotplugN. """
    log.info(f'Unplugging the card in nic{index}')
    qemu_monitor(f'device_del nic{index}\n')
    time.sleep(settle)
    netdev = f'n{index}' if index < 8 else f'hotplug{index}'
    qemu_monitor(f'netdev_del {netdev}\n')


def move_nic(log, index, pci_addr, mac):
    """ Take a card out and put the SAME card back in a different slot, which
        is what a machine looks like after someone re-seated it. """
    unplug_nic(log, index)
    return hotplug_nic(log, index, pci_addr, mac=mac)


def verify_hotplug_was_recorded(c, log, mapping_file, ifname, mac,
                                timeout=60):
    """ The hot-plug unit has to run and record the card straight away. If the
        udev rule does not match, nothing starts the unit, the card is absent
        from the store and no .link file is written for it - and a later
        reboot hides all of that, because the boot-time pass picks the card up
        anyway. Assert it here, before any reboot can paper over it. """
    log.info(f'Verify {ifname} was recorded without waiting for a reboot')
    unit = 'vyos-net-name-resolve-hotplug.service'

    # The card is registered by the Kernel well before the unit udev starts
    # has finished recording it, so poll rather than read the map once. No
    # reboot happens in between, which is what this is here to prove.
    deadline = time.time() + timeout
    tmp = 'NONE'
    while time.time() < deadline:
        tmp = get_cmd_output(
            c, f'sudo jq -r \'.hardware["{ifname}"] // "NONE"\' '
               f'{mapping_file}').lower()
        if tmp == mac:
            break
        time.sleep(2)

    if tmp != mac:
        started = get_cmd_output(
            c, f'systemctl show {unit} -p ExecMainStartTimestamp --value '
               '| grep -c . || true')
        if started != '1':
            cond = get_cmd_output(
                c, f'systemctl show {unit} -p ConditionTimestamp --value '
                   '| grep -c . || true')
            reason = ('its condition was not met' if cond == '1' else
                      'the udev rule did not match the new card')
            raise Exception(f'{unit} never ran - {reason}')
        # it ran and still did not record the card - show what it decided
        c.sendline('cat /run/vyos-net-name-resolve.json 2>&1 || true')
        c.expect(op_mode_prompt)
        c.sendline(f'sudo journalctl -u {unit} --no-pager | tail -20')
        c.expect(op_mode_prompt)
        raise Exception(f'{mapping_file} still records {ifname} on {tmp!r} '
                        f'{timeout}s after hot-plug, expected {mac}')

    tmp = get_cmd_output(
        c, f'sudo jq -r \'.interfaces["{ifname}"] // "NONE"\' {mapping_file}')
    if tmp == 'NONE':
        raise Exception(f'{ifname} is absent from {mapping_file} after hot-plug')
    log.info(f'{ifname} is in the store, on {mac}, and the unit ran')


def wait_for_ifname(c, log, ifname, timeout=60):
    """ Wait for the Kernel to register the card. This says nothing about the
        naming pass udev starts for it - that is still running afterwards. """
    deadline = time.time() + timeout
    while time.time() < deadline:
        if get_cmd_output(c, f'ip -br link show {ifname} 2>/dev/null | wc -l') == '1':
            log.info(f"'{ifname}' appeared")
            return
        time.sleep(2)
    raise Exception(f"'{ifname}' did not appear within {timeout}s after hot-plug")


def verify_ifname_has_mac(c, log, ifname, expected_mac):
    """ Assert a single interface sits on the NIC we expect. """
    tmp = get_cmd_output(
        c, f"ip -json link show {ifname} | jq -r '.[0].address'").lower()
    if tmp != expected_mac:
        raise Exception(f'Interface {ifname} has MAC {tmp}, '
                        f'expected {expected_mac}')
    log.info(f"'{ifname}' is on the expected NIC ({expected_mac})")


def verify_vmware_firmware(c, log, count=VMWARE_PORT_LABEL_COUNT):
    """ The VMware variant of the naming tests is only worth anything if the
        guest really believes it runs on VMware. Both signals the store looks
        at have to be there: the DMI vendor, and a firmware port label per
        NIC. Without the SMBIOS tables the guest is an ordinary machine and
        the run would silently repeat the plain naming test. """
    log.info('Verify the guest sees VMware firmware')
    vendor = get_cmd_output(c, 'cat /sys/class/dmi/id/sys_vendor')
    if 'VMware' not in vendor:
        raise Exception(f'DMI vendor is {vendor!r}, expected VMware - the '
                        'SMBIOS type 1 table did not reach the guest')

    c.sendline('for i in /sys/class/net/eth*; do echo "$(basename $i) '
               '$(cat $i/device/label 2>/dev/null)"; done')
    c.expect(op_mode_prompt)
    labels = {}
    for line in ansi_escape.sub('', c.before.decode(errors='replace')).splitlines():
        parts = line.split()
        if len(parts) == 2 and re.fullmatch(r'eth\d+', parts[0]):
            labels[parts[0]] = parts[1]

    missing = [f'eth{i}' for i in range(count)
               if not re.fullmatch(r'Ethernet\d+', labels.get(f'eth{i}', ''))]
    if missing:
        raise Exception(f'No firmware port label on {", ".join(missing)} - the '
                        'SMBIOS type 41 tables did not reach the guest')
    log.info(f'VMware DMI vendor and {count} port labels present')


def verify_bootup_scripts(c, log):
    """ The pre/post-config hooks normally ship in the config directory, but a
        config volume mounted over it has none - the encrypted one, for
        instance - and the boot then copies them out of the running image.
        Assert the hooks are usable either way, and that the copy, where it
        ran, did not quietly go wrong: it used to be handed a split path and
        try to copy a directory. The mode is not asserted - the packaged
        scripts and the restored ones differ, and both are fine. """
    log.info('Verify the bootup hook scripts are in place')
    for script in ('vyos-preconfig-bootup.script',
                   'vyos-postconfig-bootup.script'):
        path = f'/opt/vyatta/etc/config/scripts/{script}'
        tmp = get_cmd_output(c, f'sudo test -x {path} && echo OK || echo NO')
        if tmp != 'OK':
            raise Exception(f'{script} is missing or not executable')

    tmp = get_cmd_output(
        c, 'journalctl -b --no-pager | grep -c "omitting directory" || true')
    if tmp != '0':
        raise Exception(f'the boot logged {tmp} "omitting directory" errors - '
                        'a bootup script was copied from a split path')
    log.info('Both bootup hook scripts are usable, nothing was miss-copied')


def verify_eth_mac_mapping(c, log, count=8):
    """ NICs are attached with a mix of drivers (see get_qemu_cmd()) to cover
        different naming schemes. Regardless of driver, udev must always
        enumerate them in ascending order: eth0 carries mac0, eth1 mac1, ... -
        never scrambled. Hot-plugged cards extend the same run, so 'count'
        covers them too. """
    log.info(f'Verify eth0..eth{count - 1} are enumerated in ascending MAC order')
    c.sendline('ip -json link show | jq -r \'.[] | select(.ifname|test("^eth[0-9]+$")) | "\(.ifname) \(.address)"\'')
    c.expect(op_mode_prompt)
    lines = [l.strip() for l in c.before.decode(errors='replace').splitlines() if l.strip()]

    macs = {}
    for line in lines:
        parts = line.split()
        if len(parts) == 2 and re.fullmatch(r'eth\d+', parts[0]):
            macs[parts[0]] = parts[1].lower()

    for i in range(count):
        ifname = f'eth{i}'
        expected_mac = f'{macbase}:{i:02x}'.lower()
        if ifname not in macs:
            raise Exception(f'Interface {ifname} not found on installed system')
        if macs[ifname] != expected_mac:
            raise Exception(f'Interface {ifname} has MAC {macs[ifname]}, expected {expected_mac} - naming race?')
    log.info(f'eth0..eth{count - 1} MAC mapping verified')

def verify_radio_has_physical_device(c, log):
    """ A radio is not in the mapping file - every interface on a phy carries
        that phy's address, so there is nothing there to anchor a name to. The
        rescan has to find it on the system instead, or the interface never
        gets a node and 'interfaces wireless' shows nothing at all. """
    log.info('Verify a radio present at boot was given its physical-device')
    c.sendline('for i in /sys/class/net/wlan*; do [ -e "$i" ] && '
               'echo "$(basename $i) $(basename $(readlink $i/phy80211))"; done')
    c.expect(op_mode_prompt)

    radios = {}
    for line in ansi_escape.sub('', c.before.decode(errors='replace')).splitlines():
        parts = line.split()
        if len(parts) == 2 and re.fullmatch(r'wlan\d+', parts[0]):
            radios[parts[0]] = parts[1]

    # without one the rest of this proves nothing
    if not radios:
        raise Exception('no radio present after reboot - mac80211_hwsim did '
                        'not load at boot, so the rescan had nothing to find')

    for name, phy in sorted(radios.items()):
        tmp = get_cmd_output(
            c, f'show configuration commands | match "wireless {name} '
               'physical-device"')
        if phy not in tmp:
            raise Exception(f'{name} has no physical-device {phy} in the '
                            f'configuration, got {tmp!r}')
        log.info(f"'{name}' was given physical-device {phy}")


def firmware_diagnostics(c):
    """ Dump what the machine claims to be. The store reads the DMI vendor to
        decide whether a port label is worth looking at, and the labels
        themselves come from SMBIOS type 41 - so when a naming decision looks
        wrong, these tables say whether the input was there at all. Static for
        the life of the VM, hence once per run. """
    for command in ('cat /sys/class/dmi/id/sys_vendor',
                    'cat /sys/class/dmi/id/product_name',
                    'sudo dmidecode -t 1',
                    'sudo dmidecode -t 41'):
        c.sendline(f'{command} 2>/dev/null || true')
        c.expect(op_mode_prompt)


def verify_cloud_init_mapping(c, log, mapping_file):
    """ Which NIC the cloud considers its first one is not visible in the
        hardware, so the order the datasource gives has to be recorded in the
        mapping file before the naming pass reads it. The seed names the
        cards against the order they sit in, so deriving names from the
        hardware alone would put the other card on eth0. """
    log.info('Verify the datasource order reached the mapping file')
    expected = {'eth0': CI_CONFIG_ARGS['eth0_mac'],
                'eth1': CI_CONFIG_ARGS['eth1_mac'],
                'eth2': CI_CONFIG_ARGS['eth2_mac']}

    for ifname, mac in sorted(expected.items()):
        tmp = get_cmd_output(c, f'cat /sys/class/net/{ifname}/address').lower()
        if tmp != mac:
            raise Exception(f'{ifname} is on {tmp!r}, expected {mac} - the '
                            'names were derived from the hardware instead of '
                            'the order the datasource gave')
        log.info(f"'{ifname}' is on {mac}")

    for ifname, mac in sorted(expected.items()):
        tmp = get_cmd_output(
            c, f'sudo jq -r \'.hardware["{ifname}"] // "NONE"\' '
               f'{mapping_file}').lower()
        if tmp != mac:
            raise Exception(f'{mapping_file} records {ifname} on {tmp!r}, '
                            f'expected {mac}')

        tmp = get_cmd_output(
            c, f'sudo jq -r \'.interfaces["{ifname}"] // "NONE"\' '
               f'{mapping_file}')
        if tmp == 'NONE':
            raise Exception(f'{ifname} is absent from {mapping_file}')
        # these cards sit in a PCI slot, so a name anchored to the MAC would
        # mean the slot was never resolved
        if tmp.startswith('ID_NET_NAME_MAC='):
            raise Exception(f'{ifname} is recorded on {tmp!r}, which is its '
                            'MAC rather than the slot it sits in')
        log.info(f"'{ifname}' is recorded on {tmp}")


def ifname_diagnostics(c, mapping_file):
    """ Dump everything needed to reconstruct a naming decision after the
        fact. Cheap, and the difference between a one-line failure and an
        unreproducible one. """
    # every sysfs attribute and udev property the store keys a name on -
    # repeated per checkpoint because hot-plug changes them
    sysfs_dump = (
        'for d in /sys/class/net/*/device; do [ -e "$d" ] || continue; '
        'n=$(basename $(dirname $d)); '
        'echo "$n bus=$(basename $(readlink -f $d)) '
        'vendor=$(cat $d/vendor 2>/dev/null) '
        'subsystem_vendor=$(cat $d/subsystem_vendor 2>/dev/null) '
        'label=$(cat $d/label 2>/dev/null)"; done')
    udev_dump = (
        'for i in /sys/class/net/*; do n=$(basename $i); '
        'udevadm info -q property -p /sys/class/net/$n 2>/dev/null | '
        'grep -E "^(DEVTYPE|ID_BUS|ID_PATH|ID_NET_NAME_)" | '
        'sed "s/^/$n /"; done')

    for command in ('show interfaces ethernet',
                    'ip -br link show',
                    sysfs_dump,
                    udev_dump,
                    f'cat {mapping_file}',
                    'cat /run/vyos-net-name-resolve.json',
                    'ls /etc/systemd/network/',
                    'show log | match net-name-resolve'):
        c.sendline(f'{command} 2>/dev/null || true')
        c.expect(op_mode_prompt)


def verify_swapped_assignment(c, log, mac1, mac2):
    """ eth1 and eth2 were just swapped in the mapping store, so each must
        now be on the other's NIC. This proves the store alone decides names,
        and sets up the next check: a box whose names do not follow slot
        order, exactly like one first named by an older release. """
    log.info('Verify the swapped eth1/eth2 mapping took effect')
    c.sendline('ip -json link show | jq -r \'.[] | select(.ifname|test("^eth[0-9]+$")) | "\(.ifname) \(.address)"\'')
    c.expect(op_mode_prompt)
    lines = [l.strip() for l in c.before.decode(errors='replace').splitlines() if l.strip()]

    macs = {}
    for line in lines:
        parts = line.split()
        if len(parts) == 2 and re.fullmatch(r'eth\d+', parts[0]):
            macs[parts[0]] = parts[1].lower()

    if macs.get('eth1') != mac2:
        raise Exception(f'Interface eth1 has MAC {macs.get("eth1")}, expected {mac2} '
                         '- the mapping store was not applied')
    if macs.get('eth2') != mac1:
        raise Exception(f'Interface eth2 has MAC {macs.get("eth2")}, expected {mac1} '
                         '- the mapping store was not applied')
    log.info('Mapping store is authoritative - eth1/eth2 no longer follow slot order')

def verify_interface_keeps_own_hardware(c, log, ifname, expected_mac):
    """ An interface that still carries settings (an address) must come back
        bound to its OWN hardware after a different, unrelated interface's
        configuration is removed - while its own name does not follow slot
        order, which is what used to make names get re-derived and two
        interfaces end up on each other's cable.

        The check for this could once only be negative ("never the wrong
        MAC"), because leaving the node unresolved was the safe outcome at
        the time - so a run where the interface was missing entirely counted
        as a pass. Names no longer come from the configuration, so deleting
        one cannot put a name up for grabs and the guarantee is absolute: the
        interface must be present, and on its own hardware. Assert that
        directly - a missing interface is now a failure.
    """
    log.info(f'Verify {ifname} still owns its own physical NIC ({expected_mac})')
    c.sendline('ip -json link show | jq -r \'.[] | select(.ifname|test("^eth[0-9]+$")) | "\(.ifname) \(.address)"\'')
    c.expect(op_mode_prompt)
    lines = [l.strip() for l in c.before.decode(errors='replace').splitlines() if l.strip()]

    macs = {}
    for line in lines:
        parts = line.split()
        if len(parts) == 2 and re.fullmatch(r'eth\d+', parts[0]):
            macs[parts[0]] = parts[1].lower()

    if ifname not in macs:
        raise Exception(f'Interface {ifname} does not exist after reboot - its '
                        'name must stay bound to its own hardware, not be left '
                        'unresolved')
    if macs[ifname] != expected_mac:
        raise Exception(f'Interface {ifname} has MAC {macs[ifname]}, expected '
                        f'{expected_mac} - it is bound to the wrong physical '
                        'NIC, so settings configured on it now apply to the '
                        'wrong wire')
    log.info(f'{ifname} correctly kept its own physical NIC')

def _image_update_cli_sequence(c, log, new_image_name, server_bind_host='127.0.0.1', use_vrf=False):
    """One add-system-image/delete cycle for nested ISO over HTTP (optional Linux VRF + VyOS vrf arg)."""
    url = f'http://{server_bind_host}:{NESTED_HTTP_SERV_PORT}/{NESTED_INNER_ISO_NAME}'

    vrf_exec = ''
    if use_vrf:
        log.info(f'Configure VRF ({NESTED_HTTP_VRF_NAME}) for HTTP server - used for image update ')
        vrf_exec = f'ip vrf exec {NESTED_HTTP_VRF_NAME} '
        c.sendline('configure')
        c.expect(cfg_mode_prompt)
        c.sendline(f'set vrf name {NESTED_HTTP_VRF_NAME} table {NESTED_HTTP_VRF_TABLE}')
        c.expect(cfg_mode_prompt)
        c.sendline(f'set interfaces dummy {NESTED_HTTP_VRF_DUMMY} address {server_bind_host}/32')
        c.expect(cfg_mode_prompt)
        c.sendline(f'set interfaces dummy {NESTED_HTTP_VRF_DUMMY} vrf {NESTED_HTTP_VRF_NAME}')
        c.expect(cfg_mode_prompt)
        c.sendline('commit')
        c.expect(cfg_mode_prompt)
        c.sendline('exit')
        c.expect(op_mode_prompt)

    c.sendline(
        f'sudo bash -c \'{vrf_exec}python3 -m http.server {NESTED_HTTP_SERV_PORT} --bind {server_bind_host} '
        f'--directory {NESTED_HTTP_MOUNT_POINT} </dev/null >/tmp/nested_http.log 2>&1 &\''
    )
    c.expect(op_mode_prompt)

    time.sleep(5) # Wait for HTTP server to start

    update_cmd_cli = f'TERM=dumb add system image {url}'
    if use_vrf:
        update_cmd_cli = f'{update_cmd_cli} vrf {NESTED_HTTP_VRF_NAME}'
    c.sendline(update_cmd_cli)

    timeout = 600
    deadline = time.time() + timeout
    while True:
        if time.time() > deadline:
            raise Exception(f'add system image timed out after {timeout}s')
        i = c.expect([
            'What would you like to name this image',
            'Would you like to set the new image as the default one for boot',
            'An active configuration was found. Would you like to copy it to the new image',
            'Would you like to copy SSH host keys',
            'Would you like to copy Bash history',
            'Would you like to save the SSH known hosts (fingerprints)',
            'Signature is not available. Do you want to continue with installation',
            'There are unsaved changes to the configuration',
            'Would you like to continue',
            'Unable to',
            'Error:',
            op_mode_prompt,
        ], timeout=300)
        if i == 0:
            c.sendline(new_image_name)
        elif i == 1:
            c.sendline('n')
        elif i == 2:
            c.sendline('y')
        elif i == 3:
            c.sendline('y')
        elif i == 4:
            c.sendline('y')
        elif i == 5:
            c.sendline('y')
        elif i == 6:
            c.sendline('y')
        elif i == 7:
            c.sendline('y')
        elif i == 8:
            c.sendline('y')
        elif i == 9 or i == 10:
            raise Exception('add system image reported an error')
        elif i == 11:
            log.info('add system image completed')
            break

    c.sendline('show system image')
    c.expect(new_image_name)
    c.expect(op_mode_prompt)

    c.sendline(f'TERM=dumb delete system image {new_image_name}')
    deadline = time.time() + timeout
    while time.time() < deadline:
        j = c.expect([
            'Are you sure you want to delete',
            'Do you really want to delete the image',
            'Cannot ',
            'Error:',
            'Unable to ',
            op_mode_prompt,
        ], timeout=300)
        if j == 0 or j == 1:
            c.sendline('y')
        elif j == 2 or j == 3 or j == 4:
            raise Exception('delete system image failed')
        elif j == 5:
            break
    else:
        raise Exception('delete system image timed out')

    c.sendline('show system image')
    c.expect(op_mode_prompt)
    if new_image_name in c.before.decode(errors='replace'):
        raise Exception(f'Image {new_image_name!r} still listed after delete')

    c.sendline(f'sudo fuser -k {NESTED_HTTP_SERV_PORT}/tcp 2>/dev/null || true')
    c.expect(op_mode_prompt)

if args.qemu_cmd:
    tmp = get_qemu_cmd(qemu_name, args.uefi, args.disk, raid=diskname_raid,
                       iso_img=args.iso, vnc_enabled=args.vnc, secure_boot=args.secure_boot_test,
                       nested_cdrom_iso=nested_payload_iso_path, vmware=args.vmware)
    os.system(tmp)
    exit(0)

if args.cloud_init:
    # Build cloud-init seed iso
    CI_ISO = 'ci_seed.iso'
    CI_DATA_DIR = 'ci_data'
    # Insert cloud-init ISO into CD-ROM
    args.iso = CI_ISO

    if not os.path.exists(CI_DATA_DIR):
        os.makedirs(CI_DATA_DIR)

    # create "empty" meta-data file
    open(f'{CI_DATA_DIR}/meta-data', mode='w').close()

    # Name the cards against the order they sit in, the way a cloud hands out
    # an order of its own. It is a three-cycle: not one of them keeps the name
    # its slot would give it, so none of this holds unless the order the
    # datasource gave reached the mapping file.
    network_config = """version: 2
ethernets:
  eth0:
    match:
      macaddress: {eth0_mac}
    set-name: eth0
    dhcp4: false
    dhcp6: false
  eth1:
    match:
      macaddress: {eth1_mac}
    set-name: eth1
    dhcp4: false
    dhcp6: false
  eth2:
    match:
      macaddress: {eth2_mac}
    set-name: eth2
    dhcp4: false
    dhcp6: false
""".format(**CI_CONFIG_ARGS)

    user_data = """#cloud-config
vyos_config_commands:
  - set system host-name '{hostname}'
  - set service ntp server 1.pool.ntp.org
  - set service ntp server 2.pool.ntp.org
  - delete interfaces ethernet eth0 address 'dhcp'
  - set interfaces ethernet eth0 address '{eth0_ipv4}'
  - set interfaces ethernet eth0 address '{eth0_ipv6}'
  - set interfaces ethernet eth2 address '{eth2_ipv4}'
  - set protocols static route 0.0.0.0/0 next-hop '{default_nexthop}'
  - set protocols static route6 ::/0 next-hop '{default_nexthop6}'
""".format(**CI_CONFIG_ARGS)

    with open(f'{CI_DATA_DIR}/network-config', mode='w') as f:
        f.writelines(network_config)

    with open(f'{CI_DATA_DIR}/user-data', mode='w') as f:
        f.writelines(user_data)

    # Assemble cloud-init ISO file
    if os.path.exists(CI_ISO):
        os.unlink(CI_ISO)
    os.system(f'mkisofs -joliet -rock -volid "cidata" -output {CI_ISO} {CI_DATA_DIR}')

tpm_process = None
try:
    # Start TPM emulator
    if args.tpmtest:
        tpm_process = start_swtpm()

    #################################################
    # Installing image to disk
    #################################################
    log.info('Installing system')
    cmd = get_qemu_cmd(qemu_name, args.uefi, args.disk, raid=diskname_raid,
                       tpm=args.tpmtest, iso_img=args.iso, vnc_enabled=args.vnc,
                       secure_boot=args.secure_boot_test, nested_cdrom_iso=nested_payload_iso_path,
                       vmware=args.vmware)
    log.debug(f'Executing command: {cmd}')
    c = pexpect.spawn(cmd, logfile=stl, timeout=60)

    #################################################
    # Logging into VyOS system
    #################################################
    if sb_custom_ca:
        log.info('Disable UEFI Secure Boot for initial installation')
        toggleUEFISecureBoot(c)

    BOOTLOADERchooseSerialConsole(c, live=(not args.cloud_init))
    loginVM(c, log)

    if args.secure_boot_test and not sb_custom_ca:
        log.info('Verify live system booted with UEFI Secure Boot enabled')
        c.sendline('show secure-boot')
        c.expect('SecureBoot enabled')
        c.expect(op_mode_prompt)

    #################################################
    # Cloud-Init comes with a pre-assembled ISO - just boot and test it
    #################################################
    if args.cloud_init:
        log.info('Perform basic CLI configuration mode tests from cloud-init...')
        basic_cli_tests(c)

        # Valida assigned IPv4 and IPv6 addresses
        c.sendline('ip --json addr show dev eth0 | jq -r \'.[0].addr_info[] | select(.family=="inet") | "\(.local)/\(.prefixlen)"\'')
        c.expect(CI_CONFIG_ARGS['eth0_ipv4'])
        c.expect(op_mode_prompt)

        c.sendline('ip --json addr show dev eth0 | jq -r \'.[0].addr_info[] | select(.family=="inet6" and .scope=="global" and (.temporary|not)) | "\(.local)/\(.prefixlen)"\'')
        c.expect(CI_CONFIG_ARGS['eth0_ipv6'])
        c.expect(op_mode_prompt)

        # the last card of the cycle carries an address of its own, so a name
        # on the wrong wire shows up as an address on the wrong wire
        c.sendline('ip --json addr show dev eth2 | jq -r \'.[0].addr_info[] | select(.family=="inet") | "\(.local)/\(.prefixlen)"\'')
        c.expect(CI_CONFIG_ARGS['eth2_ipv4'])
        c.expect(op_mode_prompt)

        # Valida default route nexthops
        c.sendline('ip -4 --json route show default | jq -r ".[0].gateway"')
        c.expect(CI_CONFIG_ARGS['default_nexthop'])
        c.expect(op_mode_prompt)

        c.sendline('ip -6 --json route show default | jq -r ".[0].gateway"')
        c.expect(CI_CONFIG_ARGS['default_nexthop6'])
        c.expect(op_mode_prompt)

        ifname_diagnostics(c, IFNAME_MAPPING_FILE)
        verify_cloud_init_mapping(c, log, IFNAME_MAPPING_FILE)

        shutdownVM(c, log, 'Powering off system')
        c.close()
        raise EarlyExit

    #################################################
    # Check for no private key contents within the image
    #################################################
    msg = 'Found private key - bailing out'
    c.sendline(f'if sudo grep -rq "BEGIN PRIVATE KEY" /var/lib/shim-signed/mok; then echo {msg}; exit 1; fi')
    tmp = c.expect([f'\n{msg}', op_mode_prompt])
    if tmp == 0:
        log.error(msg)
        exit(1)

    #################################################
    # Configure boot options if required
    #################################################
    if args.huge_page_size and args.huge_page_count:
        c.sendline('configure')
        c.expect(cfg_mode_prompt)
        c.sendline(f'set system option kernel memory hugepage-size {args.huge_page_size} hugepage-count {args.huge_page_count}')
        c.expect(cfg_mode_prompt)
        if args.isolate_cpus:
            c.sendline(f'set system option kernel cpu isolate-cpus {args.isolate_cpus}')
            c.expect(cfg_mode_prompt)
        c.sendline('set system option kernel disable-mitigations')
        c.expect(cfg_mode_prompt)
        c.sendline('commit')
        c.expect(cfg_mode_prompt)
        c.sendline('save')
        c.expect(cfg_mode_prompt)
        c.sendline('exit')
        c.expect(op_mode_prompt)

    #################################################
    # Installing into VyOS system
    #################################################
    log.info('Starting installer')
    c.sendline('install image')
    c.expect('\nWould you like to continue?.*')
    c.sendline('y')
    c.expect('\nWhat would you like to name this image?.*')
    c.sendline('')
    c.expect(f'\nPlease enter a password for the "{default_user}" user.*')
    c.sendline('vyos')
    c.expect(f'\nPlease confirm password for the "{default_user}" user.*')
    c.sendline('vyos')
    c.expect('\nWhat console should be used by default?.*')
    c.sendline('S')

    if args.raid:
        c.expect('\nWould you like to configure RAID-1 mirroring??.*')
        c.sendline('y')
        c.expect('\nWould you like to configure RAID-1 mirroring on them?.*')
        c.sendline('y')
        c.expect('\nInstallation will delete all data on both drives. Continue?.*')
        c.sendline('y')
        # Creating the RAID array and the subsequent update-initramfs regularly
        # take longer than the default expect timeout
        c.expect('\nWhich file would you like as boot config?.*', timeout=300)
        c.sendline('')
    else:
        c.expect('\nWhich one should be used for installation?.*')
        c.sendline('')
        c.expect('\nInstallation will delete all data on the drive. Continue?.*')
        c.sendline('y')
        c.expect('\nWould you like to use all the free space on the drive?.*')
        c.sendline('y')
        c.expect('\nWhich file would you like as boot config?.*')
        c.sendline('')

    # GRUB installation and unmounting (flushing the copied squashfs to disk)
    # can take longer than the default pexpect timeout on large images
    c.expect(op_mode_prompt, timeout=300)

    if sb_custom_ca:
        c.sendline(f'sudo mokutil --ignore-keyring --import {SB_MOK_DER}')
        c.expect('input password:.*')
        c.sendline(mok_password)
        c.expect('input password again:.*')
        c.sendline(mok_password)
        c.expect(op_mode_prompt)

    log.info('system installed, rebooting')
    c.sendline('reboot now')

    #################################################
    # SHIM Mok Manager
    #################################################
    if sb_custom_ca:
        log.info('Install Secure Boot Machine Owner Key')
        MOK_SLEEP = 0.5
        c.expect('BdsDxe: starting Boot00.*')
        time.sleep(3)
        # press any key
        c.send(KEY_RETURN)
        time.sleep(MOK_SLEEP)

        # Enroll MOK
        c.send(KEY_DOWN)
        time.sleep(MOK_SLEEP)
        c.send(KEY_RETURN)
        time.sleep(MOK_SLEEP)

        # Continue
        c.send(KEY_DOWN)
        time.sleep(MOK_SLEEP)
        c.send(KEY_RETURN)
        time.sleep(MOK_SLEEP)

        # Enroll Keys
        c.send(KEY_DOWN)
        time.sleep(MOK_SLEEP)
        c.send(KEY_RETURN)
        time.sleep(MOK_SLEEP)

        c.sendline(mok_password)
        c.send(KEY_RETURN)
        time.sleep(MOK_SLEEP)

        # Reboot
        c.send(KEY_RETURN)
        time.sleep(MOK_SLEEP)

    #################################################
    # Re-Enable Secure Boot
    #################################################
    if sb_custom_ca:
        log.info('Enable UEFI Secure Boot for initial installation')
        toggleUEFISecureBoot(c)

    #################################################
    # Removing CD installation media
    #################################################
    time.sleep(2)
    log.info('eject installation media')
    os.system(f'echo "eject -f drive-cd1" | socat - unix-connect:/tmp/qemu-monitor-socket-{args.disk}')

    #################################################
    # Booting installed system
    #################################################
    log.info('Booting installed system')
    BOOTLOADERchooseSerialConsole(c, live=False)

    #################################################
    # Logging into VyOS system
    #################################################
    waitForLogin(c, log)
    loginVM(c, log)

    #################################################
    # Bootup hook scripts must be usable on a plain installed system
    #################################################
    verify_bootup_scripts(c, log)

    #################################################
    # Boot options require a reboot
    #################################################
    if args.huge_page_size and args.huge_page_count:
        log.info('Rebooting to apply kernel boot options')
        c.sendline('reboot now')
        loginVM(c, log)

    ################################################
    # Always load the WiFi simulation module
    ################################################
    c.sendline('sudo modprobe mac80211_hwsim')
    c.expect(op_mode_prompt)

    # Inform smoketest about this environment
    c.sendline('touch /tmp/vyos.smoketests.hint')
    c.expect(op_mode_prompt)

    #################################################
    # Basic Configmode/Opmode switch
    #################################################
    log.info('Basic CLI configuration mode test')
    basic_cli_tests(c)

    #################################################
    # Verify NIC driver mix did not scramble interface naming
    #################################################
    verify_eth_mac_mapping(c, log)

    #################################################
    # Verify /etc/os-release via lsb_release
    #################################################
    c.sendline('lsb_release --short --id 2>/dev/null')
    c.expect('VyOS')
    if os.path.isfile(manifest_file):
        c.sendline('lsb_release --short --release 2>/dev/null')
        c.expect(vyos_version)
        c.sendline('lsb_release --short --codename 2>/dev/null')
        c.expect(vyos_codename)

    # Ensure ephemeral key is loaded
    vyos_kernel_key = 'VyOS build time autogenerated kernel key'
    c.sendline(f'show log kernel | match "{vyos_kernel_key}"')
    c.expect(f'.*{vyos_kernel_key}.*')
    c.expect(op_mode_prompt)

    #################################################
    # Executing test-suite
    #################################################
    if args.tpmtest:
        def verify_mount():
            # Verify encrypted and mounted
            c.sendline('mount | grep vyos_config')
            c.expect('/dev/mapper/vyos_config on /opt/vyatta/etc/config.*')
            c.expect(op_mode_prompt)

        def verify_config():
            # Verify encrypted config is loaded
            c.sendline('show config commands | cat')
            c.expect('set system option performance \'network-latency\'')
            c.expect('set system option reboot-on-panic')
            c.expect(op_mode_prompt)

        log.info('Running TPM encrypted config tests')
        tpm_timeout = 600 # Give it 10 mins to encrypt

        # Verify TPM is loaded
        c.sendline('find /dev -name tpm0')
        c.expect('/dev/tpm0')
        c.expect(op_mode_prompt)

        # Create recovery key
        import string
        from random import choices
        test_recovery_key = ''.join(choices(string.ascii_uppercase + string.digits, k=32))

        log.info('Encrypting config to TPM')
        c.sendline('encryption enable')
        c.expect('Automatically generate a recovery key\?.*')
        c.sendline('n')
        c.expect('Enter recovery key: ')
        c.sendline(test_recovery_key)
        c.expect('Enter size of encrypted config partition.*', timeout=30)
        c.sendline('32')
        c.expect('Encrypted config volume has been enabled', timeout=tpm_timeout)
        c.expect('Backup the recovery key in a safe place!')
        c.expect(f'Recovery key: {test_recovery_key}')
        c.expect(op_mode_prompt)

        verify_mount()

        # Add some non-default config nodes this encrypted config
        log.info('Adding nodes for encrypted config test')
        c.sendline('configure')
        c.expect(cfg_mode_prompt)
        c.sendline('set system option performance network-latency')
        c.expect(cfg_mode_prompt)
        c.sendline('set system option reboot-on-panic')
        c.expect(cfg_mode_prompt)
        c.sendline('commit')
        c.expect(cfg_mode_prompt)
        c.sendline('save')
        c.expect(cfg_mode_prompt)
        c.sendline('exit')
        c.expect(op_mode_prompt)

        log.info('system installed, rebooting')
        c.sendline('reboot now')

        waitForLogin(c, log)

        # Check for vyos-router message
        c.expect('.*Mounted encrypted config volume', timeout=120)

        loginVM(c, log)

        verify_mount()
        verify_config()

        # Shutdown VM
        shutdownVM(c, log, 'Shutdown VM for TPM fail test')

        # Clear swtpm
        clearTPM()

        # Shutdown kills swtpm
        tpm_process.join()
        tpm_process.close()

        # Start emulator again
        tpm_process = start_swtpm()

        # Booting back into VM
        log.info('Booting system with cleared TPM')
        cmd = get_qemu_cmd(qemu_name, args.uefi, args.disk, raid=diskname_raid, tpm=args.tpmtest, vnc_enabled=args.vnc)
        log.debug(f'Executing command: {cmd}')
        c = pexpect.spawn(cmd, logfile=stl)

        waitForLogin(c, log)

        c.expect('.*Encrypted config volume has not been mounted', timeout=120)

        loginVM(c, log)

        # The encrypted volume is mounted over the config directory, so when it
        # stays shut the hooks are absent and the boot has to copy them out of
        # the running image. This is the one boot that exercises that path.
        verify_bootup_scripts(c, log)

        # Test loading config with recovery key
        c.sendline('encryption load')
        c.expect('Enter recovery key: ')
        c.sendline(test_recovery_key)
        c.expect('Encrypted config volume has been mounted', timeout=120)
        c.expect(op_mode_prompt)

        verify_mount()

        log.info('Loading encrypted config.boot')
        c.sendline('configure')
        c.expect(cfg_mode_prompt)
        c.sendline('load /opt/vyatta/etc/config/config.boot')
        c.expect(cfg_mode_prompt)
        c.sendline('commit')
        c.expect(cfg_mode_prompt)
        c.sendline('exit')
        c.expect(op_mode_prompt)

        verify_config()

        # Shutdown VM
        shutdownVM(c, log, 'Shutdown VM for non-TPM backed test')
        clearTPM()

        # Shutdown kills swtpm
        tpm_process.join()
        tpm_process.close()
        tpm_process = None

        # Booting back into VM
        log.info('Booting system without TPM')
        cmd = get_qemu_cmd(qemu_name, args.uefi, args.disk, raid=diskname_raid, tpm=False, vnc_enabled=args.vnc)
        log.debug(f'Executing command: {cmd}')
        c = pexpect.spawn(cmd, logfile=stl)

        waitForLogin(c, log)
        loginVM(c, log)

        # New recovery key
        test_recovery_key = ''.join(choices(string.ascii_uppercase + string.digits, k=32))

        log.info('Encrypting config')
        c.sendline('encryption enable')
        c.expect('Are you sure you want to proceed\?.*')
        c.sendline('y')
        c.expect('Enter key: ')
        c.sendline(test_recovery_key)
        c.expect('Confirm key:')
        c.sendline(test_recovery_key)
        c.expect('Enter size of encrypted config partition.*', timeout=30)
        c.sendline('32')
        c.expect('Encrypted config volume has been enabled', timeout=tpm_timeout)
        c.expect('Backup the key in a safe place!')
        c.expect(f'Key: {test_recovery_key}')
        c.expect(op_mode_prompt)

        verify_mount()

        shutdownVM(c, log, 'Shutdown VM for non-TPM config load')

        # Booting back into VM
        log.info('Booting system without TPM')
        cmd = get_qemu_cmd(qemu_name, args.uefi, args.disk, raid=diskname_raid, tpm=False, vnc_enabled=args.vnc)
        log.debug(f'Executing command: {cmd}')
        c = pexpect.spawn(cmd, logfile=stl)

        waitForLogin(c, log)

        c.expect('.*encrypted config volume will not be automatically mounted', timeout=120)

        loginVM(c, log)

        # Test loading config with recovery key
        c.sendline('encryption load')
        c.expect('Enter key: ')
        c.sendline(test_recovery_key)
        c.expect('Encrypted config volume has been mounted', timeout=120)
        c.expect(op_mode_prompt)

        verify_mount()

        log.info('Loading encrypted config.boot')
        c.sendline('configure')
        c.expect(cfg_mode_prompt)
        c.sendline('load /opt/vyatta/etc/config/config.boot')
        c.expect(cfg_mode_prompt)
        c.sendline('commit')
        c.expect(cfg_mode_prompt)
        c.sendline('exit')
        c.expect(op_mode_prompt)

    elif args.ifnametest:
        # Interface names come from the mapping store, which is keyed on where
        # the hardware sits. Nothing in the configuration decides a name any
        # more, so the guarantees under test are:
        #
        #   1. deleting an interface's configuration does not free its name
        #   2. the store is authoritative - edit it and names follow
        #   3. losing the store entirely reproduces the same names from
        #      hardware alone, because bootstrap order is a property of the
        #      machine and not of probe timing
        #
        # The NICs are pinned to ascending PCI slots with ascending MACs, so
        # eth0..eth7 must map to macbase:00..07 whenever naming is re-derived.
        log.info('Running interface naming persistence tests')
        mapping_file = IFNAME_MAPPING_FILE

        firmware_diagnostics(c)
        if args.vmware:
            verify_vmware_firmware(c, log)

        log.info('Verify the mapping store was created on first boot')
        c.sendline(f'cat {mapping_file}')
        c.expect(op_mode_prompt)
        if 'interfaces' not in c.before.decode(errors='replace'):
            raise Exception(f'{mapping_file} missing or empty after first boot')

        del_idx = random.choice(range(8))
        log.info(f'Deleting eth{del_idx} configuration entirely')
        c.sendline('configure')
        c.expect(cfg_mode_prompt)
        c.sendline(f'delete interfaces ethernet eth{del_idx}')
        c.expect(cfg_mode_prompt)
        c.sendline('commit')
        c.expect(cfg_mode_prompt)
        c.sendline('save')
        c.expect(cfg_mode_prompt)
        c.sendline('exit')
        c.expect(op_mode_prompt)

        log.info('Rebooting - a deleted configuration must not free the name')
        c.sendline('reboot now')
        waitForLogin(c, log)
        loginVM(c, log)
        ifname_diagnostics(c, mapping_file)
        verify_eth_mac_mapping(c, log)

        # The store is the only thing that decides names, so editing it must
        # be enough to move an interface onto different hardware - and the
        # change must stick across the reboot after that.
        log.info('Swapping eth1 and eth2 in the mapping store')
        c.sendline(
            "sudo python3 -c \"import json;"
            f"p='{mapping_file}';d=json.load(open(p));"
            "i=d['interfaces'];i['eth1'],i['eth2']=i['eth2'],i['eth1'];"
            "json.dump(d,open(p,'w'))\"")
        c.expect(op_mode_prompt)

        log.info('Rebooting to verify the store is authoritative')
        c.sendline('reboot now')
        waitForLogin(c, log)
        loginVM(c, log)
        ifname_diagnostics(c, mapping_file)

        mac1 = f'{macbase}:01'.lower()
        mac2 = f'{macbase}:02'.lower()
        verify_swapped_assignment(c, log, mac1, mac2)

        # eth1 and eth2 no longer follow slot order, exactly like a box first
        # named by an older release. Removing an unrelated interface's
        # configuration in that state used to be enough to re-derive names and
        # put two interfaces on each other's cable.
        log.info("Deleting eth1's configuration while eth2 is off slot order")
        c.sendline('configure')
        c.expect(cfg_mode_prompt)
        c.sendline('delete interfaces ethernet eth1')
        c.expect(cfg_mode_prompt)
        c.sendline('commit')
        c.expect(cfg_mode_prompt)
        c.sendline('save')
        c.expect(cfg_mode_prompt)
        c.sendline('exit')
        c.expect(op_mode_prompt)

        log.info('Rebooting to check eth2 stays on its own physical NIC')
        c.sendline('reboot now')
        waitForLogin(c, log)
        loginVM(c, log)
        ifname_diagnostics(c, mapping_file)
        verify_interface_keeps_own_hardware(c, log, 'eth2', mac1)

        # Finally, lose the store. Names must come back identical, because
        # bootstrap order is derived from PCI topology rather than from the
        # order drivers happened to finish probing.
        log.info('Deleting the mapping store to verify names are reproducible')
        c.sendline(f'sudo rm -f {mapping_file} /etc/systemd/network/*-vyos-*.link')
        c.expect(op_mode_prompt)
        c.sendline('reboot now')
        waitForLogin(c, log)
        loginVM(c, log)
        ifname_diagnostics(c, mapping_file)
        verify_eth_mac_mapping(c, log)

        # A card which appears after boot must be named after the interfaces
        # already known, never among them. Both slots used here sit between
        # slots already in use, so canonical hardware order would place the
        # new cards at eth4 and eth6 - the names in the store are reserved,
        # which is what has to stop that from happening.
        if platform.machine() in ['amd64', 'x86_64']:
            mac8 = hotplug_nic(log, 8, '0x8')
            wait_for_ifname(c, log, 'eth8')
            verify_hotplug_was_recorded(c, log, mapping_file, 'eth8', mac8)
            mac9 = hotplug_nic(log, 9, '0xc')
            wait_for_ifname(c, log, 'eth9')
            verify_hotplug_was_recorded(c, log, mapping_file, 'eth9', mac9)

            ifname_diagnostics(c, mapping_file)
            log.info('Verify the hot-plugged cards were appended, not inserted')
            verify_ifname_has_mac(c, log, 'eth8', mac8)
            verify_ifname_has_mac(c, log, 'eth9', mac9)
            verify_eth_mac_mapping(c, log, count=10)

            # The real corner case: with every card present from the start,
            # the one in slot 0x8 is fifth in hardware order. It must still be
            # eth8, or five interfaces move onto the wrong cable.
            log.info('Rebooting - hot-plugged names must survive re-enumeration')
            c.sendline('reboot now')
            waitForLogin(c, log)
            loginVM(c, log)
            ifname_diagnostics(c, mapping_file)
            verify_eth_mac_mapping(c, log, count=10)

            # ... and the boot-time rescan must have added a node for them.
            # config.boot is what the rescan writes, so assert on that rather
            # than on the running config - a node carrying no settings at all
            # does not necessarily survive into it.
            for ifname in ('eth8', 'eth9'):
                tmp = get_cmd_output(
                    c, f'sudo grep -c "ethernet {ifname}" /config/config.boot')
                if tmp == '0':
                    raise Exception(f'{ifname} was not added to the '
                                    'configuration by the interface rescan')
            log.info('Hot-plugged interfaces were added to the configuration')

            # A card carries its name with it. Re-seat eth9's card in a free
            # slot: the name has to follow the card, not stay behind with the
            # position. Matching on the slot alone would hand eth9 - and the
            # address configured under it - to whatever turns up there next.
            log.info("Moving eth9's card to a different PCI slot")
            move_nic(log, 9, '0x9', mac9)
            wait_for_ifname(c, log, 'eth9')
            c.sendline('reboot now')
            waitForLogin(c, log)
            loginVM(c, log)
            ifname_diagnostics(c, mapping_file)
            verify_ifname_has_mac(c, log, 'eth9', mac9)
            log.info('eth9 followed its own card to the new slot')

            # ... and the slot it vacated must not lend its name out. A card
            # added for an unrelated purpose, dropped into the freed slot, was
            # reported from the field coming up on another segment's address.
            log.info('Adding an unrelated card to the slot eth9 left behind')
            mac10 = f'{macbase}:0a'.lower()
            hotplug_nic(log, 10, '0xc', mac=mac10)
            wait_for_ifname(c, log, 'eth10')
            verify_hotplug_was_recorded(c, log, mapping_file, 'eth10', mac10)
            verify_ifname_has_mac(c, log, 'eth9', mac9)
            verify_ifname_has_mac(c, log, 'eth10', mac10)
            log.info('The newcomer was named separately, eth9 kept its card')

            # With the original card gone for good, nothing distinguishes a
            # replacement in the same slot from an unrelated card that landed
            # there. The slot decides, and the boot has to say so - that
            # warning is the only thing standing between the operator and an
            # address quietly moving to another cable.
            log.info("Replacing eth8's card with a different one in its slot")
            mac11 = f'{macbase}:0b'.lower()
            unplug_nic(log, 8)
            hotplug_nic(log, 11, '0x8', mac=mac11)
            verify_hotplug_was_recorded(c, log, mapping_file, 'eth8', mac11)
            verify_ifname_has_mac(c, log, 'eth8', mac11)

            # The pass which takes this decision is the one udev starts for
            # the new card, so look at what it reported. Rebooting first would
            # find the card already on record and nothing left to say about
            # it, which is not the same thing as the case never arising.
            tmp = get_cmd_output(
                c, 'sudo jq -r \'.matched_by_path["eth8"] // "NONE"\' '
                   '/run/vyos-net-name-resolve.json').lower()
            if tmp != mac11:
                raise Exception('the status file does not report eth8 as '
                                f'matched by slot to {mac11}, got {tmp!r}')
            tmp = get_cmd_output(
                c, 'journalctl -b --no-pager | '
                   'grep -c "eth8. was matched to new hardware" || true')
            if tmp == '0':
                raise Exception('the replacement was not warned about - eth8 '
                                'was matched to different hardware by slot')
            log.info('The replacement was taken, reported and warned about')

            # ... and it has to still be there after a reboot
            c.sendline('reboot now')
            waitForLogin(c, log)
            loginVM(c, log)
            ifname_diagnostics(c, mapping_file)
            verify_ifname_has_mac(c, log, 'eth8', mac11)
            log.info('eth8 kept the replacement card across a reboot')

            # A radio has to be there before the naming pass, not after it, or
            # the rescan has nothing to find - which is why this went
            # unnoticed: the harness loads the module once the system is
            # already up. Last in the testcase on purpose, as the node it
            # checks for is committed on the next boot and a radio which
            # failed to come up would disturb the naming checks above.
            log.info('Making a radio present at boot')
            c.sendline('echo mac80211_hwsim | sudo tee '
                       '/etc/modules-load.d/vyos-hwsim.conf')
            c.expect(op_mode_prompt)
            c.sendline('reboot now')
            waitForLogin(c, log)
            loginVM(c, log)
            verify_radio_has_physical_device(c, log)
        else:
            log.info('Skipping NIC hot-plug tests - not supported on this machine type')


    elif args.raid:
        # Verify RAID subsystem - by deleting a disk and re-create the array
        # from scratch
        c.sendline('cat /proc/mdstat')
        c.expect(op_mode_prompt)

        shutdownVM(c, log, f'Shutdown VM and start with empty RAID member "{args.disk}"')

        if os.path.exists(args.disk):
            os.unlink(args.disk)

        gen_disk(args.disk)

        #################################################
        # Booting RAID-1 system with one missing disk
        #################################################
        log.info('Booting RAID-1 system')
        cmd = get_qemu_cmd(qemu_name, args.uefi, args.disk, raid=diskname_raid, vnc_enabled=args.vnc)

        # We need to swap boot indexes to boot from second harddisk so we can
        # recreate the RAID on the first disk
        cmd = cmd.replace('bootindex=1', 'bootindex=X')
        cmd = cmd.replace('bootindex=2', 'bootindex=1')
        cmd = cmd.replace('bootindex=X', 'bootindex=2')

        log.debug(f'Executing command: {cmd}')
        c = pexpect.spawn(cmd, logfile=stl)

        #################################################
        # Logging into VyOS system
        #################################################
        waitForLogin(c, log)
        loginVM(c, log)

        c.sendline('cat /proc/mdstat')
        c.expect(op_mode_prompt)

        # Re-partitioning a disk and adding it back to the array can take
        # significantly longer then the default pexpect timeout of 30 seconds
        raid_timeout = 300
        # Upper limit we wait for the array to be fully re-synced
        raid_sync_timeout = 900

        log.info('Re-format new RAID member')
        c.sendline('format by-id disk drive-hd1 like drive-hd2')
        c.sendline('yes')
        c.expect(op_mode_prompt, timeout=raid_timeout)

        log.info('Add member to RAID1 (md0)')
        c.sendline('add raid md0 by-id member drive-hd1-part3')
        c.expect(op_mode_prompt, timeout=raid_timeout)

        log.info('Now we need to wait for re-sync to complete')

        start_time = time.time()
        while True:
            c.sendline('cat /proc/mdstat')
            # Once both members are up and in sync, mdstat reports "[2/2] [UU]"
            index = c.expect([r'\[2/2\]\s+\[UU\]', op_mode_prompt],
                             timeout=raid_timeout)
            if index == 0:
                c.expect(op_mode_prompt, timeout=raid_timeout)
                log.info('RAID1 re-sync completed')
                break
            if (start_time + raid_sync_timeout) < time.time():
                raise Exception('Timeout waiting for RAID1 re-sync to complete')
            time.sleep(20)

        # Reboot system with new primary RAID1 disk
        shutdownVM(c, log, f'Shutdown VM and start from recovered RAID member "{args.disk}"')

        log.info('Booting RAID-1 system')
        cmd = get_qemu_cmd(qemu_name, args.uefi, args.disk, raid=diskname_raid, vnc_enabled=args.vnc)
        log.debug(f'Executing command: {cmd}')
        c = pexpect.spawn(cmd, logfile=stl)

        loginVM(c, log)

        c.sendline('cat /proc/mdstat')
        c.expect(op_mode_prompt)

    elif args.smoketest:
        # run default smoketest suite
        smoketests_path = '/usr/libexec/vyos/tests/smoke'
        if args.match:
            # Remove tests that we don't want to run
            match_str = '-o '.join([f'-name "test_*{name}*.py" ' for name in args.match.split("|")]).strip()
            c.sendline(f'sudo find {smoketests_path} -maxdepth 2 -type f -name test_* ! \( {match_str} \) -delete')
            c.expect(op_mode_prompt)
        if args.no_interfaces:
            # remove interface tests as they consume a lot of time
            c.sendline(f'sudo rm -f {smoketests_path}/cli/test_interfaces_*')
            c.expect(op_mode_prompt)
        if args.no_vpp:
            # remove VPP tests
            c.sendline(f'sudo rm -f {smoketests_path}/cli/test_vpp*')
            c.expect(op_mode_prompt)

        if args.vyconf:
            c.sendline('sudo /usr/libexec/vyos/set_vyconf_backend.py --no-prompt &> /dev/null')
            c.expect(op_mode_prompt)
            log.info('Smoketests will be run using vyconfd/vyos-commitd')

        log.info('Executing VyOS smoketests')
        c.sendline('ls /usr/bin/vyos-smoketest 2>/dev/null')
        c.expect('/usr/bin/vyos-smoketest')
        c.expect(op_mode_prompt)
        c.sendline('/usr/bin/vyos-smoketest')
        i = c.expect(['\n +Invalid command:', '\n +Set failed',
                      r'\n\S+@\S+[$#]'], timeout=test_timeout)

        if i == 0:
            raise Exception('Invalid command detected')
        if i == 1:
            raise Exception('Set syntax failed :/')

        c.sendline('echo EXITCODE:$\x16?')
        i = c.expect(['EXITCODE:0', 'EXITCODE:\d+'])
        if i == 0:
            log.info('Smoketest finished successfully!')
            pass
        elif i == 1:
            log.error('Smoketest failed :/')
            raise Exception("Smoketest-failed, please look into debug output")

    # else, run configtest suite
    elif args.configtest:
        # Remove config-tests that we don't want to run
        if args.match:
            configs_path = '/usr/libexec/vyos/tests/configs'
            if args.match.startswith("!"):
                # Exclude mode — delete only the matched names
                names = args.match[1:].split("|")
                match_str = '-o '.join([f'-name "{name}"' for name in names])
                cleanup_config_dir_cmd = f'sudo find {configs_path} -mindepth 1 -maxdepth 1 -type f \\( {match_str} \\) -exec rm -rf {{}} +'
                cleanup_config_tests_dir_cmd = f'sudo find {configs_path}/assert -mindepth 1 -maxdepth 1 -type f \\( {match_str} \\) -exec rm -rf {{}} +'
            else:
                # Include mode — keep only the matched names, delete the rest
                names = args.match.split("|")
                match_str = '-o '.join([f'-name "{name}"' for name in names])
                cleanup_config_dir_cmd = f'sudo find {configs_path} -mindepth 1 -maxdepth 1 -type f ! \\( {match_str} \\) -exec rm -rf {{}} +'
                cleanup_config_tests_dir_cmd = f'sudo find {configs_path}/assert -mindepth 1 -maxdepth 1 -type f ! \\( {match_str} \\) -exec rm -rf {{}} +'

            c.sendline(cleanup_config_dir_cmd)
            c.expect(op_mode_prompt)
            c.sendline(cleanup_config_tests_dir_cmd)
            c.expect(op_mode_prompt)


        log.info('Adding a legacy WireGuard default keypair for migrations')
        c.sendline('sudo mkdir -p /config/auth/wireguard/default')
        c.expect(op_mode_prompt)
        c.sendline('echo "aGx+fvW916Ej7QRnBbW3QMoldhNv1u95/WHz45zDmF0=" | sudo tee /config/auth/wireguard/default/private.key')
        c.expect(op_mode_prompt)
        c.sendline('echo "x39C77eavJNpvYbNzPSG3n1D68rHYei6q3AEBEyL1z8=" | sudo tee /config/auth/wireguard/default/public.key')
        c.expect(op_mode_prompt)

        log.info('Generating PKI objects')
        c.sendline('/usr/bin/vyos-configtest-pki')
        c.expect(op_mode_prompt, timeout=900)

        script_file = '/config/scripts/vyos-foo-update.script'
        c.sendline(f'echo "#!/bin/sh" > {script_file}; chmod 775 {script_file}')
        c.expect(op_mode_prompt)

        log.info('Executing load config tests')
        c.sendline('/usr/bin/vyos-configtest')
        i = c.expect(['\n +Invalid command:', 'No such file or directory',
                     r'\n\S+@\S+[$#]'], timeout=test_timeout)

        if i==0:
            raise Exception('Invalid command detected')
        elif i==1:
            tmp = 'VyOS smoketest not found!'
            log.error(tmp)
            raise Exception(tmp)

        c.sendline('echo EXITCODE:$\x16?')
        i = c.expect(['EXITCODE:0', 'EXITCODE:\d+'])
        if i == 0:
            log.info('Configtest finished successfully!')
            pass
        elif i == 1:
            tmp = 'Configtest failed :/ - check debug output'
            log.error(tmp)
            raise Exception(tmp)
    elif args.test_image_update:
        log.info(f'Nested installer ISO: mount second CD-ROM ({NESTED_INNER_ISO_NAME})')
        c.sendline(f'sudo mkdir -p {NESTED_HTTP_MOUNT_POINT}')
        c.expect(op_mode_prompt)

        # After drive-cd1 eject the first SCSI CD node is often an empty tray; real
        # media may appear on sr1+. Try every optical device until one mounts.
        c.sendline(
            f'for d in /dev/sr*; do sudo mount -o ro "$d" {NESTED_HTTP_MOUNT_POINT} 2>/dev/null '
            '&& echo NESTED_ISO_MOUNT_OK && break; done; '
            f'mountpoint -q {NESTED_HTTP_MOUNT_POINT} || echo NESTED_ISO_MOUNT_FAIL'
        )
        if c.expect(['NESTED_ISO_MOUNT_OK', 'NESTED_ISO_MOUNT_FAIL']) != 0:
            raise Exception('Failed to mount nested installer payload ISO (no usable /dev/sr* media)')
        c.expect(op_mode_prompt)

        _image_update_cli_sequence(c, log, NESTED_HTTP_IMAGE_NAME)
        _image_update_cli_sequence(c, log, f'{NESTED_HTTP_IMAGE_NAME}-{NESTED_HTTP_VRF_NAME}', NESTED_HTTP_VRF_ADDR, use_vrf=True)

        log.info('Unmount nested installer ISO')
        c.sendline(f'sudo umount {NESTED_HTTP_MOUNT_POINT}')
        c.expect(op_mode_prompt)
        log.info('Nested installer ISO testcase complete')
    elif args.secure_boot_test:
        c.sendline('show secure-boot')
        c.expect('SecureBoot enabled')
        c.expect(op_mode_prompt)

        c.sendline('show secure-boot detail')
        if sb_custom_ca:
            c.expect('Issuer: ')
        else:
            log.info('Verify Linux Kernel is signed by the VyOS Secure Boot CA')
            c.expect(re.escape(f'Issuer:  {SB_VYOS_ISSUER}'))
            c.expect(re.escape(f'Subject: {SB_VYOS_SUBJECT}'))
        c.expect(op_mode_prompt)
    else:
        log.info('No testcase selected!')

    shutdownVM(c, log, 'Powering off system')
    c.close()

except EarlyExit:
    pass

except pexpect.exceptions.TIMEOUT:
    log.error('Timeout waiting for VyOS system')
    log.error(traceback.format_exc())
    EXCEPTION = 1

except pexpect.exceptions.ExceptionPexpect:
    log.error('Exception while executing QEMU')
    log.error('Is qemu working on this system?')
    log.error(traceback.format_exc())
    EXCEPTION = 1

except Exception:
    log.error('Unknown error occurred!')
    traceback.print_exc()
    EXCEPTION = 1

#################################################
# Cleaning up
#################################################
log.info("Cleaning up")

if tpm_process:
    tpm_process.terminate()
    tpm_process.join()

if args.test_image_update:
    try:
        if os.path.isdir(NESTED_ISO_DATA_DIR):
            shutil.rmtree(NESTED_ISO_DATA_DIR)
        if nested_payload_iso_path and os.path.isfile(nested_payload_iso_path) \
                and not args.keep:
            os.remove(nested_payload_iso_path)
    except OSError:
        log.warning('Could not remove nested installer ISO artefacts', exc_info=True)

if not args.keep:
    log.info(f'Removing disk file: {args.disk}')
    try:
        os.remove(args.disk)
        if diskname_raid:
            os.remove(diskname_raid)
        if args.secure_boot_test:
            os.remove(OVMF_VARS_TMP)
    except Exception:
        log.error('Exception while removing diskimage!')
        log.error(traceback.format_exc())
        EXCEPTION = 1

if EXCEPTION:
    log.error('Hmm... system got an exception while processing.')
    log.error('The ISO image is not considered usable!')
    sys.exit(1)

sys.exit(0)