File: adt_testbed.py

package info (click to toggle)
autopkgtest 5.55
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,600 kB
  • sloc: python: 15,479; sh: 2,317; makefile: 116; perl: 19
file content (2542 lines) | stat: -rw-r--r-- 97,997 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
# adt_testbed.py is part of autopkgtest
# autopkgtest is a tool for testing Debian binary packages
#
# autopkgtest is Copyright (C) 2006-2015 Canonical Ltd.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# 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, write to the Free Software
# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
#
# See the file CREDITS for a full list of credits information (often
# installed as /usr/share/doc/autopkgtest/CREDITS).

import os
import sys
import errno
import json
import time
import traceback
import re
import shlex
import signal
import subprocess
import tempfile
import textwrap
import shutil
from string import Template
import urllib.parse
import urllib.request
from typing import (
    List,
    Optional,
    Set,
    Tuple,
)

from debian.debian_support import Version
from debian.deb822 import Deb822

import adtlog
import VirtSubproc
from VirtSubproc import load_shell_script
from testdesc import Unsupported


timeouts = {"short": 100, "copy": 300, "install": 3000, "test": 10000, "build": 100000}
global_timeout = 0


# When running installed, this is /usr/share/autopkgtest.
# When running uninstalled, this is the source tree.
# Either way, it has a setup-commands subdirectory.
PKGDATADIR = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))


