chiark / gitweb /
get adtxenu username right; suppress debug properly when !--debug
[autopkgtest.git] / runner / adt-run
index 86189e03b26468737ee7df970e4c0038594cd76b..d329d00ee48f13014416c723c074901eadbde6f5 100755 (executable)
@@ -35,6 +35,7 @@ import os
 import errno
 import fnmatch
 import shutil
+import copy
 
 from optparse import OptionParser
 signal.signal(signal.SIGINT, signal.SIG_DFL) # undo stupid Python SIGINT thing
@@ -77,6 +78,12 @@ def debug(m):
        for l in m.rstrip('\n').split('\n'):
                print >>sys.stderr, 'atd-run: debug:', l
 
+def mkdir_okexist(pathname, mode=02755):
+       try:
+               os.mkdir(pathname, mode)
+       except OSError, oe:
+               if oe.errno != errno.EEXIST: raise
+
 def rmtree(what, pathname):
        debug('/ %s rmtree %s' % (what, pathname))
        shutil.rmtree(pathname)
@@ -118,19 +125,18 @@ class AutoFile:
 
  def __str__(p):
        def ptbp(tbp):
-               if p.path[tbp] is None: out = '-'
-               elif p.file[tbp] is None: out = '?'+p.path[tbp]
-               else: out = '!'+p.path[tbp]
-               out += p.dir
-               return out
+               if p.path[tbp] is None: return '-'+p.dir
+               elif p.file[tbp] is None: return p.path[tbp]+p.dir+'?'
+               else: return p.path[tbp]+p.dir+'!'
        out = p.what
+       if p.spec is not None:
+               if p.spec_tbp: out += '#'
+               else: out += '='
+               out += p.spec
+       out += ':'
        out += ptbp(False)
        out += '|'
        out += ptbp(True)
-       if p.spec is not None:
-               if p.spec_tbp: out += '>'
-               else: out += '<'
-               out += p.spec
        return out
 
  def _wrong(p, how):
@@ -155,9 +161,7 @@ class AutoFile:
        if p.dir and not p.file[tbp]:
                if not tbp:
                        p._debug('mkdir H')
