3 # Thierry Parmentelat <thierry.parmentelat@inria.fr>
4 # Copyright (C) 2010 INRIA
6 import sys, os, os.path
7 from optparse import OptionParser
9 from time import strftime
13 from TestPlc import TestPlc
14 from TestSite import TestSite
15 from TestNode import TestNode
17 # add $HOME in PYTHONPATH so we can import LocalSubstrate.py
18 sys.path.append(os.environ['HOME'])
23 subversion_id = "Now using git -- version tracker broken"
25 default_config = [ 'default' ]
27 default_build_url = "git://git.onelab.eu/tests"
30 self.path=os.path.dirname(sys.argv[0]) or "."
33 def show_env (self,options, message):
34 if self.options.verbose:
35 utils.header (message)
36 utils.show_options("main options",options)
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)
43 if not self.options.verbose:
44 print self.steps_message,
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('@')
56 for special in ['force']:
57 stepname = stepname.replace(special+'_',"")
58 print '*',step,"\r",4*"\t",
60 doc=testplc_method_dict[stepname].__doc__
63 # locate the step_<name> module
64 modulename='step_'+stepname
65 doc = __import__(modulename).__doc__
69 else: print "*** no doc found"
73 usage = """usage: %%prog [options] steps
74 arch-rpms-url defaults to the last value used, as stored in arg-arch-rpms-url,
76 config defaults to the last value used, as stored in arg-config,
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
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("-k","--keep-going",action="store",dest="keep_going",default=False,
116 help="proceeds even if some steps are failing")
117 parser.add_option("-D","--dbname",action="store",dest="dbname",default=None,
118 help="Used by plc_db_dump and plc_db_restore")
119 parser.add_option("-v","--verbose", action="store_true", dest="verbose", default=False,
120 help="Run in verbose mode")
121 parser.add_option("-i","--interactive",action="store_true",dest="interactive",default=False,
122 help="prompts before each step")
123 parser.add_option("-n","--dry-run", action="store_true", dest="dry_run", default=False,
124 help="Show environment and exits")
125 parser.add_option("-r","--restart-nm", action="store_true", dest="forcenm", default=False,
126 help="Force the NM to restart in ssh_slices step")
127 parser.add_option("-t","--trace", action="store", dest="trace_file", default=None,
128 #default="logs/trace-@TIME@.txt",
129 help="Trace file location")
130 (self.options, self.args) = parser.parse_args()
132 # allow things like "run -c 'c1 c2' -c c3"
136 if hasattr(el, "__iter__") and not isinstance(el, basestring):
137 result.extend(flatten(el))
141 # flatten relevant options
142 for optname in ['config','exclude','ips_bplc','ips_vplc','ips_bnode','ips_vnode']:
143 setattr(self.options,optname, flatten ( [ arg.split() for arg in getattr(self.options,optname) ] ))
145 # handle defaults and option persistence
146 for (recname,filename,default,need_reverse) in (
147 ('build_url','arg-build-url',TestMain.default_build_url,None) ,
148 ('ips_bplc','arg-ips-bplc',[],True),
149 ('ips_vplc','arg-ips-vplc',[],True) ,
150 ('ips_bnode','arg-ips-bnode',[],True),
151 ('ips_vnode','arg-ips-vnode',[],True) ,
152 ('config','arg-config',TestMain.default_config,False) ,
153 ('arch_rpms_url','arg-arch-rpms-url',"",None) ,
154 ('personality','arg-personality',"linux64",None),
155 ('pldistro','arg-pldistro',"onelab",None),
156 ('fcdistro','arg-fcdistro','f14',None),
158 # print 'handling',recname
160 is_list = isinstance(default,list)
161 if not getattr(self.options,recname):
163 parsed=file(path).readlines()
164 if not is_list: # strings
166 print "%s - error when parsing %s"%(sys.argv[1],path)
168 parsed=parsed[0].strip()
170 parsed=[x.strip() for x in parsed]
171 setattr(self.options,recname,parsed)
174 setattr(self.options,recname,default)
176 print "Cannot determine",recname
177 print "Run %s --help for help"%sys.argv[0]
183 fsave.write(getattr(self.options,recname) + "\n")
185 for value in getattr(self.options,recname):
186 fsave.write(value + "\n")
188 # utils.header('Saved %s into %s'%(recname,filename))
190 # lists need be reversed
191 # I suspect this is useful for the various pools but for config, it's painful
192 if isinstance(getattr(self.options,recname),list) and need_reverse:
193 getattr(self.options,recname).reverse()
195 if self.options.verbose:
196 utils.header('* Using %s = %s'%(recname,getattr(self.options,recname)))
198 # hack : if sfa is not among the published rpms, skip these tests
199 TestPlc.check_whether_build_has_sfa(self.options.arch_rpms_url)
202 if len(self.args) == 0:
203 self.options.steps=TestPlc.default_steps
205 self.options.steps = self.args
207 if self.options.list_steps:
213 if not self.options.steps:
215 #self.options.steps=['dump','clean','install','populate']
216 self.options.steps=TestPlc.default_steps
218 # rewrite '-' into '_' in step names
219 self.options.steps = [ step.replace('-','_') for step in self.options.steps ]
223 for step in self.options.steps:
225 for exclude in self.options.exclude:
226 if utils.match(step,exclude):
229 if keep: selected.append(step)
230 self.options.steps=selected
232 # this is useful when propagating on host boxes, to avoid conflicts
233 self.options.buildname = os.path.basename (os.path.abspath (self.path))
235 if self.options.verbose:
236 self.show_env(self.options,"Verbose")
240 for config in self.options.config:
241 modulename='config_'+config
243 m = __import__(modulename)
244 all_plc_specs = m.config(all_plc_specs,self.options)
246 traceback.print_exc()
247 print 'Cannot load config %s -- ignored'%modulename
250 # provision on local substrate
251 all_plc_specs = LocalSubstrate.local_substrate.provision(all_plc_specs,self.options)
253 # remember substrate IP address(es) for next run
254 ips_bplc_file=open('arg-ips-bplc','w')
255 for plc_spec in all_plc_specs:
256 ips_bplc_file.write("%s\n"%plc_spec['host_box'])
257 ips_bplc_file.close()
258 ips_vplc_file=open('arg-ips-vplc','w')
259 for plc_spec in all_plc_specs:
260 ips_vplc_file.write("%s\n"%plc_spec['PLC_API_HOST'])
261 ips_vplc_file.close()
263 ips_bnode_file=open('arg-ips-bnode','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_bnode_file.write("%s\n"%node_spec['host_box'])
268 ips_bnode_file.close()
269 ips_vnode_file=open('arg-ips-vnode','w')
270 for plc_spec in all_plc_specs:
271 for site_spec in plc_spec['sites']:
272 for node_spec in site_spec['nodes']:
273 # back to normal (unqualified) form
274 stripped=node_spec['node_fields']['hostname'].split('.')[0]
275 ips_vnode_file.write("%s\n"%stripped)
276 ips_vnode_file.close()
278 # build a TestPlc object from the result, passing options
279 for spec in all_plc_specs:
280 spec['failed_step'] = False
281 all_plcs = [ (x, TestPlc(x,self.options)) for x in all_plc_specs]
283 # pass options to utils as well
284 utils.init_options(self.options)
286 overall_result = True
287 testplc_method_dict = __import__("TestPlc").__dict__['TestPlc'].__dict__
289 for step in self.options.steps:
290 if not TestPlc.valid_step(step):
292 # some steps need to be done regardless of the previous ones: we force them
294 if step.find("force_") == 0:
295 step=step.replace("force_","")
297 # a cross step will run a method on TestPlc that has a signature like
298 # def cross_foo (self, all_test_plcs)
300 if step.find("cross_") == 0:
302 # allow for steps to specify an index like in
304 try: (step,qualifier)=step.split('@')
305 except: qualifier=self.options.qualifier
307 # try and locate a method in TestPlc
308 if testplc_method_dict.has_key(step):
309 all_step_infos += [ (step, testplc_method_dict[step] , force, cross, qualifier)]
310 # otherwise search for the 'run' method in the step_<x> module
312 modulename='step_'+step
314 # locate all methods named run* in the module
315 module_dict = __import__(modulename).__dict__
316 names = [ key for key in module_dict.keys() if key.find("run")==0 ]
318 raise Exception,"No run* method in module %s"%modulename
320 all_step_infos += [ ("%s.%s"%(step,name),module_dict[name],force,cross,qualifier) for name in names ]
322 utils.header("********** FAILED step %s (NOT FOUND) -- won't be run"%step)
323 traceback.print_exc()
324 overall_result = False
326 if self.options.dry_run:
327 self.show_env(self.options,"Dry run")
329 # init & open trace file if provided
330 if self.options.trace_file and not self.options.dry_run:
331 time=strftime("%H-%M")
332 date=strftime("%Y-%m-%d")
333 trace_file=self.options.trace_file
334 trace_file=trace_file.replace("@TIME@",time)
335 trace_file=trace_file.replace("@DATE@",date)
336 self.options.trace_file=trace_file
337 # create dir if needed
338 trace_dir=os.path.dirname(trace_file)
339 if trace_dir and not os.path.isdir(trace_dir):
340 os.makedirs(trace_dir)
341 trace=open(trace_file,"w")
343 # do all steps on all plcs
344 TIME_FORMAT="%H-%M-%S"
345 TRACE_FORMAT="TRACE: %(plc_counter)d %(beg)s->%(end)s status=%(status)s step=%(stepname)s plc=%(plcname)s force=%(force)s\n"
346 for (stepname,method,force,cross,qualifier) in all_step_infos:
348 for (spec,plc_obj) in all_plcs:
350 # skip this step if we have specified a plc_explicit
351 if qualifier and plc_counter!=int(qualifier): continue
354 across_plcs = [ o for (s,o) in all_plcs if o!=plc_obj ]
357 beg=strftime(TIME_FORMAT)
358 if not spec['failed_step'] or force or self.options.interactive or self.options.keep_going:
360 if self.options.interactive:
363 msg="%d Run step %s on %s [r](un)/d(ry_run)/s(kip)/q(uit) ? "%(plc_counter,stepname,plcname)
364 answer=raw_input(msg).strip().lower() or "r"
366 if answer in ['s','n']: # skip/no/next
367 print '%s on %s skipped'%(stepname,plcname)
370 elif answer in ['q','b']: # quit/bye
373 elif answer in ['d']: # dry_run
374 dry_run=self.options.dry_run
375 self.options.dry_run=True
376 plc_obj.options.dry_run=True
377 plc_obj.apiserver.set_dry_run(True)
378 if not cross: step_result=method(plc_obj)
379 else: step_result=method(plc_obj,across_plcs)
380 print 'dry_run step ->',step_result
381 self.options.dry_run=dry_run
382 plc_obj.options.dry_run=dry_run
383 plc_obj.apiserver.set_dry_run(dry_run)
384 elif answer in ['r','y']: # run/yes
390 if force and spec['failed_step']: force_msg=" (forced after %s has failed)"%spec['failed_step']
391 utils.header("********** %d RUNNING step %s%s on plc %s"%(plc_counter,stepname,force_msg,plcname))
392 if not cross: step_result = method(plc_obj)
393 else: step_result = method(plc_obj,across_plcs)
395 utils.header('********** %d SUCCESSFUL step %s on %s'%(plc_counter,stepname,plcname))
398 overall_result = False
399 spec['failed_step'] = stepname
400 utils.header('********** %d FAILED Step %s on %s (discarded from further steps)'\
401 %(plc_counter,stepname,plcname))
405 spec['failed_step'] = stepname
406 traceback.print_exc()
407 utils.header ('********** %d FAILED (exception) Step %s on %s (discarded from further steps)'\
408 %(plc_counter,stepname,plcname))
411 # do not run, just display it's skipped
413 why="has failed %s"%spec['failed_step']
414 utils.header("********** %d SKIPPED Step %s on %s (%s)"%(plc_counter,stepname,plcname,why))
416 if not self.options.dry_run:
417 end=strftime(TIME_FORMAT)
418 # always do this on stdout
419 print TRACE_FORMAT%locals()
420 # duplicate on trace_file if provided
421 if self.options.trace_file:
422 trace.write(TRACE_FORMAT%locals())
425 if self.options.trace_file and not self.options.dry_run:
428 # free local substrate
429 LocalSubstrate.local_substrate.release(self.options)
431 return overall_result
433 # wrapper to run, returns a shell-compatible result
442 print 'Caught SystemExit'
445 traceback.print_exc()
448 if __name__ == "__main__":
449 sys.exit(TestMain().main())