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