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