class Testbed:
    SOURCELIST_PATTERN = re.compile(
        r"(?P<type>deb|deb-src)\s+"
        + r"(?:(?P<options>\[[^]]+\])\s+)?"
        + r"(?P<uri>[^\s]+)\s+"
        + r"(?P<suite>[^\s]+)\s+"
        + r"(?P<components>.+)$"
    )

    # sample pattern: ppa:user:token@owner/name:fingerprint
    PPA_PATTERN = re.compile(
        # maybe match literal ppa: at the beginning of string, case insensitive
        r"^(?i:ppa:)?"
        # maybe match user:token for private PPA authentication;
        # for the token accept all the RFC 3986 unreserved characters
        r"((?P<user>[a-z0-9](-?[a-z0-9])+):(?P<token>[a-zA-Z0-9._~-]+)@)?"
        # match PPA owner, following most Launchpad rules for usernames
        r"(?P<owner>[a-z0-9](-?[a-z0-9])+)"
        # match PPA name, following most Launchpad rules for PPA names
        r"/(?P<name>[a-z0-9][a-zA-Z0-9.+-]*)"
        # maybe match fingerprint, discarding leading 0x if present, case insensitive
        r"(?i::(0x)?(?P<fingerprint>[0-9a-f]{40}))?$"
    )

    def __init__(
        self,
        *,
        vserver_argv: List[str],
        output_dir: str,
        test_arch: Optional[str] = None,
        user: str,
        setup_commands: List[str],
        setup_commands_boot: List[str],
        add_apt_pockets: List[str],
        copy_files: List[str],
        pin_packages: List[str],
        add_apt_sources: List[str],
        add_apt_releases: List[str],
        apt_default_release: Optional[str] = None,
        apt_upgrade: bool = False,
        enable_apt_fallback: bool = True,
        shell_fail: bool = False,
        needs_internet: str = "run",
        insecure: bool = False,
    ) -> None:
        self.sp = None
        self.lastsend = None
        self.scratch = None
        self.modified = False
        self._need_reset_apt = False
        self.stop_sent = False
        self.dpkg_arch = None
        self.test_arch = test_arch
        self.exec_cmd = None
        self.output_dir = output_dir
        self.shared_downtmp = None  # testbed's downtmp on the host, if supported
        self.vserver_argv = vserver_argv
        self.user = user
        self.setup_commands = setup_commands
        self.setup_commands_boot = setup_commands_boot
        self.add_apt_pockets = add_apt_pockets
        self.add_apt_sources = add_apt_sources
        self.add_apt_releases = add_apt_releases
        self.pin_packages = pin_packages
        self.default_release = apt_default_release
        self.apt_upgrade = apt_upgrade
        self.copy_files = copy_files
        self.initial_kernel_version = None
        self.insecure = insecure
        # tests might install a different kernel; [(testname, reboot_marker, kver)]
        self.test_kernel_versions: List[Tuple[str, str, str]] = []
        # used for tracking kernel version changes
        self.last_test_name = ""
        self.last_reboot_marker = ""
        self.eatmydata_prefix = None
        self.apt_pin_for_releases: List[str] = []
        self.enable_apt_fallback = enable_apt_fallback
        self.apt_version: Optional[Version] = None
        self.release: Optional[str] = None
        self.needs_internet = needs_internet
        self.shell_fail = shell_fail
        self.nproc = None
        self.cpu_model = None
        self.cpu_flags = None
        self._created_user = False
        self._tried_debug = False
        # False if not tried, True if successful, error message if not
        self._tried_provide_sudo = False
        # used for keeping track of the global timeout, if any
        self.start_time = int(time.time())
        self.skip_remaining_tests = False
        # Absolute path to wrapper.sh on testbed
        self.wrapper_sh = ""

        adtlog.debug("testbed init")

    @property
    def su_user(self):
        return self.user or "root"

    def start(self):
        # log date at least once; to ease finding it
        adtlog.info("starting date and time: %s" % time.strftime("%Y-%m-%d %H:%M:%S%z"))

        # are we running from a checkout?
        root_dir = PKGDATADIR
        if os.path.exists(os.path.join(root_dir, ".git")):
            try:
                head = subprocess.check_output(
                    ["git", "show", "--no-patch", "--oneline"], cwd=root_dir
                )
                head = head.decode("UTF-8").strip()
            except Exception as e:
                adtlog.debug(str(e))
                head = "cannot determine current HEAD"
            adtlog.info("git checkout: %s" % head)
        else:
            adtlog.info("version @version@")

        # log command line invocation for the log
        adtlog.info(
            "host %s; command line: %s"
            % (os.uname()[1], " ".join([shlex.quote(w) for w in sys.argv]))
        )

        self.sp = subprocess.Popen(
            self.vserver_argv,
            stdin=subprocess.PIPE,
            stdout=subprocess.PIPE,
            universal_newlines=True,
        )
        self.expect("ok", 0)

    def stop(self):
        adtlog.debug("testbed stop")
        if self.stop_sent:
            # avoid endless loop
            return
        self.stop_sent = True

        self.close()
        if self.sp is None:
            return
        ec = self.sp.returncode
        if ec is None:
            self.sp.stdout.close()
            self.send("quit")
            self.sp.stdin.close()
            ec = self.sp.wait()
        if ec:
            self.debug_fail()
            self.bomb("testbed gave exit status %d after quit" % ec)
        self.sp = None

    def open(self):
        adtlog.debug("testbed open, scratch=%s" % self.scratch)
        if self.scratch is not None:
            return
        pl = self.command("open", (), 1)
        self._opened(pl)

    def post_boot_setup(self):
        """Setup after (re)booting the test bed"""

        # provide autopkgtest-reboot command, if reboot is supported; /run is
        # usually "noexec" and /[s]bin might be readonly, so create in /tmp
        if "reboot" in self.caps and "root-on-testbed" in self.caps:
            adtlog.debug("testbed supports reboot, creating /tmp/autopkgtest-reboot")
            reboot = TestbedPath(
                self,
                os.path.join(PKGDATADIR, "lib", "in-testbed", "reboot.sh"),
                "%s/autopkgtest-reboot" % self.scratch,
                False,
            )
            reboot.copydown(mode="0755")
            # TODO: Because we're now creating a symlink, it would be OK
            # to put the symlink in /run again, even though it's noexec,
            # because the actual content is elsewhere
            self.check_exec(
                ["ln", "-fns", reboot.tb, "/tmp/autopkgtest-reboot"],
            )
            # Intentionally not check_exec, and intentionally silencing stderr:
            # /[s]bin might be read-only.
            self.execute(
                ["ln", "-fns", reboot.tb, "/sbin/autopkgtest-reboot"],
                stderr=subprocess.PIPE,
            )

            reboot_prepare = TestbedPath(
                self,
                os.path.join(PKGDATADIR, "lib", "in-testbed", "reboot-prepare.sh"),
                "%s/autopkgtest-reboot-prepare" % self.scratch,
                False,
            )
            reboot_prepare.copydown(mode="0755")
            self.check_exec(
                [
                    "ln",
                    "-fns",
                    reboot_prepare.tb,
                    "/tmp/autopkgtest-reboot-prepare",
                ],
            )

        # record running kernel version
        kver = self.check_exec(["uname", "-srv"], True).strip()
        if not self.initial_kernel_version:
            assert not self.last_test_name
            self.initial_kernel_version = kver
            adtlog.info("testbed running kernel: " + self.initial_kernel_version)
        else:
            if kver != self.initial_kernel_version:
                self.test_kernel_versions.append(
                    (self.last_test_name, self.last_reboot_marker, kver)
                )
                adtlog.info(
                    "testbed running kernel changed: %s (current test: %s%s)"
                    % (
                        kver,
                        self.last_test_name,
                        self.last_reboot_marker
                        and (", last reboot marker: " + self.last_reboot_marker)
                        or "",
                    )
                )

        # get CPU info
        if self.nproc is None:
            cpu_info = self.check_exec(
                ["sh", "-c", "nproc; cat /proc/cpuinfo 2>/dev/null || true"],
                stdout=True,
            ).strip()
            self.nproc = cpu_info.split("\n", 1)[0]
            m = re.search(
                r"^(model.*name|cpu)\s*:\s*(.*)$",
                cpu_info,
                re.MULTILINE | re.IGNORECASE,
            )
            if m:
                self.cpu_model = m.group(2)
            m = re.search(
                r"^(flags|features)\s*:\s*(.*)$", cpu_info, re.MULTILINE | re.IGNORECASE
            )
            if m:
                self.cpu_flags = m.group(2)

        xenv = ["AUTOPKGTEST_IS_SETUP_BOOT_COMMAND=1"]
        if self.user:
            xenv.append("AUTOPKGTEST_NORMAL_USER=" + self.user)
            xenv.append("ADT_NORMAL_USER=" + self.user)

        for c in self.setup_commands_boot:
            rc = self.execute(["sh", "-ec", c], xenv=xenv, kind="install")[0]
            if rc:
                # setup scripts should exit with 100 if it's the package's
                # fault, otherwise it's considered a transient testbed failure
                if self.shell_fail:
                    self.run_shell()
                if rc == 100:
                    self.badpkg("testbed boot setup commands failed with status 100")
                else:
                    self.bomb("testbed boot setup commands failed with status %i" % rc)

    def _opened(self, pl):
        self._tried_provide_sudo = False
        self.scratch = pl[0]
        self.deps_installed = []
        self.apt_pin_for_releases = []
        self.exec_cmd = list(
            map(
                urllib.parse.unquote,
                self.command("print-execute-command", (), 1)[0].split(","),
            )
        )
        self.caps = self.command("capabilities", (), None)
        if self.needs_internet in ["try", "run"]:
            self.caps.append("has_internet")
        adtlog.debug("testbed capabilities: %s" % self.caps)
        for c in self.caps:
            if c.startswith("downtmp-host="):
                self.shared_downtmp = c.split("=", 1)[1]

        wrapper_sh = TestbedPath(
            self,
            os.path.join(PKGDATADIR, "lib", "in-testbed", "wrapper.sh"),
            "%s/wrapper.sh" % self.scratch,
            False,
        )
        wrapper_sh.copydown(mode="0755")
        self.wrapper_sh = wrapper_sh.tb

        # provide a default for --user
        if self.user is None and "root-on-testbed" in self.caps:
            self.user = ""
            for c in self.caps:
                if c.startswith("suggested-normal-user="):
                    self.user = c.split("=", 1)[1]

            if "revert-full-system" in self.caps and not self.user:
                with open(
                    os.path.join(PKGDATADIR, "setup-commands", "create-normal-user"),
                    encoding="UTF-8",
                ) as reader:
                    self.check_exec(["sh", "-euc", reader.read()])
                    self._created_user = True
                    self.user = self.check_exec(
                        ["cat", "/run/autopkgtest-normal-user"],
                        stdout=True,
                    ).strip()
        elif self._created_user:
            # Re-create the same user after reset. We only do this if
            # we created it before the reset, in which case the capabilities
            # should be the same as above and the same username should still
            # be available.
            assert "revert-full-system" in self.caps, self.caps
            assert "root-on-testbed" in self.caps, self.caps
            with open(
                os.path.join(PKGDATADIR, "setup-commands", "create-normal-user"),
                encoding="UTF-8",
            ) as reader:
                self.check_exec(["sh", "-euc", reader.read(), "sh", self.user])

        if (
            self.su_user is not None
            and self.su_user != "root"
            and not any(
                c in ["isolation-machine", "isolation-container"] for c in self.caps
            )
        ):
            # scratch directory is owned by root and not world-writeable.
            # (See the rules in README.virtualisation-server.)
            #
            # But, we like to run things (particularly, tests) as a normal user.
            # That normal user needs to be able to write to this directory.
            #
            # Once upon a time, this was possible because the scratch directory was 1777.
            # Nowadays, we make it possible by making it owned by the normal user.
            #
            # This means that we make root on the testbed completely trust self.user.
            # This is OK because either:
            #   self.user came from the testbed capability suggested-normal-user=
            #   self.user came from the --user command line option
            # and in both cases this trust relationship is documented there.
            self.check_exec(["chown", self.su_user, "--", self.scratch])

        # determine testbed architecture
        self.dpkg_arch = self.check_exec(["dpkg", "--print-architecture"], True).strip()
        adtlog.info("testbed dpkg architecture: " + self.dpkg_arch)

        # the test architecture defaults to the dpkg architecture
        if not self.test_arch:
            self.test_arch = self.dpkg_arch

        self.test_arch_is_foreign = self.test_arch != self.dpkg_arch

        out = self.check_exec(
            ["dpkg-query", "-W", "-f", "${Version}", "apt"], True
        ).strip()
        adtlog.info("testbed apt version: " + out)
        try:
            self.apt_version = Version(out)
        except ValueError:
            self.bomb("can't determine the apt version on the testbed")

        # Foreign arch testing requires `apt-get satisfy`.
        if self.test_arch_is_foreign and self.apt_version < Version("1.9.0"):
            self.bomb(
                "foreign arch testing requires apt >= 1.9.0 on the testbed",
                adtlog.AutopkgtestError,
            )

        # Add foreign test architecture
        if self.test_arch_is_foreign:
            self.check_exec(["dpkg", "--add-architecture", self.test_arch])

        # do we have eatmydata?
        (code, out, err) = self.execute(
            ["sh", "-ec", "command -v eatmydata"],
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
        )
        if code == 0:
            adtlog.debug("testbed has eatmydata")
            self.eatmydata_prefix = out.strip()

        # ensure that /etc/apt/preferences.d exists
        self.check_exec(["mkdir", "-p", "/etc/apt/preferences.d"])

        self.run_setup_commands()

        # record package versions of pristine testbed
        if self.output_dir:
            pkglist = TempPath(self, "testbed-packages", autoclean=False)
            self.check_exec(
                [
                    "sh",
                    "-ec",
                    "dpkg-query --show -f '${Package}\\t${Version}\\n' > %s"
                    % pkglist.tb,
                ]
            )
            pkglist.copyup()

        self.post_boot_setup()

    def close(self):
        adtlog.debug("testbed close, scratch=%s" % self.scratch)
        if self.scratch is None:
            return
        self.scratch = None
        if self.sp is None:
            return
        self.command("close")
        self.shared_downtmp = None

    def reboot(self, prepare_only=False):
        """Reboot the testbed"""

        self.command("reboot", prepare_only and ("prepare-only",) or ())
        self.post_boot_setup()

    def run_setup_commands(self):
        """Run --setup-commmands and --copy"""

        adtlog.info("@@@@@@@@@@@@@@@@@@@@ test bed setup")
        for host, tb in self.copy_files:
            adtlog.debug("Copying file %s to testbed %s" % (host, tb))
            TestbedPath(self, host, tb, os.path.isdir(host)).copydown()

        # Pin the default release if explicitly requested.
        if self.default_release:
            self._set_default_release()

        if (
            self.apt_upgrade
            or self.add_apt_sources
            or self.add_apt_pockets
            or self.add_apt_releases
        ):
            # Update APT package index. We can't run this unconditionally because
            # we want to support not-root-on-testned and offline use cases.
            adtlog.info("updating testbed package index (apt update)")
            try:
                self._run_apt_command(action="update")
            except adtlog.AptError:
                self.bomb("failed testbed apt update")

        # Assume the testbed release to be the one that provides the candidate
        # base-files version. This requires the package index to be up-to-date.
        _, _, self.release = self.get_candidate("base-files")
        if self.release:
            adtlog.info(f"testbed release detected to be: {self.release}")
        else:
            adtlog.info(
                "could not determine the testbed release (no APT source for base-files?)"
            )
        if not self.release and (
            self.add_apt_releases
            or self.add_apt_pockets
            or any(self.PPA_PATTERN.match(s) for s in self.add_apt_sources)
        ):
            self.bomb(
                "testbed release required to be known for autopkgtest to run",
                adtlog.AutopkgtestError,
            )

        pin_packages = self.pin_packages.copy()
        add_apt_releases = self.add_apt_releases.copy()
        for pocket in self.add_apt_pockets:
            pocket = pocket.strip()
            if not pocket:
                continue
            (pocket, _, pkglist) = pocket.partition("=")
            pocket_suite = self.release + "-" + pocket

            add_apt_releases.append(pocket_suite)

            if pkglist:
                # create apt pinning for --apt-pocket=pocket=packages
                pin_packages.append(f"{pocket_suite}={pkglist}")

        # clean list and remove duplicates
        add_apt_releases = [r.strip() for r in add_apt_releases]
        add_apt_releases = [r for r in add_apt_releases if r]
        add_apt_releases = list(dict.fromkeys(add_apt_releases))
        # add releases
        for release in add_apt_releases:
            self._add_apt_release_one_line_style(release)
            self._add_apt_release_deb822(release)

            # Set baseline "general form" pin to neutralize NotAutomatic: yes.
            self._set_baseline_pin_priority_for_release(release)

        # To be done after adding add_apt_releases, so that adding releases/pocket
        # is only done based on sources the image came configured with (LP: #2091393).
        for source in self.add_apt_sources:
            if self.SOURCELIST_PATTERN.match(source):
                self._add_apt_source(
                    source, filename="autopkgtest-add-apt-sources.list"
                )
            elif self.PPA_PATTERN.match(source):
                self._add_apt_ppa(source)
            elif (
                os.path.isfile(source)
                and os.access(source, os.R_OK)
                and (source.endswith(".list") or source.endswith(".sources"))
            ):
                with open(source, "r") as s:
                    self._add_apt_source(
                        s.read(),
                        filename=os.path.basename(source),
                    )
            else:
                self.bomb(f"invalid apt source: {source}", adtlog.AutopkgtestError)

        # apt-get update, to be done after adding sources, releases, pockets,
        # but before setting up pinning for apt (<< 1.9.11) compatibility, as
        # it requires src:package expansion via apt-cache dumpavail.
        if self.apt_upgrade or self.add_apt_sources or add_apt_releases:
            adtlog.info("updating testbed package index (apt update)")
            try:
                self._run_apt_command(action="update")
            except adtlog.AptError:
                self.bomb("failed testbed apt update")

        # remove duplicates
        pin_packages = list(dict.fromkeys(pin_packages))
        # create apt pinning for --pin-packages and --apt-pocket, to be done
        # after updating the index (apt-get update) to allow expansion of
        # src:package pins via apt-cache dumpavail.
        for package_set in pin_packages:
            (release, pkglist) = package_set.split("=", 1)
            self._create_apt_pinning_for_packages(release, pkglist)

        # record the mtimes of dirs affecting the boot
        boot_dirs = " ".join(
            [
                "/boot",
                "/boot/efi",
                "/boot/grub",
                "/etc/init",
                "/etc/init.d",
                "/etc/systemd/system",
                "/lib/systemd/system",
            ]
        )
        self.check_exec(
            [
                "bash",
                "-ec",
                r"for d in %s; do [ ! -d $d ] || touch -r $d %s/${d//\//_}.stamp; done"
                % (boot_dirs, self.scratch),
            ]
        )

        xenv = ["AUTOPKGTEST_IS_SETUP_COMMAND=1"]
        if self.user:
            xenv.append("AUTOPKGTEST_NORMAL_USER=" + self.user)
            xenv.append("ADT_NORMAL_USER=" + self.user)

        for c in self.setup_commands:
            rc = self.execute(["sh", "-ec", c], xenv=xenv, kind="install")[0]
            if rc:
                # setup scripts should exit with 100 if it's the package's
                # fault, otherwise it's considered a transient testbed failure
                if self.shell_fail:
                    self.run_shell()
                if rc == 100:
                    self.badpkg("testbed setup commands failed with status 100")
                else:
                    self.bomb("testbed setup commands failed with status %i" % rc)

        if self.apt_upgrade:
            adtlog.info("upgrading testbed (apt dist-upgrade and autopurge)")
            try:
                self._run_apt_command(action="dist-upgrade")
                self._run_apt_command(action="autoremove", extra_opts=["--purge"])
            except adtlog.AptError:
                # If apt fails at this stage always consider it a testbed failure,
                # so bomb() on all AptError exceptions, including AptPermanentFailure.
                self.bomb("failed testbed apt dist-upgrade or autopurge")

        # if the setup commands affected the boot, then reboot
        if self.setup_commands and "reboot" in self.caps:
            boot_affected = self.execute(
                [
                    "bash",
                    "-ec",
                    r"[ ! -e /run/autopkgtest_no_reboot.stamp ] || exit 0;"
                    r"for d in %s; do s=%s/${d//\//_}.stamp;"
                    r"  [ ! -d $d ] || [ `stat -c %%Y $d` = `stat -c %%Y $s` ]; done"
                    % (boot_dirs, self.scratch),
                ]
            )[0]
            if boot_affected:
                adtlog.info("rebooting testbed after setup commands that affected boot")
                self.reboot()

    def reset(self, deps_new):
        """Reset the testbed, if possible and necessary"""

        adtlog.debug(
            "testbed reset: modified=%s, deps_installed=%s, deps_new=%s"
            % (self.modified, self.deps_installed, deps_new)
        )
        if "revert" in self.caps and (
            self.modified or [d for d in self.deps_installed if d not in deps_new]
        ):
            adtlog.debug("testbed reset")
            pl = self.command("revert", (), 1)
            self._opened(pl)
        self.modified = False

    def install_deps(
        self,
        deps_new: List[List[str]],
        shell_on_failure: bool = False,
        package_under_test_deps: Optional[List[List[str]]] = None,
    ) -> None:
        """
        Install test dependencies into testbed.
        """

        adtlog.debug("install_deps: deps_new=%s" % deps_new)

        self.deps_installed = deps_new
        if not deps_new:
            return

        self.satisfy_dependencies_string(
            ", ".join([" | ".join(altgroup) for altgroup in deps_new]),
            "install-deps",
            shell_on_failure=shell_on_failure,
            package_under_test_deps=package_under_test_deps,
        )

    def _provide_sudo(self) -> str:
        """
        Enable the needs-sudo restriction, or return why we can't.
        """

        if "root-on-testbed" in self.caps and not self.user:
            return "Cannot enable needs-sudo restriction: no ordinary user available"

        # This is intentionally similar to how run_test() runs it, to make
        # sure that we can sudo here if and only if we could sudo in the test.
        if "root-on-testbed" in self.caps:
            run_as_user = ["su", "-s", "/bin/bash", self.user, "-c"]
        else:
            run_as_user = ["bash", "-c"]

        # First check whether the test user is in the sudo group
        rc, out, err = self.execute(
            run_as_user + ["id -Gn"],
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
        )

        if rc == 0 and "sudo" in out.split():
            adtlog.debug(
                'User "%s" groups include sudo (%s)' % (self.user, out.strip())
            )
            # Also check whether they need a password (by default yes,
            # but in e.g. Ubuntu cloud images they don't)
            rc, out, err = self.execute(
                run_as_user + ["sudo -n true"],
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE,
            )
            adtlog.debug("sudo -n true stdout: %s" % out.strip())
            adtlog.debug("sudo -n true stderr: %s" % err.strip())
            adtlog.debug("sudo -n true status: %d" % rc)
            already_has_sudo = rc == 0
        else:
            adtlog.debug("id -Gn stdout: %s" % out.strip())
            adtlog.debug("id -Gn stderr: %s" % err.strip())
            adtlog.debug("id -Gn status: %d" % rc)
            already_has_sudo = False

        if already_has_sudo:
            adtlog.debug('User "%s" can already sudo without password' % self.user)
            return ""

        if "root-on-testbed" not in self.caps:
            return "Cannot enable needs-sudo restriction: not root"

        if "revert-full-system" not in self.caps:
            return "Cannot enable needs-sudo restriction: cannot revert"

        self.needs_reset()
        adtlog.info('Setting up user "%s" to sudo without password...' % self.user)

        with open(os.path.join(PKGDATADIR, "setup-commands", "enable-sudo")) as reader:
            script = reader.read()

        rc, _, _ = self.execute(
            ["sh", "-euc", script, "enable-sudo", self.user],
        )

        if rc != 0:
            return ("Failed to enable needs-sudo restriction: exit status %d") % rc

        return ""

    def satisfy_restrictions(
        self,
        name: str,
        restrictions: Set[str],
    ) -> None:
        """
        Try to satisfy restrictions that can be set up dynamically.
        Raise Unsupported if unable to do so.
        """

        if "needs-sudo" in restrictions:
            if not self._tried_provide_sudo:
                no_sudo_reason = self._provide_sudo()
                if no_sudo_reason:
                    raise Unsupported(name, no_sudo_reason)
                else:
                    self._tried_provide_sudo = True

    def needs_reset(self):
        # show what caused a reset
        (fname, lineno, function, code) = traceback.extract_stack(limit=2)[0]
        adtlog.debug(
            "needs_reset, previously=%s, requested by %s() line %i"
            % (self.modified, function, lineno)
        )
        self.modified = True

    def bomb(self, m, _type=adtlog.TestbedFailure):
        adtlog.debug("%s %s" % (_type.__name__, m))
        self.stop()
        raise _type(m)

    def badpkg(self, m):
        _type = adtlog.BadPackageError
        adtlog.debug("%s %s" % (_type.__name__, m))
        raise _type(m)

    def debug_fail(self):
        # Avoid recursion, and also avoid repeating ourselves if cleanup
        # fails after we already tried to debug a failure
        if self._tried_debug:
            return

        self._tried_debug = True

        # Many reasons for failure will make auxverb_debug_fail also fail.
        # Ignore that, to preserve the original exception
        try:
            self.command("auxverb_debug_fail")
        except Exception as e:
            adtlog.debug("auxverb_debug_fail failed: %s" % e)

    def send(self, string):
        try:
            adtlog.debug("sending command to virtualisation server: " + string)
            self.sp.stdin.write(string)
            self.sp.stdin.write("\n")
            self.sp.stdin.flush()
            self.lastsend = string
        except Exception as e:
            self.debug_fail()
            self.bomb("cannot send to virtualisation server: %s" % e)

    def expect(self, keyword, nresults):
        line = self.sp.stdout.readline()
        if not line:
            self.debug_fail()
            self.bomb("eof from the virtualisation server")
        if not line.endswith("\n"):
            self.bomb("unterminated line from the virtualisation server")
        line = line.rstrip("\n")
        adtlog.debug("got reply from testbed: " + line)
        ll = line.split()
        if not ll:
            self.bomb("unexpected whitespace-only line from the virtualisation server")
        if ll[0] != keyword:
            self.debug_fail()

            if self.lastsend is None:
                self.bomb("got banner `%s', expected `%s...'" % (line, keyword))
            else:
                self.bomb(
                    "sent `%s', got `%s', expected `%s...'"
                    % (self.lastsend, line, keyword)
                )
        ll = ll[1:]
        if nresults is not None and len(ll) != nresults:
            self.bomb(
                "sent `%s', got `%s' (%d result parameters),"
                " expected %d result parameters"
                % (self.lastsend, line, len(ll), nresults)
            )
        return ll

    def command(self, cmd, args=(), nresults=0, unquote=True):
        # pass args=[None,...] or =(None,...) to avoid more url quoting
        if type(cmd) is str:
            cmd = [cmd]
        if len(args) and args[0] is None:
            args = args[1:]
        else:
            args = list(map(urllib.parse.quote, args))
        al = cmd + args
        self.send(" ".join(al))
        ll = self.expect("ok", nresults)
        if unquote:
            ll = list(map(urllib.parse.unquote, ll))
        return ll

    def execute(self, argv, xenv=[], stdout=None, stderr=None, kind="short"):
        """Run command in testbed.

        The commands stdout/err will be piped directly to autopkgtest and its log
        files, unless redirection happens with the stdout/stderr arguments
        (passed to Popen).

        Return (exit code, stdout, stderr). stdout/err will be None when output
        is not redirected.
        """

        adtlog.debug(
            "testbed command %s, kind %s, sout %s, serr %s, env %s"
            % (argv, kind, stdout and "pipe" or "raw", stderr and "pipe" or "raw", xenv)
        )

        if xenv:
            argv = ["env"] + xenv + argv

        abort_after_timeout = False
        timeout = timeouts[kind]
        timeout_type = "timed out"
        if kind in ["test", "build"] and global_timeout > 0:
            remaining_time = self.start_time + global_timeout - int(time.time())
            if remaining_time <= 0:
                adtlog.error("global timeout reached even before %s" % " ".join(argv))
                raise VirtSubproc.Timeout(global_timeout, abort=True)
            if timeout > remaining_time:
                timeout = remaining_time
                timeout_type = "global timeout reached"
                abort_after_timeout = True

        VirtSubproc.timeout_start(timeout)
        try:
            proc = subprocess.Popen(
                self.exec_cmd + argv,
                stdin=subprocess.DEVNULL,
                stdout=stdout,
                stderr=stderr,
            )
            (out, err) = proc.communicate()
            if out is not None:
                out = out.decode()
            if err is not None:
                err = err.decode()
            VirtSubproc.timeout_stop()
        except VirtSubproc.Timeout as exc:
            # This is a bit of a hack, but what can we do.. we can't kill/clean
            # up sudo processes, we can only hope that they clean up themselves
            # after we stop the testbed
            killtree(proc.pid)
            adtlog.debug(
                "%s on %s %s (kind: %s)" % (timeout_type, self.exec_cmd, argv, kind)
            )
            if "sudo" not in self.exec_cmd:
                try:
                    proc.wait(timeout=10)
                except subprocess.TimeoutExpired:
                    killtree(proc.pid, signal.SIGKILL)
                    proc.wait()
            msg = '%s on command "%s" (kind: %s)' % (timeout_type, " ".join(argv), kind)
            if kind == "test":
                adtlog.error(msg)
                exc.abort = abort_after_timeout
                raise exc
            else:
                self.debug_fail()
                self.bomb(msg)

        adtlog.debug("testbed command exited with code %i" % proc.returncode)

        if proc.returncode in (254, 255):
            self.debug_fail()
            self.bomb("testbed auxverb failed with exit code %i" % proc.returncode)

        return (proc.returncode, out, err)

    def check_exec(self, argv, stdout=False, kind="short", xenv=[]):
        """Run argv in testbed.

        If stdout is True, capture stdout and return it. Otherwise, don't
        redirect and return None.

        argv must succeed and not print any stderr.
        """
        (code, out, err) = self.execute(
            argv,
            stdout=(stdout and subprocess.PIPE or None),
            stderr=subprocess.PIPE,
            kind=kind,
            xenv=xenv,
        )
        if err:
            self.bomb(
                '"%s" failed with stderr "%s"' % (" ".join(argv), err),
                adtlog.AutopkgtestError,
            )
        if code != 0:
            self.bomb(
                '"%s" failed with status %i' % (" ".join(argv), code),
                adtlog.AutopkgtestError,
            )
        return out

    def is_real_package_installed(self, package):
        """Check if a non-virtual package is installed in the testbed"""
        (rc, out, err) = self.execute(
            ["dpkg-query", "--show", "-f", "${Status}", package],
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
        )
        if rc != 0:
            if "no packages found" in err:
                return False
            self.badpkg("Failed to run dpkg-query: %s (exit code %d)" % (err, rc))
        if out == "install ok installed":
            return True
        return False

    def is_virtual_package_installed(self, package):
        """Check if a package is installed in the testbed"""
        (rc, out, err) = self.execute(
            ["dpkg-query", "--show", "-f", "${Status} ${Provides}\n", "*"],
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
        )
        if rc != 0:
            self.badpkg("Failed to run dpkg-query: %s (exit code %d)" % (err, rc))
            return False
        if not out:
            return False
        for line in out.splitlines():
            prefix = "install ok installed "
            if not line.startswith(prefix):
                continue
            line = line[len(prefix) :]
            for p in line.split(","):
                (p, _, _) = p.lstrip().partition(" ")  # ' foo (== 1.0)' => 'foo'
                if p == package:
                    return True
        return False

    def _run_apt_command(
        self,
        *,
        action: str,
        what: List[str] = [],
        extra_opts: List[str] = [],
        xenv: List[str] = [],
    ) -> None:
        """Call apt-get with an action (update, install, satisfy, ...) with
        options suitable for installing test dependencies."""

        env = xenv.copy()
        env.append("DEBIAN_FRONTEND=noninteractive")
        env.append("APT_LISTBUGS_FRONTEND=none")
        env.append("APT_LISTCHANGES_FRONTEND=none")

        cmd = []
        if self.eatmydata_prefix:
            cmd.append(self.eatmydata_prefix)
        cmd += [
            "apt-get",
            "--quiet",
            "--assume-yes",
            "-o=APT::Status-Fd=3",
            "-o=APT::Install-Recommends=false",
            f"-o=DPkg::Lock::Timeout={timeouts['copy']}",
            "-o=Dpkg::Options::=--force-confnew",
            "-o=Debug::pkgProblemResolver=true",
        ]
        cmd += extra_opts
        cmd.append(action)
        cmd += what

        # capture status-fd via stderr
        cmd = ["/bin/sh", "-ec", '"$@" 3>&2 2>&1', "run_apt_command"] + cmd

        (rc, _, serr) = self.execute(
            cmd,
            kind="install",
            stderr=subprocess.PIPE,
            xenv=env,
        )
        if rc != 0:
            adtlog.debug("apt-get %s failed; status-fd:\n%s" % (action, serr))
            # check if apt failed during package download, which might be a
            # transient error, so we likely want a "testbed failure".
            if "dlstatus:" in serr and "pmstatus:" not in serr:
                raise adtlog.AptDownloadError
            else:
                raise adtlog.AptPermanentError

    def _install_apt_package_under_test_deps(
        self, package_under_test_deps: List[List[str]]
    ) -> None:
        need_explicit_install = []
        for dep in package_under_test_deps:
            if len(dep) == 1:
                # simple test dependency (no alternatives)
                pkg = dep[0]
                if self.is_real_package_installed(pkg):
                    continue
                if self.is_virtual_package_installed(pkg):
                    need_explicit_install.append(pkg)
                    continue
                adtlog.warning("package %s is not installed though it should be" % pkg)
            else:
                # figure out which test dependency alternative got installed
                installed_virtual_packages = []
                found_a_real_package = False
                for pkg in dep:
                    if self.is_real_package_installed(pkg):
                        # no need to install anything from this set of alternatives
                        found_a_real_package = True
                        break
                    if self.is_virtual_package_installed(pkg):
                        installed_virtual_packages.append(pkg)
                if found_a_real_package:
                    continue
                if not installed_virtual_packages:
                    adtlog.warning(
                        "no alternative in %s is installed though one should be" % dep
                    )
                    continue
                if len(installed_virtual_packages) > 1:
                    adtlog.warning(
                        "more than one test dependency alternative in %s installed as a virtual package, installing the first one (%s) as the real package"
                        % (dep, installed_virtual_packages[0])
                    )
                need_explicit_install.append(installed_virtual_packages[0])

        if need_explicit_install:
            adtlog.debug(
                "installing real packages of test dependencies: %s"
                % need_explicit_install
            )
            self._run_apt_command(action="install", what=need_explicit_install)

    def _generate_satdep_deb(self, deps: str) -> "TestbedPath":
        """create a dummy deb with the deps"""
        pkgdir = tempfile.mkdtemp(prefix="autopkgtest-satdep.")
        debdir = os.path.join(pkgdir, "DEBIAN")
        os.chmod(pkgdir, 0o755)
        os.mkdir(debdir)
        os.chmod(debdir, 0o755)
        with open(os.path.join(debdir, "control"), "w") as f:
            f.write(
                textwrap.dedent(
                    f"""\
                    Package: autopkgtest-satdep
                    Section: oldlibs
                    Priority: extra
                    Maintainer: autogenerated
                    Version: 0
                    Architecture: {self.dpkg_arch}
                    Depends: {deps}
                    Description: satisfy autopkgtest test dependencies
                    """
                )
            )
        deb = TempPath(self, "autopkgtest-satdep.deb")
        subprocess.check_call(
            ["dpkg-deb", "-Zxz", "-b", pkgdir, deb.host], stdout=subprocess.PIPE
        )
        shutil.rmtree(pkgdir)
        return deb

    def install_apt(
        self,
        deps: str,
        shell_on_failure: bool = False,
        package_under_test_deps: Optional[List[List[str]]] = None,
    ) -> None:
        """Install dependencies with apt-get into testbed

        This requires root privileges and a writable file system.
        """
        # Check if apt supports the `apt-get satisfy <string>` syntax
        legacy_apt = self.apt_version < Version("1.9.0")

        if legacy_apt:
            # Fallback to installing test dependencies via a dummy binary .deb.
            #
            # TODO for when we'll be able to assume apt (>= 1.1exp1) on the testbed:
            # 1. Switch from installing deps via `dpkg --unpack autopkgtest-satdep.deb`
            #    + `apt-get --fix-broken` + `apt-get purge autokgtest-satdep` to
            #    `apt-get build-dep autopkgtest-satdep.dsc`.
            #    See: b86576aa47f6f95985c3be46e4a4e20278da4511.
            # 2. Drop the special handling of :native.
            adtlog.debug(
                "Legacy testbed apt, installing dependencies via autopkgtest-satdep.deb"
            )

            # We need to strip :native qualifiers as they are not valid in
            # DEBIAN/control Depends, see deb-control(5), and compare with
            # deb-src-control(5).
            deps = deps.replace(":native", "")

            assert self.dpkg_arch, "testbed architecture unknown"
            try:
                deps = subprocess.run(
                    [
                        os.path.join(PKGDATADIR, "lib", "parse-deps.pl"),
                        deps,
                        self.dpkg_arch,
                    ],
                    check=True,
                    capture_output=True,
                    text=True,
                ).stdout.strip()
            except subprocess.CalledProcessError as e:
                self.bomb(f"failed to run: {e.cmd}")
            adtlog.debug(f"architecture resolved deps: {deps}")

            # generate a dummy package with the deps
            satdep_package: TestbedPath = self._generate_satdep_deb(deps)
            satdep_package.copydown()

        # install the dependencies in the tb; our apt pinning is not very
        # clever wrt. resolving transitional dependencies in the pocket,
        # so we might need to retry without pinning
        while True:
            if legacy_apt:
                self.check_exec(
                    ["dpkg", "--unpack", satdep_package.tb], stdout=subprocess.PIPE
                )

            rc = 0
            try:
                if legacy_apt:
                    self._run_apt_command(action="install", extra_opts=["--fix-broken"])
                elif deps:
                    self._run_apt_command(action="satisfy", what=[deps])
                # For dependencies that are part of the source package under
                # test (for example if '@' was provided as a test dependency),
                # we explicitly install the corresponding binary packages in case
                # the dependencies on those were satisfied by versioned Provides
                if package_under_test_deps:
                    self._install_apt_package_under_test_deps(package_under_test_deps)

            except adtlog.AptDownloadError:
                self.bomb("apt failed to download packages")

            except adtlog.AptPermanentError:
                rc = -1
                if shell_on_failure:
                    self.run_shell()
            else:
                if legacy_apt:
                    # verify that we actually got autopkgtest-satdep installed
                    rc = self.execute(
                        ["dpkg", "--status", "autopkgtest-satdep"],
                        stdout=subprocess.PIPE,
                        stderr=subprocess.PIPE,
                    )[0]

            if rc != 0:
                if self.apt_pin_for_releases and self.enable_apt_fallback:
                    release = self.apt_pin_for_releases.pop()
                    adtlog.warning(
                        "Test dependencies are unsatisfiable with using apt pinning. "
                        "Retrying with using all packages from %s" % release
                    )
                    pref_file_basename = f"autopkgtest-{release}.pref"
                    # same replacement we do in _create_apt_pinning_for_packages()
                    pref_file_basename = self._sanitize_filename_for_apt(
                        pref_file_basename
                    )
                    pref_file = f"/etc/apt/preferences.d/{pref_file_basename}"
                    self.check_exec(["rm", pref_file])
                    continue

                if shell_on_failure:
                    self.run_shell()
                if self.enable_apt_fallback:
                    self.badpkg(
                        "Test dependencies are unsatisfiable. A common reason is "
                        "that your testbed is out of date with respect to the "
                        "archive, and you need to use a current testbed or run "
                        "apt-get update or use -U."
                    )
                else:
                    self.badpkg(
                        "Test dependencies are unsatisfiable. A common reason is "
                        "that the requested apt pinning prevented dependencies "
                        "from the non-default suite to be installed. In that "
                        "case you need to add those dependencies to the pinning "
                        "list."
                    )
            break

        if legacy_apt:
            # remove autopkgtest-satdep to avoid confusing tests, but avoid marking our
            # test dependencies for auto-removal
            out = self.check_exec(
                [
                    "apt-get",
                    "--simulate",
                    "--quiet",
                    "-o",
                    "APT::Get::Show-User-Simulation-Note=False",
                    "--auto-remove",
                    "purge",
                    "autopkgtest-satdep",
                ],
                True,
            )
            test_deps = []
            for line in out.splitlines():
                if not line.startswith("Purg "):
                    continue
                pkg = line.split()[1]
                if pkg != "autopkgtest-satdep":
                    test_deps.append(pkg)
            if test_deps:
                adtlog.debug(
                    "Marking test dependencies as manually installed: %s"
                    % " ".join(test_deps)
                )
                # avoid overly long command lines
                batch = 0
                while batch < len(test_deps):
                    self.check_exec(
                        ["apt-mark", "manual", "-qq"] + test_deps[batch : batch + 20]
                    )
                    batch += 20

            self.execute(["dpkg", "--purge", "autopkgtest-satdep"])

    def install_build_deps_for_package(
        self, src_package_path, shell_on_failure=False, xenv=[]
    ) -> None:
        """Install build dependencies via apt-get build-dep.

        This requires apt >= 1.1~exp1 (Debian >= 9, Ubuntu >= 16.04).
        The caller function is expected to check this.
        """
        # apt-get build-dep --simulate prints a "Inst ..." line for each package to be installed.
        # If none of those is present, it means no package actually needs to be installed.
        # We do this because with --simulate we can run apt-get as non-root; without --simulate
        # apt-get build-dep always requires root, even if no package is installed.
        apt_bd_simulate_cmd = [
            "apt-get",
            "-q",
            "--simulate",
            "build-dep",
            src_package_path,
        ]
        rc, out, _ = self.execute(
            apt_bd_simulate_cmd,
            stdout=subprocess.PIPE,
            stderr=subprocess.STDOUT,
            xenv=xenv,
        )
        bd_simulate_out = out.splitlines()

        if rc != 0:
            adtlog.error(
                f"Failed to resolve build-deps for {src_package_path}; apt-get --simulate output:"
            )
            for line in bd_simulate_out:
                adtlog.error("| " + line)
            if shell_on_failure:
                self.run_shell()
            # If we fail here we can blame the package => error out via badpkg().
            self.badpkg("Can't resolve build dependencies on testbed")

        needed_bd = [line for line in bd_simulate_out if re.match(r"^Inst ", line)]

        if not needed_bd:
            adtlog.debug("No build dependencies to install")
            return

        if "root-on-testbed" not in self.caps:
            adtlog.error(
                "Missing build dependencies, apt-get build-dep --simulate output:"
            )
            for line in bd_simulate_out:
                adtlog.error("| " + line)
            if shell_on_failure:
                self.run_shell()
            adtlog.bomb("Can't install build dependencies (must be root).")

        try:
            self._run_apt_command(
                action="build-dep",
                what=[src_package_path],
                xenv=xenv,
            )
        except adtlog.AptError:
            if shell_on_failure:
                self.run_shell()
            self.bomb("Failure installing build dependencies on testbed")

    def satisfy_dependencies_string(
        self,
        deps: str,
        what: str,
        shell_on_failure: bool = False,
        package_under_test_deps: Optional[List[List[str]]] = None,
    ) -> None:
        """Install dependencies from a string into the testbed"""

        adtlog.debug("%s: satisfying %s" % (what, deps))

        # check if we can use apt-get
        can_apt_get = False
        if "root-on-testbed" in self.caps:
            can_apt_get = True
        adtlog.debug("can use apt-get on testbed: %s" % can_apt_get)

        if can_apt_get:
            self.install_apt(deps, shell_on_failure, package_under_test_deps)
        else:
            # This whole `else` branch is meant to check if we can get
            # away without being root on the testbed because all the
            # dependencies are already installed. Hopefully one day
            # we'll replace it with something better, e.g. checking
            # the output of `apt-get --simulate`.

            has_dpkg_checkbuilddeps = (
                self.execute(
                    ["sh", "-ec", "command -v dpkg-checkbuilddeps"],
                    stdout=subprocess.DEVNULL,
                    stderr=subprocess.DEVNULL,
                )[0]
                == 0
            )
            if has_dpkg_checkbuilddeps:
                rc, _, err = self.execute(
                    ["dpkg-checkbuilddeps", "-d", deps, "/dev/null"],
                    stdout=subprocess.PIPE,
                    stderr=subprocess.PIPE,
                )
                if rc != 0:
                    missing = re.sub(
                        "dpkg-checkbuilddeps: error: Unmet build dependencies: ",
                        "",
                        err,
                    )
                    self.badpkg("test dependencies missing: %s" % missing)
            else:
                adtlog.warning(
                    "test dependencies (%s) are not fully satisfied, but continuing anyway since dpkg-checkbuilddeps it not available to determine which ones are missing."
                    % deps
                )

    def _add_apt_preference(self, preference: str, filename: str) -> None:
        """Add APT preference under /etc/apt/preferences.d"""

        preference = preference.strip()
        if not preference:
            return
        filename = self._sanitize_filename_for_apt(filename)
        adtlog.debug(f"adding APT preference to {filename}:\n{preference}")
        self.check_exec(
            [
                "sh",
                "-ec",
                f'"$@" > "/etc/apt/preferences.d/{filename}"',
                "add_apt_preference",
                "printf",
                r"%s\n",
                preference,
            ]
        )

    def run_shell(self, cwd=None, extra_env=[]):
        """Run shell in testbed for debugging tests"""

        adtlog.info(" - - - - - - - - - - running shell - - - - - - - - - -")
        self.command("shell", [cwd or "/"] + extra_env)

    def run_test(
        self,
        tree,
        test,
        extra_env=[],
        shell_on_failure=False,
        shell=False,
        build_parallel=None,
    ):
        """Run given test in testbed

        tree (a TestbedPath) is the source tree root.
        """

        def _info(m):
            adtlog.info("test %s: %s" % (test.name, m))

        self.last_test_name = test.name

        if self.skip_remaining_tests:
            test.set_skipped("global timeout exceeded")
            return

        if test.path and not os.path.exists(os.path.join(tree.host, test.path)):
            self.badpkg("%s does not exist" % test.path)

        # record installed package versions
        if self.output_dir:
            pkglist = TempPath(self, test.name + "-packages.all", autoclean=False)
            self.check_exec(
                [
                    "sh",
                    "-ec",
                    "dpkg-query --show -f '${Package}\\t${Version}\\n' > %s"
                    % pkglist.tb,
                ]
            )
            pkglist.copyup()

            # filter out packages from the base system
            with open(pkglist.host[:-4], "w") as out:
                join = subprocess.Popen(
                    [
                        "join",
                        "-v2",
                        "-t\t",
                        os.path.join(self.output_dir, "testbed-packages"),
                        pkglist.host,
                    ],
                    stdout=out,
                    env={},
                )
                join.communicate()
                if join.returncode != 0:
                    self.badpkg(
                        "failed to call join for test specific package list, code %d"
                        % join.returncode
                    )
            os.unlink(pkglist.host)

        # ensure our tests are in the testbed
        tree.copydown(check_existing=True)

        # stdout/err files in testbed
        so = TempPath(self, test.name + "-stdout", autoclean=False)
        se = TempPath(self, test.name + "-stderr", autoclean=False)

        # create script to run test
        test_artifacts = "%s/%s-artifacts" % (self.scratch, test.name)
        autopkgtest_tmp = "%s/autopkgtest_tmp" % (self.scratch)
        assert self.nproc is not None

        argv = [self.wrapper_sh]

        if adtlog.verbosity >= 2:
            # This should come first so that it affects all CLI options
            argv.append("--debug")

        if any(
            r in ["isolation-machine", "isolation-container"] for r in test.restrictions
        ):
            # Must come early, because it influences behaviour of other options eg --artifacts
            argv.append("--isolation")

        argv.extend(
            [
                "--artifacts={}".format(test_artifacts),
                "--chdir={}".format(tree.tb),
                "--env=AUTOPKGTEST_TESTBED_ARCH={}".format(self.dpkg_arch),
                "--env=AUTOPKGTEST_TEST_ARCH={}".format(self.test_arch),
                "--env=DEB_BUILD_OPTIONS=parallel={}".format(
                    build_parallel or self.nproc
                ),
                "--env=DEBIAN_FRONTEND=noninteractive",
                "--env=LANG=C.UTF-8",
                "--unset-env=LANGUAGE",
                "--unset-env=LC_ADDRESS",
                "--unset-env=LC_ALL",
                "--unset-env=LC_COLLATE",
                "--unset-env=LC_CTYPE",
                "--unset-env=LC_IDENTIFICATION",
                "--unset-env=LC_MEASUREMENT",
                "--unset-env=LC_MESSAGES",
                "--unset-env=LC_MONETARY",
                "--unset-env=LC_NAME",
                "--unset-env=LC_NUMERIC",
                "--unset-env=LC_PAPER",
                "--unset-env=LC_TELEPHONE",
                "--unset-env=LC_TIME",
                "--script-pid-file=/tmp/autopkgtest_script_pid",
                "--source-profile",
                "--stderr={}".format(se.tb),
                "--stdout={}".format(so.tb),
                "--tmp={}".format(autopkgtest_tmp),
            ]
        )

        if self.test_arch_is_foreign:
            rc, dpkg_arch_vars, _ = self.execute(
                ["dpkg-architecture", "-a" + self.test_arch],
                stdout=subprocess.PIPE,
                stderr=subprocess.DEVNULL,
            )
            testbed_has_dpkg_architecture = rc == 0
            if testbed_has_dpkg_architecture:
                for var in dpkg_arch_vars.splitlines():
                    # set up environment for cross-architecture building.
                    if var.startswith("DEB_HOST_") or var.startswith("DEB_BUILD_"):
                        argv.append(f"--env={var}")
                adtlog.info("test environment configured for cross building")

        if "needs-root" in test.restrictions and self.user is not None:
            argv.append("--env=AUTOPKGTEST_NORMAL_USER={}".format(self.user))
            argv.append("--env=ADT_NORMAL_USER={}".format(self.user))

        for e in extra_env:
            argv.append("--env={}".format(e))

        if test.path:
            test_cmd = os.path.join(tree.tb, test.path)
            argv.extend(
                [
                    "--make-executable=" + test_cmd,
                    "--",
                    test_cmd,
                ]
            )
        else:
            argv.extend(["--", "bash", "-ec", test.command])

        # Convert the argv into a shell one-line so we can wrap it in su
        script = "set -e; exec " + " ".join(map(shlex.quote, argv))

        if "needs-root" not in test.restrictions and self.user is not None:
            if "root-on-testbed" not in self.caps:
                self.bomb(
                    "cannot change to user %s without root-on-testbed" % self.user,
                    adtlog.AutopkgtestError,
                )
            # we don't want -l here which resets the environment from
            # self.execute(); so emulate the parts that we want
            # FIXME: move "run as user" as an argument of execute()/check_exec() and run with -l
            test_argv = ["su", "-s", "/bin/bash", self.su_user, "-c"]

            if "rw-build-tree" in test.restrictions:
                self.check_exec(["chown", "-R", self.user, tree.tb])
        else:
            # this ensures that we have a PAM/logind session for root tests as
            # well; with some interfaces like ttyS1 or lxc_attach we don't log
            # in to the testbed
            if "root-on-testbed" in self.caps:
                test_argv = ["su", "-s", "/bin/bash", "root", "-c"]
            else:
                test_argv = ["bash", "-c"]

        # run test script
        if test.command:
            _info(test.command)
        _info("[-----------------------")

        # tests may reboot, so we might need to run several times
        self.last_reboot_marker = ""
        timeout = False
        while True:
            if self.last_reboot_marker:
                script_prefix = (
                    'export AUTOPKGTEST_REBOOT_MARK="%s"; export ADT_REBOOT_MARK="$AUTOPKGTEST_REBOOT_MARK"; '
                    % self.last_reboot_marker
                )
            else:
                script_prefix = ""
            try:
                rc = self.execute(test_argv + [script_prefix + script], kind="test")[0]
            except VirtSubproc.Timeout as exc:
                rc = 1
                timeout = True
                self.skip_remaining_tests = exc.abort
                break

            # If the shell or su command that runs wrapper.sh exits with
            # status 128+SIGKILL, that probably means either wrapper.sh or
            # the test itself was terminated with SIGKILL, which might be
            # because the test asked for the testbed to be rebooted.
            if rc in (-signal.SIGKILL, 128 + signal.SIGKILL) and "reboot" in self.caps:
                adtlog.debug("test process SIGKILLed, checking for reboot marker")
                (code, reboot_marker, err) = self.execute(
                    ["cat", "/run/autopkgtest-reboot-mark"],
                    stdout=subprocess.PIPE,
                    stderr=subprocess.PIPE,
                )
                if code == 0:
                    self.last_reboot_marker = reboot_marker.strip()
                    adtlog.info(
                        "test process requested reboot with marker %s"
                        % self.last_reboot_marker
                    )
                    self.reboot()
                    continue

                adtlog.debug(
                    "test process SIGKILLed, checking for prepare-reboot marker"
                )
                (code, reboot_marker, err) = self.execute(
                    ["cat", "/run/autopkgtest-reboot-prepare-mark"],
                    stdout=subprocess.PIPE,
                    stderr=subprocess.PIPE,
                )
                if code == 0:
                    self.last_reboot_marker = reboot_marker.strip()
                    adtlog.info(
                        "test process requested preparation for reboot with marker %s"
                        % self.last_reboot_marker
                    )
                    self.reboot(prepare_only=True)
                    continue

                adtlog.debug("no reboot marker, considering a failure")
            break

        # give the setup_trace() cats some time to catch up
        sys.stdout.flush()
        sys.stderr.flush()
        time.sleep(0.3)
        _info("-----------------------]")
        adtlog.debug("testbed executing test finished with exit status %i" % rc)

        # copy stdout/err files to host
        try:
            so.copyup()
            se.copyup()
            se_size = os.path.getsize(se.host)
        except adtlog.TestbedFailure:
            if timeout:
                # if the test timed out, it's likely that the test destroyed
                # the testbed, so ignore this and call it a failure
                adtlog.warning("Copying up test output timed out, ignoring")
                se_size = 0
                so.host = None
                se.host = None
            else:
                # smells like a tmpfail
                raise

        # avoid mixing up stdout (from report) and stderr (from logging) in output
        sys.stdout.flush()
        sys.stderr.flush()
        time.sleep(0.1)

        _info(" - - - - - - - - - - results - - - - - - - - - -")

        if timeout:
            test.failed("timed out")
        elif rc == 77 and "skippable" in test.restrictions:
            test.set_skipped("exit status 77 and marked as skippable")
        elif rc != 0:
            if "needs-internet" in test.restrictions and self.needs_internet == "try":
                test.set_skipped(
                    "Failed, but test has needs-internet and that's not guaranteed"
                )
            else:
                test.failed("non-zero exit status %d" % rc)
        elif se_size != 0 and "allow-stderr" not in test.restrictions:
            with open(se.host, encoding="UTF-8", errors="replace") as f:
                stderr_top = f.readline().rstrip("\n \t\r")
            test.failed("stderr: %s" % stderr_top)
        else:
            test.passed()

        sys.stdout.flush()
        sys.stderr.flush()

        # skip the remaining processing if the testbed got broken
        if se.host is None:
            adtlog.debug(
                "Skipping remaining log processing and testbed restore after timeout"
            )
            return

        if os.path.getsize(so.host) == 0:
            # don't produce empty -stdout files in --output-dir
            so.autoclean = True

        if se_size != 0 and "allow-stderr" not in test.restrictions:
            # give tee processes some time to catch up, to avoid mis-ordered logs
            time.sleep(0.2)
            _info(" - - - - - - - - - - stderr - - - - - - - - - -")
            with open(se.host, "rb") as f:
                while True:
                    block = f.read1(1000000)
                    if not block:
                        break
                    sys.stderr.buffer.write(block)
            sys.stderr.buffer.flush()
        else:
            # don't produce empty -stderr files in --output-dir
            if se_size == 0:
                se.autoclean = True

        # copy artifacts to host, if we have --output-dir
        if self.output_dir:
            ap = TestbedPath(
                self,
                os.path.join(self.output_dir, "artifacts", test.name),
                test_artifacts,
                is_dir=True,
            )
            ap.copyup()
            # don't keep an empty artifacts dir around
            if not os.listdir(ap.host):
                os.rmdir(ap.host)
            if not os.listdir(os.path.dirname(ap.host)):
                os.rmdir(os.path.dirname(ap.host))

        if shell or (shell_on_failure and not test.result):
            self.run_shell(
                tree.tb,
                [
                    'AUTOPKGTEST_ARTIFACTS="%s"' % test_artifacts,
                    'AUTOPKGTEST_TMP="%s"' % autopkgtest_tmp,
                ],
            )

        # clean up artifacts and AUTOPKGTEST_TMP dirs
        self.check_exec(["rm", "-rf", test_artifacts, autopkgtest_tmp])

    #
    # helper methods
    #

    def _set_baseline_pin_priority_for_release(self, release):
        """Give Pin-Priority: 500 to any package that did not match an earlier
        preference. This prevents "NotAutomatic: yes", "ButAutomaticUpgrades:
        yes" to have any effect on the default priority of release.
        See APT's Default Priority Assignments in apt_preferences(5)."""
        # This pref file should sort last, hence the "zz" in the file name.
        pref_file = f"autopkgtest-zz-{release}-baseline.pref"
        preference = textwrap.dedent(
            f"""\
            Package: *
            Pin: release {release}
            Pin-Priority: 500
            """
        )
        self._add_apt_preference(preference, pref_file)

    def _create_apt_pinning_for_packages(self, release, pkglist):
        """Create apt pinning for --apt-pocket=pocket=pkglist and
        --pin-packages=release=pkglist"""

        pref_template = Template(
            textwrap.dedent(
                """\
                Package: $pkgs
                Pin: release $release
                Pin-Priority: $prio

                """
            )
        )

        pkglist = pkglist.split(",")

        if self.apt_version < Version("2.0"):
            # sort pkglist into source and binary packages
            binpkgs = []
            srcpkgs = []
            for i in pkglist:
                i = i.strip()
                if i.startswith("src:"):
                    srcpkgs.append(i[4:])
                else:
                    binpkgs.append(i)

            # translate src:name entries into binaries of that source
            #
            # apt 1.9.11 implemented support for pinning by source package
            # using the src:pkg syntax, as documented in apt_preferences(5),
            # however that's too new for us to use for now.
            if srcpkgs:
                apt_cache = self.check_exec(["apt-cache", "dumpavail"], True)
                for paragr in Deb822.iter_paragraphs(apt_cache):
                    pkg = paragr.get("Package")
                    src = paragr.get("Source", pkg).split()[0]
                    if src in srcpkgs and pkg not in binpkgs:
                        binpkgs.append(pkg)

            pkglist = binpkgs

        # We want pins to be valid on any architecture, so that they work
        # consistently across architectures in multi-arch systems.
        for i, pkg in enumerate(pkglist):
            if ":" not in (pkg[4:] if pkg.startswith("src:") else pkg):
                pkglist[i] += ":any"

        # Pin the release with priority 100, which is the same as if it had
        # "NotAutomatic: yes", "ButAutomaticUpgrades: yes", which is what we
        # want as only pinned packages should be taken from it.
        pref_content = pref_template.substitute(
            pkgs="*",
            release=release,
            prio="100",
        )

        # prefer given packages from the specified release
        if pkglist:
            pref_content += pref_template.substitute(
                pkgs=" ".join(pkglist),
                release=release,
                prio="995",
            )

        pref_file = f"autopkgtest-{release}.pref"
        self._add_apt_preference(pref_content, pref_file)

        self.apt_pin_for_releases.append(release)

    def _set_default_release(self):
        """Set apt's default release."""
        # The "default release" preference file should sort first so to behave
        # like APT::Default-Release. See APT's Default Priority Assignments in
        # apt_preferences(5), "Note that this has precedence...".
        pref_file = "autopkgtest-00-default-release.pref"
        preference = textwrap.dedent(
            f"""\
            Package: *
            Pin: release {self.default_release}
            Pin-Priority: 990
            """
        )
        self._add_apt_preference(preference, pref_file)

    def _add_apt_source(self, source: str, filename: str) -> None:
        source = source.strip()
        if not source:
            return
        adtlog.debug("adding APT source: %s" % source)
        filename = self._sanitize_filename_for_apt(filename)
        if filename.endswith(".sources"):
            # add empty line to ensure deb822 stanzas are correctly separated
            source += "\n"
        new_source_path = f"/etc/apt/sources.list.d/{filename}"
        self.check_exec(
            [
                "sh",
                "-ec",
                f'"$@" >> "{new_source_path}"',
                "add_apt_source",
                "printf",
                r"%s\n",
                source,
            ]
        )

        adtlog.info(f"updating testbed package index for new source {filename}")
        try:
            self._run_apt_command(
                action="update",
                # Options to only update the added source, without discarding existing data.
                extra_opts=[
                    f"-o=Dir::Etc::SourceList={new_source_path}",
                    "-o=Dir::Etc::SourceParts=/dev/null",
                    "-oAPT::Get::List-Cleanup=0",
                ],
            )
        except adtlog.AptError:
            self.bomb(f"failed testbed apt update for {filename}")

    def _get_apt_sources_one_line_style(self) -> List[str]:
        """Return list of all the configured one-line-style sources."""

        script = load_shell_script("setup-commands/get-apt-sources-one-line-style")
        sources = self.check_exec(["sh", "-ec", script], stdout=True)
        sources = sources.splitlines()
        return sources

    def _get_apt_sources_deb822(self) -> List[Deb822]:
        """Return a list of all the deb822 configured sources."""

        script = load_shell_script("setup-commands/get-apt-sources-deb822")
        sources = self.check_exec(["sh", "-ec", script], stdout=True)
        sources = Deb822.iter_paragraphs(sources)
        sources = list(sources)
        return sources

    def _add_apt_release_one_line_style(self, release: str) -> None:
        """
        For each existing "deb" one-line-style source entry where "suite" is
        the testbed's base release, make new deb and deb-src source entries
        based on the existing one, but with the suite now being <release>.

        For example, if an existing source entry looks like:

        deb [ trusted=yes ] http://archive.ubuntu.com/ubuntu/ mantic main universe

        and we are adding the release 'noble', the resulting source entries
        would be:

        deb [ trusted=yes ] http://archive.ubuntu.com/ubuntu/ noble main universe
        deb-src [ trusted=yes ] http://archive.ubuntu.com/ubuntu/ noble main universe

        The new sources are written to a new file,
        /etc/apt/sources.list.d/autopkgtest-add-apt-release-<release>.list.
        """
        sources = self._get_apt_sources_one_line_style()
        if not sources:
            return

        sources_for_release = []
        for line in sources:
            match = self.SOURCELIST_PATTERN.match(line)
            if not match:
                adtlog.info(f"Failed to parse APT list entry: {line}")
                continue
            source = match.groupdict()
            if source["type"] != "deb" or source["suite"] != self.release:
                continue

            new_source = ["deb"]
            if source["options"]:
                new_source.append(source["options"])
            new_source.append(source["uri"])
            new_source.append(release)
            new_source.append(source["components"])
            sources_for_release.append(" ".join(new_source))
            new_source[0] = "deb-src"
            sources_for_release.append(" ".join(new_source))

        self._add_apt_source(
            "\n".join(sources_for_release).strip(),
            filename=f"autopkgtest-add-apt-release-{release}.list",
        )

    def _add_apt_release_deb822(self, release: str) -> None:
        """
        For each existing deb822 source entry with "Types: deb" and Suites
        including the testbed's base release, make a new source entry that is
        a copy of the existing one, but replace the Suites with just <release>,
        and enable both deb and deb-src.

        For example, if an existing source entry looks like:

        Types: deb
        URIs: http://archive.ubuntu.com/ubuntu/
        Suites: mantic mantic-updates
        Components: main universe

        and we are adding the release 'noble', the resulting source entry
        would be:

        Types: deb deb-src
        URIs: http://archive.ubuntu.com/ubuntu/
        Suites: noble
        Components: main universe

        The new sources are written to a new file,
        /etc/apt/sources.list.d/autopkgtest-add-apt-release-<release>.sources.
        """
        sources = self._get_apt_sources_deb822()
        if not sources:
            return

        sources_for_release = []
        for source in sources:
            if "deb" not in source["Types"].split():
                continue
            if self.release not in source["Suites"].split():
                continue
            new_source = source.copy()
            new_source["Suites"] = release
            new_source["Types"] = "deb deb-src"
            sources_for_release.append(new_source)

        # Convert Deb822 objects into strings
        sources_for_release = [str(source) for source in sources_for_release]
        self._add_apt_source(
            "\n".join(sources_for_release),
            filename=f"autopkgtest-add-apt-release-{release}.sources",
        )

    def _add_apt_ppa(self, ppaspec: str) -> None:
        """Add PPA to the APT sources.list"""

        # parse the ppa spec
        ppaspec = ppaspec.strip()
        match = self.PPA_PATTERN.match(ppaspec)
        if not match:
            self.bomb(f"invalid PPA name: {ppaspec}", adtlog.AutopkgtestError)
            return
        adtlog.debug(f"adding PPA: {ppaspec}")
        ppa = match.groupdict()
        ppa_shorthand = f"{ppa['name']}/{ppa['owner']}"
        ppa_is_private = bool(ppa["user"])

        # with private PPAs we can't query Launchpad for the fingerprint
        if ppa_is_private and not ppa["fingerprint"]:
            self.bomb(
                f"fingerprint not specified for private PPA {ppa_shorthand}",
                adtlog.AutopkgtestError,
            )

        # construct PPA repository URI
        if ppa_is_private:
            lpcontent_endpoint = "private-ppa.launchpadcontent.net"
        else:
            lpcontent_endpoint = "ppa.launchpadcontent.net"
        ppa_repo_uri = (
            f"https://{lpcontent_endpoint}/{ppa['owner']}/{ppa['name']}/ubuntu/"
        )

        # create opener for PPA repository URIs
        if ppa_is_private:
            ppa_password_mgr = urllib.request.HTTPPasswordMgrWithDefaultRealm()
            ppa_password_mgr.add_password(None, ppa_repo_uri, ppa["user"], ppa["token"])
            ppa_auth_handler = urllib.request.HTTPBasicAuthHandler(ppa_password_mgr)
            ppa_urlopener = urllib.request.build_opener(ppa_auth_handler)
        else:
            ppa_urlopener = urllib.request.build_opener()

        # check that ppa exists and has contents for release; we actively probe
        # the PPA to fail early with an AutopkgtestError if case of issues, and
        # not later e.g. when updating the index, possibly causing a misleading
        # testbed failure.
        adtlog.debug(f"checking that {ppa_shorthand} has contents for {self.release}")
        http_timeout = 20
        try:
            url = urllib.parse.urljoin(ppa_repo_uri, f"dists/{self.release}/Release")
            adtlog.debug(f"checking that {ppa_shorthand} Release file exists: {url}")
            req = urllib.request.Request(url, method="HEAD")
            # we are only interested in the http status code, so we open().close()
            ppa_urlopener.open(req, timeout=http_timeout).close()

            url = urllib.parse.urljoin(
                ppa_repo_uri, f"dists/{self.release}/main/source/Release"
            )
            adtlog.debug(
                f"checking that {ppa_shorthand} source/Release file exists: {url}"
            )
            req = urllib.request.Request(url, method="HEAD")
            ppa_urlopener.open(url, timeout=http_timeout).close()
        except (urllib.error.URLError, urllib.error.HTTPError) as e:
            self.bomb(
                f"no packages found for {self.release} in PPA {ppa_shorthand}: {e}",
                adtlog.AutopkgtestError,
            )

        # get ppa signing key fingerprint
        if not ppa["fingerprint"]:
            url = f"https://api.launchpad.net/1.0/~{ppa['owner']}/+archive/ubuntu/{ppa['name']}"
            adtlog.debug(f"querying Launchpad about ppa {ppa_shorthand}: {url}")
            try:
                with urllib.request.urlopen(url, timeout=http_timeout) as response:
                    content = response.read().decode("utf-8")
            except (urllib.error.URLError, urllib.error.HTTPError) as e:
                self.bomb(
                    f"failed to get signing key fingerprint for {ppa_shorthand}: {e}",
                    adtlog.AutopkgtestError,
                )
            try:
                ppadata = json.loads(content)
            except json.JSONDecodeError as e:
                self.bomb(
                    f"bad json data for PPA {ppa_shorthand} from {url}: {e}",
                    adtlog.AutopkgtestError,
                )
            ppa["fingerprint"] = ppadata["signing_key_fingerprint"]
            adtlog.debug(
                f"PPA {ppa_shorthand} signing key fingerprint: {ppa['fingerprint']}"
            )

        # get ppa signing pubkey
        url = f"https://keyserver.ubuntu.com/pks/lookup?op=get&search=0x{ppa['fingerprint']}"
        adtlog.debug(f"retrieving pubkey for ppa {ppa_shorthand}: {url}")
        try:
            with urllib.request.urlopen(url, timeout=http_timeout) as response:
                signed_by = response.read().decode("utf-8")
        except (urllib.error.URLError, urllib.error.HTTPError) as e:
            self.bomb(
                f"failed to get signing key for {ppa_shorthand}: {e}",
                adtlog.AutopkgtestError,
            )

        # if private PPA, embed user:token in uri for inclusion in source list
        if ppa_is_private:
            parsed_uri = urllib.parse.urlparse(ppa_repo_uri)
            netloc_with_userinfo = f"{ppa['user']}:{ppa['token']}@{parsed_uri.netloc}"
            parsed_uri = parsed_uri._replace(netloc=netloc_with_userinfo)
            ppa_repo_uri = urllib.parse.urlunparse(parsed_uri)

        # construct source list for ppa
        if self.apt_version < Version("2.3.10"):
            sourcelist = f"autopkgtest-ppa-{ppa['owner']}-{ppa['name']}.list"

            # add key to APT keyring
            ppa_keyring_basename = f"autopkgtest-ppa-{ppa['owner']}-{ppa['name']}.gpg"
            ppa_keyring_basename = self._sanitize_filename_for_apt(ppa_keyring_basename)
            ppa_keyring = f"/etc/apt/trusted.gpg.d/{ppa_keyring_basename}"
            self.check_exec(
                [
                    "sh",
                    "-ec",
                    'touch "$2";printf %s "$1" | apt-key --keyring "$2" add -;',
                    "add_apt_ppa",
                    signed_by,
                    ppa_keyring,
                ],
                xenv=["APT_KEY_DONT_WARN_ON_DANGEROUS_USAGE=1"],
            )

            # construct one-line-style source list
            ppa_source = textwrap.dedent(
                f"""\
                deb [ signed-by={ppa_keyring} ] {ppa_repo_uri} {self.release} main
                deb-src [ signed-by={ppa_keyring} ] {ppa_repo_uri} {self.release} main
                """
            )
        else:
            sourcelist = f"autopkgtest-ppa-{ppa['owner']}-{ppa['name']}.sources"

            # make pubkey suitable for inclusion in a deb822(5) multiline field
            signed_by = re.sub(r"^\s*$(?=\n)", ".", signed_by, flags=re.MULTILINE)
            signed_by = re.sub(r"^(?=.)", " ", signed_by, flags=re.MULTILINE)

            # construct deb822 source list
            ppa_source = textwrap.dedent(
                f"""\
                Types: deb deb-src
                URIs: {ppa_repo_uri}
                Suites: {self.release}
                Components: main
                Signed-By:
                """
            )
            ppa_source += signed_by

        # add apt source
        self._add_apt_source(ppa_source, filename=sourcelist)

    def _sanitize_filename_for_apt(self, filename: str) -> str:
        """APT only allows a-zA-Z0-9_.- in file names of preferences and
        data sources lists, see apt_preferences(5) and sources.list(5)."""

        bad_chars = re.escape(r'~+=,()[]{}!@#$%&\'":;|\/')
        return re.sub(f"[{bad_chars}]", "_", filename)

    def get_policy_for_package(self, package: str) -> Optional[str]:
        """Return apt policy for package"""

        (rc, stdout, _) = self.execute(
            [
                "apt-cache",
                "policy",
                # . and + are valid package name characters but are
                # interpreted by $(apt-cache policy) as regex
                "^" + package.replace(".", "\\.").replace("+", "\\+") + "$",
            ],
            stdout=subprocess.PIPE,
        )

        if rc != 0 or not stdout:
            return None

        return stdout

    def get_candidate(
        self, package: str
    ) -> Tuple[Optional[Version], Optional[int], Optional[str]]:
        """Return candidate version and priority for package"""

        policy = self.get_policy_for_package(package)
        if not policy:
            return None, None, None

        # Get the candidate version of this binary
        version = None
        for line in policy.splitlines():
            if not line.strip().startswith("Candidate:"):
                continue
            if "none" in line.lower():
                break
            version = line.strip().replace("Candidate: ", "")
            break

        if not version:
            return None, None, None

        priority, suite = self._version_info_from_policy(policy, version)

        return Version(version), priority, suite

    def _version_info_from_policy(
        self, policy: str, version: str
    ) -> Tuple[int, Optional[str]]:
        """Extract the priority for a package version from its policy.

        :param policy: `apt-cache policy` output for a single package
        :type policy: str
        :param version: the version for which to extract the prioriy
        :type version: str
        :return: priority and suite for the given version
        :rtype: tuple[int, str]
        """

        # The apt-policy output for a package looks like this:
        #
        # apt:
        #   Installed: 2.7.14build2
        #   Candidate: 2.7.14build2
        #   Version table:
        #      2.9.2 100
        #         100 http://archive.ubuntu.com/ubuntu oracular-proposed/main amd64 Packages
        #      2.9.1 50
        #         100 http://archive.ubuntu.com/ubuntu oracular-baz/main amd64 Packages
        #  *** 2.7.14build2 500 (phased 20%)
        #         500 http://archive.ubuntu.com/ubuntu oracular/main amd64 Packages
        #         100 /path/to/dpkg/status
        #      0.0.1 -30000
        #        -30000 http://archive.ubuntu.com/ubuntu oracular-foo/main amd64 Packages
        #      0.0.2 1
        #           1 http://archive.ubuntu.com/ubuntu oracular-bar/main amd64 Packages
        #
        # We'll proceed in stages:
        # 1. extract the "Version table"
        # 2. from that, extract the entry for the desired version
        # 3. from that, extract the version priority from the "version line" (first line)
        # If priority != 0 (always true with apt >= 1.1~exp9) we are done, otherwise:
        # 4. extract the max priority among "file" priorities.
        #
        # Notes:
        # - The '***' indicates the currently installed version, and may or may
        #   not be present.
        # - For apt (<< 1.1~exp9) compatibility, we can't just extract the priority
        #   from the line containing the package version, as apt (<< 1.1~exp9) just
        #   prints 0 there if there is no "version pin" pin set.

        # 1. Extract the version table. Note that apt prints "file priorities"
        # with this format string: "       %4i %s\n", see private-show.cc.
        needle = re.search(
            r"(?<=^  Version table:\n)(^( {5}| \*{3} | {7,})[^ ].*\n)+",
            policy,
            flags=re.M,
        )
        assert needle is not None
        version_table = needle.group(0)

        # 2. Extract the version table entry for the specified version. Refer to
        # the apt format string mentioned above to see why we look for "^ {7,}".
        needle = re.search(
            r"^( {5}| \*{3} )" + re.escape(version) + " .*\n(^ {7,}[^ ].*\n)+",
            version_table,
            flags=re.M,
        )
        assert needle is not None, (
            "version_table doesn't contain version '%s':\n%s\npolicy:\n%s"
            % (version, version_table, policy)
        )
        version_table_for_candidate = needle.group(0).splitlines()

        # 3. Extract the "version line" and from that the priority.
        version_line = version_table_for_candidate[0]
        priority = int(version_line[5:].split()[1])

        # This will always be false with apt >= 1.1~exp9.
        if priority == 0:
            # 4. Fallback to parsing "file priorities".
            file_priorities = version_table_for_candidate[1:]
            priorities = [int(fp.split(maxsplit=1)[0]) for fp in file_priorities]
            priority = max(priorities)

        assert priority != 0, "invalid priority, bug in policy parsing?"

        # Get suite from first highest-priority file entry providing the candidate.
        suite = None
        max_file_priority = float("-inf")
        for line in version_table_for_candidate[1:]:
            file_parts = line.split()
            if len(file_parts) < 5:
                # Skip /var/lib/dpkg/status and other possibly malformed entries.
                continue
            # Use a strict > and not a >= so that we respect source order.
            this_file_priority = int(file_parts[0])
            if this_file_priority > max_file_priority:
                max_file_priority = this_file_priority
                suite = file_parts[2].split("/")[0].split("-")[0]
                assert suite, "invalid suite, bug in policy parsing?"

        return priority, suite


