test modules for sfa
[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 # add $HOME in PYTHONPATH so we can import LocalTestResources.py
16 sys.path.append(os.environ['HOME'])
17 import LocalTestResources
18
19 class TestMain:
20
21     subversion_id = "$Id$"
22
23     default_config = [ 'default' ] 
24
25     default_build_url = "http://svn.planet-lab.org/svn/build/trunk"
26
27     def __init__ (self):
28         self.path=os.path.dirname(sys.argv[0]) or "."
29         os.chdir(self.path)
30
31     def show_env (self,options, message):
32         if self.options.verbose:
33             utils.header (message)
34             utils.show_options("main options",options)
35
36     def init_steps(self):
37         self.steps_message=20*'x'+" Defaut steps are\n"+TestPlc.printable_steps(TestPlc.default_steps)
38         self.steps_message += "\n"+20*'x'+" Other useful steps are\n"+TestPlc.printable_steps(TestPlc.other_steps)
39
40     def list_steps(self):
41         if not self.options.verbose:
42             print self.steps_message
43         else:
44             testplc_method_dict = __import__("TestPlc").__dict__['TestPlc'].__dict__
45             scopes = [("Default steps",TestPlc.default_steps)]
46             if self.options.all_steps:
47                 scopes.append ( ("Other steps",TestPlc.other_steps) )
48             for (scope,steps) in scopes:
49                 print '--------------------',scope
50                 for step in [step for step in steps if TestPlc.valid_step(step)]:
51                     stepname=step
52                     if step.find("force_") == 0:
53                         stepname=step.replace("force_","")
54                         force=True
55                     print '*',step,"\r",4*"\t",
56                     try:
57                         print testplc_method_dict[stepname].__doc__
58                     except:
59                         print "*** no doc found"
60
61     @staticmethod
62     def optparse_list (option, opt, value, parser):
63         try:
64             setattr(parser.values,option.dest,getattr(parser.values,option.dest)+value.split())
65         except:
66             setattr(parser.values,option.dest,value.split())
67
68     def run (self):
69         self.init_steps()
70         usage = """usage: %%prog [options] steps
71 arch-rpms-url defaults to the last value used, as stored in arg-arch-rpms-url,
72    no default
73 build-url defaults to the last value used, as stored in arg-build-url, 
74    or %s
75 config defaults to the last value used, as stored in arg-config,
76    or %r
77 ips_node, ips_plc and ips_qemu defaults to the last value used, as stored in arg-ips-{node,plc,qemu},
78    default is to use IP scanning
79 steps refer to a method in TestPlc or to a step_* module
80 ===
81 """%(TestMain.default_build_url,TestMain.default_config)
82         usage += self.steps_message
83         parser=OptionParser(usage=usage,version=self.subversion_id)
84         parser.add_option("-u","--url",action="store", dest="arch_rpms_url", 
85                           help="URL of the arch-dependent RPMS area - for locating what to test")
86         parser.add_option("-b","--build",action="store", dest="build_url", 
87                           help="Build URL - for locating vtest-init-vserver.sh")
88         parser.add_option("-c","--config",action="callback", callback=TestMain.optparse_list, dest="config",
89                           nargs=1,type="string",
90                           help="Config module - can be set multiple times, or use quotes")
91         parser.add_option("-p","--personality",action="store", dest="personality", 
92                           help="personality - as in vbuild-nightly")
93         parser.add_option("-d","--pldistro",action="store", dest="pldistro", 
94                           help="pldistro - as in vbuild-nightly")
95         parser.add_option("-f","--fcdistro",action="store", dest="fcdistro", 
96                           help="fcdistro - as in vbuild-nightly")
97         parser.add_option("-x","--exclude",action="callback", callback=TestMain.optparse_list, dest="exclude",
98                           nargs=1,type="string",default=[],
99                           help="steps to exclude - can be set multiple times, or use quotes")
100         parser.add_option("-a","--all",action="store_true",dest="all_steps", default=False,
101                           help="Run all default steps")
102         parser.add_option("-l","--list",action="store_true",dest="list_steps", default=False,
103                           help="List known steps")
104         parser.add_option("-N","--nodes",action="callback", callback=TestMain.optparse_list, dest="ips_node",
105                           nargs=1,type="string",
106                           help="Specify the set of hostname/IP's to use for nodes")
107         parser.add_option("-P","--plcs",action="callback", callback=TestMain.optparse_list, dest="ips_plc",
108                           nargs=1,type="string",
109                           help="Specify the set of hostname/IP's to use for plcs")
110         parser.add_option("-Q","--qemus",action="callback", callback=TestMain.optparse_list, dest="ips_qemu",
111                           nargs=1,type="string",
112                           help="Specify the set of hostname/IP's to use for qemu boxes")
113         parser.add_option("-s","--size",action="store",type="int",dest="size",default=1,
114                           help="sets test size in # of plcs - default is 1")
115         parser.add_option("-D","--dbname",action="store",dest="dbname",default=None,
116                            help="Used by db_dump and db_restore")
117         parser.add_option("-v","--verbose", action="store_true", dest="verbose", default=False, 
118                           help="Run in verbose mode")
119         parser.add_option("-q","--quiet", action="store_true", dest="quiet", default=False, 
120                           help="Run in quiet mode")
121         parser.add_option("-i","--interactive",action="store_true",dest="interactive",default=False,
122                           help="prompts before each step")
123         parser.add_option("-n","--dry-run", action="store_true", dest="dry_run", default=False,
124                           help="Show environment and exits")
125         parser.add_option("-r","--restart-nm", action="store_true", dest="forcenm", default=False, 
126                           help="Force the NM to restart in check_slices step")
127         parser.add_option("-t","--trace", action="store", dest="trace_file", default=None,
128                           #default="logs/trace-@TIME@.txt",
129                           help="Trace file location")
130         (self.options, self.args) = parser.parse_args()
131         if self.options.quiet:
132             self.options.verbose=False
133
134         # no step specified
135         if len(self.args) == 0:
136             self.options.steps=TestPlc.default_steps
137         else:
138             self.options.steps = self.args
139
140         if self.options.list_steps:
141             self.list_steps()
142             sys.exit(1)
143
144         # handle defaults and option persistence
145         for (recname,filename,default) in (
146             ('build_url','arg-build-url',TestMain.default_build_url) ,
147             ('ips_node','arg-ips-node',[]) , 
148             ('ips_plc','arg-ips-plc',[]) , 
149             ('ips_qemu','arg-ips-qemu',[]) , 
150             ('config','arg-config',TestMain.default_config) , 
151             ('arch_rpms_url','arg-arch-rpms-url',"") , 
152             ('personality','arg-personality',"linux32"),
153             ('pldistro','arg-pldistro',"planetlab"),
154             ('fcdistro','arg-fcdistro','centos5'),
155             ) :
156 #            print 'handling',recname
157             path=filename
158             is_list = isinstance(default,list)
159             if not getattr(self.options,recname):
160                 try:
161                     parsed=file(path).readlines()
162                     if not is_list:    # strings
163                         if len(parsed) != 1:
164                             print "%s - error when parsing %s"%(sys.argv[1],path)
165                             sys.exit(1)
166                         parsed=parsed[0].strip()
167                     else:              # lists
168                         parsed=[x.strip() for x in parsed]
169                     setattr(self.options,recname,parsed)
170                 except:
171                     if default != "":
172                         setattr(self.options,recname,default)
173                     else:
174                         print "Cannot determine",recname
175                         print "Run %s --help for help"%sys.argv[0]                        
176                         sys.exit(1)
177
178             # save for next run
179             fsave=open(path,"w")
180             if not is_list:
181                 fsave.write(getattr(self.options,recname) + "\n")
182             else:
183                 for value in getattr(self.options,recname):
184                     fsave.write(value + "\n")
185             fsave.close()
186 #            utils.header('Saved %s into %s'%(recname,filename))
187
188             # lists need be reversed
189             if isinstance(getattr(self.options,recname),list):
190                 getattr(self.options,recname).reverse()
191
192             if self.options.verbose:
193                 utils.header('* Using %s = %s'%(recname,getattr(self.options,recname)))
194
195
196         # steps
197         if not self.options.steps:
198             #default (all) steps
199             #self.options.steps=['dump','clean','install','populate']
200             self.options.steps=TestPlc.default_steps
201
202         # rewrite '-' into '_' in step names
203         self.options.steps = [ step.replace('-','_') for step in self.options.steps ]
204
205         # exclude
206         selected=[]
207         for step in self.options.steps:
208             keep=True
209             for exclude in self.options.exclude:
210                 if utils.match(step,exclude):
211                     keep=False
212                     break
213             if keep: selected.append(step)
214         self.options.steps=selected
215
216         # this is useful when propagating on host boxes, to avoid conflicts
217         self.options.buildname = os.path.basename (os.path.abspath (self.path))
218
219         if self.options.verbose:
220             self.show_env(self.options,"Verbose")
221
222         # load configs
223         all_plc_specs = []
224         for config in self.options.config:
225             modulename='config_'+config
226             try:
227                 m = __import__(modulename)
228                 all_plc_specs = m.config(all_plc_specs,self.options)
229             except :
230                 traceback.print_exc()
231                 print 'Cannot load config %s -- ignored'%modulename
232                 raise
233
234         # run localize as defined by local_resources
235         all_plc_specs = LocalTestResources.local_resources.localize(all_plc_specs,self.options)
236
237         # remember plc IP address(es) if not specified
238         ips_plc_file=open('arg-ips-plc','w')
239         for plc_spec in all_plc_specs:
240             ips_plc_file.write("%s\n"%plc_spec['PLC_API_HOST'])
241         ips_plc_file.close()
242         # ditto for nodes
243         ips_node_file=open('arg-ips-node','w')
244         for plc_spec in all_plc_specs:
245             for site_spec in plc_spec['sites']:
246                 for node_spec in site_spec['nodes']:
247                     ips_node_file.write("%s\n"%node_spec['node_fields']['hostname'])
248         ips_node_file.close()
249         # ditto for qemu boxes
250         ips_qemu_file=open('arg-ips-qemu','w')
251         for plc_spec in all_plc_specs:
252             for site_spec in plc_spec['sites']:
253                 for node_spec in site_spec['nodes']:
254                     ips_qemu_file.write("%s\n"%node_spec['host_box'])
255         ips_qemu_file.close()
256         # build a TestPlc object from the result, passing options
257         for spec in all_plc_specs:
258             spec['disabled'] = False
259         all_plcs = [ (x, TestPlc(x,self.options)) for x in all_plc_specs]
260
261         # pass options to utils as well
262         utils.init_options(self.options)
263
264         overall_result = True
265         testplc_method_dict = __import__("TestPlc").__dict__['TestPlc'].__dict__
266         all_step_infos=[]
267         for step in self.options.steps:
268             if not TestPlc.valid_step(step):
269                 continue
270             force=False
271             # is it a forced step
272             if step.find("force_") == 0:
273                 step=step.replace("force_","")
274                 force=True
275             # try and locate a method in TestPlc
276             if testplc_method_dict.has_key(step):
277                 all_step_infos += [ (step, testplc_method_dict[step] , force)]
278             # otherwise search for the 'run' method in the step_<x> module
279             else:
280                 modulename='step_'+step
281                 try:
282                     # locate all methods named run* in the module
283                     module_dict = __import__(modulename).__dict__
284                     names = [ key for key in module_dict.keys() if key.find("run")==0 ]
285                     if not names:
286                         raise Exception,"No run* method in module %s"%modulename
287                     names.sort()
288                     all_step_infos += [ ("%s.%s"%(step,name),module_dict[name],force) for name in names ]
289                 except :
290                     print '********** step %s NOT FOUND -- ignored'%(step)
291                     traceback.print_exc()
292                     overall_result = False
293             
294         if self.options.dry_run:
295             self.show_env(self.options,"Dry run")
296         
297         # init & open trace file if provided
298         if self.options.trace_file and not self.options.dry_run:
299             time=strftime("%H-%M")
300             date=strftime("%Y-%m-%d")
301             trace_file=self.options.trace_file
302             trace_file=trace_file.replace("@TIME@",time)
303             trace_file=trace_file.replace("@DATE@",date)
304             self.options.trace_file=trace_file
305             # create dir if needed
306             trace_dir=os.path.dirname(trace_file)
307             if trace_dir and not os.path.isdir(trace_dir):
308                 os.makedirs(trace_dir)
309             trace=open(trace_file,"w")
310
311         # do all steps on all plcs
312         TRACE_FORMAT="TRACE: time=%(time)s plc=%(plcname)s step=%(stepname)s status=%(status)s force=%(force)s\n"
313         for (stepname,method,force) in all_step_infos:
314             if stepname.endswith('sfa') and (self.options.personality != 'linux32' or self.options.pldistro != 'onelab' or self.options.fcdistro != 'f8'):
315               utils.header("SFA testing currently not enabled on this dist.")
316               continue          
317             for (spec,obj) in all_plcs:
318                 plcname=spec['name']
319
320                 # run the step
321                 time=strftime("%Y-%m-%d-%H-%M")
322                 if not spec['disabled'] or force or self.options.interactive:
323                     skip_step=False
324                     if self.options.interactive:
325                         prompting=True
326                         while prompting:
327                             msg="Run step %s on %s [r](un)/d(ry_run)/s(kip)/q(uit) ? "%(stepname,plcname)
328                             answer=raw_input(msg).strip().lower() or "r"
329                             answer=answer[0]
330                             if answer in ['s','n']:     # skip/no/next
331                                 print '%s on %s skipped'%(stepname,plcname)
332                                 prompting=False
333                                 skip_step=True
334                             elif answer in ['q','b']:   # quit/bye
335                                 print 'Exiting'
336                                 return
337                             elif answer in ['d']:       # dry_run
338                                 dry_run=self.options.dry_run
339                                 self.options.dry_run=True
340                                 obj.options.dry_run=True
341                                 obj.apiserver.set_dry_run(True)
342                                 step_result=method(obj)
343                                 print 'dry_run step ->',step_result
344                                 self.options.dry_run=dry_run
345                                 obj.options.dry_run=dry_run
346                                 obj.apiserver.set_dry_run(dry_run)
347                             elif answer in ['r','y']:   # run/yes
348                                 prompting=False
349                     if skip_step:
350                         continue
351                     try:
352                         force_msg=""
353                         if force: force_msg=" (forced)"
354                         utils.header("********** RUNNING step %s%s on plc %s"%(stepname,force_msg,plcname))
355                         step_result = method(obj)
356                         if step_result:
357                             utils.header('********** SUCCESSFUL step %s on %s'%(stepname,plcname))
358                             status="OK"
359                         else:
360                             overall_result = False
361                             spec['disabled'] = True
362                             utils.header('********** FAILED Step %s on %s - discarding that plc from further steps'%(stepname,plcname))
363                             status="KO"
364                     except:
365                         overall_result=False
366                         spec['disabled'] = True
367                         traceback.print_exc()
368                         utils.header ('********** FAILED (exception) Step %s on plc %s - discarding this plc from further steps'%(stepname,plcname))
369                         status="KO"
370
371                 # do not run, just display it's skipped
372                 else:
373                     utils.header("********** IGNORED Plc %s is disabled - skipping step %s"%(plcname,stepname))
374                     status="UNDEF"
375                 if not self.options.dry_run:
376                     # alwas do this on stdout
377                     print TRACE_FORMAT%locals()
378                     # duplicate on trace_file if provided
379                     if self.options.trace_file:
380                         trace.write(TRACE_FORMAT%locals())
381
382         if self.options.trace_file and not self.options.dry_run:
383             trace.close()
384
385         return overall_result
386
387     # wrapper to run, returns a shell-compatible result
388     def main(self):
389         try:
390             success=self.run()
391             if success:
392                 return 0
393             else:
394                 return 1 
395         except SystemExit:
396             raise
397         except:
398             traceback.print_exc()
399             return 2
400
401 if __name__ == "__main__":
402     sys.exit(TestMain().main())