first step towards using testbox properly
[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_4', 'nodes_booted',
26                      'standby_6','nodes_ssh', 'check_slices','check_initscripts',
27                      'check_tcp',
28                      'kill_qemus', ]
29     other_steps = [ 'fresh_install', 'stop', 
30                     'clean_sites', 'clean_nodes', 'clean_slices', 'clean_keys',
31                     'list_all_qemus', 'kill_qemus', 'stop_nodes' ,  
32                     'db_dump' , 'db_restore',
33                     'standby_1 through 20',
34                     ]
35     default_build_url = "http://svn.planet-lab.org/svn/build/trunk"
36
37     def __init__ (self):
38         self.path=os.path.dirname(sys.argv[0])
39         os.chdir(self.path)
40
41     @staticmethod
42     def show_env (options, message):
43         utils.header (message)
44         utils.pprint("main options",options)
45
46     @staticmethod
47     def optparse_list (option, opt, value, parser):
48         try:
49             setattr(parser.values,option.dest,getattr(parser.values,option.dest)+value.split())
50         except:
51             setattr(parser.values,option.dest,value.split())
52
53     def run (self):
54         steps_message="Defaut steps are\n\t%s"%(" ".join(TestMain.default_steps))
55         steps_message += "\nOther useful steps are\n\t %s"%(" ".join(TestMain.other_steps))
56         usage = """usage: %%prog [options] steps
57 myplc-url defaults to the last value used, as stored in arg-myplc-url,
58    no default
59 build-url defaults to the last value used, as stored in arg-build-url, 
60    or %s
61 config defaults to the last value used, as stored in arg-config,
62    or %r
63 ips defaults to the last value used, as stored in arg-ips,
64    default is to use IP scanning
65 steps refer to a method in TestPlc or to a step_* module
66 ===
67 """%(TestMain.default_build_url,TestMain.default_config)
68         usage += steps_message
69         parser=OptionParser(usage=usage,version=self.subversion_id)
70         parser.add_option("-u","--url",action="store", dest="myplc_url", 
71                           help="myplc URL - for locating build output")
72         parser.add_option("-b","--build",action="store", dest="build_url", 
73                           help="Build URL - for using vtest-init-vserver.sh in native mode")
74         parser.add_option("-c","--config",action="callback", callback=TestMain.optparse_list, dest="config",
75                           nargs=1,type="string",
76                           help="Config module - can be set multiple times, or use quotes")
77         parser.add_option("-a","--all",action="store_true",dest="all_steps", default=False,
78                           help="Run all default steps")
79         parser.add_option("-l","--list",action="store_true",dest="list_steps", default=False,
80                           help="List known steps")
81         parser.add_option("-s","--state",action="store",dest="dbname",default=None,
82                            help="Used by db_dump and db_restore")
83         parser.add_option("-d","--display", action="store", dest="display", default='bellami.inria.fr:0.0',
84                           help="Set DISPLAY for vmplayer")
85         parser.add_option("-i","--ip",action="callback", callback=TestMain.optparse_list, dest="ips",
86                           nargs=1,type="string",
87                           help="Specify the set of IP addresses to use in vserver mode (disable scanning)")
88         parser.add_option("-v","--verbose", action="store_true", dest="verbose", default=False, 
89                           help="Run in verbose mode")
90         parser.add_option("-n","--dry-run", action="store_true", dest="dry_run", default=False,
91                           help="Show environment and exits")
92         parser.add_option("-f","--forcenm", action="store_true", dest="forcenm", default=False, 
93                           help="Force the NM to restart in check_slices step")
94         (self.options, self.args) = parser.parse_args()
95
96         if len(self.args) == 0:
97             if self.options.all_steps:
98                 self.options.steps=TestMain.default_steps
99             elif self.options.dry_run:
100                 self.options.steps=TestMain.default_steps
101             elif self.options.list_steps:
102                 print steps_message
103                 sys.exit(1)
104             else:
105                 print 'No step found (do you mean -a ? )'
106                 print "Run %s --help for help"%sys.argv[0]                        
107                 sys.exit(1)
108         else:
109             self.options.steps = self.args
110
111         # handle defaults and option persistence
112         for (recname,filename,default) in (
113             ('build_url','arg-build-url',TestMain.default_build_url) ,
114             ('ips','arg-ips',[]) , 
115             ('config','arg-config',TestMain.default_config) , 
116             ('myplc_url','arg-myplc-url',"") , 
117             ) :
118 #            print 'handling',recname
119             path=filename
120             is_list = isinstance(default,list)
121             if not getattr(self.options,recname):
122                 try:
123                     parsed=file(path).readlines()
124                     if not is_list:    # strings
125                         if len(parsed) != 1:
126                             print "%s - error when parsing %s"%(sys.argv[1],path)
127                             sys.exit(1)
128                         parsed=parsed[0].strip()
129                     else:              # lists
130                         parsed=[x.strip() for x in parsed]
131                     setattr(self.options,recname,parsed)
132                 except:
133                     if default != "":
134                         setattr(self.options,recname,default)
135                     else:
136                         print "Cannot determine",recname
137                         print "Run %s --help for help"%sys.argv[0]                        
138                         sys.exit(1)
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=TestMain.default_steps
156
157         # store self.path in options.path for the various callbacks
158         self.options.path = self.path
159         # this is useful when propagating on host boxes, to avoid conflicts
160         self.options.buildname = os.path.basename (os.path.abspath (self.path))
161
162         if self.options.verbose:
163             self.show_env(self.options,"Verbose")
164
165         # load configs
166         all_plc_specs = []
167         for config in self.options.config:
168             modulename='config_'+config
169             try:
170                 m = __import__(modulename)
171                 all_plc_specs = m.config(all_plc_specs,self.options)
172             except :
173                 traceback.print_exc()
174                 print 'Cannot load config %s -- ignored'%modulename
175                 raise
176         # show config
177         utils.show_test_spec("Test specifications",all_plc_specs)
178         # build a TestPlc object from the result
179         for spec in all_plc_specs:
180             spec['disabled'] = False
181         all_plcs = [ (x, TestPlc(x)) for x in all_plc_specs]
182         # expose to the various objects
183         for (spec,obj) in all_plcs:
184             obj.options=self.options
185
186         overall_result = True
187         testplc_method_dict = __import__("TestPlc").__dict__['TestPlc'].__dict__
188         all_step_infos=[]
189         for step in self.options.steps:
190             # try and locate a method in TestPlc
191             if testplc_method_dict.has_key(step):
192                 all_step_infos += [ (step, testplc_method_dict[step] )]
193             # otherwise search for the 'run' method in the step_<x> module
194             else:
195                 modulename='step_'+step
196                 try:
197                     # locate all methods named run* in the module
198                     module_dict = __import__(modulename).__dict__
199                     names = [ key for key in module_dict.keys() if key.find("run")==0 ]
200                     if not names:
201                         raise Exception,"No run* method in module %s"%modulename
202                     names.sort()
203                     all_step_infos += [ ("%s.%s"%(step,name),module_dict[name]) for name in names ]
204                 except :
205                     print 'Step %s -- ignored'%(step)
206                     traceback.print_exc()
207                     overall_result = False
208             
209         if self.options.dry_run:
210             self.show_env(self.options,"Dry run")
211             return 0
212             
213         # do all steps on all plcs
214         for (stepname,method) in all_step_infos:
215             for (spec,obj) in all_plcs:
216                 plcname=spec['name']
217                 if spec['disabled']:
218                     utils.header("Plc %s is disabled - skipping step %s"%(plcname,stepname))
219                 else:
220                     try:
221                         utils.header("Running step %s on plc %s"%(stepname,plcname))
222                         step_result = method(obj,self.options)
223                         if step_result:
224                             utils.header('********** SUCCESSFUL step %s on %s'%(stepname,plcname))
225                         else:
226                             overall_result = False
227                             spec['disabled'] = True
228                             utils.header('********** Step %s on %s FAILED - discarding that plc from further steps'%(stepname,plcname))
229                     except:
230                         overall_result=False
231                         spec['disabled'] = True
232                         utils.header ('********** Step %s on plc %s FAILED (exception) - discarding this plc from further steps'%(stepname,plcname))
233                         traceback.print_exc()
234         return overall_result
235
236     # wrapper to run, returns a shell-compatible result
237     def main(self):
238         try:
239             success=self.run()
240             if success:
241                 return 0
242             else:
243                 return 1 
244         except SystemExit:
245             raise
246         except:
247             traceback.print_exc()
248             return 2
249
250 if __name__ == "__main__":
251     sys.exit(TestMain().main())