chiark / gitweb /
* adt-xenlvm-with-testbed: sleep 1 after xm destroy, which is racy.
[autopkgtest.git] / runner / adt-run
index 8873757bb00bbf3336b50896b11bb2761dd9a384..7787e5761971fb566993e8e87bd40058ed5d01b4 100755 (executable)
@@ -45,6 +45,7 @@ signal.signal(signal.SIGINT, signal.SIG_DFL) # undo stupid Python SIGINT thing
 tmpdir = None          # pathstring on host
 testbed = None         # Testbed
 errorcode = 0          # exit status that we are going to use
+timeouts = { 'short':100, 'install':3000, 'test':10000, 'build':100000 }
 binaries = None                # Binaries (.debs we have registered)
 build_essential = ["build-essential"]
 
@@ -88,7 +89,7 @@ def pstderr(m):
 def debug(m, minlevel=0):
        if opts.debuglevel < minlevel: return
        if opts.quiet and trace_stream is None: return
-       p = 'adt-run: debug'
+       p = 'adt-run: trace'
        if minlevel: p += `minlevel`
        p += ': '
        for l in m.rstrip('\n').split('\n'):
@@ -113,7 +114,7 @@ class Errplumb:
                ep.stream = open('/dev/null','w')
                ep._sp = None
        elif count == 1:
-               if to_stderr: ep.stream = sys.stderr
+               if to_stderr: ep.stream = os.dup(2)
                else: ep.stream = trace_stream
                ep._sp = None
        else:
@@ -123,6 +124,9 @@ class Errplumb:
                ep.stream = ep._sp.stdin
  def wait(ep):
        if ep._sp is None: return
+       if type(ep.stream) == type(2):
+               os.close(ep.stream)
+               ep.stream = ()
        ep._sp.stdin.close()
        rc = ep._sp.wait()
        if rc: bomb('stderr plumbing tee(1) failed, exit code %d' % rc)
@@ -179,12 +183,14 @@ class Unsupported:
 def mkdir_okexist(pathname, mode=02755):
        try:
                os.mkdir(pathname, mode)
-       except OSError, oe:
+       except (IOError,OSError), oe:
                if oe.errno != errno.EEXIST: raise
 
 def rmtree(what, pathname):
        debug('/ %s rmtree %s' % (what, pathname), 2)
-       shutil.rmtree(pathname)
+       try: shutil.rmtree(pathname)
+       except (IOError,OSError), oe:
+               if oe.errno != errno.EEXIST: raise
 
 def debug_subprocess(what, cmdl=None, script=None):
        o = '$ '+what+':'
@@ -402,7 +408,7 @@ class Action:
        return "<Action %s %s %s>" % (a.kind, a.what, `a.af`)
 
 def parse_args():
-       global opts
+       global opts, timeouts
        global n_non_actions # argh, stupid python scoping rules
        usage = "%prog <options> --- <virt-server>..."
        parser = OptionParser(usage=usage)
@@ -415,7 +421,8 @@ def parse_args():
                'deb_forbuilds': 'auto',
                'deb_fortests': 'auto',
                'tb': False,
-               'override_control': None
+               'override_control': None,
+               'set_lang': 'C'
        }
        initial_arghandling = arghandling.copy()
        n_non_actions = 0
@@ -447,6 +454,15 @@ def parse_args():
               help='use binary package DEB according'
                    ' to most recent --binaries-* settings')
 
+       def cb_actnoarg(op,optstr,value,parser, largsentry):
+               parser.largs.append(largsentry)
+       pa('','--instantiate', action='callback', callback=cb_actnoarg,
+               callback_args=((None, ('instantiate',)),),
+               help='instantiate testbed now (during testing phase)'
+                    ' and install packages'
+                    ' selected for automatic installation, even'
+                    ' if this might apparently not be required otherwise')
+
        pa_action('override-control',   'CONTROL', ('control',), is_act=0,
               help='run tests from control file CONTROL instead,'
                    ' (applies to next test suite only)')
