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