class TestbedPath:
    """Represent a file/dir with a host and a testbed path"""

    def __init__(
        self,
        testbed: Testbed,
        host: str,
        tb: str,
        is_dir: Optional[bool] = None,
    ) -> None:
        """Create a TestbedPath object.

        The object itself is just a pair of file names, nothing more. They do
        not need to exist until you call copyup() or copydown() on them.

        testbed: the Testbed object which this refers to
        host: path of the file on the host
        tb: path of the file in testbed
        is_dir: whether path is a directory; None for "unspecified" if you only
                need copydown()
        """
        self.testbed = testbed
        self.host = host
        self.tb = tb
        self.is_dir = is_dir

    def copydown(
        self,
        check_existing=False,
        mode="",
    ) -> None:
        """Copy file from the host to the testbed

        If check_existing is True, don't copy if the testbed path already
        exists.
        """
        if check_existing and self.testbed.execute(["test", "-e", self.tb])[0] == 0:
            adtlog.debug("copydown: tb path %s already exists" % self.tb)
            return

        # create directory on testbed
        self.testbed.check_exec(["mkdir", "-p", os.path.dirname(self.tb)])

        if os.path.isdir(self.host):
            # directories need explicit '/' appended for VirtSubproc
            self.testbed.command("copydown", (self.host + "/", self.tb + "/"))
        else:
            self.testbed.command("copydown", (self.host, self.tb))

        # we usually want our files be readable for the non-root user
        if mode:
            self.testbed.check_exec(["chmod", "-R", mode, "--", self.tb])
        elif self.testbed.user:
            rc = self.testbed.execute(
                ["chown", "-R", self.testbed.user, "--", self.tb],
                stderr=subprocess.PIPE,
            )[0]
            if rc != 0:
                # chowning doesn't work on all shared downtmps, try to chmod
                # instead

                # I believe this is only needed for autopkgtest-virt-unshare, which
                # no longer advertises a downtmp at all.
                # But we allow it still, with --insecure, in case someone needs it.
                assert self.testbed.insecure
                self.testbed.check_exec(["chmod", "-R", "go+rwX", "--", self.tb])

    def copyup(self, check_existing=False):
        """Copy file from the testbed to the host

        If check_existing is True, don't copy if the host path already
        exists.
        """
        if check_existing and os.path.exists(self.host):
            adtlog.debug("copyup: host path %s already exists" % self.host)
            return

        os.makedirs(os.path.dirname(self.host), exist_ok=True, mode=0o2755)
        assert self.is_dir is not None
        if self.is_dir:
            self.testbed.command("copyup", (self.tb + "/", self.host + "/"))
        else:
            self.testbed.command("copyup", (self.tb, self.host))


