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