reviewed list options parsing
[tests.git] / system / TestMain.py
1 #!/usr/bin/python -u
2
3 # Thierry Parmentelat <thierry.parmentelat@inria.fr>
4 # Copyright (C) 2010 INRIA 
5 #
6 import sys, os, os.path
7 from optparse import OptionParser
8 import traceback
9 from time import strftime
10 import readline
11
12 import utils
13 from TestPlc import TestPlc
14 from TestSite import TestSite
15 from TestNode import TestNode
16
17 # add $HOME in PYTHONPATH so we can import LocalTestResources.py
18 sys.path.append(os.environ['HOME'])
19 import LocalTestResources
20
21 class TestMain:
22
23     subversion_id = "Now using git -- version tracker broken"
24
25     default_config = [ 'default' ] 
26
27     default_build_url = "git://git.onelab.eu/tests"
28
29     def __init__ (self):
30         self.path=os.path.dirname(sys.argv[0]) or "."
31         os.chdir(self.path)
32
33     def show_env (self,options, message):
34         if self.options.verbose:
35             utils.header (message)
36             utils.show_options("main options",options)
37
38     def init_steps(self):
39         self.steps_message  = 20*'x'+" Defaut steps are\n"+TestPlc.printable_steps(TestPlc.default_steps)
40         self.steps_message += 20*'x'+" Other useful steps are\n"+TestPlc.printable_steps(TestPlc.other_steps)
41
42     def list_steps(self):
43         if not self.options.verbose:
44             print self.steps_message,
45         else:
46             testplc_method_dict = __import__("TestPlc").__dict__['TestPlc'].__dict__
47             scopes = [("Default steps",TestPlc.default_steps)]
48             if self.options.all_steps:
49                 scopes.append ( ("Other steps",TestPlc.other_steps) )
50             for (scope,steps) in scopes:
51                 print '--------------------',scope
52                 for step in [step for step in steps if TestPlc.valid_step(step)]:
53                     stepname=step
54                     if step.find("force_") == 0:
55                         stepname=step.replace("force_","")
56                         force=True
57                     print '*',step,"\r",4*"\t",
58                     try:
59                         print testplc_method_dict[stepname].__doc__
60                     except:
61                         print "*** no doc found"
62
63     def run (self):
64         self.init_steps()
65         usage = """usage: %%prog [options] steps
66 arch-rpms-url defaults to the last value used, as stored in arg-arch-rpms-url,
67    no default
68 config defaults to the last value used, as stored in arg-config,
69    or %r
70 ips_node, ips_plc and ips_qemu defaults to the last value used, as stored in arg-ips-{node,plc,qemu},
71    default is to use IP scanning
72 steps refer to a method in TestPlc or to a step_* module
73 ===
74 """%(TestMain.default_config)
75         usage += self.steps_message
76         parser=OptionParser(usage=usage,version=self.subversion_id)
77         parser.add_option("-u","--url",action="store", dest="arch_rpms_url", 
78                           help="URL of the arch-dependent RPMS area - for locating what to test")
79         parser.add_option("-b","--build",action="store", dest="build_url", 
80                           help="ignored, for legacy only")
81         parser.add_option("-c","--config",action="append", dest="config", default=[],
82                           help="Config module - can be set multiple times, or use quotes")
83         parser.add_option("-p","--personality",action="store", dest="personality", 
84                           help="personality - as in vbuild-nightly")
85         parser.add_option("-d","--pldistro",action="store", dest="pldistro", 
86                           help="pldistro - as in vbuild-nightly")
87         parser.add_option("-f","--fcdistro",action="store", dest="fcdistro", 
88                           help="fcdistro - as in vbuild-nightly")
89         parser.add_option("-x","--exclude",action="append", dest="exclude", default=[],
90                           help="steps to exclude - can be set multiple times, or use quotes")
91         parser.add_option("-a","--all",action="store_true",dest="all_steps", default=False,
92                           help="Run all default steps")
93         parser.add_option("-l","--list",action="store_true",dest="list_steps", default=False,
94                           help="List known steps")
95         parser.add_option("-N","--nodes",action="append", dest="ips_node", default=[],
96                           help="Specify the set of hostname/IP's to use for nodes")
97         parser.add_option("-P","--plcs",action="append", dest="ips_plc", default=[],
98                           help="Specify the set of hostname/IP's to use for plcs")
99         parser.add_option("-Q","--qemus",action="append", dest="ips_qemu", default=[],
100                           help="Specify the set of hostname/IP's to use for qemu boxes")
101         parser.add_option("-s","--size",action="store",type="int",dest="size",default=1,
102                           help="sets test size in # of plcs - default is 1")
103         parser.add_option("-D","--dbname",action="store",dest="dbname",default=None,
104                            help="Used by db_dump and db_restore")
105         parser.add_option("-v","--verbose", action="store_true", dest="verbose", default=False, 
106                           help="Run in verbose mode")
107         parser.add_option("-i","--interactive",action="store_true",dest="interactive",default=False,
108                           help="prompts before each step")
109         parser.add_option("-n","--dry-run", action="store_true", dest="dry_run", default=False,
110                           help="Show environment and exits")
111         parser.add_option("-r","--restart-nm", action="store_true", dest="forcenm", default=False, 
112                           help="Force the NM to restart in check_slices step")
113         parser.add_option("-t","--trace", action="store", dest="trace_file", default=None,
114                           #default="logs/trace-@TIME@.txt",
115                           help="Trace file location")
116         (self.options, self.args) = parser.parse_args()
117
118         # allow things like "run -c 'c1 c2' -c c3"
119         def flatten (x):
120             result = []
121             for el in x:
122                 if hasattr(el, "__iter__") and not isinstance(el, basestring):
123                     result.extend(flatten(el))
124                 else:
125                     result.append(el)
126             return result
127         # flatten relevant options
128         for optname in ['config','exclude','ips_node','ips_plc','ips_qemu']:
129             setattr(self.options,optname, flatten ( [ arg.split() for arg in getattr(self.options,optname) ] ))
130
131         # handle defaults and option persistence
132         for (recname,filename,default) in (
133             ('build_url','arg-build-url',TestMain.default_build_url) ,
134             ('ips_node','arg-ips-node',[]) , 
135             ('ips_plc','arg-ips-plc',[]) , 
136             ('ips_qemu','arg-ips-qemu',[]) , 
137             ('config','arg-config',TestMain.default_config) , 
138             ('arch_rpms_url','arg-arch-rpms-url',"") , 
139             ('personality','arg-personality',"linux32"),
140             ('pldistro','arg-pldistro',"planetlab"),
141             ('fcdistro','arg-fcdistro','centos5'),
142             ) :
143 #            print 'handling',recname
144             path=filename
145             is_list = isinstance(default,list)
146             if not getattr(self.options,recname):
147                 try:
148                     parsed=file(path).readlines()
149                     if not is_list:    # strings
150                         if len(parsed) != 1:
151                             print "%s - error when parsing %s"%(sys.argv[1],path)
152                             sys.exit(1)
153                         parsed=parsed[0].strip()
154                     else:              # lists
155                         parsed=[x.strip() for x in parsed]
156                     setattr(self.options,recname,parsed)
157                 except:
158                     if default != "":
159                         setattr(self.options,recname,default)
160                     else:
161                         print "Cannot determine",recname
162                         print "Run %s --help for help"%sys.argv[0]                        
163                         sys.exit(1)
164
165             # save for next run
166             fsave=open(path,"w")
167             if not is_list:
168                 fsave.write(getattr(self.options,recname) + "\n")
169             else:
170                 for value in getattr(self.options,recname):
171                     fsave.write(value + "\n")
172             fsave.close()
173 #            utils.header('Saved %s into %s'%(recname,filename))
174
175             # lists need be reversed
176             if isinstance(getattr(self.options,recname),list):
177                 getattr(self.options,recname).reverse()
178
179             if self.options.verbose:
180                 utils.header('* Using %s = %s'%(recname,getattr(self.options,recname)))
181
182         # hack : if sfa is not among the published rpms, skip these tests
183         TestPlc.check_whether_build_has_sfa(self.options.arch_rpms_url)
184
185         # no step specified
186         if len(self.args) == 0:
187             self.options.steps=TestPlc.default_steps
188         else:
189             self.options.steps = self.args
190
191         if self.options.list_steps:
192             self.init_steps()
193             self.list_steps()
194             sys.exit(1)
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         TIME_FORMAT="%H-%M-%S"
313         TRACE_FORMAT="TRACE: beg=%(beg)s end=%(end)s status=%(status)s step=%(stepname)s plc=%(plcname)s force=%(force)s\n"
314         for (stepname,method,force) in all_step_infos:
315             for (spec,obj) in all_plcs:
316                 plcname=spec['name']
317
318                 # run the step
319                 beg=strftime(TIME_FORMAT)
320                 if not spec['disabled'] or force or self.options.interactive:
321                     skip_step=False
322                     if self.options.interactive:
323                         prompting=True
324                         while prompting:
325                             msg="Run step %s on %s [r](un)/d(ry_run)/s(kip)/q(uit) ? "%(stepname,plcname)
326                             answer=raw_input(msg).strip().lower() or "r"
327                             answer=answer[0]
328                             if answer in ['s','n']:     # skip/no/next
329                                 print '%s on %s skipped'%(stepname,plcname)
330                                 prompting=False
331                                 skip_step=True
332                             elif answer in ['q','b']:   # quit/bye
333                                 print 'Exiting'
334                                 return
335                             elif answer in ['d']:       # dry_run
336                                 dry_run=self.options.dry_run
337                                 self.options.dry_run=True
338                                 obj.options.dry_run=True
339                                 obj.apiserver.set_dry_run(True)
340                                 step_result=method(obj)
341                                 print 'dry_run step ->',step_result
342                                 self.options.dry_run=dry_run
343                                 obj.options.dry_run=dry_run
344                                 obj.apiserver.set_dry_run(dry_run)
345                             elif answer in ['r','y']:   # run/yes
346                                 prompting=False
347                     if skip_step:
348                         continue
349                     try:
350                         force_msg=""
351                         if force: force_msg=" (forced)"
352                         utils.header("********** RUNNING step %s%s on plc %s"%(stepname,force_msg,plcname))
353                         step_result = method(obj)
354                         if step_result:
355                             utils.header('********** SUCCESSFUL step %s on %s'%(stepname,plcname))
356                             status="OK"
357                         else:
358                             overall_result = False
359                             spec['disabled'] = True
360                             utils.header('********** FAILED Step %s on %s - discarding that plc from further steps'%(stepname,plcname))
361                             status="KO"
362                     except:
363                         overall_result=False
364                         spec['disabled'] = True
365                         traceback.print_exc()
366                         utils.header ('********** FAILED (exception) Step %s on plc %s - discarding this plc from further steps'%(stepname,plcname))
367                         status="KO"
368
369                 # do not run, just display it's skipped
370                 else:
371                     utils.header("********** IGNORED Plc %s is disabled - skipping step %s"%(plcname,stepname))
372                     status="UNDEF"
373                 if not self.options.dry_run:
374                     end=strftime(TIME_FORMAT)
375                     # always do this on stdout
376                     print TRACE_FORMAT%locals()
377                     # duplicate on trace_file if provided
378                     if self.options.trace_file:
379                         trace.write(TRACE_FORMAT%locals())
380                         trace.flush()
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             print 'Caught SystemExit'
397             raise
398         except:
399             traceback.print_exc()
400             return 2
401
402 if __name__ == "__main__":
403     sys.exit(TestMain().main())