-                       try: os.mkdir(p.path[tbp])
-                       except OSError, oe:
-                               if oe.errno != errno.EEXIST: raise
+                       mkdir_okexist(p.path[tbp])
                else:
                        cmdl = ['sh','-ec',
                                'test -d "$1" || mkdir "$1"',
@@ -183,17 +187,7 @@ class AutoFile:
                testbed.command(cud, (src, dst))
                p.file[tbp] = p.path[tbp]
 
-       return p.file[tbp]
-
- def subpath(p, what, leaf, constructor):
-       p._debug('subpath %s /%s %s...' % (what, leaf, `constructor`))
-       if not p.dir: p._wrong("creating subpath of non-directory")
-       return constructor(what, p.spec+p.dir+leaf, p.spec_tbp)
- def sibling(p, what, leaf, constructor):
-       p._debug('sibling what=%s leaf=%s %s...' % (what, leaf, `constructor`))
-       dir = os.path.dirname(p.spec)
-       if dir: dir += '/'
-       return constructor(what, dir+leaf, p.spec_tbp)
+       return p.file[tbp] + p.dir
 
  def invalidate(p, tbp=False):
        p.file[tbp] = None
@@ -218,12 +212,32 @@ class AutoFile:
                        bomb("directory `%s' specified for "
                             "non-directory %s" % (pf[tbp], p.what))
 
+ def _relative_init(p, what, parent, leaf, onlyon_tbp, setfiles, sibling):
+       AutoFile.__init__(p,what)
+       sh_on = ''; sh_sibl = ''
+       if onlyon_tbp is not None: sh_on = ' (on %s)' % ('HT'[onlyon_tbp])
+       if sibling: sh_sibl=' (sibling)'
+       parent._debug('using as base: %s: %s%s%s' %
+                       (str(parent), leaf, sh_on, sh_sibl))
+       if not sibling and not parent.dir:
+               parent._wrong('asked for non-sibling relative path of non-dir')
+       if sibling: trim = os.path.dirname
+       else: trim = lambda x: x
+       for tbp in [False,True]:
+               if parent.path[tbp] is None: continue
+               trimmed = trim(parent.path[tbp])
+               if trimmed: trimmed += '/'
+               p.path[tbp] = trimmed + leaf
+               if setfiles and (onlyon_tbp is None or onlyon_tbp == tbp):
+                       p.file[tbp] = p.path[tbp]
+
 class InputFile(AutoFile):
  def _init(p, what, spec, spec_tbp=False):
        AutoFile.__init__(p, what)
        p.spec = spec
        p.spec_tbp = spec_tbp
-       p.path[spec_tbp] = p.file[spec_tbp] = spec
+       p.path[spec_tbp] = spec
+       p.file[p.spec_tbp] = p.path[p.spec_tbp]
  def __init__(p, what, spec, spec_tbp=False):
        p._init(what,spec,spec_tbp)
        p._constructed()
@@ -250,6 +264,16 @@ class OutputDir(OutputFile):
        p.dir = '/'
        p._constructed()
 
+class RelativeInputFile(AutoFile):
+ def __init__(p, what, parent, leaf, onlyon_tbp=None, sibling=False):
+       p._relative_init(what, parent, leaf, onlyon_tbp, True, sibling)
+       p._constructed()
+
+class RelativeOutputFile(AutoFile):
+ def __init__(p, what, parent, leaf, sibling=False):
+       p._relative_init(what, parent, leaf, None, False, sibling)
+       p._constructed()
+
 class TemporaryFile(AutoFile):
  def __init__(p, what):
        AutoFile.__init__(p, what)
@@ -468,7 +492,15 @@ def parse_args():
                opts.actions.append(Action(kind, af, arghandling, what))
 
 def finalise_options():
-       global opts, tb
+       global opts, tb, tmpdir
+
+       if opts.tmpdir is not None:
+               rmtree('tmpdir(specified)',opts.tmpdir)
+               mkdir_okexist(opts.tmpdir, 0700)
+               tmpdir = opts.tmpdir
+       else:
+               assert(tmpdir is None)
+               tmpdir = tempfile.mkdtemp()
 
        if opts.user is None and 'root-on-testbed' not in testbed.caps:
                opts.user = ''
@@ -476,7 +508,7 @@ def finalise_options():
        if opts.user is None:
                su = 'suggested-normal-user='
                ul = [
-                       e[length(su):]
+                       e[len(su):]
                        for e in testbed.caps
                        if e.startswith(su)
                        ]
@@ -519,7 +551,11 @@ class Testbed:
        tb.scratch = None
        tb.modified = False
        tb.blamed = []
+       tb._debug('init')
+ def _debug(tb, m):
+       debug('** '+m)
  def start(tb):
+       tb._debug('start')
        p = subprocess.PIPE
        debug_subprocess('vserver', opts.vserver)
        tb.sp = subprocess.Popen(opts.vserver,
@@ -527,6 +563,7 @@ class Testbed:
        tb.expect('ok')
        tb.caps = tb.commandr('capabilities')
  def stop(tb):
+       tb._debug('stop')
        tb.close()
        if tb.sp is None: return
        ec = tb.sp.returncode
@@ -538,25 +575,32 @@ class Testbed:
        if ec:
                tb.bomb('testbed gave exit status %d after quit' % ec)
  def open(tb):
+       tb._debug('open, scratch=%s' % tb.scratch)
        if tb.scratch is not None: return
        pl = tb.commandr('open')
        tb.scratch = InputDir('tb-scratch', pl[0], True)
  def close(tb):
+       tb._debug('close, scratch=%s' % tb.scratch)
        if tb.scratch is None: return
        tb.scratch = None
        if tb.sp is None: return
        tb.command('close')
  def prepare(tb):
+       tb._debug('prepare, modified=%s' % tb.modified)
        if tb.modified and 'reset' in tb.caps:
+               tb._debug('reset **')
                tb.command('reset')
                tb.blamed = []
        tb.modified = False
        binaries.publish()
  def needs_reset(tb):
+       tb._debug('needs_reset, previously=%s' % tb.modified)
        tb.modified = True
  def blame(tb, m):
+       tb._debug('blame += %s' % m)
        tb.blamed.append(m)
  def bomb(tb, m):
+       tb._debug('bomb %s' % m)
        if tb.sp is not None:
                tb.sp.stdout.close()
                tb.sp.stdin.close()
@@ -613,15 +657,18 @@ class Testbed:
        rl = tb.commandr(cmd, args, 1)
        return rl[0]
  def execute(tb, what, cmdargs,
-               si='/dev/null', so='/dev/null', se=None, cwd=None):
+               si='/dev/null', so='/dev/null', se=None, cwd=None,
+               dump_fd=None):
        if cwd is None: cwd = tb.scratch.write(True)
        se_use = se
        if se_use is None:
                se_af = TemporaryFile('xerr-'+what)
                se_use = se_af.write(True)
-       rc = tb.commandr1('execute', [None,
-                               ','.join(map(urllib.quote, cmdargs)),
-                               si, so, se_use, cwd])
+       cmdl = [None,
+               ','.join(map(urllib.quote, cmdargs)),
+               si, so, se_use, cwd]
+       if dump_fd is not None: cmdl += ['debug=%d-%d' % (dump_fd,2)]
+       rc = tb.commandr1('execute', cmdl)
        try: rc = int(rc)
        except ValueError: bomb("execute for %s gave invalid response `%s'"
                                        % (what,rc))
@@ -658,6 +705,7 @@ class FieldIgnore(FieldBase):
 class Restriction:
  def __init__(r,rname,base): pass
 
+class Restriction_rw_build_tree(Restriction): pass
 class Restriction_rw_tests_tree(Restriction): pass
 class Restriction_breaks_testbed(Restriction):
  def __init__(r, rname, base):
@@ -685,8 +733,8 @@ class Field_Tests_directory(FieldBase):
                'Tests-Directory may not be absolute')
        base['testsdir'] = td
 
