File: VirtSubproc.py

package info (click to toggle)
autopkgtest 5.53
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,600 kB
  • sloc: python: 15,484; sh: 2,317; makefile: 116; perl: 19
file content (949 lines) | stat: -rw-r--r-- 28,391 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
# VirtSubproc is part of autopkgtest
# autopkgtest is a tool for testing Debian binary packages
#
# autopkgtest is Copyright (C) 2006-2007 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 __main__

from functools import partial
import sys
import os
from urllib.parse import quote as url_quote
from urllib.parse import unquote as url_unquote
import signal
import subprocess
import traceback
import errno
import fcntl
import time
import socket
import shutil
import shlex
from typing import List, Optional, Union, Tuple

import adtlog

# When running installed, this is /usr/share/autopkgtest.
# When running uninstalled, this is the source tree.
# Either way, it has a lib subdirectory from which virtualization
# backends can read extra files.
PKGDATADIR = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))

progname = "<VirtSubproc>"
caller = __main__
copy_timeout = int(os.getenv("AUTOPKGTEST_VIRT_COPY_TIMEOUT", "300"))

downtmp_open = None  # downtmp after opening testbed
downtmp = None  # current downtmp (None after close)
auxverb = None  # prefix to run command argv in testbed
cleaning = False
in_mainloop = False


class Quit(RuntimeError):
    def __init__(self, ec, m):
        self.ec = ec
        self.m = m


class Timeout(RuntimeError):
    def __init__(self, timeout_secs, abort=False):
        self.timeout_secs = timeout_secs
        self.abort = abort


def alarm_handler(to, *a):
    raise Timeout(to)


def timeout_start(to):
    signal.signal(signal.SIGALRM, partial(alarm_handler, to))
    signal.alarm(to)


def timeout_stop():
    signal.alarm(0)


class FailedCmd(RuntimeError):
    def __init__(self, e):
        self.e = e


def bomb(m):
    if in_mainloop:
        raise Quit(12, progname + ": failure: %s" % m)
    else:
        sys.stderr.write(m)
        sys.stderr.write("\n")
        sys.exit(1)


def ok():
    print("ok")


def cmdnumargs(c, ce, nargs=0, noptargs=0):
    if len(c) < 1 + nargs:
        bomb("too few arguments to command `%s'" % ce[0])
    if noptargs is not None and len(c) > 1 + nargs + noptargs:
        bomb("too many arguments to command `%s'" % ce[0])


def cmd_capabilities(c, ce):
    cmdnumargs(c, ce)
    return caller.hook_capabilities()


def cmd_quit(c, ce):
    cmdnumargs(c, ce)
    raise Quit(0, "")


def cmd_close(c, ce):
    cmdnumargs(c, ce)
    if not downtmp:
        bomb("`close' when not open")
    cleanup()


def cmd_print_execute_command(c, ce):
    global auxverb

    cmdnumargs(c, ce)
    if not downtmp:
        bomb("`print-execute-command' when not open")
    return [",".join(map(url_quote, auxverb))]


def execute_timeout(instr, timeout, *popenargs, **popenargsk):
    """Popen wrapper with timeout supervision

    If instr is given, it is fed into stdin, otherwise stdin will be /dev/null.

    Return (status, stdout, stderr)
    """
    adtlog.debug("execute-timeout: " + " ".join(popenargs[0]))
    if instr is None:
        popenargsk["stdin"] = subprocess.DEVNULL
    else:
        popenargsk["stdin"] = subprocess.PIPE
        instr = instr.encode("UTF-8")
    sp = subprocess.Popen(*popenargs, **popenargsk)
    timeout_start(timeout)
    try:
        (out, err) = sp.communicate(instr)
        if out is not None:
            out = out.decode("UTF-8", "replace")
        if err is not None:
            err = err.decode("UTF-8", "replace")
    except Timeout:
        try:
            sp.kill()
            sp.wait()
        except OSError as e:
            adtlog.error(
                "WARNING: Cannot kill timed out process %s: %s" % (popenargs[0], e)
            )
        raise
    timeout_stop()
    status = sp.wait()
    return (status, out, err)


