0518e1b4e006c8e234e7960d7bccacd714a41cdd
[tests.git] / system / TestMain.py
1 #!/usr/bin/python -u
2
3 # Thierry Parmentelat <thierry.parmentelat@inria.fr>
4 # Copyright (C) 2010 INRIA 
5 #
6 import sys, os, os.path
7 from argparse import ArgumentParser
8 import traceback
9 import readline
10 import glob
11 from datetime import datetime
12
13 import utils
14 from TestPlc import TestPlc, Ignored
15 from TestBonding import TestBonding, onelab_bonding_spec
16 from TestSite import TestSite
17 from TestNode import TestNode
18 from macros import sequences
19
20 # add $HOME in PYTHONPATH so we can import LocalSubstrate.py
21 sys.path.append(os.environ['HOME'])
22 import LocalSubstrate
23
24 class Step:
25
26     natives = TestPlc.__dict__
27
28     def display (self):
29         return self.name.replace('_', '-')
30     def internal (self):
31         return self.name.replace('-', '_')
32
33     def __init__ (self, name):
34         self.name = name
35         # a native step is implemented as a method on TestPlc
36         self.native = self.internal() in Step.natives
37         if self.native:
38             self.method = Step.natives[self.internal()]
39         else:
40             try:
41                 self.substeps = sequences[self.internal()]
42             except Exception,e:
43                 print "macro step {} not found in macros.py ({}) - exiting".format(self.display(),e)
44                 raise
45
46     def print_doc (self, level=0):
47         tab = 32
48         trail = 8
49         if self.native:
50             start = level*' ' + '* '
51             # 2 is the len of '* '
52             width = tab - level - 2
53             format = "%%-%ds" % width
54             line = start + format % self.display()
55             print line,
56             try:
57                 print self.method.__doc__
58             except:
59                 print "*** no doc found"
60         else:
61             beg_start = level*' ' + '>>> '
62             end_start = level*' ' + '<<< '
63             trailer = trail * '-'
64             # 4 is the len of '>>> '
65             width = tab - level - 4 - trail
66             format = "%%-%ds" % width
67             beg_line = beg_start + format % self.display() + trail*'>'
68             end_line = end_start + format % self.display() + trail*'<'
69             print beg_line
70             for step in self.substeps:
71                 Step(step).print_doc(level+1)
72             print end_line
73
74     # return a list of (name, method) for all native steps involved
75     def tuples (self):
76         if self.native:
77             return [ (self.internal(), self.method,) ]
78         else:
79             result = []
80             for substep in [ Step(name) for name in self.substeps ] : 
81                 result += substep.tuples()
82             return result
83
84     # convenience for listing macros
85     # just do a listdir, hoping we're in the right directory...
86     @staticmethod
87     def list_macros ():
88         names= sequences.keys()
89         names.sort()
90         return names
91
92 class TestMain:
93
94     default_config = [ 'default' ] 
95 #    default_rspec_styles = [ 'pl', 'pg' ]
96     default_rspec_styles = [ 'pg' ]
97
98     default_build_url = "git://git.onelab.eu/tests"
99
100     def __init__(self):
101         self.path = os.path.dirname(sys.argv[0]) or "."
102         os.chdir(self.path)
103
104     def show_env(self, options, message):
105         if self.options.verbose:
106             utils.header(message)
107             utils.show_options("main options", options)
108
109     def init_steps(self):
110         self.steps_message  = ""
111         if not self.options.bonding:
112             self.steps_message += 20*'x' + " Defaut steps are\n" + \
113                                   TestPlc.printable_steps(TestPlc.default_steps)
114             self.steps_message += 20*'x' + " Other useful steps are\n" + \
115                                   TestPlc.printable_steps(TestPlc.other_steps)
116             self.steps_message += 20*'x' + " Macro steps are\n" + \
117                                   " ".join(Step.list_macros())
118         else:
119             self.steps_message += 20*'x' + " Default steps with bonding are\n" + \
120                                   TestPlc.printable_steps(TestPlc.bonding_steps)
121
122     def list_steps(self):
123         if not self.options.verbose:
124             print self.steps_message
125         else:
126             # steps mentioned on the command line
127             if self.options.steps:
128                 scopes = [("Argument steps",self.options.steps)]
129             else:
130                 scopes = [("Default steps", TestPlc.default_steps)]
131                 if self.options.all_steps:
132                     scopes.append ( ("Other steps", TestPlc.other_steps) )
133                     # try to list macro steps as well
134                     scopes.append ( ("Macro steps", Step.list_macros()) )
135             for (scope, steps) in scopes:
136                 print '--------------------', scope
137                 for step in [step for step in steps if TestPlc.valid_step(step)]:
138                     try:
139                         (step, qualifier) = step.split('@')
140                     except:
141                         pass
142                     stepname = step
143                     for special in ['force', 'ignore']:
144                         stepname = stepname.replace('_'+special, "")
145                     Step(stepname).print_doc()
146
147     def run (self):
148         usage = """usage: %%prog [options] steps
149 arch-rpms-url defaults to the last value used, as stored in arg-arch-rpms-url,
150    no default
151 config defaults to the last value used, as stored in arg-config,
152    or {}
153 ips_vnode, ips_vplc and ips_qemu defaults to the last value used, 
154    as stored in arg-ips-{{bplc,vplc,bnode,vnode}},
155    default is to use IP scanning
156 steps refer to a method in TestPlc or to a step_* module
157
158 run with -l to see a list of available steps
159 ===
160 """.format(TestMain.default_config)
161
162         parser = ArgumentParser(usage = usage)
163         parser.add_argument("-u", "--url", action="store",  dest="arch_rpms_url", 
164                             help="URL of the arch-dependent RPMS area - for locating what to test")
165         parser.add_argument("-b", "--build", action="store", dest="build_url", 
166                             help="ignored, for legacy only")
167         parser.add_argument("-c", "--config", action="append", dest="config", default=[],
168                             help="Config module - can be set multiple times, or use quotes")
169         parser.add_argument("-p", "--personality", action="store", dest="personality", 
170                             help="personality - as in vbuild-nightly")
171         parser.add_argument("-d", "--pldistro", action="store", dest="pldistro", 
172                             help="pldistro - as in vbuild-nightly")
173         parser.add_argument("-f", "--fcdistro", action="store", dest="fcdistro", 
174                             help="fcdistro - as in vbuild-nightly")
175         parser.add_argument("-e", "--exclude", action="append", dest="exclude", default=[],
176                             help="steps to exclude - can be set multiple times, or use quotes")
177         parser.add_argument("-i", "--ignore", action="append", dest="ignore", default=[],
178                             help="steps to run but ignore - can be set multiple times, or use quotes")
179         parser.add_argument("-a", "--all", action="store_true", dest="all_steps", default=False,
180                             help="Run all default steps")
181         parser.add_argument("-l", "--list", action="store_true", dest="list_steps", default=False,
182                             help="List known steps")
183         parser.add_argument("-V", "--vserver", action="append", dest="ips_bplc", default=[],
184                             help="Specify the set of hostnames for the boxes that host the plcs")
185         parser.add_argument("-P", "--plcs", action="append", dest="ips_vplc", default=[],
186                             help="Specify the set of hostname/IP's to use for vplcs")
187         parser.add_argument("-Q", "--qemus", action="append", dest="ips_bnode", default=[],
188                             help="Specify the set of hostnames for the boxes that host the nodes")
189         parser.add_argument("-N", "--nodes", action="append", dest="ips_vnode", default=[],
190                             help="Specify the set of hostname/IP's to use for vnodes")
191         parser.add_argument("-s", "--size", action="store", dest="size", default=1,
192                             type=int, 
193                             help="set test size in # of plcs - default is 1")
194         parser.add_argument("-q", "--qualifier", action="store", dest="qualifier", default=None,
195                             type=int, 
196                             help="run steps only on plc numbered <qualifier>, starting at 1")
197         parser.add_argument("-y", "--rspec-style", action="append", dest="rspec_styles", default=[],
198                             help="pl is for planetlab rspecs, pg is for protogeni")
199         parser.add_argument("-k", "--keep-going", action="store", dest="keep_going", default=False,
200                             help="proceeds even if some steps are failing")
201         parser.add_argument("-D", "--dbname", action="store", dest="dbname", default=None,
202                             help="Used by plc_db_dump and plc_db_restore")
203         parser.add_argument("-v", "--verbose", action="store_true", dest="verbose", default=False, 
204                             help="Run in verbose mode")
205         parser.add_argument("-I", "--interactive", action="store_true", dest="interactive", default=False,
206                             help="prompts before each step")
207         parser.add_argument("-n", "--dry-run", action="store_true", dest="dry_run", default=False,
208                             help="Show environment and exits")
209         parser.add_argument("-t", "--trace", action="store", dest="trace_file", default=None,
210                             help="Trace file location")
211         parser.add_argument("-g", "--bonding", action='store', dest='bonding', default=None,
212                             help="specify build to bond with")
213         parser.add_argument("steps", nargs='*')
214         self.options = parser.parse_args()
215
216         # allow things like "run -c 'c1 c2' -c c3"
217         def flatten (x):
218             result = []
219             for el in x:
220                 if hasattr(el, "__iter__") and not isinstance(el, basestring):
221                     result.extend(flatten(el))
222                 else:
223                     result.append(el)
224             return result
225         # flatten relevant options
226         for optname in ['config', 'exclude', 'ignore', 'ips_bplc', 'ips_vplc', 'ips_bnode', 'ips_vnode']:
227             setattr(self.options, optname,
228                     flatten([arg.split() for arg in getattr(self.options, optname)]))
229
230         if not self.options.rspec_styles:
231             self.options.rspec_styles = TestMain.default_rspec_styles
232
233         # handle defaults and option persistence
234         for recname, filename, default, need_reverse in (
235             ('build_url', 'arg-build-url', TestMain.default_build_url, None),
236             ('ips_bplc', 'arg-ips-bplc', [], True),
237             ('ips_vplc', 'arg-ips-vplc', [], True), 
238             ('ips_bnode', 'arg-ips-bnode', [], True),
239             ('ips_vnode', 'arg-ips-vnode', [], True), 
240             ('config', 'arg-config', TestMain.default_config, False), 
241             ('arch_rpms_url', 'arg-arch-rpms-url', "", None), 
242             ('personality', 'arg-personality', "linux64", None),
243             ('pldistro', 'arg-pldistro', "onelab", None),
244             ('fcdistro', 'arg-fcdistro', 'f14', None),
245             ):
246 #            print 'handling',recname
247             path = filename
248             is_list = isinstance(default, list)
249             is_bool = isinstance(default, bool)
250             if not getattr(self.options, recname):
251                 try:
252                     parsed = file(path).readlines()
253                     if is_list:         # lists
254                         parsed = [x.strip() for x in parsed]
255                     else:               # strings and booleans
256                         if len(parsed) != 1:
257                             print "{} - error when parsing {}".format(sys.argv[1], path)
258                             sys.exit(1)
259                         parsed = parsed[0].strip()
260                         if is_bool:
261                             parsed = parsed.lower() == 'true'
262                     setattr(self.options, recname, parsed)
263                 except:
264                     if default != "":
265                         setattr(self.options, recname, default)
266                     else:
267                         print "Cannot determine", recname
268                         print "Run {} --help for help".format(sys.argv[0])
269                         sys.exit(1)
270
271             # save for next run
272             fsave = open(path, "w")
273             if is_list:                 # lists
274                 for value in getattr(self.options, recname):
275                     fsave.write(value + "\n")
276             else:                       # strings and booleans - just call str()
277                 fsave.write(str(getattr(self.options, recname)) + "\n")
278             fsave.close()
279 #            utils.header('Saved {} into {}'.format(recname, filename))
280
281             # lists need be reversed
282             # I suspect this is useful for the various pools but for config, it's painful
283             if isinstance(getattr(self.options, recname), list) and need_reverse:
284                 getattr(self.options, recname).reverse()
285
286             if self.options.verbose:
287                 utils.header('* Using {} = {}'.format(recname, getattr(self.options, recname)))
288
289         # hack : if sfa is not among the published rpms, skip these tests
290         TestPlc.check_whether_build_has_sfa(self.options.arch_rpms_url)
291
292         # initialize steps
293         if not self.options.steps:
294             # defaults, depends on using bonding or not
295             if self.options.bonding:
296                 self.options.steps = TestPlc.bonding_steps
297             else:
298                 self.options.steps = TestPlc.default_steps
299
300         if self.options.list_steps:
301             self.init_steps()
302             self.list_steps()
303             return 'SUCCESS'
304
305         # rewrite '-' into '_' in step names
306         self.options.steps   = [ step.replace('-', '_') for step in self.options.steps ]
307         self.options.exclude = [ step.replace('-', '_') for step in self.options.exclude ]
308         self.options.ignore  = [ step.replace('-', '_') for step in self.options.ignore ]
309
310         # technicality, decorate known steps to produce the '_ignore' version
311         TestPlc.create_ignore_steps()
312
313         # exclude
314         selected = []
315         for step in self.options.steps:
316             keep = True
317             for exclude in self.options.exclude:
318                 if utils.match(step, exclude):
319                     keep = False
320                     break
321             if keep:
322                 selected.append(step)
323
324         # ignore
325         selected = [ step if step not in self.options.ignore else step + "_ignore"
326                      for step in selected ]
327
328         self.options.steps = selected
329
330         # this is useful when propagating on host boxes, to avoid conflicts
331         self.options.buildname = os.path.basename(os.path.abspath(self.path))
332
333         if self.options.verbose:
334             self.show_env(self.options, "Verbose")
335
336         # load configs
337         all_plc_specs = []
338         for config in self.options.config:
339             modulename = 'config_' + config
340             try:
341                 m = __import__(modulename)
342                 all_plc_specs = m.config(all_plc_specs, self.options)
343             except :
344                 traceback.print_exc()
345                 print 'Cannot load config {} -- ignored'.format(modulename)
346                 raise
347
348         # provision on local substrate
349         all_plc_specs = LocalSubstrate.local_substrate.provision(all_plc_specs, self.options)
350
351         # remember substrate IP address(es) for next run
352         ips_bplc_file = open('arg-ips-bplc', 'w')
353         for plc_spec in all_plc_specs:
354             ips_bplc_file.write("{}\n".format(plc_spec['host_box']))
355         ips_bplc_file.close()
356         ips_vplc_file = open('arg-ips-vplc', 'w')
357         for plc_spec in all_plc_specs:
358             ips_vplc_file.write("{}\n".format(plc_spec['settings']['PLC_API_HOST']))
359         ips_vplc_file.close()
360         # ditto for nodes
361         ips_bnode_file = open('arg-ips-bnode', 'w')
362         for plc_spec in all_plc_specs:
363             for site_spec in plc_spec['sites']:
364                 for node_spec in site_spec['nodes']:
365                     ips_bnode_file.write("{}\n".format(node_spec['host_box']))
366         ips_bnode_file.close()
367         ips_vnode_file = open('arg-ips-vnode','w')
368         for plc_spec in all_plc_specs:
369             for site_spec in plc_spec['sites']:
370                 for node_spec in site_spec['nodes']:
371                     # back to normal (unqualified) form
372                     stripped = node_spec['node_fields']['hostname'].split('.')[0]
373                     ips_vnode_file.write("{}\n".format(stripped))
374         ips_vnode_file.close()
375
376         # build a TestPlc object from the result, passing options
377         for spec in all_plc_specs:
378             spec['failed_step'] = False
379         all_plcs = [ (x, TestPlc(x,self.options)) for x in all_plc_specs]
380
381         # pass options to utils as well
382         utils.init_options(self.options)
383
384         # populate TestBonding objects
385         # need to wait until here as we need all_plcs
386         if self.options.bonding:
387             ## allow to pass -g ../2015.03.15--f18 so we can use bash completion
388             self.options.bonding = os.path.basename(self.options.bonding)
389             # this will fail if ../{bonding} has not the right arg- files
390             for spec, test_plc in all_plcs:
391                 test_plc.test_bonding = TestBonding (test_plc,
392                                                      onelab_bonding_spec(self.options.bonding),
393                                                      self.options)
394         
395         overall_result = 'SUCCESS'
396         all_step_infos = []
397         for step in self.options.steps:
398             if not TestPlc.valid_step(step):
399                 continue
400             # some steps need to be done regardless of the previous ones: we force them
401             force = False
402             if step.endswith("_force"):
403                 step = step.replace("_force", "")
404                 force = True
405             # allow for steps to specify an index like in 
406             # run checkslice@2
407             try:
408                 step, qualifier = step.split('@')
409             except:
410                 qualifier = self.options.qualifier
411
412             try:
413                 stepobj = Step (step)
414                 for substep, method in stepobj.tuples():
415                     # a cross step will run a method on TestPlc that has a signature like
416                     # def cross_foo (self, all_test_plcs)
417                     cross = False
418                     if substep.find("cross_") == 0:
419                         cross = True
420                     all_step_infos.append ( (substep, method, force, cross, qualifier, ) )
421             except :
422                 utils.header("********** FAILED step {} (NOT FOUND) -- won't be run".format(step))
423                 traceback.print_exc()
424                 overall_result = 'FAILURE'
425             
426         if self.options.dry_run:
427             self.show_env(self.options, "Dry run")
428         
429         # init & open trace file if provided
430         if self.options.trace_file and not self.options.dry_run:
431             # create dir if needed
432             trace_dir = os.path.dirname(self.options.trace_file)
433             if trace_dir and not os.path.isdir(trace_dir):
434                 os.makedirs(trace_dir)
435             trace = open(self.options.trace_file,"w")
436
437         # do all steps on all plcs
438         TIME_FORMAT = "%H-%M-%S"
439         TRACE_FORMAT = "TRACE: {plc_counter:d} {begin}->{seconds}s={duration}s " + \
440                        "status={status} step={stepname} plc={plcname} force={force}\n"
441         for stepname, method, force, cross, qualifier in all_step_infos:
442             plc_counter = 0
443             for spec, plc_obj in all_plcs:
444                 plc_counter += 1
445                 # skip this step if we have specified a plc_explicit
446                 if qualifier and plc_counter != int(qualifier):
447                     continue
448
449                 plcname = spec['name']
450                 across_plcs = [ o for (s,o) in all_plcs if o!=plc_obj ]
451
452                 # run the step
453                 beg_time = datetime.now()
454                 begin = beg_time.strftime(TIME_FORMAT)
455                 if not spec['failed_step'] or force or self.options.interactive or self.options.keep_going:
456                     skip_step = False
457                     if self.options.interactive:
458                         prompting = True
459                         while prompting:
460                             msg="{:d} Run step {} on {} [r](un)/d(ry_run)/p(roceed)/s(kip)/q(uit) ? "\
461                                 .format(plc_counter, stepname, plcname)
462                             answer = raw_input(msg).strip().lower() or "r"
463                             answer = answer[0]
464                             if answer in ['s','n']:     # skip/no/next
465                                 print '{} on {} skipped'.format(stepname, plcname)
466                                 prompting = False
467                                 skip_step = True
468                             elif answer in ['q','b']:   # quit/bye
469                                 print 'Exiting'
470                                 return 'FAILURE'
471                             elif answer in ['d']:       # dry_run
472                                 dry_run = self.options.dry_run
473                                 self.options.dry_run = True
474                                 plc_obj.options.dry_run = True
475                                 plc_obj.apiserver.set_dry_run(True)
476                                 if not cross:
477                                     step_result=method(plc_obj)
478                                 else:
479                                     step_result=method(plc_obj, across_plcs)
480                                 print 'dry_run step ->', step_result
481                                 self.options.dry_run = dry_run
482                                 plc_obj.options.dry_run = dry_run
483                                 plc_obj.apiserver.set_dry_run(dry_run)
484                             elif answer in ['p']:
485                                 # take it as a yes and leave interactive mode
486                                 prompting = False
487                                 self.options.interactive = False
488                             elif answer in ['r','y']:   # run/yes
489                                 prompting = False
490                     if skip_step:
491                         continue
492                     try:
493                         force_msg = ""
494                         if force and spec['failed_step']:
495                             force_msg=" (forced after {} has failed)".format(spec['failed_step'])
496                         utils.header("********** {:d} RUNNING step {}{} on plc {}"\
497                                      .format(plc_counter, stepname, force_msg, plcname))
498                         if not cross:
499                             step_result = method(plc_obj)
500                         else:
501                             step_result = method(plc_obj, across_plcs)
502                         if isinstance (step_result, Ignored):
503                             step_result = step_result.result
504                             if step_result:
505                                 msg = "OK"
506                             else:
507                                 msg = "KO"
508                                 # do not overwrite if FAILURE
509                                 if overall_result == 'SUCCESS': 
510                                     overall_result = 'IGNORED'
511                             utils.header('********** {} IGNORED ({}) step {} on {}'\
512                                          .format(plc_counter, msg, stepname, plcname))
513                             status="{}[I]".format(msg)
514                         elif step_result:
515                             utils.header('********** {:d} SUCCESSFUL step {} on {}'\
516                                          .format(plc_counter, stepname, plcname))
517                             status = "OK"
518                         else:
519                             overall_result = 'FAILURE'
520                             spec['failed_step'] = stepname
521                             utils.header('********** {:d} FAILED step {} on {} (discarded from further steps)'\
522                                          .format(plc_counter, stepname, plcname))
523                             status = "KO"
524                     except:
525                         overall_result = 'FAILURE'
526                         spec['failed_step'] = stepname
527                         traceback.print_exc()
528                         utils.header ('********** {} FAILED (exception) step {} on {} (discarded from further steps)'\
529                                       .format(plc_counter, stepname, plcname))
530                         status = "KO"
531
532                 # do not run, just display it's skipped
533                 else:
534                     why = "has failed {}".format(spec['failed_step'])
535                     utils.header("********** {} SKIPPED Step {} on {} ({})"\
536                                  .format(plc_counter, stepname, plcname, why))
537                     status = "UNDEF"
538                 if not self.options.dry_run:
539                     delay = datetime.now()-beg_time
540                     seconds = int(delay.total_seconds())
541                     duration = str(delay)
542                     # always do this on stdout
543                     print TRACE_FORMAT.format(**locals())
544                     # duplicate on trace_file if provided
545                     if self.options.trace_file:
546                         trace.write(TRACE_FORMAT.format(**locals()))
547                         trace.flush()
548
549         if self.options.trace_file and not self.options.dry_run:
550             trace.close()
551
552         # free local substrate
553         LocalSubstrate.local_substrate.release(self.options)
554         
555         return overall_result
556
557     # wrapper to run, returns a shell-compatible result
558     # retcod:
559     # 0: SUCCESS
560     # 1: FAILURE
561     # 2: SUCCESS but some ignored steps failed
562     # 3: OTHER ERROR
563     def main(self):
564         try:
565             success = self.run()
566             if success == 'SUCCESS':
567                 return 0
568             elif success == 'IGNORED':
569                 return 2
570             else:
571                 return 1
572         except SystemExit:
573             print 'Caught SystemExit'
574             return 3
575         except:
576             traceback.print_exc()
577             return 3
578
579 if __name__ == "__main__":
580     exit_code = TestMain().main()
581     print "TestMain exit code", exit_code
582     sys.exit(exit_code)