3 # adt-run is part of autopkgtest
4 # autopkgtest is a tool for testing Debian binary packages
6 # autopkgtest is Copyright (C) 2006 Canonical Ltd.
8 # This program is free software; you can redistribute it and/or modify
9 # it under the terms of the GNU General Public License as published by
10 # the Free Software Foundation; either version 2 of the License, or
11 # (at your option) any later version.
13 # This program is distributed in the hope that it will be useful,
14 # but WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 # GNU General Public License for more details.
18 # You should have received a copy of the GNU General Public License
19 # along with this program; if not, write to the Free Software
20 # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
22 # See the file CREDITS for a full list of credits information (often
23 # installed as /usr/share/doc/autopkgtest/CREDITS).
39 from optparse import OptionParser
40 signal.signal(signal.SIGINT, signal.SIG_DFL) # undo stupid Python SIGINT thing
42 #---------- global variables
44 tmpdir = None # pathstring on host
45 testbed = None # Testbed
46 errorcode = 0 # exit status that we are going to use
47 binaries = None # Binaries (.debs we have registered)
49 #---------- errors we define
52 def __init__(q,ec,m): q.ec = ec; q.m = m
55 print >>sys.stderr, se
56 raise Quit(20, "unexpected error: %s" % m)
59 print >>sys.stderr, se
60 print 'blame: ', ' '.join(testbed.blamed)
61 raise Quit(12, "erroneous package: %s" % m)
63 def report(tname, result): print '%-20s %s' % (tname, result)
66 def __init__(u, lno, m):
67 if lno >= 0: u.m = '%s (control line %d)' % (m, lno)
72 report(tname, 'SKIP %s' % u.m)
76 if not opts.debug: return
77 for l in m.rstrip('\n').split('\n'):
78 print >>sys.stderr, 'atd-run: debug:', l
80 def rmtree(what, pathname):
81 debug('/ %s rmtree %s' % (what, pathname))
82 shutil.rmtree(pathname)
84 def debug_subprocess(what, cmdl=None, script=None):
89 if x is script: x = '<SCRIPT>'
90 ol.append(x. replace('\\','\\\\').
92 o += ' '+ ' '.join(ol)
93 if script is not None:
95 for l in script.rstrip('\n').split('\n'):
100 return reduce((lambda a,b: a + b), l, [])
102 #---------- fancy automatic file-copying class
106 # p.path[tb] None or path not None => path known
107 # p.file[tb] None or path not None => file exists
108 # p.spec string or None
109 # p.spec_tbp True or False, or not set if spec is None
112 def __init__(p, what):
121 if p.path[tbp] is None: out = '-'
122 elif p.file[tbp] is None: out = '?'+p.path[tbp]
123 else: out = '!'+p.path[tbp]
130 if p.spec is not None:
131 if p.spec_tbp: out += '>'
138 if p.spec is not None: xtra = ' spec[%s]=%s' % (p.spec, p.spec_tb)
139 raise ("internal error: %s (%s)" % (how, str(p)))
141 def _ensure_path(p, tbp):
142 if p.path[tbp] is None:
144 p._debug('tmp-parent %s...' % 'HT'[tbp])
145 TemporaryDir(os.path.dirname(p.what)).write(tbp)
147 p.path[tbp] = tmpdir+'/'+p.what
149 p.path[tbp] = testbed.scratch.path[True]+'/'+p.what
151 def write(p, tbp=False):
152 p._debug('write %s...' % 'HT'[tbp])
155 if p.dir and not p.file[tbp]:
158 try: os.mkdir(p.path[tbp])
160 if oe.errno != errno.EEXIST: raise
163 'test -d "$1" || mkdir "$1"',
165 tf_what = urllib.quote(p.what).replace('/','%2F')
166 (rc,se) = testbed.execute('mkdir-'+tf_what, cmdl)
167 if rc: bomb('failed to create directory %s' %
170 p.file[tbp] = p.path[tbp]
173 def read(p, tbp=False):
174 p._debug('read %s...' % 'HT'[tbp])
177 if p.file[tbp] is None:
178 if p.file[not tbp] is None:
179 p._wrong("requesting read but nonexistent")
180 cud = ['copyup','copydown'][tbp]
181 src = p.file[not tbp] + p.dir
182 dst = p.path[tbp] + p.dir
183 testbed.command(cud, (src, dst))
184 p.file[tbp] = p.path[tbp]
188 def subpath(p, what, leaf, constructor):
189 p._debug('subpath %s /%s %s...' % (what, leaf, `constructor`))
190 if not p.dir: p._wrong("creating subpath of non-directory")
191 return constructor(what, p.spec+p.dir+leaf, p.spec_tbp)
192 def sibling(p, what, leaf, constructor):
193 p._debug('sibling what=%s leaf=%s %s...' % (what, leaf, `constructor`))
194 dir = os.path.dirname(p.spec)
196 return constructor(what, dir+leaf, p.spec_tbp)
198 def invalidate(p, tbp=False):
200 p._debug('invalidated %s' % 'HT'[tbp])
203 debug('/ %s#%x: %s' % (p.what, id(p), m))
206 p._debug('constructed: '+str(p))
210 for tbp in [False,True]:
211 for pf in [p.path, p.file]:
212 if pf[tbp] is None: continue
213 if not pf[tbp]: bomb('empty path specified for '+p.what)
214 if p.dir and pf[tbp].endswith('/'):
215 pf[tbp] = pf[tbp].rstrip('/')
216 if not pf[tbp]: pf[tbp] = '/'
217 if not p.dir and pf[tbp].endswith('/'):
218 bomb("directory `%s' specified for "
219 "non-directory %s" % (pf[tbp], p.what))
221 class InputFile(AutoFile):
222 def _init(p, what, spec, spec_tbp=False):
223 AutoFile.__init__(p, what)
225 p.spec_tbp = spec_tbp
226 p.path[spec_tbp] = p.file[spec_tbp] = spec
227 def __init__(p, what, spec, spec_tbp=False):
228 p._init(what,spec,spec_tbp)
231 class InputDir(InputFile):
232 def __init__(p, what, spec, spec_tbp=False):
233 InputFile._init(p,what,spec,spec_tbp)
237 class OutputFile(AutoFile):
238 def _init(p, what, spec, spec_tbp=False):
239 AutoFile.__init__(p, what)
241 p.spec_tbp = spec_tbp
242 p.path[spec_tbp] = spec
243 def __init__(p, what, spec, spec_tbp=False):
244 p._init(what,spec,spec_tbp)
247 class OutputDir(OutputFile):
248 def __init__(p, what, spec, spec_tbp=False):
249 OutputFile._init(p,what,spec,spec_tbp)
253 class TemporaryFile(AutoFile):
254 def __init__(p, what):
255 AutoFile.__init__(p, what)
258 class TemporaryDir(AutoFile):
259 def __init__(p, what):
260 AutoFile.__init__(p, what)
264 #---------- parsing and representation of the arguments
267 def __init__(a, kind, af, arghandling, what):
268 # extra attributes get added during processing
276 usage = "%prog <options> --- <virt-server>..."
277 parser = OptionParser(usage=usage)
278 pa = parser.add_option
279 pe = parser.add_option
284 'deb_forbuilds': 'auto',
285 'deb_fortests': 'auto',
287 'override_control': None
289 initial_arghandling = arghandling.copy()
293 # actions (ie, test sets to run, sources to build, binaries to use):
295 def cb_action(op,optstr,value,parser, long,kindpath,is_act):
296 print >>sys.stderr, "cb_action", is_act
297 parser.largs.append((value,kindpath))
298 n_non_actions += not(is_act)
300 def pa_action(long, metavar, kindpath, help, is_act=True):
301 pa('','--'+long, action='callback', callback=cb_action,
302 nargs=1, type='string',
303 callback_args=(long,kindpath,is_act), help=help)
305 pa_action('build-tree', 'TREE', '@/',
306 help='run tests from build tree TREE')
308 pa_action('source', 'DSC', '@.dsc',
309 help='build DSC and use its tests and/or'
310 ' generated binary packages')
312 pa_action('binary', 'DEB', '@.deb',
313 help='use binary package DEB according'
314 ' to most recent --binaries-* settings')
316 pa_action('override-control', 'CONTROL', ('control',), is_act=0,
317 help='run tests from control file CONTROL instead,'
318 ' (applies to next test suite only)')
321 # argument handling settings (what ways to use action
322 # arguments, and pathname processing):
324 def cb_setah(option, opt_str, value, parser, toset,setval):
325 if type(setval) == list:
326 if not value in setval:
327 parser.error('value for %s option (%s) is not '
328 'one of the permitted values (%s)' %
329 (value, opt_str, setval.join(' ')))
330 elif setval is not None:
333 arghandling[v] = value
334 parser.largs.append(arghandling.copy())
336 def pa_setah(long, affected,effect, metavar=None, **kwargs):
338 if type is not None: type = 'string'
339 pa('',long, action='callback', callback=cb_setah,
340 callback_args=(affected,effect), **kwargs)
342 #---- paths: host or testbed:
344 pa_setah('--paths-testbed', ['tb'],True,
345 help='subsequent path specifications refer to the testbed')
346 pa_setah('--paths-host', ['tb'],False,
347 help='subsequent path specifications refer to the host')
349 #---- source processing settings:
351 pa_setah('--sources-tests', ['dsc_tests'],True,
352 help='run tests from builds of subsequent sources')
353 pa_setah('--sources-no-tests', ['dsc_tests'],False,
354 help='do not run tests from builds of subsequent sources')
356 pa_setah('--built-binaries-filter', ['dsc_filter'],None,
357 type='string', metavar='PATTERN-LIST',
358 help='from subsequent sources, use binaries matching'
359 ' PATTERN-LIST (comma-separated glob patterns)'
360 ' according to most recent --binaries-* settings')
361 pa_setah('--no-built-binaries', ['dsc_filter'], '_',
362 help='from subsequent sources, do not use any binaries')
364 #---- binary package processing settings:
366 def pa_setahbins(long,toset,how):
367 pa_setah(long, toset,['ignore','auto','install'],
368 type='string', metavar='IGNORE|AUTO|INSTALL', default='auto',
369 help=how+' ignore binaries, install them as needed'
370 ' for dependencies, or unconditionally install'
371 ' them, respectively')
372 pa_setahbins('--binaries', ['deb_forbuilds','deb_fortests'], '')
373 pa_setahbins('--binaries-forbuilds', ['deb_forbuilds'], 'for builds, ')
374 pa_setahbins('--binaries-fortests', ['deb_fortests'], 'for tests, ')
379 def cb_vserv(op,optstr,value,parser):
380 parser.values.vserver = list(parser.rargs)
383 def cb_path(op,optstr,value,parser, constructor,long,dir):
384 name = long.replace('-','_')
385 af = constructor(arghandling['tb'], value, long, dir)
386 setattr(parser.values, name, af)
388 def pa_path(long, constructor, help, dir=False):
389 pa('','--'+long, action='callback', callback=cb_path,
390 callback_args=(constructor,long,dir),
391 nargs=1, type='string',
392 help=help, metavar='PATH')
394 pa_path('output-dir', OutputDir, dir=True,
395 help='write stderr/out files in PATH')
397 pa('','--tmp-dir', type='string', dest='tmpdir',
398 help='write temporary files to TMPDIR, emptying it'
399 ' beforehand and leaving it behind at the end')
401 pa('','--user', type='string', dest='user',
402 help='run tests as USER (needs root on testbed)')
403 pa('','--gain-root', type='string', dest='gainroot',
404 help='prefix debian/rules binary with GAINROOT')
405 pa('-d', '--debug', action='store_true', dest='debug');
406 pa('','--gnupg-home', type='string', dest='gnupghome',
407 default='~/.autopkgtest/gpg',
408 help='use GNUPGHOME rather than ~/.autopkgtest (for'
409 " signing private apt archive);"
410 " `fresh' means generate new key each time.")
415 class SpecialOption(optparse.Option): pass
416 vs_op = SpecialOption('','--VSERVER-DUMMY')
417 vs_op.action = 'callback'
421 vs_op.callback = cb_vserv
422 vs_op.callback_args = ( )
423 vs_op.callback_kwargs = { }
424 vs_op.help = 'introduces virtualisation server and args'
425 vs_op._short_opts = []
426 vs_op._long_opts = ['---']
430 (opts,args) = parser.parse_args()
431 if not hasattr(opts,'vserver'):
432 parser.error('you must specifiy --- <virt-server>...')
433 if n_non_actions >= len(parser.largs):
434 parser.error('nothing to do specified')
436 arghandling = initial_arghandling
440 if type(act) == dict:
443 elif type(act) == tuple:
445 elif type(act) == str:
448 raise ("unknown action in list `%s' having"
449 " type `%s'" % (act, type(act)))
450 (pathstr, kindpath) = act
452 constructor = InputFile
453 if type(kindpath) is tuple: kind = kindpath[0]
454 elif kindpath.endswith('.deb'): kind = 'deb'
455 elif kindpath.endswith('.dsc'): kind = 'dsc'
456 elif kindpath.endswith('/'):
458 constructor = InputDir
459 else: parser.error("do not know how to handle filename \`%s';"
460 " specify --source --binary or --build-tree")
462 what = '%s%s' % (kind,ix); ix += 1
464 if kind == 'dsc': fwhatx = '/' + os.path.basename(pathstr)
465 else: fwhatx = '-'+kind
467 af = constructor(what+fwhatx, pathstr, arghandling['tb'])
468 opts.actions.append(Action(kind, af, arghandling, what))
470 def finalise_options():
473 if opts.user is None and 'root-on-testbed' not in testbed.caps:
476 if opts.user is None:
477 su = 'suggested-normal-user='
480 for e in testbed.caps
489 if 'root-on-testbed' not in testbed.caps:
490 print >>sys.stderr, ("warning: virtualisation"
491 " system does not offer root on testbed,"
492 " but --user option specified: failure likely")
493 opts.user_wrap = lambda x: 'su %s -c "%s"' % (opts.user, x)
495 opts.user_wrap = lambda x: x
497 if opts.gainroot is None:
500 'root-on-testbed' not in testbed.caps):
501 opts.gainroot = 'fakeroot'
503 if opts.gnupghome.startswith('~/'):
504 try: home = os.environ['HOME']
506 parser.error("HOME environment variable"
507 " not set, needed for --gnupghome=`%s"
509 opts.gnupghome = home + opts.gnupghome[1:]
510 elif opts.gnupghome == 'fresh':
511 opts.gnupghome = None
513 #---------- testbed management - the Testbed class
524 debug_subprocess('vserver', opts.vserver)
525 tb.sp = subprocess.Popen(opts.vserver,
526 stdin=p, stdout=p, stderr=None)
528 tb.caps = tb.commandr('capabilities')
531 if tb.sp is None: return
532 ec = tb.sp.returncode
539 tb.bomb('testbed gave exit status %d after quit' % ec)
541 if tb.scratch is not None: return
542 pl = tb.commandr('open')
543 tb.scratch = InputDir('tb-scratch', pl[0], True)
545 if tb.scratch is None: return
547 if tb.sp is None: return
550 if tb.modified and 'reset' in tb.caps:
560 if tb.sp is not None:
564 if ec: print >>sys.stderr, ('adt-run: testbed failing,'
565 ' exit status %d' % ec)
567 raise Quit(16, 'testbed failed: %s' % m)
568 def send(tb, string):
572 print >>tb.sp.stdin, string
576 (type, value, dummy) = sys.exc_info()
577 tb.bomb('cannot send to testbed: %s' % traceback.
578 format_exception_only(type, value))
579 def expect(tb, keyword, nresults=None):
580 l = tb.sp.stdout.readline()
581 if not l: tb.bomb('unexpected eof from the testbed')
582 if not l.endswith('\n'): tb.bomb('unterminated line from the testbed')
586 if not ll: tb.bomb('unexpected whitespace-only line from the testbed')
588 if tb.lastsend is None:
589 tb.bomb("got banner `%s', expected `%s...'" %
592 tb.bomb("sent `%s', got `%s', expected `%s...'" %
593 (tb.lastsend, l, keyword))
595 if nresults is not None and len(ll) != nresults:
596 tb.bomb("sent `%s', got `%s' (%d result parameters),"
597 " expected %d result parameters" %
598 (string, l, len(ll), nresults))
600 def commandr(tb, cmd, args=(), nresults=None):
601 # pass args=[None,...] or =(None,...) to avoid more url quoting
602 if type(cmd) is str: cmd = [cmd]
603 if len(args) and args[0] is None: args = args[1:]
604 else: args = map(urllib.quote, args)
606 tb.send(string.join(al))
607 ll = tb.expect('ok', nresults)
608 rl = map(urllib.unquote, ll)
610 def command(tb, cmd, args=()):
611 tb.commandr(cmd, args, 0)
612 def commandr1(tb, cmd, args=()):
613 rl = tb.commandr(cmd, args, 1)
615 def execute(tb, what, cmdargs,
616 si='/dev/null', so='/dev/null', se=None, cwd=None):
617 if cwd is None: cwd = tb.scratch.write(True)
620 se_af = TemporaryFile('xerr-'+what)
621 se_use = se_af.write(True)
622 rc = tb.commandr1('execute', [None,
623 ','.join(map(urllib.quote, cmdargs)),
624 si, so, se_use, cwd])
626 except ValueError: bomb("execute for %s gave invalid response `%s'"
628 if se is not None: return rc
629 return (rc, file(se_af.read()).read())
631 #---------- representation of test control files: Field*, Test, etc.
634 def __init__(f, fname, stz, base, tnames, vl):
644 r = map((lambda w: (lno, w)), r)
646 return flatten(map(distribute, f.vl))
651 raise Unsupported(f.vl[1][0],
652 'only one %s field allowed' % fn)
655 class FieldIgnore(FieldBase):
659 def __init__(r,rname,base): pass
661 class Restriction_rw_tests_tree(Restriction): pass
662 class Restriction_breaks_testbed(Restriction):
663 def __init__(r, rname, base):
664 if 'reset' not in testbed.caps:
665 raise Unsupported(f.lno,
666 'Test breaks testbed but testbed cannot reset')
668 class Field_Restrictions(FieldBase):
670 for wle in f.words():
672 rname = rname.replace('-','_')
673 try: rclass = globals()['Restriction_'+rname]
674 except KeyError: raise Unsupported(lno,
675 'unknown restriction %s' % rname)
676 r = rclass(rname, f.base)
677 f.base['restrictions'].append(r)
679 class Field_Tests(FieldIgnore): pass
681 class Field_Tests_directory(FieldBase):
684 if td.startswith('/'): raise Unspported(f.lno,
685 'Tests-Directory may not be absolute')
686 base['testsdir'] = td
688 def run_tests(stanzas):
690 for stanza in stanzas:
691 tests = stanza[' tests']
693 report('*', 'SKIP no tests in this package')
698 if 'breaks-testbed' in t.restrictions:
699 testbed.needs_reset()
700 testbed.needs_reset()
703 def __init__(t, tname, base, act_what):
704 if '/' in tname: raise Unsupported(base[' lno'],
705 'test name may not contain / character')
706 for k in base: setattr(t,k,base[k])
708 t.what = act_what+'-'+tname
709 if len(base['testsdir']): tpath = base['testsdir'] + '/' + tname
711 t.af = opts.tests_tree.subpath('test-'+tname, tpath, InputFile)
714 def reportfail(t, m):
717 report(t.what, 'FAIL ' + m)
720 idstr = oe + '-' + t.what
721 if opts.output_dir is not None and opts.output_dir.tb:
722 use_dir = opts.output_dir
724 use_dir = testbed.scratch
725 return use_dir.subpath(idstr, idstr, OutputFile)
727 so = stdouterr('stdout')
728 se = stdouterr('stderr')
729 rc = testbed.execute('test-'+t.what,
730 [opts.user_wrap(t.af.read(True))],
731 so=so, se=se, cwd=opts.tests_tree.write(True))
733 stab = os.stat(se.read())
734 if stab.st_size != 0:
735 l = file(se.read()).readline()
736 l = l.rstrip('\n \t\r')
737 if len(l) > 40: l = l[:40] + '...'
738 t.reportfail('status: %d, stderr: %s' % (rc, l))
740 t.reportfail('non-zero exit status %d' % rc)
744 def read_control(act, tree, control_override):
747 if control_override is not None:
748 control_af = control_override
749 testbed.blame('arg:'+control_override.spec)
751 control_af = tree.subpath(act.what+'-testcontrol',
752 'debian/tests/control', InputFile)
755 control = file(control_af.read(), 'r')
757 if oe[0] != errno.ENOENT: raise
761 def badctrl(m): act.bomb('tests/control line %d: %s' % (lno, m))
762 stz = None # stz[field_name][index] = (lno, value)
763 # special field names:
764 # stz[' lno'] = number
765 # stz[' tests'] = list of Test objects
767 if stz is None: return
773 initre = regexp.compile('([A-Z][-0-9a-z]*)\s*\:\s*(.*)$')
775 l = control.readline()
778 if not l.endswith('\n'): badctrl('unterminated line')
779 if regexp.compile('\s*\#').match(l): continue
780 if not regexp.compile('\S').match(l): end_stanza(stz); continue
781 initmat = initre.match(l)
783 (fname, l) = initmat.groups()
784 fname = string.capwords(fname)
786 stz = { ' lno': lno, ' tests': [] }
787 if not stz.has_key(fname): stz[fname] = [ ]
788 hcurrent = stz[fname]
789 elif regexp.compile('\s').match(l):
790 if not hcurrent: badctrl('unexpected continuation')
792 badctrl('syntax error')
793 hcurrent.append((lno, l))
796 def testbadctrl(stz, lno, m):
797 report_badctrl(lno, m)
802 try: tnames = stz['Tests']
805 raise Unsupported(stz[' lno'],
807 tnames = map((lambda lt: lt[1]), tnames)
808 tnames = string.join(tnames).split()
811 'testsdir': 'debian/tests'
813 for fname in stz.keys():
814 if fname.startswith(' '): continue
816 try: fclass = globals()['Field_'+
817 fname.replace('-','_')]
818 except KeyError: raise Unsupported(vl[0][0],
819 'unknown metadata field %s' % fname)
820 f = fclass(stz, fname, base, tnames, vl)
823 t = Test(tname, base, act.what)
824 stz[' tests'].append(t)
825 except Unsupported, u:
826 for tname in tnames: u.report(tname)
831 def print_exception(ei, msgprefix=''):
832 if msgprefix: print >>sys.stderr, msgprefix
835 print >>sys.stderr, 'adt-run:', q.m
838 print >>sys.stderr, "adt-run: unexpected, exceptional, error:"
839 traceback.print_exc()
845 if tmpdir is not None:
846 rmtree('tmpdir', tmpdir)
847 if testbed is not None:
849 if rm_ec: bomb('rm -rf -- %s failed, code %d' % (tmpdir, ec))
851 print_exception(sys.exc_info(),
852 '\nadt-run: error cleaning up:\n')
855 #---------- registration, installation etc. of .deb's: Binaries
857 def determine_package(act):
858 cmd = 'dpkg-deb --info --'.split(' ')+[act.af.read(),'control']
859 running = Popen(cmd, stdout=PIPE)
860 output = running.communicate()[0]
862 if rc: badpkg('failed to parse binary package, code %d' % rc)
863 re = regexp.compile('^\s*Package\s*:\s*([0-9a-z][-+.0-9a-z]*)\s*$')
865 for l in '\n'.split(output):
868 if act.pkg: badpkg('two Package: lines in control file')
870 if not act.pkg: badpkg('no good Package: line in control file')
874 b.dir = TemporaryDir('binaries')
878 if opts.gnupghome is None:
879 opts.gnupghome = tmpdir+'/gnupg'
882 for x in ['pubring','secring']:
883 os.stat(opts.gnupghome + '/' + x + '.gpg')
886 if oe.errno != errno.ENOENT: raise
888 if ok: debug('# no key generation needed')
893 os.mkdir(os.path.dirname(opts.gnupghome), 02755)
894 os.mkdir(opts.gnupghome, 0700)
896 if oe.errno != errno.EEXIST: raise
900 exec >key-gen-log 2>&1
901 cat <<"END" >key-gen-params
905 Name-Real: autopkgtest per-run key
906 Name-Comment: do not trust this key
907 Name-Email: autopkgtest@example.com
910 gpg --homedir="$1" --batch --gen-key key-gen-params
912 cmdl = ['sh','-ec',script,'x',opts.gnupghome]
913 debug_subprocess('genkey', cmdl, script=script)
914 rc = subprocess.call(cmdl)
917 f = open(opts.gnupghome+'/key-gen-log')
919 except OSError, e: tp = e
920 print >>sys.stderr, tp
921 bomb('key generation failed, code %d' % rc)
924 rmtree('binaries', b.dir.read())
930 def register(b, act, pkg, af, forwhat, blamed):
931 if act.ah['deb_'+forwhat] == 'ignore': return
933 b.blamed += testbed.blamed
935 leafname = pkg+'.deb'
936 dest = b.dir.subpath('binaries--'+leafname, leafname, OutputFile)
938 try: os.remove(dest.write())
940 if oe.errno != errno.ENOENT: raise e
942 try: os.link(af.read(), dest.write())
944 if oe.errno != errno.EXDEV: raise e
945 shutil.copy(af.read(), dest)
947 if act.ah['deb_'+forwhat] == 'install':
948 b.install.append(pkg)
953 apt-ftparchive packages . >Packages
955 apt-ftparchive release . >Release
956 gpg --homedir="$2" --batch --detach-sign --armour -o Release.gpg Release
957 gpg --homedir="$2" --batch --export >archive-key.pgp
959 cmdl = ['sh','-ec',script,'x',b.dir.write(),opts.gnupghome]
960 debug_subprocess('ftparchive', cmdl, script)
961 rc = subprocess.call(cmdl)
962 if rc: bomb('apt-ftparchive or signature failed, code %d' % rc)
964 b.dir.invalidate(True)
965 apt_source = b.dir.read(True)
968 apt-key add archive-key.pgp
969 echo "deb file:///'+apt_source+'/ /" >/etc/apt/sources.list.d/autopkgtest
971 debug_subprocess('apt-key', script=script)
972 (rc,se) = testbed.execute('apt-key',
974 cwd=b.dir.write(True))
975 if rc: bomb('apt setup failed with exit code %d' % rc, se)
977 testbed.blamed += b.blamed
979 for pkg in b.install:
981 (rc,se) = testbed.execute('install-%s'+act.what,
982 ['apt-get','-qy','install',pkg])
983 if rc: badpkg("installation of %s failed, exit code %d"
986 #---------- processing of sources (building)
988 def source_rules_command(act,script,what,which,work,results_lines=0):
989 script = "exec 3>&1 >&2\n" + '\n'.join(script)
990 so = TemporaryFile('%s-%s-results' % (what,which))
991 se = TemporaryFile('%s-%s-log' % (what,which))
992 debug_subprocess('source-rules-command/%s/%s' % (act.what, which),
994 rc = testbed.execute('%s-%s' % (what,which),
995 ['sh','-xec',script],
996 so=so.write(True), se=se.write(True),
997 cwd= work.write(True))
998 results = file(so.read()).read().split("\n")
999 se = file(se.read()).read()
1000 if rc: badpkg("%s failed with exit code %d" % (which,rc), se)
1001 if results_lines is not None and len(results) != results_lines:
1002 badpkg("got %d lines of results from %s where %d expected"
1003 % (len(results), which, results_lines), se)
1004 if results_lines==1: return results[0]
1007 def build_source(act):
1008 act.blame = 'arg:'+act.af.spec
1009 testbed.blame(act.blame)
1010 testbed.needs_reset()
1016 dsc_file = open(dsc.read())
1018 fre = regexp.compile('^\s+[0-9a-f]+\s+\d+\s+([^/.][^/]*)$')
1021 if l.startswith('Files:'): in_files = True; continue
1022 elif l.startswith('#'): pass
1023 elif not l.startswith(' '):
1025 if l.startswith('Source:'):
1026 act.blame = 'dsc:'+l[7:].strip()
1027 testbed.blame(act.blame)
1028 if not in_files: continue
1031 if not m: badpkg(".dsc contains unparseable line"
1032 " in Files: `%s'" % l)
1033 leaf = m.groups(0)[0]
1034 subfile = dsc.sibling(
1035 what+'/'+leaf, leaf,
1040 work = TemporaryDir(what+'-build')
1043 'cd '+work.write(True),
1045 'apt-get -y install build-essential',
1046 'gdebi '+dsc.read(True) +'||apt-get -y install dpatch bison',
1047 'dpkg-source -x '+dsc.read(True),
1049 'dpkg-checkbuilddeps',
1051 opts.user_wrap('debian/rules build'),
1053 result_pwd = source_rules_command(act,script,what,'build',work,1)
1055 if os.path.dirname(result_pwd) != work.read(True):
1056 badpkg("results dir `%s' is not in expected parent dir `%s'"
1057 % (results[0], work.read(True)))
1059 act.tests_tree = InputDir(what+'-tests-tree',
1060 work.read(True)+os.path.basename(results[0]),
1062 if act.ah['dsc_tests']:
1063 act.tests_tree.read()
1064 act.tests_tree.invalidate(True)
1066 act.blamed = testbed.blamed.copy()
1069 if act.ah['dsc_filter'] != '_':
1071 'cd '+work.write(True)+'/*/.',
1072 opts.user_wrap(opts.gainroot+' debian/rules binary'),
1076 result_debs = source_rules_command(act,script,what,
1078 if result_debs == '*': debs = []
1079 else: debs = debs.split(' ')
1080 re = regexp.compile('^([-+.0-9a-z]+)_[^_/]+(?:_[^_/]+)\.deb$')
1083 if not m: badpkg("badly-named binary `%s'" % deb)
1085 for pat in act.ah['dsc_filter'].split(','):
1086 if fnmatch.fnmatchcase(pkg,pat):
1087 deb_af = work.read()+'/'+deb
1088 deb_what = pkg+'_'+what+'.deb'
1089 bin = InputFile(deb_what,deb_af,True)
1091 binaries.register(act,pkg,bin,'builds',
1093 act.binaries.subpath((pkg,bin))
1096 #---------- main processing loop and main program
1098 def process_actions():
1102 binaries = Binaries()
1105 for act in opts.actions:
1107 if act.kind == 'deb':
1108 blame('arg:'+act.af.spec)
1109 determine_package(act)
1110 blame('deb:'+act.pkg)
1111 binaries.register(act,act.pkg,act.af,'builds',
1113 if act.kind == 'dsc':
1117 control_override = None
1118 for act in opts.actions:
1120 if act.kind == 'control':
1121 control_override = act.af
1122 if act.kind == 'deb':
1123 binaries.register(act,act.pkg,act.af,'tests',
1125 if act.kind == 'dsc':
1126 for (pkg,bin) in act.binaries:
1127 binaries.register(act,pkg,bin,'tests',
1129 if act.ah['dsc_tests']:
1130 stanzas = read_control(act, act.tests_tree,
1132 testbed.blamed += act.blamed
1133 run_tests(act, stanzas)
1134 control_override = None
1135 if act.kind == 'tree':
1136 testbed.blame('arg:'+act.af.spec)
1137 stanzas = read_control(act, act.af,
1139 run_tests(act, stanzas)
1140 control_override = None
1147 except SystemExit, se:
1150 tmpdir = tempfile.mkdtemp()
1156 ec = print_exception(sys.exc_info(), '')