def check_exec(
    argv, *, downp=False, outp=False, instr=None, timeout=0, fail_on_stderr=True
):
    """Run successful command (argv list)

    Command must succeed (exit code 0) and not produce any stderr. If downp is
    True, command is run in testbed. If outp is True, stdout will be captured
    and returned.

    If instr is given, it is fed into stdin, otherwise stdin will be /dev/null.

    Returns stdout (or None if outp is False).
    """
    global auxverb

    if downp:
        real_argv = auxverb + argv
    else:
        real_argv = argv
    if outp:
        stdout = subprocess.PIPE
    else:
        stdout = None

    (status, out, err) = execute_timeout(
        instr, timeout, real_argv, stdout=stdout, stderr=subprocess.PIPE
    )

    if status:
        bomb(
            "%s%s failed (exit status %d, stderr %r)"
            % ((downp and "(down) " or ""), argv, status, err)
        )
    if fail_on_stderr and err:
        bomb("%s unexpectedly produced stderr output `%s'" % (argv, err))

    if outp and out and out[-1] == "\n":
        out = out[:-1]
    return out


def load_shell_script(path: str) -> str:
    if not os.path.isabs(path):
        path = os.path.join(PKGDATADIR, path)

    with open(path) as reader:
        return reader.read()


def wait_booted(
    exec_command: List[str],
    timeout: int = 120,
    short_command_timeout: int = 10,
) -> None:
    """
    Wait until a container or VM with an init system has sufficiently
    booted to interact with it.

    timeout: how long to wait for the testbed to complete boot

    short_command_timeout: how long we will wait for a relatively quick command
    to finish
    """
    await_boot = load_shell_script("lib/in-testbed/await-boot.sh")

    while timeout > 0:
        timeout -= 1
        time.sleep(1)
        adtlog.debug("wait_booted: trying to execute trivial command on container")
        try:
            (rc, _, _) = execute_timeout(
                None,
                short_command_timeout,
                exec_command + ["true"],
            )
        except Timeout:
            # With some virt servers, commands can get stuck when executed
            # while the testbed is booting, or at least this is what we observe.
            # The wait_booted() retry loop has its own timeout, so we shouldn't
            # stop on timeouts internal to the loop.
            rc = 1
        if rc == 0:
            adtlog.debug("wait_booted: trivial command executed successfully")
            break
    else:
        bomb("timed out waiting for testbed to start")

    adtlog.debug("testbed is alive, waiting for boot to complete")
    try:
        check_exec(
            exec_command + ["sh", "-es"],
            instr=await_boot,
            timeout=timeout,
            fail_on_stderr=False,
        )
        adtlog.debug("wait_booted: boot completed")
    except Timeout:
        bomb("timed out waiting for testbed to complete boot")


class timeout:
    def __init__(self, secs, exit_msg=None):
        """Context manager that times out after given number of seconds.

        If exit_msg is given, the program bomb()s with that message,
        otherwise it raises a Timeout exception.
        """
        self.secs = secs
        self.exit_msg = exit_msg

    def __enter__(self):
        timeout_start(self.secs)

    def __exit__(self, type_, value, traceback):
        timeout_stop()
        if type_ is Timeout and self.exit_msg:
            bomb(self.exit_msg)
            return True
        return False


def get_unix_socket(path):
    """Open a connected client socket to given Unix socket with a 5s timeout"""

    s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
    with timeout(5, "Timed out waiting for %s socket\n" % path):
        while True:
            try:
                s.connect(path)
                break
            except socket.error:
                continue
    return s


def matches_expectation(
    haystack: bytes,
    needle: Union[None, bytes, str, Tuple[Union[bytes, str]]],
) -> bool:
    if needle is None:
        return True
    elif isinstance(needle, tuple):
        for n in needle:
            if matches_expectation(haystack, n):
                return True
        else:
            return False
    elif isinstance(needle, bytes):
        return needle in haystack
    elif isinstance(needle, str):
        return needle.encode("utf-8") in haystack
    else:
        raise TypeError(repr(needle))


