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