-def run_tests(stanzas):
-       global errorcode
+def run_tests(stanzas, tree):
+       global errorcode, testbed
        for stanza in stanzas:
                tests = stanza[' tests']
                if not tests:
@@ -694,7 +742,7 @@ def run_tests(stanzas):
                        errorcode |= 8
                for t in tests:
                        testbed.prepare()
-                       t.run()
+                       t.run(tree)
                        if 'breaks-testbed' in t.restrictions:
                                testbed.needs_reset()
                testbed.needs_reset()
@@ -705,30 +753,30 @@ class Test:
                'test name may not contain / character')
        for k in base: setattr(t,k,base[k])
        t.tname = tname
-       t.what = act_what+'-'+tname
-       if len(base['testsdir']): tpath = base['testsdir'] + '/' + tname
-       else: tpath = tname
-       t.af = opts.tests_tree.subpath('test-'+tname, tpath, InputFile)
+       t.what = act_what+'t-'+tname
+       if len(base['testsdir']): t.path = base['testsdir'] + '/' + tname
+       else: t.path = tname
  def report(t, m):
        report(t.what, m)
  def reportfail(t, m):
        global errorcode
        errorcode |= 4
        report(t.what, 'FAIL ' + m)
- def run(t):
+ def run(t, tree):
        def stdouterr(oe):
-               idstr = oe + '-' + t.what
+               idstr = t.what + '-' + oe
                if opts.output_dir is not None and opts.output_dir.tb:
                        use_dir = opts.output_dir
                else:
                        use_dir = testbed.scratch
-               return use_dir.subpath(idstr, idstr, OutputFile)
+               return RelativeOutputFile(idstr, use_dir, idstr)
 
+       af = RelativeInputFile(t.what, tree, t.path)
        so = stdouterr('stdout')
        se = stdouterr('stderr')
        rc = testbed.execute('test-'+t.what,
-               [opts.user_wrap(t.af.read(True))],
-               so=so, se=se, cwd=opts.tests_tree.write(True))
+               [opts.user_wrap(af.read(True))],
+               so=so.write(True), se=se.write(True), cwd=tree.write(True))
                        
        stab = os.stat(se.read())
        if stab.st_size != 0:
