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