@@ -494,7 +510,6 @@ def parse_args():
                     ' according to most recent --binaries-* settings')
        pa_setah('--no-built-binaries', ['dsc_filter'], '_',
                help='from subsequent sources, do not use any binaries')
-
        #---- binary package processing settings:
 
        def pa_setahbins(long,toset,how):
@@ -528,6 +543,11 @@ def parse_args():
        pa_path('output-dir', OutputDir, dir=True,
                help='write stderr/out files in PATH')
 
+       pa('--leave-lang', dest='set_lang', action='store_false',
+               help="leave LANG on testbed set to testbed's default")
+       pa('--set-lang', dest='set_lang', action='store', metavar='LANGVAL',
+               help='set LANG on testbed to LANGVAL', default='C')
+
        pa('','--tmp-dir',              type='string', dest='tmpdir',
                help='write temporary files to TMPDIR, emptying it'
                     ' beforehand and leaving it behind at the end')
@@ -538,6 +558,13 @@ def parse_args():
                help='write a summary report to SUMMARY,'
                     ' emptying it beforehand')
 
+       for k in timeouts.keys():
+               pa('','--timeout-'+k,   type='int', dest='timeout_'+k,
+                       metavar='T', help='set %s timeout to T')
+       pa('','--timeout-factor',       type='float', dest='timeout_factor',
+                       metavar='FACTOR', default=1.0,
+                       help='multiply all default timeouts by FACTOR')
+
        pa('','--user',                 type='string', dest='user',
                help='run tests as USER (needs root on testbed)')
        pa('','--gain-root',            type='string', dest='gainroot',
@@ -574,6 +601,11 @@ def parse_args():
        if n_non_actions >= len(parser.largs):
                parser.error('nothing to do specified')
 
+       for k in timeouts.keys():
+               t = getattr(opts,'timeout_'+k)
+               if t is None: t = timeouts[k] * opts.timeout_factor
+               timeouts[k] = int(t)
+
        arghandling = initial_arghandling
        opts.actions = []
        ix = 0
@@ -600,15 +632,17 @@ def parse_args():
                elif kindpath.endswith('/'):
                        kind = 'tree'
                        constructor = InputDir
-               else: parser.error("do not know how to handle filename \`%s';"
-                       " specify --source --binary or --build-tree")
+               else: parser.error("do not know how to handle filename `%s';"
+                       " specify --source --binary or --build-tree" %
+                       kindpath)
 
                what = '%s%s' % (kind,ix); ix += 1
 
                if kind == 'dsc': fwhatx = '/' + os.path.basename(pathstr)
                else: fwhatx = '-'+kind
 
-               af = constructor(what+fwhatx, pathstr, arghandling['tb'])
+               if pathstr is None: af = None
+               else: af = constructor(what+fwhatx, pathstr, arghandling['tb'])
                opts.actions.append(Action(kind, af, arghandling, what))
 
 def setup_trace():
@@ -632,7 +666,7 @@ def setup_trace():
        if opts.summary is not None:
                summary_stream = open(opts.summary, 'w', 0)
 
-       debug('options: '+`opts`, 1)
+       debug('options: '+`opts`+'; timeouts: '+`timeouts`, 1)
 
 def finalise_options():
        global opts, tb, build_essential
@@ -726,8 +760,8 @@ class Testbed:
  def reset_apt(tb):
        if not tb._need_reset_apt: return
        what = 'aptget-update-reset'
-       cmdl = ['apt-get','-qy','update']
-       rc = tb.execute(what, cmdl)
+       cmdl = ['sh','-c','apt-get -qy update 2>&1']
+       rc = tb.execute(what, cmdl, kind='install')
        if rc:
                pstderr("\n" "warning: failed to restore"
                        " testbed apt cache, exit code %d" % rc)
@@ -771,7 +805,8 @@ class Testbed:
                ]])
        cmdl = ['python','-c',script]
        what = 'install-deps'