@@ -748,9 +796,8 @@ def read_control(act, tree, control_override):
                control_af = control_override
                testbed.blame('arg:'+control_override.spec)
        else:
-               control_af = tree.subpath(act.what+'-testcontrol',
-                       'debian/tests/control', InputFile)
-
+               control_af = RelativeInputFile(act.what+'-testcontrol',
+                       tree, 'debian/tests/control')
        try:
                control = file(control_af.read(), 'r')
        except OSError, oe:
@@ -842,7 +889,7 @@ def print_exception(ei, msgprefix=''):
 def cleanup():
        try:
                rm_ec = 0
-               if tmpdir is not None:
+               if opts.tmpdir is None and tmpdir is not None:
                        rmtree('tmpdir', tmpdir)
                if testbed is not None:
                        testbed.stop()
@@ -878,6 +925,7 @@ class Binaries:
        if opts.gnupghome is None:
                opts.gnupghome = tmpdir+'/gnupg'
 
+       b._debug('initialising')
        try:
                for x in ['pubring','secring']:
                        os.stat(opts.gnupghome + '/' + x + '.gpg')
@@ -885,15 +933,17 @@ class Binaries:
        except OSError, oe:
                if oe.errno != errno.ENOENT: raise
 
-       if ok: debug('# no key generation needed')
+       if ok: b._debug('no key generation needed')
        else: b.genkey()
 
+ def _debug(b, s):
+       debug('* '+s)
+
  def genkey(b):
-       try:
-               os.mkdir(os.path.dirname(opts.gnupghome), 02755)
-               os.mkdir(opts.gnupghome, 0700)
-       except OSError, oe:
-               if oe.errno != errno.EEXIST: raise
+       b._debug('preparing for key generation')
+
+       mkdir_okexist(os.path.dirname(opts.gnupghome), 02755)
+       mkdir_okexist(opts.gnupghome, 0700)
 
        script = '''
   cd "$1"
@@ -921,6 +971,7 @@ END
                bomb('key generation failed, code %d' % rc)
 
  def reset(b):
+       b._debug('reset')
        rmtree('binaries', b.dir.read())
        b.dir.invalidate()
        b.dir.write()
@@ -928,12 +979,15 @@ END
        b.blamed = []
 
  def register(b, act, pkg, af, forwhat, blamed):
+       b._debug('register what=%s deb_%s=%s pkg=%s af=%s'
+               % (act.what, forwhat, act.ah['deb_'+forwhat], pkg, str(af)))
+
        if act.ah['deb_'+forwhat] == 'ignore': return
 
        b.blamed += testbed.blamed
 
        leafname = pkg+'.deb'
-       dest = b.dir.subpath('binaries--'+leafname, leafname, OutputFile)
+       dest = RelativeOutputFile('binaries--'+leafname, b.dir, leafname)
 
        try: os.remove(dest.write())
        except OSError, oe:
@@ -948,6 +1002,8 @@ END
                b.install.append(pkg)
 
  def publish(b):
+       b._debug('publish')
+
        script = '''
   cd "$1"
   apt-ftparchive packages . >Packages
