preserve IP addresses for any further re-run
[tests.git] / system / TestMain.py
1 #!/usr/bin/env python
2 # $Id$
3
4 import sys, os, os.path
5 from optparse import OptionParser
6 import traceback
7 from time import strftime
8
9 import utils
10 from TestPlc import TestPlc
11 from TestSite import TestSite
12 from TestNode import TestNode
13
14 class TestMain:
15
16     subversion_id = "$Id$"
17
18     default_config = [ 'default' ] 
19
20     default_build_url = "http://svn.planet-lab.org/svn/build/trunk"
21
22     def __init__ (self):
23         self.path=os.path.dirname(sys.argv[0]) or "."
24         os.chdir(self.path)
25
26     @staticmethod
27     def show_env (options, message):
28         utils.header (message)
29         utils.show_options("main options",options)
30
31     @staticmethod
32     def optparse_list (option, opt, value, parser):
33         try:
34             setattr(parser.values,option.dest,getattr(parser.values,option.dest)+value.split())
35         except:
36             setattr(parser.values,option.dest,value.split())
37
38     def run (self):
39         steps_message=20*'x'+" Defaut steps are\n"+TestPlc.printable_steps(TestPlc.default_steps)
40         steps_message += "\n"+20*'x'+" Other useful steps are\n"+TestPlc.printable_steps(TestPlc.other_steps)
41         usage = """usage: %%prog [options] steps
42 arch-rpms-url defaults to the last value used, as stored in arg-arch-rpms-url,
43    no default
44 build-url defaults to the last value used, as stored in arg-build-url, 
45    or %s
46 config defaults to the last value used, as stored in arg-config,
47    or %r
48 node-ips and plc-ips defaults to the last value used, as stored in arg-node-ips and arg-plc-ips,
49    default is to use IP scanning
50 steps refer to a method in TestPlc or to a step_* module
51 ===
52 """%(TestMain.default_build_url,TestMain.default_config)
53         usage += steps_message
54         parser=OptionParser(usage=usage,version=self.subversion_id)
55         parser.add_option("-u","--url",action="store", dest="arch_rpms_url", 
56                           help="URL of the arch-dependent RPMS area - for locating what to test")
57         parser.add_option("-b","--build",action="store", dest="build_url", 
58                           help="Build URL - for locating vtest-init-vserver.sh")
59         parser.add_option("-c","--config",action="callback", callback=TestMain.optparse_list, dest="config",
60                           nargs=1,type="string",
61                           help="Config module - can be set multiple times, or use quotes")
62         parser.add_option("-p","--personality",action="store", dest="personality", 
63                           help="personality - as in vbuild-nightly")
64         parser.add_option("-d","--pldistro",action="store", dest="pldistro", 
65                           help="pldistro - as in vbuild-nightly")
66         parser.add_option("-f","--fcdistro",action="store", dest="fcdistro", 
67                           help="fcdistro - as in vbuild-nightly")
68         parser.add_option("-x","--exclude",action="callback", callback=TestMain.optparse_list, dest="exclude",
69                           nargs=1,type="string",default=[],
70                           help="steps to exclude - can be set multiple times, or use quotes")
71         parser.add_option("-a","--all",action="store_true",dest="all_steps", default=False,
72                           help="Run all default steps")
73         parser.add_option("-l","--list",action="store_true",dest="list_steps", default=False,
74                           help="List known steps")
75         parser.add_option("-N","--nodes",action="callback", callback=TestMain.optparse_list, dest="node_ips",
76                           nargs=1,type="string",
77                           help="Specify the set of IP addresses to use for nodes (scanning disabled)")
78         parser.add_option("-P","--plcs",action="callback", callback=TestMain.optparse_list, dest="plc_ips",
79                           nargs=1,type="string",
80                           help="Specify the set of IP addresses to use for plcs (scanning disabled)")
81         parser.add_option("-1","--small",action="store_true",dest="small_test",default=False,
82                           help="run a small test -- typically only one node")
83         parser.add_option("-D","--dbname",action="store",dest="dbname",default=None,
84                            help="Used by db_dump and db_restore")
85         parser.add_option("-v","--verbose", action="store_true", dest="verbose", default=False, 
86                           help="Run in verbose mode")
87         parser.add_option("-q","--quiet", action="store_true", dest="quiet", default=False, 
88                           help="Run in quiet mode")
89         parser.add_option("-n","--dry-run", action="store_true", dest="dry_run", default=False,
90                           help="Show environment and exits")
91         parser.add_option("-r","--restart-nm", action="store_true", dest="forcenm", default=False, 
92                           help="Force the NM to restart in check_slices step")
93         parser.add_option("-t","--trace", action="store", dest="trace_file", default=None,
94                           #default="logs/trace-@TIME@.txt",
95                           help="Trace file location")
96         (self.options, self.args) = parser.parse_args()
97
98         if len(self.args) == 0:
99             if self.options.all_steps:
100                 self.options.steps=TestPlc.default_steps
101             elif self.options.dry_run:
102                 self.options.steps=TestPlc.default_steps
103             elif self.options.list_steps:
104                 print steps_message
105                 sys.exit(1)
106             else:
107                 print 'No step found (do you mean -a ? )'
108                 print "Run %s --help for help"%sys.argv[0]                        
109                 sys.exit(1)
110         else:
111             self.options.steps = self.args
112
113         # handle defaults and option persistence
114         for (recname,filename,default) in (
115             ('build_url','arg-build-url',TestMain.default_build_url) ,
116             ('node_ips','arg-node-ips',[]) , 
117             ('plc_ips','arg-plc-ips',[]) , 
118             ('config','arg-config',TestMain.default_config) , 
119             ('arch_rpms_url','arg-arch-rpms-url',"") , 
120             ('personality','arg-personality',"linux32"),
121             ('pldistro','arg-pldistro',"planetlab"),
122             ('fcdistro','arg-fcdistro','f8'),
123             ) :
124 #            print 'handling',recname
125             path=filename
126             is_list = isinstance(default,list)
127             if not getattr(self.options,recname):
128                 try:
129                     parsed=file(path).readlines()
130                     if not is_list:    # strings
131                         if len(parsed) != 1:
132                             print "%s - error when parsing %s"%(sys.argv[1],path)
133                             sys.exit(1)
134                         parsed=parsed[0].strip()
135                     else:              # lists
136                         parsed=[x.strip() for x in parsed]
137                     setattr(self.options,recname,parsed)
138                 except:
139                     if default != "":
140                         setattr(self.options,recname,default)
141                     else:
142                         print "Cannot determine",recname
143                         print "Run %s --help for help"%sys.argv[0]                        
144                         sys.exit(1)
145             if not self.options.quiet:
146                 utils.header('* Using %s = %s'%(recname,getattr(self.options,recname)))
147
148             # save for next run
149             fsave=open(path,"w")
150             if not is_list:
151                 fsave.write(getattr(self.options,recname) + "\n")
152             else:
153                 for value in getattr(self.options,recname):
154                     fsave.write(value + "\n")
155             fsave.close()
156 #            utils.header('Saved %s into %s'%(recname,filename))
157
158         if self.options.personality == "linux32":
159             self.options.arch = "i386"
160         elif self.options.personality == "linux64":
161             self.options.arch = "x86_64"
162         else:
163             raise Exception, "Unsupported personality %r"%self.options.personality
164         # steps
165         if not self.options.steps:
166             #default (all) steps
167             #self.options.steps=['dump','clean','install','populate']
168             self.options.steps=TestPlc.default_steps
169
170         # exclude
171         selected=[]
172         for step in self.options.steps:
173             keep=True
174             for exclude in self.options.exclude:
175                 if utils.match(step,exclude):
176                     keep=False
177                     break
178             if keep: selected.append(step)
179         self.options.steps=selected
180
181         # this is useful when propagating on host boxes, to avoid conflicts
182         self.options.buildname = os.path.basename (os.path.abspath (self.path))
183
184         if self.options.verbose:
185             self.show_env(self.options,"Verbose")
186
187         # load configs
188         all_plc_specs = []
189         for config in self.options.config:
190             modulename='config_'+config
191             try:
192                 m = __import__(modulename)
193                 all_plc_specs = m.config(all_plc_specs,self.options)
194             except :
195                 traceback.print_exc()
196                 print 'Cannot load config %s -- ignored'%modulename
197                 raise
198         # show config
199         if not self.options.quiet:
200             utils.show_test_spec("Test specifications",all_plc_specs)
201         # remember plc IP address(es) if not specified
202         current=file('arg-plc-ips').read()
203         if not current:
204             plc_ips_file=open('arg-plc-ips','w')
205             for plc_spec in all_plc_specs:
206                 plc_ips_file.write("%s\n"%plc_spec['PLC_API_HOST'])
207             plc_ips_file.close()
208         # build a TestPlc object from the result, passing options
209         for spec in all_plc_specs:
210             spec['disabled'] = False
211         all_plcs = [ (x, TestPlc(x,self.options)) for x in all_plc_specs]
212
213         # pass options to utils as well
214         utils.init_options(self.options)
215
216         overall_result = True
217         testplc_method_dict = __import__("TestPlc").__dict__['TestPlc'].__dict__
218         all_step_infos=[]
219         for step in self.options.steps:
220             if not TestPlc.valid_step(step):
221                 continue
222             force=False
223             # is it a forced step
224             if step.find("force_") == 0:
225                 step=step.replace("force_","")
226                 force=True
227             # try and locate a method in TestPlc
228             if testplc_method_dict.has_key(step):
229                 all_step_infos += [ (step, testplc_method_dict[step] , force)]
230             # otherwise search for the 'run' method in the step_<x> module
231             else:
232                 modulename='step_'+step
233                 try:
234                     # locate all methods named run* in the module
235                     module_dict = __import__(modulename).__dict__
236                     names = [ key for key in module_dict.keys() if key.find("run")==0 ]
237                     if not names:
238                         raise Exception,"No run* method in module %s"%modulename
239                     names.sort()
240                     all_step_infos += [ ("%s.%s"%(step,name),module_dict[name],force) for name in names ]
241                 except :
242                     print '********** step %s NOT FOUND -- ignored'%(step)
243                     traceback.print_exc()
244                     overall_result = False
245             
246         if self.options.dry_run:
247             self.show_env(self.options,"Dry run")
248         
249         # init & open trace file if provided
250         if self.options.trace_file and not self.options.dry_run:
251             time=strftime("%H-%M")
252             date=strftime("%Y-%m-%d")
253             trace_file=self.options.trace_file
254             trace_file=trace_file.replace("@TIME@",time)
255             trace_file=trace_file.replace("@DATE@",date)
256             self.options.trace_file=trace_file
257             # create dir if needed
258             trace_dir=os.path.dirname(trace_file)
259             if trace_dir and not os.path.isdir(trace_dir):
260                 os.makedirs(trace_dir)
261             trace=open(trace_file,"w")
262
263         # do all steps on all plcs
264         TRACE_FORMAT="TRACE: time=%(time)s plc=%(plcname)s step=%(stepname)s status=%(status)s force=%(force)s\n"
265         for (stepname,method,force) in all_step_infos:
266             for (spec,obj) in all_plcs:
267                 plcname=spec['name']
268
269                 # run the step
270                 time=strftime("%Y-%m-%d-%H-%M")
271                 if not spec['disabled'] or force:
272                     try:
273                         force_msg=""
274                         if force: force_msg=" (forced)"
275                         utils.header("********** RUNNING step %s%s on plc %s"%(stepname,force_msg,plcname))
276                         step_result = method(obj)
277                         if step_result:
278                             utils.header('********** SUCCESSFUL step %s on %s'%(stepname,plcname))
279                             status="OK"
280                         else:
281                             overall_result = False
282                             spec['disabled'] = True
283                             utils.header('********** FAILED Step %s on %s - discarding that plc from further steps'%(stepname,plcname))
284                             status="KO"
285                     except:
286                         overall_result=False
287                         spec['disabled'] = True
288                         traceback.print_exc()
289                         utils.header ('********** FAILED (exception) Step %s on plc %s - discarding this plc from further steps'%(stepname,plcname))
290                         status="KO"
291
292                 # do not run, just display it's skipped
293                 else:
294                     utils.header("********** IGNORED Plc %s is disabled - skipping step %s"%(plcname,stepname))
295                     status="UNDEF"
296                 if not self.options.dry_run:
297                     # alwas do this on stdout
298                     print TRACE_FORMAT%locals()
299                     # duplicate on trace_file if provided
300                     if self.options.trace_file:
301                         trace.write(TRACE_FORMAT%locals())
302
303         if self.options.trace_file and not self.options.dry_run:
304             trace.close()
305
306         return overall_result
307
308     # wrapper to run, returns a shell-compatible result
309     def main(self):
310         try:
311             success=self.run()
312             if success:
313                 return 0
314             else:
315                 return 1 
316         except SystemExit:
317             raise
318         except:
319             traceback.print_exc()
320             return 2
321
322 if __name__ == "__main__":
323     sys.exit(TestMain().main())