-       rc = testbed.execute(what+'-debinstall', cmdl, script=script)
+       rc = testbed.execute(what+'-debinstall', cmdl, script=script,
+                               kind='install')
        if rc: badpkg('dependency install failed, exit code %d' % rc)
  def needs_reset(tb):
        tb._debug('needs_reset, previously=%s' % tb.modified, 1)
@@ -838,7 +873,7 @@ class Testbed:
        return rl[0]
  def execute(tb, what, cmdl,
                si='/dev/null', so='/dev/null', se=None, cwd=None,
-               script=False, tmpdir=None):
+               script=False, tmpdir=None, kind='short'):
        # Options for script:
        #   False - do not call debug_subprocess, no synch. reporting required
        #   None or string - call debug_subprocess with that value,
@@ -847,6 +882,8 @@ class Testbed:
        #   None - usual Errplumb (output is of kind 2c)
        #   string - path on testbed (output is of kind 2d)
 
+       timeout = timeouts[kind]
+
        if script is not False: debug_subprocess(what, cmdl, script=script)
        if cwd is None: cwd = tb.scratch.write(True)
 
@@ -867,8 +904,14 @@ class Testbed:
                ','.join(map(urllib.quote, cmdl)),
                si, so, se_use, cwd]
 
+       if timeout is not None and timeout > 0:
+               cmdl.append('timeout=%d' % timeout)
+
        if xdump is not None and 'execute-debug' in tb.caps: cmdl += [xdump]
        if tmpdir is not None: cmdl.append('env=TMPDIR=%s' % tmpdir)
+       if kind=='install': cmdl.append('env=DEBIAN_FRONTEND=noninteractive')
+       if opts.set_lang is not False:
+               cmdl.append('env=LANG=%s' % opts.set_lang)
 
        rc = tb.commandr1('execute', cmdl)
        try: rc = int(rc)
@@ -1029,7 +1072,8 @@ class Test:
                        use_dir = testbed.scratch
                return RelativeOutputFile(idstr, use_dir, idstr)
 
-       t.act.work.write(True)
+       if hasattr(t.act,'work'): t.act.work.write(True)
+       tree.read(True)
 
        af = RelativeInputFile(t.what, tree, t.path)
        so = stdouterr('stdout')
@@ -1037,7 +1081,6 @@ class Test:
 
        tf = af.read(True)
        tmpdir = None
-       tree.read(True)
 
        rc = testbed.execute('testchmod-'+t.what, ['chmod','+x','--',tf])
        if rc: bomb('failed to chmod +x %s' % tf)
@@ -1058,7 +1101,7 @@ class Test:
 
        rc = testbed.execute('test-'+t.what, tfl,
                so=so.write(True), se=se.write(True), cwd=tree.read(True),
-               tmpdir=tmpdir)
+               tmpdir=tmpdir, kind='test')
 
        so_read = so.read()
        se_read = se.read()
@@ -1097,7 +1140,7 @@ def read_control(act, tree, control_override):
                        tree, 'debian/tests/control')
        try:
                control = open(control_af.read(), 'r')
-       except OSError, oe:
+       except (IOError,OSError), oe:
                if oe[0] != errno.ENOENT: raise
                return []
 
@@ -1194,13 +1237,11 @@ def print_exception(ei, msgprefix=''):
 def cleanup():
        global trace_stream
        try:
-               rm_ec = 0
-               if opts.tmpdir is None and tmpdir is not None:
-                       rmtree('tmpdir', tmpdir)
                if testbed is not None:
                        testbed.reset_apt()
                        testbed.stop()
-               if rm_ec: bomb('rm -rf -- %s failed, code %d' % (tmpdir, ec))
+               if opts.tmpdir is None and tmpdir is not None:
+                       rmtree('tmpdir', tmpdir)
                if trace_stream is not None:
                        trace_stream.close()
                        trace_stream = None