@@ -966,7 +1022,7 @@ END
 
        script = '''
   apt-key add archive-key.pgp
-  echo "deb file:///'+apt_source+'/ /" >/etc/apt/sources.list.d/autopkgtest
+  echo "deb file:///'''+apt_source+'''/ /" >/etc/apt/sources.list.d/autopkgtest
                '''
        debug_subprocess('apt-key', script=script)
        (rc,se) = testbed.execute('apt-key',
@@ -977,16 +1033,28 @@ END
        testbed.blamed += b.blamed
 
        for pkg in b.install:
+               b._debug('publish install %s' % pkg)
                testbed.blame(pkg)
+               debug_subprocess('apt-get(b.install)', script=script)
                (rc,se) = testbed.execute('install-%s'+act.what,
                        ['apt-get','-qy','install',pkg])
                if rc: badpkg("installation of %s failed, exit code %d"
                                % (pkg, rc), se)
 
+       b._debug('publish done')
+
 #---------- processing of sources (building)
 
 def source_rules_command(act,script,what,which,work,results_lines=0):
-       script = "exec 3>&1 >&2\n" + '\n'.join(script)
+       if opts.debug:
+               trace = "%s-%s-trace" % (what,which)
+               script = [      "mkfifo -m600 "+trace,
+                               "tee <"+trace+" /dev/stderr >&4 &",
+                               "exec >"+trace+" 2>&1"  ] + script
+
+       script = [      "exec 3>&1 >&2",
+                       "set -x"        ] + script
+       script = '\n'.join(script)
        so = TemporaryFile('%s-%s-results' % (what,which))
        se = TemporaryFile('%s-%s-log' % (what,which))
        debug_subprocess('source-rules-command/%s/%s' % (act.what, which),
@@ -994,8 +1062,8 @@ def source_rules_command(act,script,what,which,work,results_lines=0):
        rc = testbed.execute('%s-%s' % (what,which),
                        ['sh','-xec',script],
                        so=so.write(True), se=se.write(True),
-                       cwd= work.write(True))
-       results = file(so.read()).read().split("\n")
+                       cwd= work.write(True), dump_fd=4)
+       results = file(so.read()).read().rstrip('\n').split("\n")
        se = file(se.read()).read()
        if rc: badpkg("%s failed with exit code %d" % (which,rc), se)
        if results_lines is not None and len(results) != results_lines:
@@ -1031,9 +1099,8 @@ def build_source(act):
                if not m: badpkg(".dsc contains unparseable line"
                                " in Files: `%s'" % l)
                leaf = m.groups(0)[0]
-               subfile = dsc.sibling(
-                               what+'/'+leaf, leaf,
-                               InputFile)
+               subfile = RelativeInputFile(what+'/'+leaf, dsc, leaf,
+                               sibling=True)
                subfile.read(True)
        dsc.read(True)
        
@@ -1042,8 +1109,8 @@ def build_source(act):
        script = [
                        'cd '+work.write(True),
                        'apt-get update',
-                       'apt-get -y install build-essential',
-                       'gdebi '+dsc.read(True) +'||apt-get -y install dpatch bison',
+                       'apt-get -qy install build-essential',
+                       'gdebi '+dsc.read(True) +' ||apt-get -y install dpatch bison', # fixme fixme
                        'dpkg-source -x '+dsc.read(True),
                        'cd */.',
                        'dpkg-checkbuilddeps',
@@ -1052,21 +1119,24 @@ def build_source(act):
        ]
        result_pwd = source_rules_command(act,script,what,'build',work,1)
 
-       if os.path.dirname(result_pwd) != work.read(True):
+       if os.path.dirname(result_pwd)+'/' != work.read(True):
                badpkg("results dir `%s' is not in expected parent dir `%s'"
-                       % (results[0], work.read(True)))
+                       % (result_pwd, work.read(True)))
 
        act.tests_tree = InputDir(what+'-tests-tree',
-                               work.read(True)+os.path.basename(results[0]),
-                               InputDir)
+                               work.read(True)+os.path.basename(result_pwd),
+                               True)
        if act.ah['dsc_tests']:
                act.tests_tree.read()
                act.tests_tree.invalidate(True)
 
-       act.blamed = testbed.blamed.copy()
+       act.blamed = copy.copy(testbed.blamed)
 
+       def debug_b(m): debug('* <dsc:%s> %s' % (act.what, m))
        act.binaries = []
