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