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