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