oops, this needs to move as well
[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
8 import utils
9 from TestPlc import TestPlc
10 from TestSite import TestSite
11 from TestNode import TestNode
12
13 class TestMain:
14
15     subversion_id = "$Id$"
16
17     default_config = [ 'main' , '1vnodes' , '1testbox64' ]
18
19     default_build_url = "http://svn.planet-lab.org/svn/build/trunk"
20
21     def __init__ (self):
22         self.path=os.path.dirname(sys.argv[0]) or "."
23         os.chdir(self.path)
24
25     @staticmethod
26     def show_env (options, message):
27         utils.header (message)
28         utils.show_options("main options",options)
29
30     @staticmethod
31     def optparse_list (option, opt, value, parser):
32         try:
33             setattr(parser.values,option.dest,getattr(parser.values,option.dest)+value.split())
34         except:
35             setattr(parser.values,option.dest,value.split())
36
37     def run (self):
38         steps_message=20*'x'+" Defaut steps are\n"+TestPlc.printable_steps(TestPlc.default_steps)
39         steps_message += "\n"+20*'x'+" Other useful steps are\n"+TestPlc.printable_steps(TestPlc.other_steps)
40         usage = """usage: %%prog [options] steps
41 myplc-url defaults to the last value used, as stored in arg-myplc-url,
42    no default
43 build-url defaults to the last value used, as stored in arg-build-url, 
44    or %s
45 config defaults to the last value used, as stored in arg-config,
46    or %r
47 ips defaults to the last value used, as stored in arg-ips,
48    default is to use IP scanning
49 steps refer to a method in TestPlc or to a step_* module
50 ===
51 """%(TestMain.default_build_url,TestMain.default_config)
52         usage += steps_message
53         parser=OptionParser(usage=usage,version=self.subversion_id)
54         parser.add_option("-u","--url",action="store", dest="myplc_url", 
55                           help="myplc URL - for locating build output")
56         parser.add_option("-b","--build",action="store", dest="build_url", 
57                           help="Build URL - for using vtest-init-vserver.sh in native mode")
58         parser.add_option("-c","--config",action="callback", callback=TestMain.optparse_list, dest="config",
59                           nargs=1,type="string",
60                           help="Config module - can be set multiple times, or use quotes")
61         parser.add_option("-x","--exclude",action="callback", callback=TestMain.optparse_list, dest="exclude",
62                           nargs=1,type="string",default=[],
63                           help="steps to exclude - can be set multiple times, or use quotes")
64         parser.add_option("-a","--all",action="store_true",dest="all_steps", default=False,
65                           help="Run all default steps")
66         parser.add_option("-l","--list",action="store_true",dest="list_steps", default=False,
67                           help="List known steps")
68         parser.add_option("-i","--ip",action="callback", callback=TestMain.optparse_list, dest="ips",
69                           nargs=1,type="string",
70                           help="Specify the set of IP addresses to use in vserver mode (disable scanning)")
71         parser.add_option("-s","--small",action="store_true",dest="small_test",default=False,
72                           help="run a small test -- typically only one node")
73         parser.add_option("-d","--dbname",action="store",dest="dbname",default=None,
74                            help="Used by db_dump and db_restore")
75         parser.add_option("-v","--verbose", action="store_true", dest="verbose", default=False, 
76                           help="Run in verbose mode")
77         parser.add_option("-q","--quiet", action="store_true", dest="quiet", default=False, 
78                           help="Run in quiet mode")
79         parser.add_option("-n","--dry-run", action="store_true", dest="dry_run", default=False,
80                           help="Show environment and exits")
81         parser.add_option("-f","--forcenm", action="store_true", dest="forcenm", default=False, 
82                           help="Force the NM to restart in check_slices step")
83         (self.options, self.args) = parser.parse_args()
84
85         # tmp : force small test 
86         utils.header("XXX WARNING : forcing small tests")
87         self.options.small_test = True
88
89         if len(self.args) == 0:
90             if self.options.all_steps:
91                 self.options.steps=TestPlc.default_steps
92             elif self.options.dry_run:
93                 self.options.steps=TestPlc.default_steps
94             elif self.options.list_steps:
95                 print steps_message
96                 sys.exit(1)
97             else:
98                 print 'No step found (do you mean -a ? )'
99                 print "Run %s --help for help"%sys.argv[0]                        
100                 sys.exit(1)
101         else:
102             self.options.steps = self.args
103
104         # handle defaults and option persistence
105         for (recname,filename,default) in (
106             ('build_url','arg-build-url',TestMain.default_build_url) ,
107             ('ips','arg-ips',[]) , 
108             ('config','arg-config',TestMain.default_config) , 
109             ('myplc_url','arg-myplc-url',"") , 
110             ) :
111 #            print 'handling',recname
112             path=filename
113             is_list = isinstance(default,list)
114             if not getattr(self.options,recname):
115                 try:
116                     parsed=file(path).readlines()
117                     if not is_list:    # strings
118                         if len(parsed) != 1:
119                             print "%s - error when parsing %s"%(sys.argv[1],path)
120                             sys.exit(1)
121                         parsed=parsed[0].strip()
122                     else:              # lists
123                         parsed=[x.strip() for x in parsed]
124                     setattr(self.options,recname,parsed)
125                 except:
126                     if default != "":
127                         setattr(self.options,recname,default)
128                     else:
129                         print "Cannot determine",recname
130                         print "Run %s --help for help"%sys.argv[0]                        
131                         sys.exit(1)
132             if not self.options.quiet:
133                 utils.header('* Using %s = %s'%(recname,getattr(self.options,recname)))
134
135             # save for next run
136             fsave=open(path,"w")
137             if not is_list:
138                 fsave.write(getattr(self.options,recname) + "\n")
139             else:
140                 for value in getattr(self.options,recname):
141                     fsave.write(value + "\n")
142             fsave.close()
143 #            utils.header('Saved %s into %s'%(recname,filename))
144
145         # steps
146         if not self.options.steps:
147             #default (all) steps
148             #self.options.steps=['dump','clean','install','populate']
149             self.options.steps=TestPlc.default_steps
150
151         # exclude
152         selected=[]
153         for step in self.options.steps:
154             keep=True
155             for exclude in self.options.exclude:
156                 if utils.match(step,exclude):
157                     keep=False
158                     break
159             if keep: selected.append(step)
160         self.options.steps=selected
161
162         # this is useful when propagating on host boxes, to avoid conflicts
163         self.options.buildname = os.path.basename (os.path.abspath (self.path))
164
165         if self.options.verbose:
166             self.show_env(self.options,"Verbose")
167
168         # load configs
169         all_plc_specs = []
170         for config in self.options.config:
171             modulename='config_'+config
172             try:
173                 m = __import__(modulename)
174                 all_plc_specs = m.config(all_plc_specs,self.options)
175             except :
176                 traceback.print_exc()
177                 print 'Cannot load config %s -- ignored'%modulename
178                 raise
179         # show config
180         if not self.options.quiet:
181             utils.show_test_spec("Test specifications",all_plc_specs)
182         # build a TestPlc object from the result, passing options
183         for spec in all_plc_specs:
184             spec['disabled'] = False
185         all_plcs = [ (x, TestPlc(x,self.options)) for x in all_plc_specs]
186
187         # pass options to utils as well
188         utils.init_options(self.options)
189
190         overall_result = True
191         testplc_method_dict = __import__("TestPlc").__dict__['TestPlc'].__dict__
192         all_step_infos=[]
193         for step in self.options.steps:
194             if step == SEP:
195                 continue
196             force=False
197             # is it a forcedstep
198             if step.find("force_") == 0:
199                 step=step.replace("force_","")
200                 force=True
201             # try and locate a method in TestPlc
202             if testplc_method_dict.has_key(step):
203                 all_step_infos += [ (step, testplc_method_dict[step] , force)]
204             # otherwise search for the 'run' method in the step_<x> module
205             else:
206                 modulename='step_'+step
207                 try:
208                     # locate all methods named run* in the module
209                     module_dict = __import__(modulename).__dict__
210                     names = [ key for key in module_dict.keys() if key.find("run")==0 ]
211                     if not names:
212                         raise Exception,"No run* method in module %s"%modulename
213                     names.sort()
214                     all_step_infos += [ ("%s.%s"%(step,name),module_dict[name],force) for name in names ]
215                 except :
216                     print '********** step %s NOT FOUND -- ignored'%(step)
217                     traceback.print_exc()
218                     overall_result = False
219             
220         if self.options.dry_run:
221             self.show_env(self.options,"Dry run")
222             
223         # do all steps on all plcs
224         for (stepname,method,force) in all_step_infos:
225             for (spec,obj) in all_plcs:
226                 plcname=spec['name']
227
228                 # run the step
229                 if not spec['disabled'] or force:
230                     try:
231                         force_msg=""
232                         if force: force_msg=" (forced)"
233                         utils.header("********** RUNNING step %s%s on plc %s"%(stepname,force_msg,plcname))
234                         step_result = method(obj)
235                         if step_result:
236                             utils.header('********** SUCCESSFUL step %s on %s'%(stepname,plcname))
237                         else:
238                             overall_result = False
239                             spec['disabled'] = True
240                             utils.header('********** FAILED Step %s on %s - discarding that plc from further steps'%(stepname,plcname))
241                     except:
242                         overall_result=False
243                         spec['disabled'] = True
244                         traceback.print_exc()
245                         utils.header ('********** FAILED (exception) Step %s on plc %s - discarding this plc from further steps'%(stepname,plcname))
246
247                 # do not run, just display it's skipped
248                 else:
249                     utils.header("********** IGNORED Plc %s is disabled - skipping step %s"%(plcname,stepname))
250
251         return overall_result
252
253     # wrapper to run, returns a shell-compatible result
254     def main(self):
255         try:
256             success=self.run()
257             if success:
258                 return 0
259             else:
260                 return 1 
261         except SystemExit:
262             raise
263         except:
264             traceback.print_exc()
265             return 2
266
267 if __name__ == "__main__":
268     sys.exit(TestMain().main())