def expect(
    sock: socket.socket,
    search: Union[None, bytes, str, Tuple[Union[bytes, str]]],
    timeout_sec: int,
    description: Optional[str] = None,
    echo: bool = False,
):
    adtlog.debug("expect: %r" % (search,))
    what = repr(description or search or "data")
    out = b""
    with timeout(
        timeout_sec, description and ("timed out waiting for %s" % what) or None
    ):
        while True:
            block = sock.recv(4096)
            if not block:
                time.sleep(0.1)
                continue
            if echo:
                sys.stderr.buffer.write(block)
            out += block

            if matches_expectation(out, search):
                adtlog.debug('expect: found "%s"' % what)
                break

    return out


def cmd_open(c, ce):
    global auxverb, downtmp, downtmp_open
    cmdnumargs(c, ce)
    if downtmp:
        bomb("`open' when already open")
    caller.hook_open()
    adtlog.debug("auxverb = %s, downtmp = %s" % (str(auxverb), downtmp))
    downtmp = caller.hook_downtmp(downtmp_open)
    if downtmp_open and downtmp_open != downtmp:
        bomb(
            "virt-runner failed to restore downtmp path %s, gave %s instead"
            % (downtmp_open, downtmp)
        )
    downtmp_open = downtmp
    return [downtmp]


def downtmp_mktemp(capabilities, path, downtmp_prefix):
    """Generate a downtmp

    When a path is given, this is the downtmp that we created when opening the
    testbed the first time. We always want to keep the same path between
    resets, as built package trees sometimes refer to absolute paths and thus
    fail if they get moved around.

    capabilities will be used to determine the appropriate permissions.

    If downtmp_prefix is not None, updates capabilities to add an downtmp-host,
    consisting of downtmp_prefix + the downtmp path.
    """

    # The caller is entitled to use the scratch directory normally, without taking
    # the kind of extreme special care needed for a world-writeable directory.
    if any(cap in ["isolation-container", "isolation-machine"] for cap in capabilities):
        # The testbed is fully isolated by the host, so the only things running
        # in the testbed are part of the testbed or specified by the caller.
        # So there is no untrusted code.
        #
        # Make the scratch directory world-writeable is convenient for use cases
        # that have to deal with multiple users.
        #
        # If the downtmp is visible to the host, then the isolation is not enough.
        # This assertion is a double-check, therefore, that we aren't exposing
        # the caller's code (which is using the downtmp) to possible hostile actions.
        assert downtmp_prefix is None
        mode = "777"
    else:
        # Untrusted code might be running in the testbed - so we must protect it.
        mode = "755"

    if path:
        check_exec(
            ["/bin/mkdir", f"--mode={mode}", "--parents", downtmp_open], downp=True
        )
        d = path
    else:
        d = check_exec(
            ["/bin/mktemp", "--directory", "--tmpdir", "autopkgtest.XXXXXX"],
            downp=True,
            outp=True,
        )
        check_exec(["/bin/chmod", mode, d], downp=True)
    if downtmp_prefix is not None:
        capabilities.append("downtmp-host=" + downtmp_prefix + d)
    return d


def downtmp_remove(capabilities):
    """Removes the downtmp

    Also removes any downtmp-host entry from capabilities.
    """
    global downtmp, auxverb

    # Remove from capabilities first.  Some call sites catch exceptions and continue,
    # and they also want to see downtmp removed.
    capabilities[:] = [c for c in capabilities if not c.startswith("downtmp-host=")]

    if downtmp:
        execute_timeout(None, copy_timeout, auxverb + ["rm", "-rf", "--", downtmp])
        downtmp = None