class TempPath(TestbedPath):
    """Represent a file in the hosts'/testbed's temporary directories

    These are only guaranteed to exit within one testbed run.
    """

    # private; used to make sure the names of autocleaned files don't collide
    _filename_prefix = 1

    def __init__(
        self,
        testbed: Testbed,
        name: str,
        is_dir: bool = False,
        autoclean: bool = True,
    ) -> None:
        """Create a temporary TestbedPath object.

        The object itself is just a pair of file names, nothing more. They do
        not need to exist until you call copyup() or copydown() on them.

        testbed: the Testbed object which this refers to
        name: name of the temporary file (without path); host and tb
              will then be derived from that
        is_dir: whether path is a directory; None for "unspecified" if you only
                need copydown()
        autoclean: If True (default), remove file when test finishes. Should
                be set to False for files which you want to keep in the
                --output-dir which are useful for reporting results, like test
                stdout/err, log files, and binaries.
        """
        # if the testbed supports a shared downtmp, use that to avoid
        # unnecessary copying, unless we want to permanently keep the file
        if testbed.shared_downtmp and (not testbed.output_dir or autoclean):
            host = testbed.shared_downtmp
        else:
            host = testbed.output_dir
        self.autoclean = autoclean
        if autoclean:
            name = str(self._filename_prefix) + "-" + name
            TempPath._filename_prefix += 1

        assert testbed.scratch, "undefined scratch directory"
        TestbedPath.__init__(
            self,
            testbed,
            os.path.join(host, name),
            os.path.join(testbed.scratch, name),
            is_dir,
        )

    def __del__(self):
        if self.autoclean:
            if os.path.exists(self.host):
                try:
                    os.unlink(self.host)
                except OSError as e:
                    if e.errno == errno.EPERM:
                        self.testbed.check_exec(["rm", "-rf", self.tb])
                    else:
                        raise


#
# Helper functions
#


def child_ps(pid):
    """Get all child processes of pid"""

    try:
        out = subprocess.check_output(["ps", "-o", "pid=", "--ppid", str(pid)])
        return [int(p) for p in out.split()]
    except subprocess.CalledProcessError:
        return []


def killtree(pid, kill_signal=signal.SIGTERM):
    """Recursively kill pid and all of its children"""

    for child in child_ps(pid):
        killtree(child, kill_signal)
    try:
        os.kill(pid, kill_signal)
    except OSError:
        pass


def locate_setup_command(name: str) -> str:
    # Shortcut for shipped scripts
    if "/" not in name:
        shipped = os.path.join(PKGDATADIR, "setup-commands", name)

        if os.path.exists(shipped):
            return shipped

    return name