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