def cmd_revert(c, ce):
    global auxverb, downtmp, downtmp_open
    cmdnumargs(c, ce)
    if not downtmp:
        bomb("`revert' when not open")
    if "revert" not in caller.hook_capabilities():
        bomb("`revert' when `revert' not advertised")
    caller.hook_revert()
    downtmp = caller.hook_downtmp(downtmp_open)
    if downtmp_open and downtmp_open != downtmp:
        bomb(
            "virt-runner failed to restore downtmp path %s, gave %s instead"
            % (downtmp_open, downtmp)
        )
    adtlog.debug("auxverb = %s, downtmp = %s" % (str(auxverb), downtmp))

    return [downtmp]


def reboot_testbed():
    (systemd_check, out, err) = execute_timeout(
        None,
        10,
        auxverb + ["test", "-d", "/run/systemd/system"],
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
    )
    if systemd_check == 0:
        reboot_cmd = [
            "systemd-run",
            "--no-block",
            "--quiet",
            "sh",
            "-c",
            "sleep 3; systemctl reboot",
        ]
        adtlog.debug("rebooting with command: %s" % reboot_cmd)
        status, out, err = execute_timeout(None, 30, auxverb + reboot_cmd)

        if status == 0:
            return
        else:
            adtlog.debug("Cannot reboot with %s, trying something else" % reboot_cmd)

    reboot_cmd = ["sh", "-c", "(sleep 3; reboot) >/dev/null 2>&1 &"]
    adtlog.debug("rebooting with command: %s" % reboot_cmd)
    status, out, err = execute_timeout(None, 30, auxverb + reboot_cmd)


def cmd_reboot(c, ce):
    global downtmp
    cmdnumargs(c, ce, 0, 1)
    wait_reboot_args = {}
    if not downtmp:
        bomb("`reboot' when not open")
    if "reboot" not in caller.hook_capabilities():
        bomb("`reboot' when `reboot' not advertised")

    # save current downtmp; try a few locations, as /var/cache might be r/o
    # (argh Ubuntu touch)
    directories = "/var/cache /home"
    check_exec(
        [
            "/bin/sh",
            "-ec",
            "for d in %s; do if [ -w $d ]; then "
            "  /bin/tar --warning=none --create --absolute-names "
            """    -f $d/autopkgtest-tmpdir.tar '%s'; """
            "  /bin/rm -f /run/autopkgtest-reboot-prepare-mark; "
            "  exit 0; fi; done; exit 1" % (directories, downtmp),
        ],
        downp=True,
        timeout=copy_timeout,
    )
    adtlog.debug("cmd_reboot: saved current downtmp, rebooting")

    try:
        wait_reboot_args = caller.hook_prepare_reboot() or {}
    except AttributeError:
        pass

    # reboot
    if len(c) > 1 and c[1] == "prepare-only":
        adtlog.info("state saved, waiting for testbed to reboot...")
    else:
        reboot_testbed()

    caller.hook_wait_reboot(**wait_reboot_args)

    # restore downtmp
    check_exec(
        [
            "/bin/sh",
            "-ec",
            "for d in %s; do "
            "if [ -e $d/autopkgtest-tmpdir.tar ]; then "
            " /bin/tar --warning=none --extract --absolute-names "
            "     -f $d/autopkgtest-tmpdir.tar;"
            " /bin/rm $d/autopkgtest-tmpdir.tar; exit 0; "
            "fi; done; exit 1" % directories,
        ],
        downp=True,
        timeout=copy_timeout,
    )
    adtlog.debug("cmd_reboot: restored downtmp after reboot")


def get_downtmp_host():
    """Return host directory of the testbed's downtmp dir, if supported"""

    for cap in caller.hook_capabilities():
        if cap.startswith("downtmp-host="):
            return cap.split("=", 1)[1]
    return None


def copytree(src, dst):
    """Like shutils.copytree(), but merges with existing dst"""

    if not os.path.exists(dst):
        shutil.copytree(src, dst, symlinks=True)
        return

    for f in os.listdir(src):
        fsrc = os.path.join(src, f)
        subprocess.check_call(
            ["cp", "-r", "--preserve=timestamps,links", "--target-directory", dst, fsrc]
        )


