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