fixed kill_qemus : uses qemu -pidfile for locating pids
[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_10', 'nodes_booted',
26                      'standby_6','nodes_ssh', 'check_slices','check_initscripts',
27                      'force_kill_qemus', ]
28     other_steps = [ 'stop_all_vservers','fresh_install', 'stop','check_tcp', 
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("-s","--state",action="store",dest="dbname",default=None,
81                            help="Used by db_dump and db_restore")
82         parser.add_option("-d","--display", action="store", dest="display", default='bellami.inria.fr:0.0',
83                           help="Set DISPLAY for vmplayer")
84         parser.add_option("-i","--ip",action="callback", callback=TestMain.optparse_list, dest="ips",
85                           nargs=1,type="string",
86                           help="Specify the set of IP addresses to use in vserver mode (disable scanning)")
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         if len(self.args) == 0:
98             if self.options.all_steps:
99                 self.options.steps=TestMain.default_steps
100             elif self.options.dry_run:
101                 self.options.steps=TestMain.default_steps
102             elif self.options.list_steps:
103                 print steps_message
104                 sys.exit(1)
105             else:
106                 print 'No step found (do you mean -a ? )'
107                 print "Run %s --help for help"%sys.argv[0]                        
108                 sys.exit(1)
109         else:
110             self.options.steps = self.args
111
112         # handle defaults and option persistence
113         for (recname,filename,default) in (
114             ('build_url','arg-build-url',TestMain.default_build_url) ,
115             ('ips','arg-ips',[]) , 
116             ('config','arg-config',TestMain.default_config) , 
117             ('myplc_url','arg-myplc-url',"") , 
118             ) :
119 #            print 'handling',recname
120             path=filename
121             is_list = isinstance(default,list)
122             if not getattr(self.options,recname):
123                 try:
124                     parsed=file(path).readlines()
125                     if not is_list:    # strings
126                         if len(parsed) != 1:
127                             print "%s - error when parsing %s"%(sys.argv[1],path)
128                             sys.exit(1)
129                         parsed=parsed[0].strip()
130                     else:              # lists
131                         parsed=[x.strip() for x in parsed]
132                     setattr(self.options,recname,parsed)
133                 except:
134                     if default != "":
135                         setattr(self.options,recname,default)
136                     else:
137                         print "Cannot determine",recname
138                         print "Run %s --help for help"%sys.argv[0]                        
139                         sys.exit(1)
140             if not self.options.quiet:
141                 utils.header('* Using %s = %s'%(recname,getattr(self.options,recname)))
142
143             # save for next run
144             fsave=open(path,"w")
145             if not is_list:
146                 fsave.write(getattr(self.options,recname) + "\n")
147             else:
148                 for value in getattr(self.options,recname):
149                     fsave.write(value + "\n")
150             fsave.close()
151 #            utils.header('Saved %s into %s'%(recname,filename))
152
153         # steps
154         if not self.options.steps:
155             #default (all) steps
156             #self.options.steps=['dump','clean','install','populate']
157             self.options.steps=TestMain.default_steps
158
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         if not self.options.quiet:
178             utils.show_test_spec("Test specifications",all_plc_specs)
179         # build a TestPlc object from the result
180         for spec in all_plc_specs:
181             spec['disabled'] = False
182         all_plcs = [ (x, TestPlc(x)) for x in all_plc_specs]
183         # expose to the various objects
184         for (spec,obj) in all_plcs:
185             obj.options=self.options
186
187         overall_result = True
188         testplc_method_dict = __import__("TestPlc").__dict__['TestPlc'].__dict__
189         all_step_infos=[]
190         for step in self.options.steps:
191             force=False
192             # is it a forcedstep
193             if step.find("force_") == 0:
194                 step=step.replace("force_","")
195                 force=True
196             # try and locate a method in TestPlc
197             if testplc_method_dict.has_key(step):
198                 all_step_infos += [ (step, testplc_method_dict[step] , force)]
199             # otherwise search for the 'run' method in the step_<x> module
200             else:
201                 modulename='step_'+step
202                 try:
203                     # locate all methods named run* in the module
204                     module_dict = __import__(modulename).__dict__
205                     names = [ key for key in module_dict.keys() if key.find("run")==0 ]
206                     if not names:
207                         raise Exception,"No run* method in module %s"%modulename
208                     names.sort()
209                     all_step_infos += [ ("%s.%s"%(step,name),module_dict[name],force) for name in names ]
210                 except :
211                     print 'Step %s -- ignored'%(step)
212                     traceback.print_exc()
213                     overall_result = False
214             
215         if self.options.dry_run:
216             self.show_env(self.options,"Dry run")
217             return 0
218             
219         # do all steps on all plcs
220         for (stepname,method,force) in all_step_infos:
221             for (spec,obj) in all_plcs:
222                 plcname=spec['name']
223
224                 # run the step
225                 if not spec['disabled'] or force:
226                     try:
227                         force_msg=""
228                         if force: force_msg=" (forced)"
229                         utils.header("Running step %s%s on plc %s"%(stepname,force_msg,plcname))
230                         step_result = method(obj,self.options)
231                         if step_result:
232                             utils.header('********** SUCCESSFUL step %s on %s'%(stepname,plcname))
233                         else:
234                             overall_result = False
235                             spec['disabled'] = True
236                             utils.header('********** Step %s on %s FAILED - discarding that plc from further steps'%(stepname,plcname))
237                     except:
238                         overall_result=False
239                         spec['disabled'] = True
240                         traceback.print_exc()
241                         utils.header ('********** Step %s on plc %s FAILED (exception) - discarding this plc from further steps'%(stepname,plcname))
242
243                 # do not run, just display it's skipped
244                 else:
245                     utils.header("Plc %s is disabled - skipping step %s"%(plcname,stepname))
246
247         return overall_result
248
249     # wrapper to run, returns a shell-compatible result
250     def main(self):
251         try:
252             success=self.run()
253             if success:
254                 return 0
255             else:
256                 return 1 
257         except SystemExit:
258             raise
259         except:
260             traceback.print_exc()
261             return 2
262
263 if __name__ == "__main__":
264     sys.exit(TestMain().main())