qemu instances are left running, need a tracker
[tests.git] / system / TestMain.py
1 #!/usr/bin/python -u
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 ips_node, ips_plc and ips_qemu defaults to the last value used, as stored in arg-ips-{node,plc,qemu},
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 hostname/IP's to use for nodes")
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 hostname/IP's to use for plcs")
82         parser.add_option("-Q","--qemus",action="callback", callback=TestMain.optparse_list, dest="ips_qemu",
83                           nargs=1,type="string",
84                           help="Specify the set of hostname/IP's to use for qemu boxes")
85         parser.add_option("-s","--size",action="store",type="int",dest="size",default=1,
86                           help="sets test size in # of plcs - default is 1")
87         parser.add_option("-D","--dbname",action="store",dest="dbname",default=None,
88                            help="Used by db_dump and db_restore")
89         parser.add_option("-v","--verbose", action="store_true", dest="verbose", default=False, 
90                           help="Run in verbose mode")
91         parser.add_option("-q","--quiet", action="store_true", dest="quiet", default=False, 
92                           help="Run in quiet mode")
93         parser.add_option("-i","--interactive",action="store_true",dest="interactive",default=False,
94                           help="prompts before each step")
95         parser.add_option("-n","--dry-run", action="store_true", dest="dry_run", default=False,
96                           help="Show environment and exits")
97         parser.add_option("-r","--restart-nm", action="store_true", dest="forcenm", default=False, 
98                           help="Force the NM to restart in check_slices step")
99         parser.add_option("-t","--trace", action="store", dest="trace_file", default=None,
100                           #default="logs/trace-@TIME@.txt",
101                           help="Trace file location")
102         (self.options, self.args) = parser.parse_args()
103         if self.options.quiet:
104             self.options.verbose=False
105
106         if len(self.args) == 0:
107             if self.options.all_steps:
108                 self.options.steps=TestPlc.default_steps
109             elif self.options.dry_run:
110                 self.options.steps=TestPlc.default_steps
111             elif self.options.list_steps:
112                 print steps_message
113                 sys.exit(1)
114             else:
115                 print 'No step found (do you mean -a ? )'
116                 print "Run %s --help for help"%sys.argv[0]                        
117                 sys.exit(1)
118         else:
119             self.options.steps = self.args
120
121         # handle defaults and option persistence
122         for (recname,filename,default) in (
123             ('build_url','arg-build-url',TestMain.default_build_url) ,
124             ('ips_node','arg-ips-node',[]) , 
125             ('ips_plc','arg-ips-plc',[]) , 
126             ('ips_qemu','arg-ips-qemu',[]) , 
127             ('config','arg-config',TestMain.default_config) , 
128             ('arch_rpms_url','arg-arch-rpms-url',"") , 
129             ('personality','arg-personality',"linux32"),
130             ('pldistro','arg-pldistro',"planetlab"),
131             ('fcdistro','arg-fcdistro','centos5'),
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
155             # save for next run
156             fsave=open(path,"w")
157             if not is_list:
158                 fsave.write(getattr(self.options,recname) + "\n")
159             else:
160                 for value in getattr(self.options,recname):
161                     fsave.write(value + "\n")
162             fsave.close()
163 #            utils.header('Saved %s into %s'%(recname,filename))
164
165             # lists need be reversed
166             if isinstance(getattr(self.options,recname),list):
167                 getattr(self.options,recname).reverse()
168
169             if not self.options.quiet:
170                 utils.header('* Using %s = %s'%(recname,getattr(self.options,recname)))
171
172
173         # steps
174         if not self.options.steps:
175             #default (all) steps
176             #self.options.steps=['dump','clean','install','populate']
177             self.options.steps=TestPlc.default_steps
178
179         # rewrite '-' into '_' in step names
180         self.options.steps = [ step.replace('-','_') for step in self.options.steps ]
181
182         # exclude
183         selected=[]
184         for step in self.options.steps:
185             keep=True
186             for exclude in self.options.exclude:
187                 if utils.match(step,exclude):
188                     keep=False
189                     break
190             if keep: selected.append(step)
191         self.options.steps=selected
192
193         # this is useful when propagating on host boxes, to avoid conflicts
194         self.options.buildname = os.path.basename (os.path.abspath (self.path))
195
196         if self.options.verbose:
197             self.show_env(self.options,"Verbose")
198
199         # load configs
200         all_plc_specs = []
201         for config in self.options.config:
202             modulename='config_'+config
203             try:
204                 m = __import__(modulename)
205                 all_plc_specs = m.config(all_plc_specs,self.options)
206             except :
207                 traceback.print_exc()
208                 print 'Cannot load config %s -- ignored'%modulename
209                 raise
210         # remember plc IP address(es) if not specified
211         ips_plc_file=open('arg-ips-plc','w')
212         for plc_spec in all_plc_specs:
213             ips_plc_file.write("%s\n"%plc_spec['PLC_API_HOST'])
214         ips_plc_file.close()
215         # ditto for nodes
216         ips_node_file=open('arg-ips-node','w')
217         for plc_spec in all_plc_specs:
218             for site_spec in plc_spec['sites']:
219                 for node_spec in site_spec['nodes']:
220                     ips_node_file.write("%s\n"%node_spec['node_fields']['hostname'])
221         ips_node_file.close()
222         # ditto for qemu boxes
223         ips_qemu_file=open('arg-ips-qemu','w')
224         for plc_spec in all_plc_specs:
225             for site_spec in plc_spec['sites']:
226                 for node_spec in site_spec['nodes']:
227                     ips_qemu_file.write("%s\n"%node_spec['host_box'])
228         ips_qemu_file.close()
229         # build a TestPlc object from the result, passing options
230         for spec in all_plc_specs:
231             spec['disabled'] = False
232         all_plcs = [ (x, TestPlc(x,self.options)) for x in all_plc_specs]
233
234         # pass options to utils as well
235         utils.init_options(self.options)
236
237         overall_result = True
238         testplc_method_dict = __import__("TestPlc").__dict__['TestPlc'].__dict__
239         all_step_infos=[]
240         for step in self.options.steps:
241             if not TestPlc.valid_step(step):
242                 continue
243             force=False
244             # is it a forced step
245             if step.find("force_") == 0:
246                 step=step.replace("force_","")
247                 force=True
248             # try and locate a method in TestPlc
249             if testplc_method_dict.has_key(step):
250                 all_step_infos += [ (step, testplc_method_dict[step] , force)]
251             # otherwise search for the 'run' method in the step_<x> module
252             else:
253                 modulename='step_'+step
254                 try:
255                     # locate all methods named run* in the module
256                     module_dict = __import__(modulename).__dict__
257                     names = [ key for key in module_dict.keys() if key.find("run")==0 ]
258                     if not names:
259                         raise Exception,"No run* method in module %s"%modulename
260                     names.sort()
261                     all_step_infos += [ ("%s.%s"%(step,name),module_dict[name],force) for name in names ]
262                 except :
263                     print '********** step %s NOT FOUND -- ignored'%(step)
264                     traceback.print_exc()
265                     overall_result = False
266             
267         if self.options.dry_run:
268             self.show_env(self.options,"Dry run")
269         
270         # init & open trace file if provided
271         if self.options.trace_file and not self.options.dry_run:
272             time=strftime("%H-%M")
273             date=strftime("%Y-%m-%d")
274             trace_file=self.options.trace_file
275             trace_file=trace_file.replace("@TIME@",time)
276             trace_file=trace_file.replace("@DATE@",date)
277             self.options.trace_file=trace_file
278             # create dir if needed
279             trace_dir=os.path.dirname(trace_file)
280             if trace_dir and not os.path.isdir(trace_dir):
281                 os.makedirs(trace_dir)
282             trace=open(trace_file,"w")
283
284         # do all steps on all plcs
285         TRACE_FORMAT="TRACE: time=%(time)s plc=%(plcname)s step=%(stepname)s status=%(status)s force=%(force)s\n"
286         for (stepname,method,force) in all_step_infos:
287             for (spec,obj) in all_plcs:
288                 plcname=spec['name']
289
290                 # run the step
291                 time=strftime("%Y-%m-%d-%H-%M")
292                 if not spec['disabled'] or force or self.options.interactive:
293                     skip_step=False
294                     if self.options.interactive:
295                         prompting=True
296                         while prompting:
297                             msg="Run step %s on %s [r](un)/d(ry_run)/s(kip)/q(uit) ? "%(stepname,plcname)
298                             answer=raw_input(msg).strip().lower() or "r"
299                             answer=answer[0]
300                             if answer in ['s','n']:     # skip/no/next
301                                 print '%s on %s skipped'%(stepname,plcname)
302                                 prompting=False
303                                 skip_step=True
304                             elif answer in ['q','b']:   # quit/bye
305                                 print 'Exiting'
306                                 return
307                             elif answer in ['d']:       # dry_run
308                                 dry_run=self.options.dry_run
309                                 self.options.dry_run=True
310                                 obj.options.dry_run=True
311                                 obj.apiserver.set_dry_run(True)
312                                 step_result=method(obj)
313                                 print 'dry_run step ->',step_result
314                                 self.options.dry_run=dry_run
315                                 obj.options.dry_run=dry_run
316                                 obj.apiserver.set_dry_run(dry_run)
317                             elif answer in ['r','y']:   # run/yes
318                                 prompting=False
319                     if skip_step:
320                         continue
321                     try:
322                         force_msg=""
323                         if force: force_msg=" (forced)"
324                         utils.header("********** RUNNING step %s%s on plc %s"%(stepname,force_msg,plcname))
325                         step_result = method(obj)
326                         if step_result:
327                             utils.header('********** SUCCESSFUL step %s on %s'%(stepname,plcname))
328                             status="OK"
329                         else:
330                             overall_result = False
331                             spec['disabled'] = True
332                             utils.header('********** FAILED Step %s on %s - discarding that plc from further steps'%(stepname,plcname))
333                             status="KO"
334                     except:
335                         overall_result=False
336                         spec['disabled'] = True
337                         traceback.print_exc()
338                         utils.header ('********** FAILED (exception) Step %s on plc %s - discarding this plc from further steps'%(stepname,plcname))
339                         status="KO"
340
341                 # do not run, just display it's skipped
342                 else:
343                     utils.header("********** IGNORED Plc %s is disabled - skipping step %s"%(plcname,stepname))
344                     status="UNDEF"
345                 if not self.options.dry_run:
346                     # alwas do this on stdout
347                     print TRACE_FORMAT%locals()
348                     # duplicate on trace_file if provided
349                     if self.options.trace_file:
350                         trace.write(TRACE_FORMAT%locals())
351
352         if self.options.trace_file and not self.options.dry_run:
353             trace.close()
354
355         return overall_result
356
357     # wrapper to run, returns a shell-compatible result
358     def main(self):
359         try:
360             success=self.run()
361             if success:
362                 return 0
363             else:
364                 return 1 
365         except SystemExit:
366             raise
367         except:
368             traceback.print_exc()
369             return 2
370
371 if __name__ == "__main__":
372     sys.exit(TestMain().main())