forcing small test for now
[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 = [ 'onelab' ]
18
19     default_steps = ['uninstall','install','install_rpm',
20                      'configure', 'start', 
21                      'clear_ssh_config','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                     'list_all_qemus', 'list_qemus', 'stop_nodes' ,  
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("-a","--all",action="store_true",dest="all_steps", default=False,
77                           help="Run all default steps")
78         parser.add_option("-l","--list",action="store_true",dest="list_steps", default=False,
79                           help="List known steps")
80         parser.add_option("-i","--ip",action="callback", callback=TestMain.optparse_list, dest="ips",
81                           nargs=1,type="string",
82                           help="Specify the set of IP addresses to use in vserver mode (disable scanning)")
83         parser.add_option("-s","--small",action="store_true",dest="small_test",default=False,
84                           help="run a small test -- typically only one node")
85         parser.add_option("-d","--dbname",action="store",dest="dbname",default=None,
86                            help="Used by db_dump and db_restore")
87         parser.add_option("-v","--verbose", action="store_true", dest="verbose", default=False, 
88                           help="Run in verbose mode")
89         parser.add_option("-q","--quiet", action="store_true", dest="quiet", default=False, 
90                           help="Run in quiet mode")
91         parser.add_option("-n","--dry-run", action="store_true", dest="dry_run", default=False,
92                           help="Show environment and exits")
93         parser.add_option("-f","--forcenm", action="store_true", dest="forcenm", default=False, 
94                           help="Force the NM to restart in check_slices step")
95         (self.options, self.args) = parser.parse_args()
96
97         # tmp : force small test 
98         utils.header("XXX WARNING : forcing small tests")
99         self.options.small_test = True
100
101         if len(self.args) == 0:
102             if self.options.all_steps:
103                 self.options.steps=TestMain.default_steps
104             elif self.options.dry_run:
105                 self.options.steps=TestMain.default_steps
106             elif self.options.list_steps:
107                 print steps_message
108                 sys.exit(1)
109             else:
110                 print 'No step found (do you mean -a ? )'
111                 print "Run %s --help for help"%sys.argv[0]                        
112                 sys.exit(1)
113         else:
114             self.options.steps = self.args
115
116         # handle defaults and option persistence
117         for (recname,filename,default) in (
118             ('build_url','arg-build-url',TestMain.default_build_url) ,
119             ('ips','arg-ips',[]) , 
120             ('config','arg-config',TestMain.default_config) , 
121             ('myplc_url','arg-myplc-url',"") , 
122             ) :
123 #            print 'handling',recname
124             path=filename
125             is_list = isinstance(default,list)
126             if not getattr(self.options,recname):
127                 try:
128                     parsed=file(path).readlines()
129                     if not is_list:    # strings
130                         if len(parsed) != 1:
131                             print "%s - error when parsing %s"%(sys.argv[1],path)
132                             sys.exit(1)
133                         parsed=parsed[0].strip()
134                     else:              # lists
135                         parsed=[x.strip() for x in parsed]
136                     setattr(self.options,recname,parsed)
137                 except:
138                     if default != "":
139                         setattr(self.options,recname,default)
140                     else:
141                         print "Cannot determine",recname
142                         print "Run %s --help for help"%sys.argv[0]                        
143                         sys.exit(1)
144             if not self.options.quiet:
145                 utils.header('* Using %s = %s'%(recname,getattr(self.options,recname)))
146
147             # save for next run
148             fsave=open(path,"w")
149             if not is_list:
150                 fsave.write(getattr(self.options,recname) + "\n")
151             else:
152                 for value in getattr(self.options,recname):
153                     fsave.write(value + "\n")
154             fsave.close()
155 #            utils.header('Saved %s into %s'%(recname,filename))
156
157         # steps
158         if not self.options.steps:
159             #default (all) steps
160             #self.options.steps=['dump','clean','install','populate']
161             self.options.steps=TestMain.default_steps
162
163         # this is useful when propagating on host boxes, to avoid conflicts
164         self.options.buildname = os.path.basename (os.path.abspath (self.path))
165
166         if self.options.verbose:
167             self.show_env(self.options,"Verbose")
168
169         # load configs
170         all_plc_specs = []
171         for config in self.options.config:
172             modulename='config_'+config
173             try:
174                 m = __import__(modulename)
175                 all_plc_specs = m.config(all_plc_specs,self.options)
176             except :
177                 traceback.print_exc()
178                 print 'Cannot load config %s -- ignored'%modulename
179                 raise
180         # show config
181         if not self.options.quiet:
182             utils.show_test_spec("Test specifications",all_plc_specs)
183         # build a TestPlc object from the result
184         for spec in all_plc_specs:
185             spec['disabled'] = False
186         all_plcs = [ (x, TestPlc(x,self.options)) for x in all_plc_specs]
187
188         overall_result = True
189         testplc_method_dict = __import__("TestPlc").__dict__['TestPlc'].__dict__
190         all_step_infos=[]
191         for step in self.options.steps:
192             force=False
193             # is it a forcedstep
194             if step.find("force_") == 0:
195                 step=step.replace("force_","")
196                 force=True
197             # try and locate a method in TestPlc
198             if testplc_method_dict.has_key(step):
199                 all_step_infos += [ (step, testplc_method_dict[step] , force)]
200             # otherwise search for the 'run' method in the step_<x> module
201             else:
202                 modulename='step_'+step
203                 try:
204                     # locate all methods named run* in the module
205                     module_dict = __import__(modulename).__dict__
206                     names = [ key for key in module_dict.keys() if key.find("run")==0 ]
207                     if not names:
208                         raise Exception,"No run* method in module %s"%modulename
209                     names.sort()
210                     all_step_infos += [ ("%s.%s"%(step,name),module_dict[name],force) for name in names ]
211                 except :
212                     print 'Step %s -- ignored'%(step)
213                     traceback.print_exc()
214                     overall_result = False
215             
216         if self.options.dry_run:
217             self.show_env(self.options,"Dry run")
218             return 0
219             
220         # do all steps on all plcs
221         for (stepname,method,force) in all_step_infos:
222             for (spec,obj) in all_plcs:
223                 plcname=spec['name']
224
225                 # run the step
226                 if not spec['disabled'] or force:
227                     try:
228                         force_msg=""
229                         if force: force_msg=" (forced)"
230                         utils.header("********** RUNNING step %s%s on plc %s"%(stepname,force_msg,plcname))
231                         step_result = method(obj,self.options)
232                         if step_result:
233                             utils.header('********** SUCCESSFUL step %s on %s'%(stepname,plcname))
234                         else:
235                             overall_result = False
236                             spec['disabled'] = True
237                             utils.header('********** FAILED Step %s on %s - discarding that plc from further steps'%(stepname,plcname))
238                     except:
239                         overall_result=False
240                         spec['disabled'] = True
241                         traceback.print_exc()
242                         utils.header ('********** FAILED (exception) Step %s on plc %s - discarding this plc from further steps'%(stepname,plcname))
243
244                 # do not run, just display it's skipped
245                 else:
246                     utils.header("********** IGNORED Plc %s is disabled - skipping step %s"%(plcname,stepname))
247
248         return overall_result
249
250     # wrapper to run, returns a shell-compatible result
251     def main(self):
252         try:
253             success=self.run()
254             if success:
255                 return 0
256             else:
257                 return 1 
258         except SystemExit:
259             raise
260         except:
261             traceback.print_exc()
262             return 2
263
264 if __name__ == "__main__":
265     sys.exit(TestMain().main())