def copyup_shareddir(tb, host, is_dir, downtmp_host):
    adtlog.debug(
        "copyup_shareddir: tb %s host %s is_dir %s downtmp_host %s"
        % (tb, host, is_dir, downtmp_host)
    )

    host = os.path.normpath(host)
    tb = os.path.normpath(tb)
    downtmp_host = os.path.normpath(downtmp_host)

    timeout_start(copy_timeout)
    try:
        tb_tmp = None
        if tb.startswith(downtmp):
            # translate into host path
            tb = downtmp_host + tb[len(downtmp) :]
        else:
            tb_tmp = os.path.join(downtmp, os.path.basename(host))
            adtlog.debug(
                "copyup_shareddir: tb path %s is not already in "
                "downtmp, copying to %s" % (tb, tb_tmp)
            )
            check_exec(
                ["/bin/cp", "-r", "--preserve=timestamps,links", tb, tb_tmp], downp=True
            )
            # translate into host path
            tb = os.path.join(downtmp_host, os.path.basename(host))

        if tb == host:
            tb_tmp = None
        else:
            adtlog.debug(
                "copyup_shareddir: tb(host) %s is not already at "
                "destination %s, copying" % (tb, host)
            )
            if is_dir:
                copytree(tb, host)
            else:
                shutil.copy(tb, host)

        if tb_tmp:
            adtlog.debug("copyup_shareddir: rm intermediate copy: %s" % tb)
            check_exec(["/bin/rm", "-rf", tb_tmp], downp=True)
    finally:
        timeout_stop()


def copydown_shareddir(host, tb, is_dir, downtmp_host):
    adtlog.debug(
        "copydown_shareddir: host %s tb %s is_dir %s downtmp_host %s"
        % (host, tb, is_dir, downtmp_host)
    )

    host = os.path.normpath(host)
    tb = os.path.normpath(tb)
    downtmp_host = os.path.normpath(downtmp_host)

    timeout_start(copy_timeout)
    try:
        host_tmp = None
        if host.startswith(downtmp_host):
            # translate into tb path
            host = downtmp + host[len(downtmp_host) :]
        else:
            host_tmp = os.path.join(downtmp_host, os.path.basename(tb))
            if is_dir:
                if os.path.exists(host_tmp):
                    try:
                        shutil.rmtree(host_tmp)
                    except OSError as e:
                        adtlog.warning(
                            "cannot remove old %s, moving it "
                            "instead: %s" % (host_tmp, e)
                        )
                        # some undeletable files? hm, move it aside instead
                        counter = 0
                        while True:
                            p = host_tmp + ".old%i" % counter
                            if not os.path.exists(p):
                                os.rename(host_tmp, p)
                                break
                            counter += 1

                shutil.copytree(host, host_tmp, symlinks=True)
            else:
                shutil.copy(host, host_tmp)
            # translate into tb path
            host = os.path.join(downtmp, os.path.basename(tb))

        if host == tb:
            host_tmp = None
        else:
            check_exec(["/bin/rm", "-rf", tb], downp=True)
            check_exec(
                ["/bin/cp", "-r", "--preserve=timestamps,links", host, tb], downp=True
            )
        if host_tmp:
            (is_dir and shutil.rmtree or os.unlink)(host_tmp)
    finally:
        timeout_stop()


def copyupdown(c, ce, upp):
    cmdnumargs(c, ce, 2)
    copyupdown_internal(ce[0], c[1:], upp)


