fix multi-configs, now uses natural order
[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 optparse import OptionParser
8 import traceback
9 from time import strftime
10 import readline
11
12 import utils
13 from TestPlc import TestPlc
14 from TestSite import TestSite
15 from TestNode import TestNode
16
17 # add $HOME in PYTHONPATH so we can import LocalTestResources.py
18 sys.path.append(os.environ['HOME'])
19 import LocalTestResources
20
21 class TestMain:
22
23     subversion_id = "Now using git -- version tracker broken"
24
25     default_config = [ 'default' ] 
26
27     default_build_url = "git://git.onelab.eu/tests"
28
29     def __init__ (self):
30         self.path=os.path.dirname(sys.argv[0]) or "."
31         os.chdir(self.path)
32
33     def show_env (self,options, message):
34         if self.options.verbose:
35             utils.header (message)
36             utils.show_options("main options",options)
37
38     def init_steps(self):
39         self.steps_message  = 20*'x'+" Defaut steps are\n"+TestPlc.printable_steps(TestPlc.default_steps)
40         self.steps_message += 20*'x'+" Other useful steps are\n"+TestPlc.printable_steps(TestPlc.other_steps)
41
42     def list_steps(self):
43         if not self.options.verbose:
44             print self.steps_message,
45         else:
46             testplc_method_dict = __import__("TestPlc").__dict__['TestPlc'].__dict__
47             scopes = [("Default steps",TestPlc.default_steps)]
48             if self.options.all_steps:
49                 scopes.append ( ("Other steps",TestPlc.other_steps) )
50             for (scope,steps) in scopes:
51                 print '--------------------',scope
52                 for step in [step for step in steps if TestPlc.valid_step(step)]:
53                     try:        (step,qualifier)=step.split('@')
54                     except:     pass
55                     stepname=step
56                     for special in ['force']:
57                         stepname = stepname.replace(special+'_',"")
58                     print '*',step,"\r",4*"\t",
59                     try:
60                         doc=testplc_method_dict[stepname].__doc__
61                     except:
62                         try:
63                             # locate the step_<name> module
64                             modulename='step_'+stepname
65                             doc = __import__(modulename).__doc__
66                         except:
67                             doc=None
68                     if doc: print doc
69                     else:   print "*** no doc found"
70
71     def run (self):
72         self.init_steps()
73         usage = """usage: %%prog [options] steps
74 arch-rpms-url defaults to the last value used, as stored in arg-arch-rpms-url,
75    no default
76 config defaults to the last value used, as stored in arg-config,
77    or %r
78 ips_node, ips_plc and ips_qemu defaults to the last value used, as stored in arg-ips-{node,plc,qemu},
79    default is to use IP scanning
80 steps refer to a method in TestPlc or to a step_* module
81 ===
82 """%(TestMain.default_config)
83         usage += self.steps_message
84         parser=OptionParser(usage=usage,version=self.subversion_id)
85         parser.add_option("-u","--url",action="store", dest="arch_rpms_url", 
86                           help="URL of the arch-dependent RPMS area - for locating what to test")
87         parser.add_option("-b","--build",action="store", dest="build_url", 
88                           help="ignored, for legacy only")
89         parser.add_option("-c","--config",action="append", dest="config", default=[],
90                           help="Config module - can be set multiple times, or use quotes")
91         parser.add_option("-p","--personality",action="store", dest="personality", 
92                           help="personality - as in vbuild-nightly")
93         parser.add_option("-d","--pldistro",action="store", dest="pldistro", 
94                           help="pldistro - as in vbuild-nightly")
95         parser.add_option("-f","--fcdistro",action="store", dest="fcdistro", 
96                           help="fcdistro - as in vbuild-nightly")
97         parser.add_option("-x","--exclude",action="append", dest="exclude", default=[],
98                           help="steps to exclude - can be set multiple times, or use quotes")
99         parser.add_option("-a","--all",action="store_true",dest="all_steps", default=False,
100                           help="Run all default steps")
101         parser.add_option("-l","--list",action="store_true",dest="list_steps", default=False,
102                           help="List known steps")
103         parser.add_option("-N","--nodes",action="append", dest="ips_node", default=[],
104                           help="Specify the set of hostname/IP's to use for nodes")
105         parser.add_option("-P","--plcs",action="append", dest="ips_plc", default=[],
106                           help="Specify the set of hostname/IP's to use for plcs")
107         parser.add_option("-Q","--qemus",action="append", dest="ips_qemu", default=[],
108                           help="Specify the set of hostname/IP's to use for qemu boxes")
109         parser.add_option("-s","--size",action="store",type="int",dest="size",default=1,
110                           help="sets test size in # of plcs - default is 1")
111         parser.add_option("-q","--qualifier",action="store",type="int",dest="qualifier",default=None,
112                           help="run steps only on plc numbered <qualifier>, starting at 1")
113         parser.add_option("-k","--keep-going",action="store",dest="keep_going",default=False,
114                           help="proceeds even if some steps are failing")
115         parser.add_option("-D","--dbname",action="store",dest="dbname",default=None,
116                            help="Used by plc_db_dump and plc_db_restore")
117         parser.add_option("-v","--verbose", action="store_true", dest="verbose", default=False, 
118                           help="Run in verbose mode")
119         parser.add_option("-i","--interactive",action="store_true",dest="interactive",default=False,
120                           help="prompts before each step")
121         parser.add_option("-n","--dry-run", action="store_true", dest="dry_run", default=False,
122                           help="Show environment and exits")
123         parser.add_option("-r","--restart-nm", action="store_true", dest="forcenm", default=False, 
124                           help="Force the NM to restart in ssh_slices step")
125         parser.add_option("-t","--trace", action="store", dest="trace_file", default=None,
126                           #default="logs/trace-@TIME@.txt",
127                           help="Trace file location")
128         (self.options, self.args) = parser.parse_args()
129
130         # allow things like "run -c 'c1 c2' -c c3"
131         def flatten (x):
132             result = []
133             for el in x:
134                 if hasattr(el, "__iter__") and not isinstance(el, basestring):
135                     result.extend(flatten(el))
136                 else:
137                     result.append(el)
138             return result
139         # flatten relevant options
140         for optname in ['config','exclude','ips_node','ips_plc','ips_qemu']:
141             setattr(self.options,optname, flatten ( [ arg.split() for arg in getattr(self.options,optname) ] ))
142
143         # handle defaults and option persistence
144         for (recname,filename,default,need_reverse) in (
145             ('build_url','arg-build-url',TestMain.default_build_url,None) ,
146             ('ips_node','arg-ips-node',[],True) , 
147             ('ips_plc','arg-ips-plc',[],True) , 
148             ('ips_qemu','arg-ips-qemu',[],True) , 
149             ('config','arg-config',TestMain.default_config,False) , 
150             ('arch_rpms_url','arg-arch-rpms-url',"",None) , 
151             ('personality','arg-personality',"linux32",None),
152             ('pldistro','arg-pldistro',"planetlab",None),
153             ('fcdistro','arg-fcdistro','centos5',None),
154             ) :
155 #            print 'handling',recname
156             path=filename
157             is_list = isinstance(default,list)
158             if not getattr(self.options,recname):
159                 try:
160                     parsed=file(path).readlines()
161                     if not is_list:    # strings
162                         if len(parsed) != 1:
163                             print "%s - error when parsing %s"%(sys.argv[1],path)
164                             sys.exit(1)
165                         parsed=parsed[0].strip()
166                     else:              # lists
167                         parsed=[x.strip() for x in parsed]
168                     setattr(self.options,recname,parsed)
169                 except:
170                     if default != "":
171                         setattr(self.options,recname,default)
172                     else:
173                         print "Cannot determine",recname
174                         print "Run %s --help for help"%sys.argv[0]                        
175                         sys.exit(1)
176
177             # save for next run
178             fsave=open(path,"w")
179             if not is_list:
180                 fsave.write(getattr(self.options,recname) + "\n")
181             else:
182                 for value in getattr(self.options,recname):
183                     fsave.write(value + "\n")
184             fsave.close()
185 #            utils.header('Saved %s into %s'%(recname,filename))
186
187             # lists need be reversed
188             # I suspect this is useful for the various pools but for config, it's painful
189             if isinstance(getattr(self.options,recname),list) and need_reverse:
190                 getattr(self.options,recname).reverse()
191
192             if self.options.verbose:
193                 utils.header('* Using %s = %s'%(recname,getattr(self.options,recname)))
194
195         # hack : if sfa is not among the published rpms, skip these tests
196         TestPlc.check_whether_build_has_sfa(self.options.arch_rpms_url)
197
198         # no step specified
199         if len(self.args) == 0:
200             self.options.steps=TestPlc.default_steps
201         else:
202             self.options.steps = self.args
203
204         if self.options.list_steps:
205             self.init_steps()
206             self.list_steps()
207             return True
208
209         # steps
210         if not self.options.steps:
211             #default (all) steps
212             #self.options.steps=['dump','clean','install','populate']
213             self.options.steps=TestPlc.default_steps
214
215         # rewrite '-' into '_' in step names
216         self.options.steps = [ step.replace('-','_') for step in self.options.steps ]
217
218         # exclude
219         selected=[]
220         for step in self.options.steps:
221             keep=True
222             for exclude in self.options.exclude:
223                 if utils.match(step,exclude):
224                     keep=False
225                     break
226             if keep: selected.append(step)
227         self.options.steps=selected
228
229         # this is useful when propagating on host boxes, to avoid conflicts
230         self.options.buildname = os.path.basename (os.path.abspath (self.path))
231
232         if self.options.verbose:
233             self.show_env(self.options,"Verbose")
234
235         # load configs
236         all_plc_specs = []
237         for config in self.options.config:
238             modulename='config_'+config
239             try:
240                 m = __import__(modulename)
241                 all_plc_specs = m.config(all_plc_specs,self.options)
242             except :
243                 traceback.print_exc()
244                 print 'Cannot load config %s -- ignored'%modulename
245                 raise
246
247         # run localize as defined by local_resources
248         all_plc_specs = LocalTestResources.local_resources.localize(all_plc_specs,self.options)
249
250         # remember plc IP address(es) if not specified
251         ips_plc_file=open('arg-ips-plc','w')
252         for plc_spec in all_plc_specs:
253             ips_plc_file.write("%s\n"%plc_spec['PLC_API_HOST'])
254         ips_plc_file.close()
255         # ditto for nodes
256         ips_node_file=open('arg-ips-node','w')
257         for plc_spec in all_plc_specs:
258             for site_spec in plc_spec['sites']:
259                 for node_spec in site_spec['nodes']:
260                     ips_node_file.write("%s\n"%node_spec['node_fields']['hostname'])
261         ips_node_file.close()
262         # ditto for qemu boxes
263         ips_qemu_file=open('arg-ips-qemu','w')
264         for plc_spec in all_plc_specs:
265             for site_spec in plc_spec['sites']:
266                 for node_spec in site_spec['nodes']:
267                     ips_qemu_file.write("%s\n"%node_spec['host_box'])
268         ips_qemu_file.close()
269         # build a TestPlc object from the result, passing options
270         for spec in all_plc_specs:
271             spec['failed_step'] = False
272         all_plcs = [ (x, TestPlc(x,self.options)) for x in all_plc_specs]
273
274         # pass options to utils as well
275         utils.init_options(self.options)
276
277         overall_result = True
278         testplc_method_dict = __import__("TestPlc").__dict__['TestPlc'].__dict__
279         all_step_infos=[]
280         for step in self.options.steps:
281             if not TestPlc.valid_step(step):
282                 continue
283             # some steps need to be done regardless of the previous ones: we force them
284             force=False
285             if step.find("force_") == 0:
286                 step=step.replace("force_","")
287                 force=True
288             # a cross step will run a method on TestPlc that has a signature like
289             # def cross_foo (self, all_test_plcs)
290             cross=False
291             if step.find("cross_") == 0:
292                 cross=True
293             # allow for steps to specify an index like in 
294             # run checkslice@2
295             try:        (step,qualifier)=step.split('@')
296             except:     qualifier=self.options.qualifier
297
298             # try and locate a method in TestPlc
299             if testplc_method_dict.has_key(step):
300                 all_step_infos += [ (step, testplc_method_dict[step] , force, cross, qualifier)]
301             # otherwise search for the 'run' method in the step_<x> module
302             else:
303                 modulename='step_'+step
304                 try:
305                     # locate all methods named run* in the module
306                     module_dict = __import__(modulename).__dict__
307                     names = [ key for key in module_dict.keys() if key.find("run")==0 ]
308                     if not names:
309                         raise Exception,"No run* method in module %s"%modulename
310                     names.sort()
311                     all_step_infos += [ ("%s.%s"%(step,name),module_dict[name],force,cross,qualifier) for name in names ]
312                 except :
313                     utils.header("********** FAILED step %s (NOT FOUND) -- won't be run"%step)
314                     traceback.print_exc()
315                     overall_result = False
316             
317         if self.options.dry_run:
318             self.show_env(self.options,"Dry run")
319         
320         # init & open trace file if provided
321         if self.options.trace_file and not self.options.dry_run:
322             time=strftime("%H-%M")
323             date=strftime("%Y-%m-%d")
324             trace_file=self.options.trace_file
325             trace_file=trace_file.replace("@TIME@",time)
326             trace_file=trace_file.replace("@DATE@",date)
327             self.options.trace_file=trace_file
328             # create dir if needed
329             trace_dir=os.path.dirname(trace_file)
330             if trace_dir and not os.path.isdir(trace_dir):
331                 os.makedirs(trace_dir)
332             trace=open(trace_file,"w")
333
334         # do all steps on all plcs
335         TIME_FORMAT="%H-%M-%S"
336         TRACE_FORMAT="TRACE: %(plc_counter)d %(beg)s->%(end)s status=%(status)s step=%(stepname)s plc=%(plcname)s force=%(force)s\n"
337         for (stepname,method,force,cross,qualifier) in all_step_infos:
338             plc_counter=0
339             for (spec,plc_obj) in all_plcs:
340                 plc_counter+=1
341                 # skip this step if we have specified a plc_explicit
342                 if qualifier and plc_counter!=int(qualifier): continue
343
344                 plcname=spec['name']
345                 across_plcs = [ o for (s,o) in all_plcs if o!=plc_obj ]
346
347                 # run the step
348                 beg=strftime(TIME_FORMAT)
349                 if not spec['failed_step'] or force or self.options.interactive or self.options.keep_going:
350                     skip_step=False
351                     if self.options.interactive:
352                         prompting=True
353                         while prompting:
354                             msg="%d Run step %s on %s [r](un)/d(ry_run)/s(kip)/q(uit) ? "%(plc_counter,stepname,plcname)
355                             answer=raw_input(msg).strip().lower() or "r"
356                             answer=answer[0]
357                             if answer in ['s','n']:     # skip/no/next
358                                 print '%s on %s skipped'%(stepname,plcname)
359                                 prompting=False
360                                 skip_step=True
361                             elif answer in ['q','b']:   # quit/bye
362                                 print 'Exiting'
363                                 return
364                             elif answer in ['d']:       # dry_run
365                                 dry_run=self.options.dry_run
366                                 self.options.dry_run=True
367                                 plc_obj.options.dry_run=True
368                                 plc_obj.apiserver.set_dry_run(True)
369                                 if not cross:   step_result=method(plc_obj)
370                                 else:           step_result=method(plc_obj,across_plcs)
371                                 print 'dry_run step ->',step_result
372                                 self.options.dry_run=dry_run
373                                 plc_obj.options.dry_run=dry_run
374                                 plc_obj.apiserver.set_dry_run(dry_run)
375                             elif answer in ['r','y']:   # run/yes
376                                 prompting=False
377                     if skip_step:
378                         continue
379                     try:
380                         force_msg=""
381                         if force and spec['failed_step']: force_msg=" (forced after %s has failed)"%spec['failed_step']
382                         utils.header("********** %d RUNNING step %s%s on plc %s"%(plc_counter,stepname,force_msg,plcname))
383                         if not cross:   step_result = method(plc_obj)
384                         else:           step_result = method(plc_obj,across_plcs)
385                         if step_result:
386                             utils.header('********** %d SUCCESSFUL step %s on %s'%(plc_counter,stepname,plcname))
387                             status="OK"
388                         else:
389                             overall_result = False
390                             spec['failed_step'] = stepname
391                             utils.header('********** %d FAILED Step %s on %s (discarded from further steps)'\
392                                              %(plc_counter,stepname,plcname))
393                             status="KO"
394                     except:
395                         overall_result=False
396                         spec['failed_step'] = stepname
397                         traceback.print_exc()
398                         utils.header ('********** %d FAILED (exception) Step %s on %s (discarded from further steps)'\
399                                           %(plc_counter,stepname,plcname))
400                         status="KO"
401
402                 # do not run, just display it's skipped
403                 else:
404                     why="has failed %s"%spec['failed_step']
405                     utils.header("********** %d SKIPPED Step %s on %s (%s)"%(plc_counter,stepname,plcname,why))
406                     status="UNDEF"
407                 if not self.options.dry_run:
408                     end=strftime(TIME_FORMAT)
409                     # always do this on stdout
410                     print TRACE_FORMAT%locals()
411                     # duplicate on trace_file if provided
412                     if self.options.trace_file:
413                         trace.write(TRACE_FORMAT%locals())
414                         trace.flush()
415
416         if self.options.trace_file and not self.options.dry_run:
417             trace.close()
418
419         return overall_result
420
421     # wrapper to run, returns a shell-compatible result
422     def main(self):
423         try:
424             success=self.run()
425             if success:
426                 return 0
427             else:
428                 return 1 
429         except SystemExit:
430             print 'Caught SystemExit'
431             raise
432         except:
433             traceback.print_exc()
434             return 2
435
436 if __name__ == "__main__":
437     sys.exit(TestMain().main())