82e6c3b0138e2a87e7ccc430d9a6b00b41b6fc50
[tests.git] / system / TestMain.py
1 #!/usr/bin/env python
2 # $Id$
3
4 import os, sys
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                      'start_nodes', 'check_nodesStatus','standby','check_nodesConnectivity', 'check_slices' ]
25     other_steps = [ 'fresh_install', 'stop', 
26                     'clean_sites', 'clean_nodes', 'clean_slices', 'clean_keys',
27                     'stop_nodes' ,  'db_dump' , 'db_restore',
28                     ]
29     default_build_url = "http://svn.planet-lab.org/svn/build/trunk"
30
31     def __init__ (self):
32         self.path=os.path.dirname(sys.argv[0])
33
34     @staticmethod
35     def show_env (options, message):
36         utils.header (message)
37         utils.show_spec("main options",options)
38
39     @staticmethod
40     def optparse_list (option, opt, value, parser):
41         try:
42             setattr(parser.values,option.dest,getattr(parser.values,option.dest)+value.split())
43         except:
44             setattr(parser.values,option.dest,value.split())
45
46     def run (self):
47         steps_message="Defaut steps are\n\t%s"%(" ".join(TestMain.default_steps))
48         steps_message += "\nOther useful steps are\n\t %s"%(" ".join(TestMain.other_steps))
49         usage = """usage: %%prog [options] steps
50 myplc-url defaults to the last value used, as stored in arg-myplc-url,
51    no default
52 build-url defaults to the last value used, as stored in arg-build-url, 
53    or %s
54 config defaults to the last value used, as stored in arg-config,
55    or %r
56 ips defaults to the last value used, as stored in arg-ips,
57    default is to use IP scanning
58 steps refer to a method in TestPlc or to a step_* module
59 ===
60 """%(TestMain.default_build_url,TestMain.default_config)
61         usage += steps_message
62         parser=OptionParser(usage=usage,version=self.subversion_id)
63         parser.add_option("-u","--url",action="store", dest="myplc_url", 
64                           help="myplc URL - for locating build output")
65         parser.add_option("-b","--build",action="store", dest="build_url", 
66                           help="Build URL - for using vtest-init-vserver.sh in native mode")
67         parser.add_option("-c","--config",action="callback", callback=TestMain.optparse_list, dest="config",
68                           nargs=1,type="string",
69                           help="Config module - 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("-s","--state",action="store",dest="dbname",default=None,
75                            help="Used by db_dump and db_restore")
76         parser.add_option("-d","--display", action="store", dest="display", default='bellami.inria.fr:0.0',
77                           help="Set DISPLAY for vmplayer")
78         parser.add_option("-i","--ip",action="callback", callback=TestMain.optparse_list, dest="ips",
79                           nargs=1,type="string",
80                           help="Specify the set of IP addresses to use in vserver mode (disable scanning)")
81         parser.add_option("-v","--verbose", action="store_true", dest="verbose", default=False, 
82                           help="Run in verbose mode")
83         parser.add_option("-n","--dry-run", action="store_true", dest="dry_run", default=False,
84                           help="Show environment and exits")
85         parser.add_option("-f","--forcenm", action="store_true", dest="forcenm", default=False, 
86                           help="Force the NM to restart in check_slices step")
87         (self.options, self.args) = parser.parse_args()
88
89         if len(self.args) == 0:
90             if self.options.all_steps:
91                 self.options.steps=TestMain.default_steps
92             elif self.options.dry_run:
93                 self.options.steps=TestMain.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 ( ('myplc_url','arg-myplc-url',"") , 
106                                             ('build_url','arg-build-url',TestMain.default_build_url) ,
107                                             ('ips','arg-ips',[]) , 
108                                             ('config','arg-config',TestMain.default_config) , ) :
109             print 'handling',recname
110             path="%s/%s"%(self.path,filename)
111             is_list = isinstance(default,list)
112             if not getattr(self.options,recname):
113                 try:
114                     parsed=file(path).readlines()
115                     if not is_list:    # strings
116                         if len(parsed) != 1:
117                             print "%s - error when parsing %s"%(sys.argv[1],path)
118                             sys.exit(1)
119                         parsed=parsed[0].strip()
120                     else:              # lists
121                         parsed=[x.strip() for x in parsed]
122                     setattr(self.options,recname,parsed)
123                 except:
124                     if default != "":
125                         setattr(self.options,recname,default)
126                     else:
127                         print "Cannot determine",recname
128                         print "Run %s --help for help"%sys.argv[0]                        
129                         sys.exit(1)
130             utils.header('* Using %s = %s'%(recname,getattr(self.options,recname)))
131
132             # save for next run
133             fsave=open(path,"w")
134             if not is_list:
135                 fsave.write(getattr(self.options,recname) + "\n")
136             else:
137                 for value in getattr(self.options,recname):
138                     fsave.write(value + "\n")
139             fsave.close()
140             utils.header('Saved %s into %s'%(recname,filename))
141
142         # steps
143         if not self.options.steps:
144             #default (all) steps
145             #self.options.steps=['dump','clean','install','populate']
146             self.options.steps=TestMain.default_steps
147
148         # store self.path in options.path for the various callbacks
149         self.options.path = self.path
150
151         if self.options.verbose:
152             self.show_env(self.options,"Verbose")
153
154         # load configs
155         all_plc_specs = []
156         for config in self.options.config:
157             modulename='config_'+config
158             try:
159                 m = __import__(modulename)
160                 all_plc_specs = m.config(all_plc_specs,self.options)
161             except :
162                 traceback.print_exc()
163                 print 'Cannot load config %s -- ignored'%modulename
164                 raise
165         # show config
166         utils.show_spec("Test specifications",all_plc_specs)
167         # build a TestPlc object from the result
168         for spec in all_plc_specs:
169             spec['disabled'] = False
170         all_plcs = [ (x, TestPlc(x)) for x in all_plc_specs]
171
172         overall_result = True
173         testplc_method_dict = __import__("TestPlc").__dict__['TestPlc'].__dict__
174         all_step_infos=[]
175         for step in self.options.steps:
176             # try and locate a method in TestPlc
177             if testplc_method_dict.has_key(step):
178                 all_step_infos += [ (step, testplc_method_dict[step] )]
179             # otherwise search for the 'run' method in the step_<x> module
180             else:
181                 modulename='step_'+step
182                 try:
183                     # locate all methods named run* in the module
184                     module_dict = __import__(modulename).__dict__
185                     names = [ key for key in module_dict.keys() if key.find("run")==0 ]
186                     if not names:
187                         raise Exception,"No run* method in module %s"%modulename
188                     names.sort()
189                     all_step_infos += [ ("%s.%s"%(step,name),module_dict[name]) for name in names ]
190                 except :
191                     print 'Step %s -- ignored'%(step)
192                     traceback.print_exc()
193                     overall_result = False
194             
195         if self.options.dry_run:
196             self.show_env(self.options,"Dry run")
197             return 0
198             
199         # do all steps on all plcs
200         for (stepname,method) in all_step_infos:
201             for (spec,obj) in all_plcs:
202                 plcname=spec['name']
203                 if spec['disabled']:
204                     utils.header("Plc %s is disabled - skipping step %s"%(plcname,stepname))
205                 else:
206                     try:
207                         utils.header("Running step %s on plc %s"%(stepname,plcname))
208                         step_result = method(obj,self.options)
209                         if step_result:
210                             utils.header('Successful step %s on %s'%(stepname,plcname))
211                         else:
212                             overall_result = False
213                             spec['disabled'] = True
214                             utils.header('Step %s on %s FAILED - discarding that plc from further steps'%(stepname,plcname))
215                     except:
216                         overall_result=False
217                         spec['disabled'] = True
218                         utils.header ('Step %s on plc %s FAILED (exception) - discarding this plc from further steps'%(stepname,plcname))
219                         traceback.print_exc()
220         return overall_result
221
222     # wrapper to run, returns a shell-compatible result
223     def main(self):
224         try:
225             success=self.run()
226             if success:
227                 return 0
228             else:
229                 return 1 
230         except SystemExit:
231             raise
232         except:
233             traceback.print_exc()
234             return 2
235
236 if __name__ == "__main__":
237     sys.exit(TestMain().main())