4 import sys, os, os.path
5 from optparse import OptionParser
7 from time import strftime
11 from TestPlc import TestPlc
12 from TestSite import TestSite
13 from TestNode import TestNode
15 # add $HOME in PYTHONPATH so we can import LocalTestResources.py
16 sys.path.append(os.environ['HOME'])
17 import LocalTestResources
21 subversion_id = "$Id$"
23 default_config = [ 'default' ]
25 default_build_url = "git://git.onelab.eu/tests"
28 self.path=os.path.dirname(sys.argv[0]) or "."
31 def show_env (self,options, message):
32 if self.options.verbose:
33 utils.header (message)
34 utils.show_options("main options",options)
37 self.steps_message=20*'x'+" Defaut steps are\n"+TestPlc.printable_steps(TestPlc.default_steps)
38 self.steps_message += "\n"+20*'x'+" Other useful steps are\n"+TestPlc.printable_steps(TestPlc.other_steps)
41 if not self.options.verbose:
42 print self.steps_message
44 testplc_method_dict = __import__("TestPlc").__dict__['TestPlc'].__dict__
45 scopes = [("Default steps",TestPlc.default_steps)]
46 if self.options.all_steps:
47 scopes.append ( ("Other steps",TestPlc.other_steps) )
48 for (scope,steps) in scopes:
49 print '--------------------',scope
50 for step in [step for step in steps if TestPlc.valid_step(step)]:
52 if step.find("force_") == 0:
53 stepname=step.replace("force_","")
55 print '*',step,"\r",4*"\t",
57 print testplc_method_dict[stepname].__doc__
59 print "*** no doc found"
62 def optparse_list (option, opt, value, parser):
64 setattr(parser.values,option.dest,getattr(parser.values,option.dest)+value.split())
66 setattr(parser.values,option.dest,value.split())
70 usage = """usage: %%prog [options] steps
71 arch-rpms-url defaults to the last value used, as stored in arg-arch-rpms-url,
73 config defaults to the last value used, as stored in arg-config,
75 ips_node, ips_plc and ips_qemu defaults to the last value used, as stored in arg-ips-{node,plc,qemu},
76 default is to use IP scanning
77 steps refer to a method in TestPlc or to a step_* module
79 """%(TestMain.default_config)
80 usage += self.steps_message
81 parser=OptionParser(usage=usage,version=self.subversion_id)
82 parser.add_option("-u","--url",action="store", dest="arch_rpms_url",
83 help="URL of the arch-dependent RPMS area - for locating what to test")
84 parser.add_option("-b","--build",action="store", dest="build_url",
85 help="ignored, for legacy only")
86 parser.add_option("-c","--config",action="callback", callback=TestMain.optparse_list, dest="config",
87 nargs=1,type="string",
88 help="Config module - can be set multiple times, or use quotes")
89 parser.add_option("-p","--personality",action="store", dest="personality",
90 help="personality - as in vbuild-nightly")
91 parser.add_option("-d","--pldistro",action="store", dest="pldistro",
92 help="pldistro - as in vbuild-nightly")
93 parser.add_option("-f","--fcdistro",action="store", dest="fcdistro",
94 help="fcdistro - as in vbuild-nightly")
95 parser.add_option("-x","--exclude",action="callback", callback=TestMain.optparse_list, dest="exclude",
96 nargs=1,type="string",default=[],
97 help="steps to exclude - can be set multiple times, or use quotes")
98 parser.add_option("-a","--all",action="store_true",dest="all_steps", default=False,
99 help="Run all default steps")
100 parser.add_option("-l","--list",action="store_true",dest="list_steps", default=False,
101 help="List known steps")
102 parser.add_option("-N","--nodes",action="callback", callback=TestMain.optparse_list, dest="ips_node",
103 nargs=1,type="string",
104 help="Specify the set of hostname/IP's to use for nodes")
105 parser.add_option("-P","--plcs",action="callback", callback=TestMain.optparse_list, dest="ips_plc",
106 nargs=1,type="string",
107 help="Specify the set of hostname/IP's to use for plcs")
108 parser.add_option("-Q","--qemus",action="callback", callback=TestMain.optparse_list, dest="ips_qemu",
109 nargs=1,type="string",
110 help="Specify the set of hostname/IP's to use for qemu boxes")
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("-D","--dbname",action="store",dest="dbname",default=None,
114 help="Used by db_dump and db_restore")
115 parser.add_option("-v","--verbose", action="store_true", dest="verbose", default=False,
116 help="Run in verbose mode")
117 parser.add_option("-i","--interactive",action="store_true",dest="interactive",default=False,
118 help="prompts before each step")
119 parser.add_option("-n","--dry-run", action="store_true", dest="dry_run", default=False,
120 help="Show environment and exits")
121 parser.add_option("-r","--restart-nm", action="store_true", dest="forcenm", default=False,
122 help="Force the NM to restart in check_slices step")
123 parser.add_option("-t","--trace", action="store", dest="trace_file", default=None,
124 #default="logs/trace-@TIME@.txt",
125 help="Trace file location")
126 (self.options, self.args) = parser.parse_args()
129 if len(self.args) == 0:
130 self.options.steps=TestPlc.default_steps
132 self.options.steps = self.args
134 if self.options.list_steps:
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'),
150 # print 'handling',recname
152 is_list = isinstance(default,list)
153 if not getattr(self.options,recname):
155 parsed=file(path).readlines()
156 if not is_list: # strings
158 print "%s - error when parsing %s"%(sys.argv[1],path)
160 parsed=parsed[0].strip()
162 parsed=[x.strip() for x in parsed]
163 setattr(self.options,recname,parsed)
166 setattr(self.options,recname,default)
168 print "Cannot determine",recname
169 print "Run %s --help for help"%sys.argv[0]
175 fsave.write(getattr(self.options,recname) + "\n")
177 for value in getattr(self.options,recname):
178 fsave.write(value + "\n")
180 # utils.header('Saved %s into %s'%(recname,filename))
182 # lists need be reversed
183 if isinstance(getattr(self.options,recname),list):
184 getattr(self.options,recname).reverse()
186 if self.options.verbose:
187 utils.header('* Using %s = %s'%(recname,getattr(self.options,recname)))
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)
193 if not self.options.steps:
195 #self.options.steps=['dump','clean','install','populate']
196 self.options.steps=TestPlc.default_steps
198 # rewrite '-' into '_' in step names
199 self.options.steps = [ step.replace('-','_') for step in self.options.steps ]
203 for step in self.options.steps:
205 for exclude in self.options.exclude:
206 if utils.match(step,exclude):
209 if keep: selected.append(step)
210 self.options.steps=selected
212 # this is useful when propagating on host boxes, to avoid conflicts
213 self.options.buildname = os.path.basename (os.path.abspath (self.path))
215 if self.options.verbose:
216 self.show_env(self.options,"Verbose")
220 for config in self.options.config:
221 modulename='config_'+config
223 m = __import__(modulename)
224 all_plc_specs = m.config(all_plc_specs,self.options)
226 traceback.print_exc()
227 print 'Cannot load config %s -- ignored'%modulename
230 # run localize as defined by local_resources
231 all_plc_specs = LocalTestResources.local_resources.localize(all_plc_specs,self.options)
233 # remember plc IP address(es) if not specified
234 ips_plc_file=open('arg-ips-plc','w')
235 for plc_spec in all_plc_specs:
236 ips_plc_file.write("%s\n"%plc_spec['PLC_API_HOST'])
239 ips_node_file=open('arg-ips-node','w')
240 for plc_spec in all_plc_specs:
241 for site_spec in plc_spec['sites']:
242 for node_spec in site_spec['nodes']:
243 ips_node_file.write("%s\n"%node_spec['node_fields']['hostname'])
244 ips_node_file.close()
245 # ditto for qemu boxes
246 ips_qemu_file=open('arg-ips-qemu','w')
247 for plc_spec in all_plc_specs:
248 for site_spec in plc_spec['sites']:
249 for node_spec in site_spec['nodes']:
250 ips_qemu_file.write("%s\n"%node_spec['host_box'])
251 ips_qemu_file.close()
252 # build a TestPlc object from the result, passing options
253 for spec in all_plc_specs:
254 spec['disabled'] = False
255 all_plcs = [ (x, TestPlc(x,self.options)) for x in all_plc_specs]
257 # pass options to utils as well
258 utils.init_options(self.options)
260 overall_result = True
261 testplc_method_dict = __import__("TestPlc").__dict__['TestPlc'].__dict__
263 for step in self.options.steps:
264 if not TestPlc.valid_step(step):
267 # is it a forced step
268 if step.find("force_") == 0:
269 step=step.replace("force_","")
271 # try and locate a method in TestPlc
272 if testplc_method_dict.has_key(step):
273 all_step_infos += [ (step, testplc_method_dict[step] , force)]
274 # otherwise search for the 'run' method in the step_<x> module
276 modulename='step_'+step
278 # locate all methods named run* in the module
279 module_dict = __import__(modulename).__dict__
280 names = [ key for key in module_dict.keys() if key.find("run")==0 ]
282 raise Exception,"No run* method in module %s"%modulename
284 all_step_infos += [ ("%s.%s"%(step,name),module_dict[name],force) for name in names ]
286 print '********** step %s NOT FOUND -- ignored'%(step)
287 traceback.print_exc()
288 overall_result = False
290 if self.options.dry_run:
291 self.show_env(self.options,"Dry run")
293 # init & open trace file if provided
294 if self.options.trace_file and not self.options.dry_run:
295 time=strftime("%H-%M")
296 date=strftime("%Y-%m-%d")
297 trace_file=self.options.trace_file
298 trace_file=trace_file.replace("@TIME@",time)
299 trace_file=trace_file.replace("@DATE@",date)
300 self.options.trace_file=trace_file
301 # create dir if needed
302 trace_dir=os.path.dirname(trace_file)
303 if trace_dir and not os.path.isdir(trace_dir):
304 os.makedirs(trace_dir)
305 trace=open(trace_file,"w")
307 # do all steps on all plcs
308 TRACE_FORMAT="TRACE: time=%(time)s status=%(status)s step=%(stepname)s plc=%(plcname)s force=%(force)s\n"
309 for (stepname,method,force) in all_step_infos:
310 for (spec,obj) in all_plcs:
314 time=strftime("%Y-%m-%d-%H-%M")
315 if not spec['disabled'] or force or self.options.interactive:
317 if self.options.interactive:
320 msg="Run step %s on %s [r](un)/d(ry_run)/s(kip)/q(uit) ? "%(stepname,plcname)
321 answer=raw_input(msg).strip().lower() or "r"
323 if answer in ['s','n']: # skip/no/next
324 print '%s on %s skipped'%(stepname,plcname)
327 elif answer in ['q','b']: # quit/bye
330 elif answer in ['d']: # dry_run
331 dry_run=self.options.dry_run
332 self.options.dry_run=True
333 obj.options.dry_run=True
334 obj.apiserver.set_dry_run(True)
335 step_result=method(obj)
336 print 'dry_run step ->',step_result
337 self.options.dry_run=dry_run
338 obj.options.dry_run=dry_run
339 obj.apiserver.set_dry_run(dry_run)
340 elif answer in ['r','y']: # run/yes
346 if force: force_msg=" (forced)"
347 utils.header("********** RUNNING step %s%s on plc %s"%(stepname,force_msg,plcname))
348 step_result = method(obj)
350 utils.header('********** SUCCESSFUL step %s on %s'%(stepname,plcname))
353 overall_result = False
354 spec['disabled'] = True
355 utils.header('********** FAILED Step %s on %s - discarding that plc from further steps'%(stepname,plcname))
359 spec['disabled'] = True
360 traceback.print_exc()
361 utils.header ('********** FAILED (exception) Step %s on plc %s - discarding this plc from further steps'%(stepname,plcname))
364 # do not run, just display it's skipped
366 utils.header("********** IGNORED Plc %s is disabled - skipping step %s"%(plcname,stepname))
368 if not self.options.dry_run:
369 # alwas do this on stdout
370 print TRACE_FORMAT%locals()
371 # duplicate on trace_file if provided
372 if self.options.trace_file:
373 trace.write(TRACE_FORMAT%locals())
376 if self.options.trace_file and not self.options.dry_run:
379 return overall_result
381 # wrapper to run, returns a shell-compatible result
392 traceback.print_exc()
395 if __name__ == "__main__":
396 sys.exit(TestMain().main())