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