@@ -1238,7 +1279,7 @@ class Binaries:
                for x in ['pubring','secring']:
                        os.stat(opts.gnupghome + '/' + x + '.gpg')
                ok = True
-       except OSError, oe:
+       except (IOError,OSError), oe:
                if oe.errno != errno.ENOENT: raise
 
        if ok: b._debug('no key generation needed')
@@ -1268,18 +1309,13 @@ END
   gpg --homedir="$1" --batch --gen-key key-gen-params
                '''
        cmdl = ['sh','-ec',script,'x',opts.gnupghome]
-       rc = subprocess_cooked(cmdl, dbg=(genkey,script))[0]
-       if rc:
-               try:
-                       f = open(opts.gnupghome+'/key-gen-log')
-                       tp = file.read()
-               except OSError, e: tp = e
-               pstderr(tp)
-               bomb('key generation failed, code %d' % rc)
+       rc = subprocess_cooked(cmdl, dbg=('genkey',script))[0]
+       if rc: bomb('key generation failed, code %d' % rc)
 
  def apt_configs(b):
        return {
                "Dir::Etc::sourcelist": b.dir.read(True)+'sources.list',
+               "Debug::pkgProblemResolver": "true",
        }
 
  def apt_pkg_gdebi_script(b, arg, middle):
@@ -1312,7 +1348,7 @@ END
        ag = ['apt-get','-qy']
        for kv in b.apt_configs().iteritems():
                ag += ['-o', '%s=%s' % kv]
-       return ag
+       return ' '.join(ag)
 
  def reset(b):
        b._debug('reset')
@@ -1335,11 +1371,11 @@ END
        dest = RelativeOutputFile('binaries--'+leafname, b.dir, leafname)
 
        try: os.remove(dest.write())
-       except OSError, oe:
+       except (IOError,OSError), oe:
                if oe.errno != errno.ENOENT: raise e
 
        try: os.link(af.read(), dest.write())
-       except OSError, oe:
+       except (IOError,OSError), oe:
                if oe.errno != errno.EXDEV: raise e
                shutil.copy(af.read(), dest)
 
@@ -1377,13 +1413,13 @@ END
   if [ "x`ls /var/lib/dpkg/updates`" != x ]; then
     echo >&2 "/var/lib/dpkg/updates contains some files, aargh"; exit 1
   fi
-  '''+ ' '.join(b.apt_get()) +''' update >&2
+  '''+ b.apt_get() +''' update >&2
   cat /var/lib/dpkg/status >&3
                '''
        testbed.mungeing_apt()
        rc = testbed.execute('apt-key', ['sh','-ec',script],
                                so=so.write(True), cwd=b.dir.write(True),
-                               script=script)
+                               script=script, kind='install')
        if rc: bomb('apt setup failed with exit code %d' % rc)
 
        testbed.blamed += b.blamed
@@ -1402,9 +1438,10 @@ END
        if pkgs_reinstall:
                for pkg in pkgs_reinstall: testbed.blame(pkg)
                what = 'apt-get-reinstall'
-               cmdl = (b.apt_get() + ['--reinstall','install'] +
-                       [pkg for pkg in pkgs_reinstall])
-               rc = testbed.execute(what, cmdl, script=None)
+               cmdl = (b.apt_get() + ' --reinstall install '+
+                       ' '.join([pkg for pkg in pkgs_reinstall])+' >&2')
+               cmdl = ['sh','-c',cmdl]
+               rc = testbed.execute(what, cmdl, script=None, kind='install')
                if rc: badpkg("installation of basic binarries failed,"
                                " exit code %d" % rc)
 
@@ -1412,8 +1449,9 @@ END
        for pkg in b.install:
                what = 'apt-get-install-%s' % pkg
                testbed.blame(pkg)