-       if act.ah['dsc_filter'] != '_':
+       filter = act.ah['dsc_filter']
+       debug_b('filter=%s' % filter)
+       if filter != '_':
                script = [
                        'cd '+work.write(True)+'/*/.',
                        opts.user_wrap(opts.gainroot+' debian/rules binary'),
@@ -1076,68 +1146,93 @@ def build_source(act):
                result_debs = source_rules_command(act,script,what,
                                'binary',work,1)
                if result_debs == '*': debs = []
-               else: debs = debs.split(' ')
+               else: debs = result_debs.split(' ')
+               debug_b('debs='+`debs`)
                re = regexp.compile('^([-+.0-9a-z]+)_[^_/]+(?:_[^_/]+)\.deb$')
                for deb in debs:
                        m = re.match(deb)
                        if not m: badpkg("badly-named binary `%s'" % deb)
-                       pkg = m.groups(0)
-                       for pat in act.ah['dsc_filter'].split(','):
-                               if fnmatch.fnmatchcase(pkg,pat):
-                                       deb_af = work.read()+'/'+deb
-                                       deb_what = pkg+'_'+what+'.deb'
-                                       bin = InputFile(deb_what,deb_af,True)
-                                       bin.preserve_now()
-                                       binaries.register(act,pkg,bin,'builds',
-                                               testbed.blamed)
-                                       act.binaries.subpath((pkg,bin))
-                                       break
+                       pkg = m.groups()[0]
+                       debug_b(' deb=%s, pkg=%s' % (deb,pkg))
+                       for pat in filter.split(','):
+                               debug_b('  pat=%s' % pat)
+                               if not fnmatch.fnmatchcase(pkg,pat):
+                                       debug_b('   no match')
+                                       continue
+                               deb_what = pkg+'_'+what+'.deb'
+                               bin = RelativeInputFile(deb_what,work,deb,True)
+                               debug_b('  deb_what=%s, bin=%s' %
+                                       (deb_what, str(bin)))
+                               binaries.register(act,pkg,bin,
+                                       'forbuilds',testbed.blamed)
+                               act.binaries.append((pkg,bin))
+                               break
+               debug_b('all done.')
 
 #---------- main processing loop and main program
 
 def process_actions():
        global binaries
 
+       def debug_a1(m): debug('@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ '+m)
+       def debug_a2(m): debug('@@@@@@@@@@@@@@@@@@@@ '+m)
+       def debug_a3(m): debug('@@@@@@@@@@ '+m)
+
+       debug_a1('starting')
        testbed.open()
        binaries = Binaries()
 
        binaries.reset()
+
+       debug_a1('builds ...')
        for act in opts.actions:
+               debug_a2('%s %s' %
+                       (act.kind, act.what))
+
                testbed.prepare()
                if act.kind == 'deb':
                        blame('arg:'+act.af.spec)
                        determine_package(act)
                        blame('deb:'+act.pkg)
-                       binaries.register(act,act.pkg,act.af,'builds',
-                               testbed.blamed)
+                       binaries.register(act,act.pkg,act.af,
+                               'forbuilds',testbed.blamed)
                if act.kind == 'dsc':
                        build_source(act)
 
+       debug_a1('builds done.')
+
        binaries.reset()
        control_override = None
+
+       debug_a1('tests ...')
        for act in opts.actions:
-               testbed.prepare()
+               debug_a2('test %s %s' % (act.kind, act.what))
+
+               testbed.needs_reset()
                if act.kind == 'control':
                        control_override = act.af
                if act.kind == 'deb':
-                       binaries.register(act,act.pkg,act.af,'tests',
+                       binaries.register(act,act.pkg,act.af,'fortests',
                                ['deb:'+act.pkg])
                if act.kind == 'dsc':
                        for (pkg,bin) in act.binaries:
-                               binaries.register(act,pkg,bin,'tests',
+                               binaries.register(act,pkg,bin,'fortests',
                                        act.blamed)
                        if act.ah['dsc_tests']:
+                               debug_a3('read control ...')
                                stanzas = read_control(act, act.tests_tree,
                                                control_override)
                                testbed.blamed += act.blamed
-                               run_tests(act, stanzas)
+                               debug_a3('run_tests ...')
+                               run_tests(stanzas, act.tests_tree)
                        control_override = None
                if act.kind == 'tree':
                        testbed.blame('arg:'+act.af.spec)
-                       stanzas = read_control(act, act.af,
-                                       control_override)
-                       run_tests(act, stanzas)
+                       stanzas = read_control(act, act.af, control_override)
+                       debug_a3('run_tests ...')
+                       run_tests(stanzas, act.af)
                        control_override = None
+       debug_a1('tests done.')
 
 def main():
        global testbed
@@ -1147,7 +1242,6 @@ def main():
        except SystemExit, se:
                os._exit(20)
        try:
-               tmpdir = tempfile.mkdtemp()
                testbed = Testbed()
                testbed.start()
                finalise_options()