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)))
191 if not self.options.steps:
193 #self.options.steps=['dump','clean','install','populate']
194 self.options.steps=TestPlc.default_steps
196 # rewrite '-' into '_' in step names
197 self.options.steps = [ step.replace('-','_') for step in self.options.steps ]
201 for step in self.options.steps:
203 for exclude in self.options.exclude:
204 if utils.match(step,exclude):
207 if keep: selected.append(step)
208 self.options.steps=selected
210 # this is useful when propagating on host boxes, to avoid conflicts
211 self.options.buildname = os.path.basename (os.path.abspath (self.path))
213 if self.options.verbose:
214 self.show_env(self.options,"Verbose")
218 for config in self.options.config:
219 modulename='config_'+config
221 m = __import__(modulename)
222 all_plc_specs = m.config(all_plc_specs,self.options)
224 traceback.print_exc()
225 print 'Cannot load config %s -- ignored'%modulename
228 # run localize as defined by local_resources
229 all_plc_specs = LocalTestResources.local_resources.localize(all_plc_specs,self.options)
231 # remember plc IP address(es) if not specified
232 ips_plc_file=open('arg-ips-plc','w')
233 for plc_spec in all_plc_specs:
234 ips_plc_file.write("%s\n"%plc_spec['PLC_API_HOST'])
237 ips_node_file=open('arg-ips-node','w')
238 for plc_spec in all_plc_specs:
239 for site_spec in plc_spec['sites']:
240 for node_spec in site_spec['nodes']:
241 ips_node_file.write("%s\n"%node_spec['node_fields']['hostname'])
242 ips_node_file.close()
243 # ditto for qemu boxes
244 ips_qemu_file=open('arg-ips-qemu','w')
245 for plc_spec in all_plc_specs:
246 for site_spec in plc_spec['sites']:
247 for node_spec in site_spec['nodes']:
248 ips_qemu_file.write("%s\n"%node_spec['host_box'])
249 ips_qemu_file.close()
250 # build a TestPlc object from the result, passing options
251 for spec in all_plc_specs:
252 spec['disabled'] = False
253 all_plcs = [ (x, TestPlc(x,self.options)) for x in all_plc_specs]
255 # pass options to utils as well
256 utils.init_options(self.options)
258 overall_result = True
259 testplc_method_dict = __import__("TestPlc").__dict__['TestPlc'].__dict__
261 for step in self.options.steps:
262 if not TestPlc.valid_step(step):
265 # is it a forced step
266 if step.find("force_") == 0:
267 step=step.replace("force_","")
269 # try and locate a method in TestPlc
270 if testplc_method_dict.has_key(step):
271 all_step_infos += [ (step, testplc_method_dict[step] , force)]
272 # otherwise search for the 'run' method in the step_<x> module
274 modulename='step_'+step
276 # locate all methods named run* in the module
277 module_dict = __import__(modulename).__dict__
278 names = [ key for key in module_dict.keys() if key.find("run")==0 ]
280 raise Exception,"No run* method in module %s"%modulename
282 all_step_infos += [ ("%s.%s"%(step,name),module_dict[name],force) for name in names ]
284 print '********** step %s NOT FOUND -- ignored'%(step)
285 traceback.print_exc()
286 overall_result = False
288 if self.options.dry_run:
289 self.show_env(self.options,"Dry run")
291 # init & open trace file if provided
292 if self.options.trace_file and not self.options.dry_run:
293 time=strftime("%H-%M")
294 date=strftime("%Y-%m-%d")
295 trace_file=self.options.trace_file
296 trace_file=trace_file.replace("@TIME@",time)
297 trace_file=trace_file.replace("@DATE@",date)
298 self.options.trace_file=trace_file
299 # create dir if needed
300 trace_dir=os.path.dirname(trace_file)
301 if trace_dir and not os.path.isdir(trace_dir):
302 os.makedirs(trace_dir)
303 trace=open(trace_file,"w")
305 # do all steps on all plcs
306 TRACE_FORMAT="TRACE: time=%(time)s status=%(status)s step=%(stepname)s plc=%(plcname)s force=%(force)s\n"
307 for (stepname,method,force) in all_step_infos:
308 for (spec,obj) in all_plcs:
312 time=strftime("%Y-%m-%d-%H-%M")
313 if not spec['disabled'] or force or self.options.interactive:
315 if self.options.interactive:
318 msg="Run step %s on %s [r](un)/d(ry_run)/s(kip)/q(uit) ? "%(stepname,plcname)
319 answer=raw_input(msg).strip().lower() or "r"
321 if answer in ['s','n']: # skip/no/next
322 print '%s on %s skipped'%(stepname,plcname)
325 elif answer in ['q','b']: # quit/bye
328 elif answer in ['d']: # dry_run
329 dry_run=self.options.dry_run
330 self.options.dry_run=True
331 obj.options.dry_run=True
332 obj.apiserver.set_dry_run(True)
333 step_result=method(obj)
334 print 'dry_run step ->',step_result
335 self.options.dry_run=dry_run
336 obj.options.dry_run=dry_run
337 obj.apiserver.set_dry_run(dry_run)
338 elif answer in ['r','y']: # run/yes
344 if force: force_msg=" (forced)"
345 utils.header("********** RUNNING step %s%s on plc %s"%(stepname,force_msg,plcname))
346 step_result = method(obj)
348 utils.header('********** SUCCESSFUL step %s on %s'%(stepname,plcname))
351 overall_result = False
352 spec['disabled'] = True
353 utils.header('********** FAILED Step %s on %s - discarding that plc from further steps'%(stepname,plcname))
357 spec['disabled'] = True
358 traceback.print_exc()
359 utils.header ('********** FAILED (exception) Step %s on plc %s - discarding this plc from further steps'%(stepname,plcname))
362 # do not run, just display it's skipped
364 utils.header("********** IGNORED Plc %s is disabled - skipping step %s"%(plcname,stepname))
366 if not self.options.dry_run:
367 # alwas do this on stdout
368 print TRACE_FORMAT%locals()
369 # duplicate on trace_file if provided
370 if self.options.trace_file:
371 trace.write(TRACE_FORMAT%locals())
374 if self.options.trace_file and not self.options.dry_run:
377 return overall_result
379 # wrapper to run, returns a shell-compatible result
390 traceback.print_exc()
393 if __name__ == "__main__":
394 sys.exit(TestMain().main())