-               cmdl = b.apt_get() + ['install',pkg]
-               rc = testbed.execute(what, cmdl, script=None)
+               cmdl = b.apt_get() + ' install ' + pkg + ' >&2'
+               cmdl = ['sh','-c',cmdl]
+               rc = testbed.execute(what, cmdl, script=None, kind='install')
                if rc: badpkg("installation of %s failed, exit code %d"
                                % (pkg, rc))
 
@@ -1429,7 +1467,7 @@ def source_rules_command(act,script,what,which,work,cwd,
        so = TemporaryFile('%s-%s-results' % (what,which))
        rc = testbed.execute('%s-%s' % (what,which),
                        ['sh','-ec',script]+xargs, script=script,
-                       so=so.write(True), cwd=cwd)
+                       so=so.write(True), cwd=cwd, kind='build')
        results = open(so.read()).read().rstrip('\n')
        if len(results): results = results.split("\n")
        else: results = []
@@ -1499,7 +1537,7 @@ def build_source(act, control_override):
                        ]])
                cmdl = ['python','-c',script]
                whatp = what+'-dpkgsource'
-               rc = testbed.execute(what, cmdl, script=script)
+               rc = testbed.execute(what, cmdl, script=script, kind='install')
                if rc: badpkg('dpkg-source install failed, exit code %d' % rc)
 
        work = TemporaryDir(what+'-build')
@@ -1545,7 +1583,7 @@ def build_source(act, control_override):
                        [ create_command ])
 
        script += [
-                       'cd */.',
+                       'cd [a-z0-9]*-*/.',
                        'pwd >&3',
                        'set +e; test -f debian/tests/control; echo $? >&3'
                ]
@@ -1610,7 +1648,7 @@ def build_source(act, control_override):
 
                cmdl = ['python','-c',script]
                whatp = what+'-builddeps'
-               rc = testbed.execute(what, cmdl, script=script)
+               rc = testbed.execute(what, cmdl, script=script, kind='install')
                if rc: badpkg('build-depends install failed,'
                              ' exit code %d' % rc)
 
@@ -1644,7 +1682,7 @@ def build_source(act, control_override):
        debug_b('filter=%s' % filter)
        if filter != '_':
                script = tmpdir_script + [
-                       'cd '+work.write(True)+'/*/.',
+                       'cd '+work.write(True)+'/[a-z0-9]*-*/.',
                        opts.user_wrap(opts.gainroot+' debian/rules binary'),
                        'cd ..',
                        'echo *.deb >&3',
@@ -1652,7 +1690,7 @@ def build_source(act, control_override):
                result_debs = source_rules_command(act,script,what,
                                'binary',work,work.write(True),
                                results_lines=1, xargs=['x',tmpdir])
-               if result_debs == '*': debs = []
+               if result_debs == '*.deb': debs = []
                else: debs = result_debs.split(' ')
                debug_b('debs='+`debs`)
                re = regexp.compile('^([-+.0-9a-z]+)_[^_/]+(?:_[^_/]+)\.deb$')
@@ -1690,7 +1728,7 @@ def process_actions():
        binaries = Binaries()
 
        for act in opts.actions:
-               if not act.af.spec_tbp:
+               if act.af is not None and not act.af.spec_tbp:
                        testbed.register_ephemeral(act.af)
 
        binaries.reset()
@@ -1715,6 +1753,8 @@ def process_actions():
                        act.binaries = []
                if act.kind.endswith('tree') or act.kind == 'dsc':
                        control_override = None
+               if act.kind == 'instantiate':
+                       pass
 
        debug_a1('builds done.')
 
@@ -1750,6 +1790,8 @@ def process_actions():
                        debug_a3('run_tests ...')
                        run_tests(stanzas, act.af)
                        control_override = None
+               if act.kind == 'instantiate':
+                       testbed.prepare([])
        debug_a1('tests done.')
 
 def main():