def copyupdown_internal(wh, sd, upp):
    """Copy up/down a file or dir.

    wh: 'copyup' or 'copydown'
    sd: (source, destination) paths
    upp: True for copyup, False for copydown
    """
    if not downtmp:
        bomb("%s when not open" % wh)
    if not sd[0] or not sd[1]:
        bomb("%s paths must be nonempty" % wh)
    dirsp = sd[0][-1] == "/"
    if dirsp != (sd[1][-1] == "/"):
        bomb(
            "%s paths must agree about directoryness"
            " (presence or absence of trailing /)" % wh
        )

    # if we have a shared directory, we just need to copy it from/to there; in
    # most cases, it's testbed end is already in the downtmp dir
    downtmp_host = get_downtmp_host()
    if downtmp_host:
        try:
            if upp:
                copyup_shareddir(sd[0], sd[1], dirsp, downtmp_host)
            else:
                copydown_shareddir(sd[0], sd[1], dirsp, downtmp_host)
            return
        except Timeout:
            raise FailedCmd(["timeout"])
        except (shutil.Error, subprocess.CalledProcessError) as e:
            adtlog.debug(
                "Cannot copy %s to %s through shared dir: %s, falling back to tar"
                % (sd[0], sd[1], str(e))
            )

    isrc = 0
    idst = 1
    ilocal = 0 + upp
    iremote = 1 - upp

    deststdout = subprocess.DEVNULL
    srcstdin = subprocess.DEVNULL
    remfileq = shlex.quote(sd[iremote])
    if not dirsp:
        rune = "cat %s%s" % ("><"[upp], remfileq)
        if upp:
            deststdout = open(sd[idst], "wb")
        else:
            srcstdin = open(sd[isrc], "rb")
            status = os.fstat(srcstdin.fileno())
            if status.st_mode & 0o111:
                rune += "; chmod +x -- %s" % (remfileq)
        localcmdl = ["cat"]
    else:
        taropts = [None, None]
        taropts[isrc] = "--warning=none -c ."
        taropts[idst] = (
            "--warning=none --preserve-permissions --extract --no-same-owner"
        )

        rune = "cd %s; tar %s -f -" % (remfileq, taropts[iremote])
        if upp:
            try:
                os.mkdir(sd[ilocal])
            except (IOError, OSError) as oe:
                if oe.errno != errno.EEXIST:
                    raise
        else:
            rune = (
                "if ! test -d %s; then mkdir -- %s; fi; " % (remfileq, remfileq)
            ) + rune

        localcmdl = ["tar", "--directory", sd[ilocal]] + (
            ("%s -f -" % taropts[ilocal]).split()
        )
    downcmdl = auxverb + ["sh", "-ec", rune]

    if upp:
        cmdls = (downcmdl, localcmdl)
    else:
        cmdls = (localcmdl, downcmdl)

    adtlog.debug(str(["cmdls", str(cmdls)]))
    adtlog.debug(str(["srcstdin", str(srcstdin), "deststdout", str(deststdout)]))

    subprocs = [None, None]
    adtlog.debug(" +< %s" % " ".join(cmdls[0]))
    subprocs[0] = subprocess.Popen(cmdls[0], stdin=srcstdin, stdout=subprocess.PIPE)
    adtlog.debug(" +> %s" % " ".join(cmdls[1]))
    subprocs[1] = subprocess.Popen(
        cmdls[1], stdin=subprocs[0].stdout, stdout=deststdout
    )
    subprocs[0].stdout.close()
    try:
        timeout_start(copy_timeout)
        for sdn in [1, 0]:
            adtlog.debug(" +" + "<>"[sdn] + "?")
            status = subprocs[sdn].wait()
            if not (status == 0 or (sdn == 0 and status == -13)):
                timeout_stop()
                adtlog.info(
                    "%s %s failed, status %d"
                    % (wh, ["source", "destination"][sdn], status)
                )
                raise FailedCmd(["copy-failed"])
        timeout_stop()
    except Timeout:
        for sdn in [1, 0]:
            subprocs[sdn].kill()
            subprocs[sdn].wait()
        raise FailedCmd(["timeout"])


def cmd_copydown(c, ce):
    copyupdown(c, ce, False)


def cmd_copyup(c, ce):
    copyupdown(c, ce, True)


