This file is indexed.

/usr/bin/adt-virt-lxc is in autopkgtest 3.6jessie1.

This file is owned by root:root, with mode 0o755.

The actual contents of the file can be viewed below.

  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
#!/usr/bin/python3
#
# adt-virt-lxc is part of autopkgtest
# autopkgtest is a tool for testing Debian binary packages
#
# autopkgtest is Copyright (C) 2006-2014 Canonical Ltd.
#
# adt-virt-lxc was derived from adt-virt-schroot and modified to suit LXC by
# Robie Basak <robie.basak@canonical.com>.
#
# 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 sys
import os
import string
import random
import subprocess
import time
import tempfile
import shutil
import argparse

try:
    our_base = os.environ['AUTOPKGTEST_BASE'] + '/lib'
except KeyError:
    our_base = '/usr/share/autopkgtest/python'
sys.path.insert(1, our_base)

import VirtSubproc
import adtlog


capabilities = ['revert', 'revert-full-system', 'root-on-testbed',
                'isolation-container']

args = None
lxc_container_name = None
normal_user = None
shared_dir = None


def parse_args():
    global args

    parser = argparse.ArgumentParser(fromfile_prefix_chars='@')

    parser.add_argument('-d', '--debug', action='store_true',
                        help='Enable debugging output')
    parser.add_argument('--eatmydata', action='store_true',
                        help='Use eatmydata inside the container to improve performance')
    parser.add_argument('-e', '--ephemeral', action='store_true',
                        help='Use ephemeral overlays instead of cloning (much '
                        'faster, but might cause errors in some corner cases)')
    parser.add_argument('-s', '--sudo', action='store_true',
                        help='Run lxc-* commands with sudo; use if you run '
                        'adt-run as normal user')
    parser.add_argument('template', help='LXC container name that will be '
                        'used as a template')
    args = parser.parse_args()
    if args.debug:
        adtlog.verbosity = 2


def sudoify(command):
    '''Prepend sudo to command with the --sudo option'''

    if args.sudo:
        return ['sudo'] + command
    else:
        return command


def check_for_eatmydata(container, template_name):
    with open('/dev/null', 'wb') as null:
        result = VirtSubproc.execute_timeout(
            None, 10, sudoify(['lxc-attach', '--name', container, '--', 'sh', '-c',
                               'type eatmydata']),
            close_fds=True, stdout=null, stderr=null)
    if result:
        raise RuntimeError(
            ('Container %s does not contain eatmydata, which is required '
             'for the --eatmydata option.' % repr(template_name))
        )


def get_available_lxc_container_name():
    '''Return an LXC container name that isn't already taken.

    There is a race condition between returning this name and creation of
    the container. Ideally lxc-start-ephemeral would generate a name in a
    race free way and return the name used in machine-readable way, so that
    this function would not be necessary. See LP: #1197754.
    '''
    while True:
        # generate random container name
        rnd = [random.choice(string.ascii_lowercase) for i in range(6)]
        candidate = 'adt-virt-lxc-' + ''.join(rnd)

        containers = VirtSubproc.check_exec(sudoify(['lxc-ls']), outp=True,
                                            timeout=10)
        if candidate not in containers:
            return candidate


def wait_booted(lxc_name):
    '''Wait until the container has sufficiently booted to interact with it

    Do this by checking that the runlevel is someting numeric, i. e. not
    "unknown" or "S".
    '''
    timeout = 60
    while timeout > 0:
        timeout -= 1
        time.sleep(1)
        (rc, out, _) = VirtSubproc.execute_timeout(
            None, 10, sudoify(['lxc-attach', '--name', lxc_name, 'runlevel']),
            stdout=subprocess.PIPE)
        if rc != 0:
            adtlog.debug('wait_booted: lxc-attach failed, retrying...')
            continue
        out = out.strip()
        if out.split()[-1].isdigit():
            return

        adtlog.debug('wait_booted: runlevel "%s", retrying...' % out)

    VirtSubproc.bomb('timed out waiting for container %s to start; '
                     'last runlevel "%s"' % (lxc_name, out))


