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 LocalTestResources.py
18 sys.path.append(os.environ['HOME'])
19 import LocalTestResources
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)]:
54 if step.find("force_") == 0:
55 stepname=step.replace("force_","")
57 print '*',step,"\r",4*"\t",
59 print testplc_method_dict[stepname].__doc__
61 print "*** no doc found"
65 usage = """usage: %%prog [options] steps
66 arch-rpms-url defaults to the last value used, as stored in arg-arch-rpms-url,
68 config defaults to the last value used, as stored in arg-config,
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
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("-D","--dbname",action="store",dest="dbname",default=None,
106 help="Used by db_dump and db_restore")
107 parser.add_option("-v","--verbose", action="store_true", dest="verbose", default=False,
108 help="Run in verbose mode")
109 parser.add_option("-i","--interactive",action="store_true",dest="interactive",default=False,
110 help="prompts before each step")
111 parser.add_option("-n","--dry-run", action="store_true", dest="dry_run", default=False,
112 help="Show environment and exits")
113 parser.add_option("-r","--restart-nm", action="store_true", dest="forcenm", default=False,
114 help="Force the NM to restart in check_slices step")
115 parser.add_option("-t","--trace", action="store", dest="trace_file", default=None,
116 #default="logs/trace-@TIME@.txt",
117 help="Trace file location")
118 (self.options, self.args) = parser.parse_args()
120 # allow things like "run -c 'c1 c2' -c c3"
124 if hasattr(el, "__iter__") and not isinstance(el, basestring):
125 result.extend(flatten(el))
129 # flatten relevant options
130 for optname in ['config','exclude','ips_node','ips_plc','ips_qemu']:
131 setattr(self.options,optname, flatten ( [ arg.split() for arg in getattr(self.options,optname) ] ))
133 # handle defaults and option persistence
134 for (recname,filename,default) in (
135 ('build_url','arg-build-url',TestMain.default_build_url) ,
136 ('ips_node','arg-ips-node',[]) ,
137 ('ips_plc','arg-ips-plc',[]) ,
138 ('ips_qemu','arg-ips-qemu',[]) ,
139 ('config','arg-config',TestMain.default_config) ,
140 ('arch_rpms_url','arg-arch-rpms-url',"") ,
141 ('personality','arg-personality',"linux32"),
142 ('pldistro','arg-pldistro',"planetlab"),
143 ('fcdistro','arg-fcdistro','centos5'),
145 # print 'handling',recname
147 is_list = isinstance(default,list)
148 if not getattr(self.options,recname):
150 parsed=file(path).readlines()
151 if not is_list: # strings
153 print "%s - error when parsing %s"%(sys.argv[1],path)
155 parsed=parsed[0].strip()
157 parsed=[x.strip() for x in parsed]
158 setattr(self.options,recname,parsed)
161 setattr(self.options,recname,default)
163 print "Cannot determine",recname
164 print "Run %s --help for help"%sys.argv[0]
170 fsave.write(getattr(self.options,recname) + "\n")
172 for value in getattr(self.options,recname):
173 fsave.write(value + "\n")
175 # utils.header('Saved %s into %s'%(recname,filename))
177 # lists need be reversed
178 if isinstance(getattr(self.options,recname),list):
179 getattr(self.options,recname).reverse()
181 if self.options.verbose:
182 utils.header('* Using %s = %s'%(recname,getattr(self.options,recname)))
184 # hack : if sfa is not among the published rpms, skip these tests
185 TestPlc.check_whether_build_has_sfa(self.options.arch_rpms_url)
188 if len(self.args) == 0:
189 self.options.steps=TestPlc.default_steps
191 self.options.steps = self.args
193 if self.options.list_steps:
199 if not self.options.steps:
201 #self.options.steps=['dump','clean','install','populate']
202 self.options.steps=TestPlc.default_steps
204 # rewrite '-' into '_' in step names
205 self.options.steps = [ step.replace('-','_') for step in self.options.steps ]
209 for step in self.options.steps:
211 for exclude in self.options.exclude:
212 if utils.match(step,exclude):
215 if keep: selected.append(step)
216 self.options.steps=selected
218 # this is useful when propagating on host boxes, to avoid conflicts
219 self.options.buildname = os.path.basename (os.path.abspath (self.path))
221 if self.options.verbose:
222 self.show_env(self.options,"Verbose")
226 for config in self.options.config:
227 modulename='config_'+config
229 m = __import__(modulename)
230 all_plc_specs = m.config(all_plc_specs,self.options)
232 traceback.print_exc()
233 print 'Cannot load config %s -- ignored'%modulename
236 # run localize as defined by local_resources
237 all_plc_specs = LocalTestResources.local_resources.localize(all_plc_specs,self.options)
239 # remember plc IP address(es) if not specified
240 ips_plc_file=open('arg-ips-plc','w')
241 for plc_spec in all_plc_specs:
242 ips_plc_file.write("%s\n"%plc_spec['PLC_API_HOST'])
245 ips_node_file=open('arg-ips-node','w')
246 for plc_spec in all_plc_specs:
247 for site_spec in plc_spec['sites']:
248 for node_spec in site_spec['nodes']:
249 ips_node_file.write("%s\n"%node_spec['node_fields']['hostname'])
250 ips_node_file.close()
251 # ditto for qemu boxes
252 ips_qemu_file=open('arg-ips-qemu','w')
253 for plc_spec in all_plc_specs:
254 for site_spec in plc_spec['sites']:
255 for node_spec in site_spec['nodes']:
256 ips_qemu_file.write("%s\n"%node_spec['host_box'])
257 ips_qemu_file.close()
258 # build a TestPlc object from the result, passing options
259 for spec in all_plc_specs:
260 spec['disabled'] = False
261 all_plcs = [ (x, TestPlc(x,self.options)) for x in all_plc_specs]
263 # pass options to utils as well
264 utils.init_options(self.options)
266 overall_result = True
267 testplc_method_dict = __import__("TestPlc").__dict__['TestPlc'].__dict__
269 for step in self.options.steps:
270 if not TestPlc.valid_step(step):
272 # some steps need to be done regardless of the previous ones: we force them
274 if step.find("force_") == 0:
275 step=step.replace("force_","")
277 # a cross step will run a method on TestPlc that has a signature like
278 # def cross_foo (self, all_test_plcs)
280 if step.find("cross_") == 0:
282 # allow for steps to specify an index like in
284 try: (step,qualifier)=step.split('@')
285 except: qualifier=self.options.qualifier
287 # try and locate a method in TestPlc
288 if testplc_method_dict.has_key(step):
289 all_step_infos += [ (step, testplc_method_dict[step] , force, cross, qualifier)]
290 # otherwise search for the 'run' method in the step_<x> module
292 modulename='step_'+step
294 # locate all methods named run* in the module
295 module_dict = __import__(modulename).__dict__
296 names = [ key for key in module_dict.keys() if key.find("run")==0 ]
298 raise Exception,"No run* method in module %s"%modulename
300 all_step_infos += [ ("%s.%s"%(step,name),module_dict[name],force,cross,qualifier) for name in names ]
302 print '********** step %s NOT FOUND -- ignored'%(step)
303 traceback.print_exc()
304 overall_result = False
306 if self.options.dry_run:
307 self.show_env(self.options,"Dry run")
309 # init & open trace file if provided
310 if self.options.trace_file and not self.options.dry_run:
311 time=strftime("%H-%M")
312 date=strftime("%Y-%m-%d")
313 trace_file=self.options.trace_file
314 trace_file=trace_file.replace("@TIME@",time)
315 trace_file=trace_file.replace("@DATE@",date)
316 self.options.trace_file=trace_file
317 # create dir if needed
318 trace_dir=os.path.dirname(trace_file)
319 if trace_dir and not os.path.isdir(trace_dir):
320 os.makedirs(trace_dir)
321 trace=open(trace_file,"w")
323 # do all steps on all plcs
324 TIME_FORMAT="%H-%M-%S"
325 TRACE_FORMAT="TRACE: beg=%(beg)s end=%(end)s status=%(status)s step=%(stepname)s plc=%(plcname)s force=%(force)s\n"
326 for (stepname,method,force,cross,qualifier) in all_step_infos:
328 for (spec,plc_obj) in all_plcs:
330 # skip this step if we have specified a plc_explicit
331 if qualifier and plc_counter!=int(qualifier): continue
334 across_plcs = [ o for (s,o) in all_plcs if o!=plc_obj ]
337 beg=strftime(TIME_FORMAT)
338 if not spec['disabled'] or force or self.options.interactive:
340 if self.options.interactive:
343 msg="%d Run step %s on %s [r](un)/d(ry_run)/s(kip)/q(uit) ? "%(plc_counter,stepname,plcname)
344 answer=raw_input(msg).strip().lower() or "r"
346 if answer in ['s','n']: # skip/no/next
347 print '%s on %s skipped'%(stepname,plcname)
350 elif answer in ['q','b']: # quit/bye
353 elif answer in ['d']: # dry_run
354 dry_run=self.options.dry_run
355 self.options.dry_run=True
356 plc_obj.options.dry_run=True
357 plc_obj.apiserver.set_dry_run(True)
358 if not cross: step_result=method(plc_obj)
359 else: step_result=method(plc_obj,across_plcs)
360 print 'dry_run step ->',step_result
361 self.options.dry_run=dry_run
362 plc_obj.options.dry_run=dry_run
363 plc_obj.apiserver.set_dry_run(dry_run)
364 elif answer in ['r','y']: # run/yes
370 if force: force_msg=" (forced)"
371 utils.header("********** %d RUNNING step %s%s on plc %s"%(plc_counter,stepname,force_msg,plcname))
372 if not cross: step_result = method(plc_obj)
373 else: step_result = method(plc_obj,across_plcs)
375 utils.header('********** %d SUCCESSFUL step %s on %s'%(plc_counter,stepname,plcname))
378 overall_result = False
379 spec['disabled'] = True
380 utils.header('********** %d FAILED Step %s on %s (discarded from further steps)'\
381 %(plc_counter,stepname,plcname))
385 spec['disabled'] = True
386 traceback.print_exc()
387 utils.header ('********** %d FAILED (exception) Step %s on %s (discarded from further steps)'\
388 %(plc_counter,stepname,plcname))
391 # do not run, just display it's skipped
393 utils.header("********** %d IGNORED Plc %s is disabled - skipping step %s"%(plc_counter,plcname,stepname))
395 if not self.options.dry_run:
396 end=strftime(TIME_FORMAT)
397 # always do this on stdout
398 print TRACE_FORMAT%locals()
399 # duplicate on trace_file if provided
400 if self.options.trace_file:
401 trace.write(TRACE_FORMAT%locals())
404 if self.options.trace_file and not self.options.dry_run:
407 return overall_result
409 # wrapper to run, returns a shell-compatible result
418 print 'Caught SystemExit'
421 traceback.print_exc()
424 if __name__ == "__main__":
425 sys.exit(TestMain().main())