clears known_hosts for test nodes
[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 SEP='<sep>'
14
15 class TestMain:
16
17     subversion_id = "$Id$"
18
19     default_config = [ 'main' , '1vnodes' , '1testbox64' ]
20
21     default_steps = ['uninstall','install','install_rpm', 
22                      'configure', 'start', SEP,
23                      'store_keys', 'clear_known_hosts', 'initscripts', SEP,
24                      'sites', 'nodes', 'slices', 'nodegroups', SEP,
25                      'init_node','bootcd', 'configure_qemu', SEP,
26                      'kill_all_qemus', 'start_nodes', SEP,
27                      'standby_20', SEP,
28                      'nodes_booted', 'nodes_ssh', 'check_slices',
29                      'check_initscripts', 'check_tcp',SEP,
30                      'force_gather_logs', 'force_kill_qemus', ]
31     other_steps = [ 'stop_all_vservers','fresh_install', 'cache_rpm', 'stop', SEP,
32                     'clean_sites', 'clean_nodes', 'clean_slices', 'clean_keys', SEP,
33                     'show_boxes', 'list_all_qemus', 'list_qemus', SEP,
34                     'db_dump' , 'db_restore',
35                     'standby_1 through 20'
36                     ]
37     default_build_url = "http://svn.planet-lab.org/svn/build/trunk"
38
39     def __init__ (self):
40         self.path=os.path.dirname(sys.argv[0]) or "."
41         os.chdir(self.path)
42
43     @staticmethod
44     def show_env (options, message):
45         utils.header (message)
46         utils.show_options("main options",options)
47
48     @staticmethod
49     def optparse_list (option, opt, value, parser):
50         try:
51             setattr(parser.values,option.dest,getattr(parser.values,option.dest)+value.split())
52         except:
53             setattr(parser.values,option.dest,value.split())
54
55     @staticmethod
56     def printable_steps (list):
57         return " ".join(list).replace(" "+SEP+" ","\n")
58
59     def run (self):
60         steps_message=20*'x'+" Defaut steps are\n"+TestMain.printable_steps(TestMain.default_steps)
61         steps_message += "\n"+20*'x'+" Other useful steps are\n"+TestMain.printable_steps(TestMain.other_steps)
62         usage = """usage: %%prog [options] steps
63 myplc-url defaults to the last value used, as stored in arg-myplc-url,
64    no default
65 build-url defaults to the last value used, as stored in arg-build-url, 
66    or %s
67 config defaults to the last value used, as stored in arg-config,
68    or %r
69 ips defaults to the last value used, as stored in arg-ips,
70    default is to use IP scanning
71 steps refer to a method in TestPlc or to a step_* module
72 ===
73 """%(TestMain.default_build_url,TestMain.default_config)
74         usage += steps_message
75         parser=OptionParser(usage=usage,version=self.subversion_id)
76         parser.add_option("-u","--url",action="store", dest="myplc_url", 
77                           help="myplc URL - for locating build output")
78         parser.add_option("-b","--build",action="store", dest="build_url", 
79                           help="Build URL - for using vtest-init-vserver.sh in native mode")
80         parser.add_option("-c","--config",action="callback", callback=TestMain.optparse_list, dest="config",
81                           nargs=1,type="string",
82                           help="Config module - can be set multiple times, or use quotes")
83         parser.add_option("-x","--exclude",action="callback", callback=TestMain.optparse_list, dest="exclude",
84                           nargs=1,type="string",default=[],
85                           help="steps to exclude - can be set multiple times, or use quotes")
86         parser.add_option("-a","--all",action="store_true",dest="all_steps", default=False,
87                           help="Run all default steps")
88         parser.add_option("-l","--list",action="store_true",dest="list_steps", default=False,
89                           help="List known steps")
90         parser.add_option("-i","--ip",action="callback", callback=TestMain.optparse_list, dest="ips",
91                           nargs=1,type="string",
92                           help="Specify the set of IP addresses to use in vserver mode (disable scanning)")
93         parser.add_option("-s","--small",action="store_true",dest="small_test",default=False,
94                           help="run a small test -- typically only one node")
95         parser.add_option("-d","--dbname",action="store",dest="dbname",default=None,
96                            help="Used by db_dump and db_restore")
97         parser.add_option("-v","--verbose", action="store_true", dest="verbose", default=False, 
98                           help="Run in verbose mode")
99         parser.add_option("-q","--quiet", action="store_true", dest="quiet", default=False, 
100                           help="Run in quiet mode")
101         parser.add_option("-n","--dry-run", action="store_true", dest="dry_run", default=False,
102                           help="Show environment and exits")
103         parser.add_option("-f","--forcenm", action="store_true", dest="forcenm", default=False, 
104                           help="Force the NM to restart in check_slices step")
105         (self.options, self.args) = parser.parse_args()
106
107         # tmp : force small test 
108         utils.header("XXX WARNING : forcing small tests")
109         self.options.small_test = True
110
111         if len(self.args) == 0:
112             if self.options.all_steps:
113                 self.options.steps=TestMain.default_steps
114             elif self.options.dry_run:
115                 self.options.steps=TestMain.default_steps
116             elif self.options.list_steps:
117                 print steps_message
118                 sys.exit(1)
119             else:
120                 print 'No step found (do you mean -a ? )'
121                 print "Run %s --help for help"%sys.argv[0]                        
122                 sys.exit(1)
123         else:
124             self.options.steps = self.args
125
126         # handle defaults and option persistence
127         for (recname,filename,default) in (
128             ('build_url','arg-build-url',TestMain.default_build_url) ,
129             ('ips','arg-ips',[]) , 
130             ('config','arg-config',TestMain.default_config) , 
131             ('myplc_url','arg-myplc-url',"") , 
132             ) :
133 #            print 'handling',recname
134             path=filename
135             is_list = isinstance(default,list)
136             if not getattr(self.options,recname):
137                 try:
138                     parsed=file(path).readlines()
139                     if not is_list:    # strings
140                         if len(parsed) != 1:
141                             print "%s - error when parsing %s"%(sys.argv[1],path)
142                             sys.exit(1)
143                         parsed=parsed[0].strip()
144                     else:              # lists
145                         parsed=[x.strip() for x in parsed]
146                     setattr(self.options,recname,parsed)
147                 except:
148                     if default != "":
149                         setattr(self.options,recname,default)
150                     else:
151                         print "Cannot determine",recname
152                         print "Run %s --help for help"%sys.argv[0]                        
153                         sys.exit(1)
154             if not self.options.quiet:
155                 utils.header('* Using %s = %s'%(recname,getattr(self.options,recname)))
156
157             # save for next run
158             fsave=open(path,"w")
159             if not is_list:
160                 fsave.write(getattr(self.options,recname) + "\n")
161             else:
162                 for value in getattr(self.options,recname):
163                     fsave.write(value + "\n")
164             fsave.close()
165 #            utils.header('Saved %s into %s'%(recname,filename))
166
167         # steps
168         if not self.options.steps:
169             #default (all) steps
170             #self.options.steps=['dump','clean','install','populate']
171             self.options.steps=TestMain.default_steps
172
173         # exclude
174         selected=[]
175         for step in self.options.steps:
176             keep=True
177             for exclude in self.options.exclude:
178                 if utils.match(step,exclude):
179                     keep=False
180                     break
181             if keep: selected.append(step)
182         self.options.steps=selected
183
184         # this is useful when propagating on host boxes, to avoid conflicts
185         self.options.buildname = os.path.basename (os.path.abspath (self.path))
186
187         if self.options.verbose:
188             self.show_env(self.options,"Verbose")
189
190         # load configs
191         all_plc_specs = []
192         for config in self.options.config:
193             modulename='config_'+config
194             try:
195                 m = __import__(modulename)
196                 all_plc_specs = m.config(all_plc_specs,self.options)
197             except :
198                 traceback.print_exc()
199                 print 'Cannot load config %s -- ignored'%modulename
200                 raise
201         # show config
202         if not self.options.quiet:
203             utils.show_test_spec("Test specifications",all_plc_specs)
204         # build a TestPlc object from the result, passing options
205         for spec in all_plc_specs:
206             spec['disabled'] = False
207         all_plcs = [ (x, TestPlc(x,self.options)) for x in all_plc_specs]
208
209         # pass options to utils as well
210         utils.init_options(self.options)
211
212         overall_result = True
213         testplc_method_dict = __import__("TestPlc").__dict__['TestPlc'].__dict__
214         all_step_infos=[]
215         for step in self.options.steps:
216             if step == SEP:
217                 continue
218             force=False
219             # is it a forcedstep
220             if step.find("force_") == 0:
221                 step=step.replace("force_","")
222                 force=True
223             # try and locate a method in TestPlc
224             if testplc_method_dict.has_key(step):
225                 all_step_infos += [ (step, testplc_method_dict[step] , force)]
226             # otherwise search for the 'run' method in the step_<x> module
227             else:
228                 modulename='step_'+step
229                 try:
230                     # locate all methods named run* in the module
231                     module_dict = __import__(modulename).__dict__
232                     names = [ key for key in module_dict.keys() if key.find("run")==0 ]
233                     if not names:
234                         raise Exception,"No run* method in module %s"%modulename
235                     names.sort()
236                     all_step_infos += [ ("%s.%s"%(step,name),module_dict[name],force) for name in names ]
237                 except :
238                     print '********** step %s NOT FOUND -- ignored'%(step)
239                     traceback.print_exc()
240                     overall_result = False
241             
242         if self.options.dry_run:
243             self.show_env(self.options,"Dry run")
244             
245         # do all steps on all plcs
246         for (stepname,method,force) in all_step_infos:
247             for (spec,obj) in all_plcs:
248                 plcname=spec['name']
249
250                 # run the step
251                 if not spec['disabled'] or force:
252                     try:
253                         force_msg=""
254                         if force: force_msg=" (forced)"
255                         utils.header("********** RUNNING step %s%s on plc %s"%(stepname,force_msg,plcname))
256                         step_result = method(obj)
257                         if step_result:
258                             utils.header('********** SUCCESSFUL step %s on %s'%(stepname,plcname))
259                         else:
260                             overall_result = False
261                             spec['disabled'] = True
262                             utils.header('********** FAILED Step %s on %s - discarding that plc from further steps'%(stepname,plcname))
263                     except:
264                         overall_result=False
265                         spec['disabled'] = True
266                         traceback.print_exc()
267                         utils.header ('********** FAILED (exception) Step %s on plc %s - discarding this plc from further steps'%(stepname,plcname))
268
269                 # do not run, just display it's skipped
270                 else:
271                     utils.header("********** IGNORED Plc %s is disabled - skipping step %s"%(plcname,stepname))
272
273         return overall_result
274
275     # wrapper to run, returns a shell-compatible result
276     def main(self):
277         try:
278             success=self.run()
279             if success:
280                 return 0
281             else:
282                 return 1 
283         except SystemExit:
284             raise
285         except:
286             traceback.print_exc()
287             return 2
288
289 if __name__ == "__main__":
290     sys.exit(TestMain().main())