1 #!/usr/bin/env python -u
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
17 subversion_id = "$Id$"
19 default_config = [ 'default' ]
21 default_build_url = "http://svn.planet-lab.org/svn/build/trunk"
24 self.path=os.path.dirname(sys.argv[0]) or "."
28 def show_env (options, message):
29 utils.header (message)
30 utils.show_options("main options",options)
33 def optparse_list (option, opt, value, parser):
35 setattr(parser.values,option.dest,getattr(parser.values,option.dest)+value.split())
37 setattr(parser.values,option.dest,value.split())
40 steps_message=20*'x'+" Defaut steps are\n"+TestPlc.printable_steps(TestPlc.default_steps)
41 steps_message += "\n"+20*'x'+" Other useful steps are\n"+TestPlc.printable_steps(TestPlc.other_steps)
42 usage = """usage: %%prog [options] steps
43 arch-rpms-url defaults to the last value used, as stored in arg-arch-rpms-url,
45 build-url defaults to the last value used, as stored in arg-build-url,
47 config defaults to the last value used, as stored in arg-config,
49 node-ips and plc-ips defaults to the last value used, as stored in arg-ips-node and arg-ips-plc,
50 default is to use IP scanning
51 steps refer to a method in TestPlc or to a step_* module
53 """%(TestMain.default_build_url,TestMain.default_config)
54 usage += steps_message
55 parser=OptionParser(usage=usage,version=self.subversion_id)
56 parser.add_option("-u","--url",action="store", dest="arch_rpms_url",
57 help="URL of the arch-dependent RPMS area - for locating what to test")
58 parser.add_option("-b","--build",action="store", dest="build_url",
59 help="Build URL - for locating vtest-init-vserver.sh")
60 parser.add_option("-c","--config",action="callback", callback=TestMain.optparse_list, dest="config",
61 nargs=1,type="string",
62 help="Config module - can be set multiple times, or use quotes")
63 parser.add_option("-p","--personality",action="store", dest="personality",
64 help="personality - as in vbuild-nightly")
65 parser.add_option("-d","--pldistro",action="store", dest="pldistro",
66 help="pldistro - as in vbuild-nightly")
67 parser.add_option("-f","--fcdistro",action="store", dest="fcdistro",
68 help="fcdistro - as in vbuild-nightly")
69 parser.add_option("-x","--exclude",action="callback", callback=TestMain.optparse_list, dest="exclude",
70 nargs=1,type="string",default=[],
71 help="steps to exclude - can be set multiple times, or use quotes")
72 parser.add_option("-a","--all",action="store_true",dest="all_steps", default=False,
73 help="Run all default steps")
74 parser.add_option("-l","--list",action="store_true",dest="list_steps", default=False,
75 help="List known steps")
76 parser.add_option("-N","--nodes",action="callback", callback=TestMain.optparse_list, dest="ips_node",
77 nargs=1,type="string",
78 help="Specify the set of IP addresses to use for nodes (scanning disabled)")
79 parser.add_option("-P","--plcs",action="callback", callback=TestMain.optparse_list, dest="ips_plc",
80 nargs=1,type="string",
81 help="Specify the set of IP addresses to use for plcs (scanning disabled)")
82 parser.add_option("-s","--size",action="store",type="int",dest="size",default=1,
83 help="sets test size in # of plcs - default is 1")
84 parser.add_option("-D","--dbname",action="store",dest="dbname",default=None,
85 help="Used by db_dump and db_restore")
86 parser.add_option("-v","--verbose", action="store_true", dest="verbose", default=False,
87 help="Run in verbose mode")
88 parser.add_option("-q","--quiet", action="store_true", dest="quiet", default=False,
89 help="Run in quiet mode")
90 parser.add_option("-i","--interactive",action="store_true",dest="interactive",default=False,
91 help="prompts before each step")
92 parser.add_option("-n","--dry-run", action="store_true", dest="dry_run", default=False,
93 help="Show environment and exits")
94 parser.add_option("-r","--restart-nm", action="store_true", dest="forcenm", default=False,
95 help="Force the NM to restart in check_slices step")
96 parser.add_option("-t","--trace", action="store", dest="trace_file", default=None,
97 #default="logs/trace-@TIME@.txt",
98 help="Trace file location")
99 (self.options, self.args) = parser.parse_args()
100 if self.options.quiet:
101 self.options.verbose=False
103 if len(self.args) == 0:
104 if self.options.all_steps:
105 self.options.steps=TestPlc.default_steps
106 elif self.options.dry_run:
107 self.options.steps=TestPlc.default_steps
108 elif self.options.list_steps:
112 print 'No step found (do you mean -a ? )'
113 print "Run %s --help for help"%sys.argv[0]
116 self.options.steps = self.args
118 # handle defaults and option persistence
119 for (recname,filename,default) in (
120 ('build_url','arg-build-url',TestMain.default_build_url) ,
121 ('ips_node','arg-ips-node',[]) ,
122 ('ips_plc','arg-ips-plc',[]) ,
123 ('config','arg-config',TestMain.default_config) ,
124 ('arch_rpms_url','arg-arch-rpms-url',"") ,
125 ('personality','arg-personality',"linux32"),
126 ('pldistro','arg-pldistro',"planetlab"),
127 ('fcdistro','arg-fcdistro','centos5'),
129 # print 'handling',recname
131 is_list = isinstance(default,list)
132 if not getattr(self.options,recname):
134 parsed=file(path).readlines()
135 if not is_list: # strings
137 print "%s - error when parsing %s"%(sys.argv[1],path)
139 parsed=parsed[0].strip()
141 parsed=[x.strip() for x in parsed]
142 setattr(self.options,recname,parsed)
145 setattr(self.options,recname,default)
147 print "Cannot determine",recname
148 print "Run %s --help for help"%sys.argv[0]
154 fsave.write(getattr(self.options,recname) + "\n")
156 for value in getattr(self.options,recname):
157 fsave.write(value + "\n")
159 # utils.header('Saved %s into %s'%(recname,filename))
161 # lists need be reversed
162 if isinstance(getattr(self.options,recname),list):
163 getattr(self.options,recname).reverse()
165 if not self.options.quiet:
166 utils.header('* Using %s = %s'%(recname,getattr(self.options,recname)))
169 if self.options.personality == "linux32":
170 self.options.arch = "i386"
171 elif self.options.personality == "linux64":
172 self.options.arch = "x86_64"
174 raise Exception, "Unsupported personality %r"%self.options.personality
176 if not self.options.steps:
178 #self.options.steps=['dump','clean','install','populate']
179 self.options.steps=TestPlc.default_steps
183 for step in self.options.steps:
185 for exclude in self.options.exclude:
186 if utils.match(step,exclude):
189 if keep: selected.append(step)
190 self.options.steps=selected
192 # this is useful when propagating on host boxes, to avoid conflicts
193 self.options.buildname = os.path.basename (os.path.abspath (self.path))
195 if self.options.verbose:
196 self.show_env(self.options,"Verbose")
200 for config in self.options.config:
201 modulename='config_'+config
203 m = __import__(modulename)
204 all_plc_specs = m.config(all_plc_specs,self.options)
206 traceback.print_exc()
207 print 'Cannot load config %s -- ignored'%modulename
209 # remember plc IP address(es) if not specified
210 ips_plc_file=open('arg-ips-plc','w')
211 for plc_spec in all_plc_specs:
212 ips_plc_file.write("%s\n"%plc_spec['PLC_API_HOST'])
215 ips_node_file=open('arg-ips-node','w')
216 for plc_spec in all_plc_specs:
217 for site_spec in plc_spec['sites']:
218 for node_spec in site_spec['nodes']:
219 ips_node_file.write("%s\n"%node_spec['node_fields']['hostname'])
220 ips_node_file.close()
221 # build a TestPlc object from the result, passing options
222 for spec in all_plc_specs:
223 spec['disabled'] = False
224 all_plcs = [ (x, TestPlc(x,self.options)) for x in all_plc_specs]
226 # pass options to utils as well
227 utils.init_options(self.options)
229 overall_result = True
230 testplc_method_dict = __import__("TestPlc").__dict__['TestPlc'].__dict__
232 for step in self.options.steps:
233 if not TestPlc.valid_step(step):
236 # is it a forced step
237 if step.find("force_") == 0:
238 step=step.replace("force_","")
240 # try and locate a method in TestPlc
241 if testplc_method_dict.has_key(step):
242 all_step_infos += [ (step, testplc_method_dict[step] , force)]
243 # otherwise search for the 'run' method in the step_<x> module
245 modulename='step_'+step
247 # locate all methods named run* in the module
248 module_dict = __import__(modulename).__dict__
249 names = [ key for key in module_dict.keys() if key.find("run")==0 ]
251 raise Exception,"No run* method in module %s"%modulename
253 all_step_infos += [ ("%s.%s"%(step,name),module_dict[name],force) for name in names ]
255 print '********** step %s NOT FOUND -- ignored'%(step)
256 traceback.print_exc()
257 overall_result = False
259 if self.options.dry_run:
260 self.show_env(self.options,"Dry run")
262 # init & open trace file if provided
263 if self.options.trace_file and not self.options.dry_run:
264 time=strftime("%H-%M")
265 date=strftime("%Y-%m-%d")
266 trace_file=self.options.trace_file
267 trace_file=trace_file.replace("@TIME@",time)
268 trace_file=trace_file.replace("@DATE@",date)
269 self.options.trace_file=trace_file
270 # create dir if needed
271 trace_dir=os.path.dirname(trace_file)
272 if trace_dir and not os.path.isdir(trace_dir):
273 os.makedirs(trace_dir)
274 trace=open(trace_file,"w")
276 # do all steps on all plcs
277 TRACE_FORMAT="TRACE: time=%(time)s plc=%(plcname)s step=%(stepname)s status=%(status)s force=%(force)s\n"
278 for (stepname,method,force) in all_step_infos:
279 for (spec,obj) in all_plcs:
283 time=strftime("%Y-%m-%d-%H-%M")
284 if not spec['disabled'] or force or self.options.interactive:
286 if self.options.interactive:
289 msg="Run step %s on %s [r](un)/d(ry_run)/s(kip)/q(uit) ? "%(stepname,plcname)
290 answer=raw_input(msg).strip().lower() or "r"
292 if answer in ['s','n']: # skip/no/next
293 print '%s on %s skipped'%(stepname,plcname)
296 elif answer in ['q','b']: # quit/bye
299 elif answer in ['d']: # dry_run
300 dry_run=self.options.dry_run
301 self.options.dry_run=True
302 obj.options.dry_run=True
303 obj.apiserver.set_dry_run(True)
304 step_result=method(obj)
305 print 'dry_run step ->',step_result
306 self.options.dry_run=dry_run
307 obj.options.dry_run=dry_run
308 obj.apiserver.set_dry_run(dry_run)
309 elif answer in ['r','y']: # run/yes
315 if force: force_msg=" (forced)"
316 utils.header("********** RUNNING step %s%s on plc %s"%(stepname,force_msg,plcname))
317 step_result = method(obj)
319 utils.header('********** SUCCESSFUL step %s on %s'%(stepname,plcname))
322 overall_result = False
323 spec['disabled'] = True
324 utils.header('********** FAILED Step %s on %s - discarding that plc from further steps'%(stepname,plcname))
328 spec['disabled'] = True
329 traceback.print_exc()
330 utils.header ('********** FAILED (exception) Step %s on plc %s - discarding this plc from further steps'%(stepname,plcname))
333 # do not run, just display it's skipped
335 utils.header("********** IGNORED Plc %s is disabled - skipping step %s"%(plcname,stepname))
337 if not self.options.dry_run:
338 # alwas do this on stdout
339 print TRACE_FORMAT%locals()
340 # duplicate on trace_file if provided
341 if self.options.trace_file:
342 trace.write(TRACE_FORMAT%locals())
344 if self.options.trace_file and not self.options.dry_run:
347 return overall_result
349 # wrapper to run, returns a shell-compatible result
360 traceback.print_exc()
363 if __name__ == "__main__":
364 sys.exit(TestMain().main())