pass build env : (personality x fcdistro x pldistro) to test env for vserver creation
[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", default="linux32",
63                           help="personality - as in vbuild-nightly")
64         parser.add_option("-d","--pldistro",action="store", dest="pldistro", default="planetlab",
65                           help="pldistro - as in vbuild-nightly")
66         parser.add_option("-f","--fcdistro",action="store", dest="fcdistro", default="f8",
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         # build a TestPlc object from the result, passing options
202         for spec in all_plc_specs:
203             spec['disabled'] = False
204         all_plcs = [ (x, TestPlc(x,self.options)) for x in all_plc_specs]
205
206         # pass options to utils as well
207         utils.init_options(self.options)
208
209         overall_result = True
210         testplc_method_dict = __import__("TestPlc").__dict__['TestPlc'].__dict__
211         all_step_infos=[]
212         for step in self.options.steps:
213             if not TestPlc.valid_step(step):
214                 continue
215             force=False
216             # is it a forcedstep
217             if step.find("force_") == 0:
218                 step=step.replace("force_","")
219                 force=True
220             # try and locate a method in TestPlc
221             if testplc_method_dict.has_key(step):
222                 all_step_infos += [ (step, testplc_method_dict[step] , force)]
223             # otherwise search for the 'run' method in the step_<x> module
224             else:
225                 modulename='step_'+step
226                 try:
227                     # locate all methods named run* in the module
228                     module_dict = __import__(modulename).__dict__
229                     names = [ key for key in module_dict.keys() if key.find("run")==0 ]
230                     if not names:
231                         raise Exception,"No run* method in module %s"%modulename
232                     names.sort()
233                     all_step_infos += [ ("%s.%s"%(step,name),module_dict[name],force) for name in names ]
234                 except :
235                     print '********** step %s NOT FOUND -- ignored'%(step)
236                     traceback.print_exc()
237                     overall_result = False
238             
239         if self.options.dry_run:
240             self.show_env(self.options,"Dry run")
241         
242         # init & open trace file if provided
243         if self.options.trace_file and not self.options.dry_run:
244             time=strftime("%H-%M")
245             date=strftime("%Y-%m-%d")
246             trace_file=self.options.trace_file
247             trace_file=trace_file.replace("@TIME@",time)
248             trace_file=trace_file.replace("@DATE@",date)
249             self.options.trace_file=trace_file
250             # create dir if needed
251             trace_dir=os.path.dirname(trace_file)
252             if trace_dir and not os.path.isdir(trace_dir):
253                 os.makedirs(trace_dir)
254             trace=open(trace_file,"w")
255
256         # do all steps on all plcs
257         TRACE_FORMAT="TRACE: time=%(time)s plc=%(plcname)s step=%(stepname)s status=%(status)s force=%(force)s\n"
258         for (stepname,method,force) in all_step_infos:
259             for (spec,obj) in all_plcs:
260                 plcname=spec['name']
261
262                 # run the step
263                 time=strftime("%Y-%m-%d-%H-%M")
264                 if not spec['disabled'] or force:
265                     try:
266                         force_msg=""
267                         if force: force_msg=" (forced)"
268                         utils.header("********** RUNNING step %s%s on plc %s"%(stepname,force_msg,plcname))
269                         step_result = method(obj)
270                         if step_result:
271                             utils.header('********** SUCCESSFUL step %s on %s'%(stepname,plcname))
272                             status="OK"
273                         else:
274                             overall_result = False
275                             spec['disabled'] = True
276                             utils.header('********** FAILED Step %s on %s - discarding that plc from further steps'%(stepname,plcname))
277                             status="KO"
278                     except:
279                         overall_result=False
280                         spec['disabled'] = True
281                         traceback.print_exc()
282                         utils.header ('********** FAILED (exception) Step %s on plc %s - discarding this plc from further steps'%(stepname,plcname))
283                         status="KO"
284
285                 # do not run, just display it's skipped
286                 else:
287                     utils.header("********** IGNORED Plc %s is disabled - skipping step %s"%(plcname,stepname))
288                     status="UNDEF"
289                 if not self.options.dry_run:
290                     # alwas do this on stdout
291                     print TRACE_FORMAT%locals()
292                     # duplicate on trace_file if provided
293                     if self.options.trace_file:
294                         trace.write(TRACE_FORMAT%locals())
295
296         if self.options.trace_file and not self.options.dry_run:
297             trace.close()
298
299         return overall_result
300
301     # wrapper to run, returns a shell-compatible result
302     def main(self):
303         try:
304             success=self.run()
305             if success:
306                 return 0
307             else:
308                 return 1 
309         except SystemExit:
310             raise
311         except:
312             traceback.print_exc()
313             return 2
314
315 if __name__ == "__main__":
316     sys.exit(TestMain().main())