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