def cmd_shell(c, ce):
    cmdnumargs(c, ce, 1, None)
    if not downtmp:
        bomb("`shell' when not open")
    # runners can provide a hook if they need a special treatment
    try:
        caller.hook_shell(*c[1:])
    except AttributeError:
        adtlog.debug("cmd_shell: using default shell command, dir %s" % c[1])
        cmd = 'cd "%s"; ' % c[1]
        for e in c[2:]:
            cmd += 'export "%s"; ' % e
        # use host's $TERM to provide a sane shell
        try:
            cmd += 'export TERM="%s"; ' % os.environ["TERM"]
        except KeyError:
            pass
        cmd += "bash -i"
        try:
            with open("/dev/tty", "rb") as sin:
                with open("/dev/tty", "wb") as sout:
                    with open("/dev/tty", "wb") as serr:
                        subprocess.call(
                            auxverb + ["sh", "-c", cmd],
                            stdin=sin,
                            stdout=sout,
                            stderr=serr,
                        )
        except (OSError, IOError) as e:
            adtlog.error("Cannot run shell: %s" % e)


def command():
    sys.stdout.flush()
    ce = sys.stdin.readline()
    if not ce:
        bomb("end of file - caller quit?")
    ce = ce.rstrip().split()
    c = list(map(url_unquote, ce))
    if not c:
        bomb("empty commands are not permitted")
    adtlog.debug("executing " + " ".join(ce))
    c_lookup = c[0].replace("-", "_")
    try:
        f = globals()["cmd_" + c_lookup]
    except KeyError:
        bomb("unknown command `%s'" % ce[0])
    try:
        r = f(c, ce)
        if not r:
            r = []
        r.insert(0, "ok")
    except FailedCmd as fc:
        r = fc.e
    print(" ".join(r))


signal_list = [signal.SIGHUP, signal.SIGTERM, signal.SIGINT, signal.SIGPIPE]


def sethandlers(f):
    for signum in signal_list:
        signal.signal(signum, f)


def cleanup():
    global downtmp, cleaning
    adtlog.debug("cleanup...")
    sethandlers(signal.SIG_DFL)
    # avoid recursion if something bomb()s in hook_cleanup()
    if not cleaning:
        cleaning = True
        if downtmp:
            caller.hook_cleanup()
        cleaning = False
        downtmp = None


def error_cleanup():
    try:
        ok = False
        try:
            cleanup()
            ok = True
        except Quit as q:
            sys.stderr.write(q.m)
            sys.stderr.write("\n")
        except Exception:
            sys.stderr.write("Unexpected cleanup error:\n")
            traceback.print_exc()
            sys.stderr.write("\n")
        if not ok:
            sys.stderr.write("while cleaning up because of another error:\n")
    except Exception:
        pass


def prepare():
    def handler(sig, *any):
        cleanup()
        os.kill(os.getpid(), sig)

    sethandlers(handler)


def cmd_auxverb_debug_fail(c, ce):
    cmdnumargs(c, ce)
    try:
        adtlog.info(caller.hook_debug_fail())
    except AttributeError:
        pass


def mainloop():
    global in_mainloop

    if (fcntl.fcntl(0, fcntl.F_GETFL) & os.O_NONBLOCK) != 0:
        # Some versions of autopkgtest-virt-* would try to cope
        # by sleeping 0.1 when they got EOF/EAGAIN.
        # But that causes us to hang, looping, when our caller goes away.
        #
        # Even though this is an egregious violation of Unix calling
        # conventions, and would be entirely the caller's fault,
        # detecting this situation and crashing is sensible.
        # Otherwise we would produce misleading error messages -
        # stdin.readline() returns '', not EAGAIN, which looks just like EOF.
        # (And in theory, we might read, and act on, partial commands!)
        bomb("stdin to autopkgtest virt server is nonblocking!")

    in_mainloop = True

    try:
        while True:
            command()
    except Quit as q:
        error_cleanup()
        if q.m:
            sys.stderr.write(q.m)
            sys.stderr.write("\n")
        sys.exit(q.ec)
    except Exception:
        error_cleanup()
        sys.stderr.write("Unexpected error:\n")
        traceback.print_exc()
        sys.exit(16)
    finally:
        in_mainloop = False


def main():
    ok()
    prepare()
    mainloop()