def determine_normal_user(lxc_name):
    '''Check for a normal user to run tests as.'''

    global capabilities, normal_user

    # get the first UID >= 500
    cmd = ['lxc-attach', '--name', lxc_name, '--', 'sh', '-c',
           'getent passwd | sort -t: -nk3 | '
           "awk -F: '{if ($3 >= 500) { print $1; exit } }'"]
    out = VirtSubproc.execute_timeout(None, 10, sudoify(cmd),
                                      stdout=subprocess.PIPE)[1].strip()
    if out:
        normal_user = out
        capabilities.append('suggested-normal-user=' + normal_user)
        adtlog.debug('determine_normal_user: got user "%s"' % normal_user)
    else:
        adtlog.debug('determine_normal_user: no uid >= 500 available')


def hook_open():
    global args, lxc_container_name, shared_dir

    lxc_container_name = get_available_lxc_container_name()
    adtlog.debug('using container name %s' % lxc_container_name)
    if shared_dir is None:
        shared_dir = tempfile.mkdtemp(prefix='adt-virt-lxc.shared.')
    else:
        # don't change the name between resets, to provide stable downtmp paths
        os.makedirs(shared_dir)
    os.chmod(shared_dir, 0o755)
    if args.ephemeral:
        VirtSubproc.check_exec(sudoify(
            ['lxc-start-ephemeral', '--name', lxc_container_name,
             '--keep-data', '--daemon', '--bdir', shared_dir,
             '--orig', args.template]), outp=True)
        # work around https://launchpad.net/bugs/1367730
        VirtSubproc.check_exec(sudoify([
            'lxc-attach', '--name', lxc_container_name, '--', 'chmod', 'go+rx', '/']),
            timeout=30)
    else:
        VirtSubproc.check_exec(sudoify(
            ['lxc-clone', '--new', lxc_container_name, '--orig', args.template]), outp=True)
        VirtSubproc.check_exec(sudoify(
            ['lxc-start', '--name', lxc_container_name, '--daemon',
             '--define', 'lxc.mount.entry=%s %s none bind,create=dir 0 0' % (shared_dir, shared_dir[1:])]))
    try:
        adtlog.debug('waiting for lxc guest start')
        wait_booted(lxc_container_name)
        adtlog.debug('lxc guest started')
        determine_normal_user(lxc_container_name)
        # provide a minimal and clean environment in the container
        VirtSubproc.auxverb = [
            'lxc-attach', '--name', lxc_container_name, '--',
            'env', '-i', 'sh', '-ac',
            '[ -r /etc/environment ] && . /etc/environment 2>/dev/null || true; '
            '[ -r /etc/default/locale ] && . /etc/default/locale 2>/dev/null || true; '
            '[ -r /etc/profile ] && . /etc/profile 2>/dev/null || true; '
            'exec "$@"', '--'
        ]
        if args.sudo:
            VirtSubproc.auxverb = ['sudo', '--preserve-env'] + VirtSubproc.auxverb
        if args.eatmydata:
            check_for_eatmydata(lxc_container_name, args.template)
            VirtSubproc.auxverb.extend(['eatmydata', '--'])
    except:
        # Clean up on failure
        VirtSubproc.check_exec(sudoify(['lxc-stop', '--name', lxc_container_name]))
        VirtSubproc.check_exec(sudoify(['lxc-destroy', '--name', lxc_container_name]))
        raise


def hook_downtmp(path):
    global capabilities, shared_dir

    if shared_dir:
        d = os.path.join(shared_dir, 'downtmp')
        # these permissions are ugly, but otherwise we can't clean up files
        # written by the testbed when running as user
        VirtSubproc.check_exec(['mkdir', '-m', '777', d], downp=True)
        capabilities.append('downtmp-host=' + d)
    else:
        d = VirtSubproc.downtmp_mktemp(path)
    return d


def hook_revert():
    hook_cleanup()
    hook_open()


def hook_cleanup():
    global capabilities, shared_dir

    VirtSubproc.downtmp_remove()
    capabilities = [c for c in capabilities if not c.startswith('downtmp-host')]
    if shared_dir:
        shutil.rmtree(shared_dir)

    VirtSubproc.check_exec(sudoify(['lxc-stop', '--name', lxc_container_name]))
    VirtSubproc.check_exec(sudoify(['lxc-destroy', '--name', lxc_container_name]))


def hook_forked_inchild():
    pass


def hook_capabilities():
    return capabilities


parse_args()
VirtSubproc.main()