checkpoint
[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 LocalSubstrate.py
18 sys.path.append(os.environ['HOME'])
19 import LocalSubstrate
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                     try:        (step,qualifier)=step.split('@')
54                     except:     pass
55                     stepname=step
56                     for special in ['force']:
57                         stepname = stepname.replace(special+'_',"")
58                     print '*',step,"\r",4*"\t",
59                     try:
60                         doc=testplc_method_dict[stepname].__doc__
61                     except:
62                         try:
63                             # locate the step_<name> module
64                             modulename='step_'+stepname
65                             doc = __import__(modulename).__doc__
66                         except:
67                             doc=None
68                     if doc: print doc
69                     else:   print "*** no doc found"
70
71     def run (self):
72         self.init_steps()
73         usage = """usage: %%prog [options] steps
74 arch-rpms-url defaults to the last value used, as stored in arg-arch-rpms-url,
75    no default
76 config defaults to the last value used, as stored in arg-config,
77    or %r
78 ips_vnode, ips_vplc and ips_qemu defaults to the last value used, as stored in arg-ips-{node,vplc,qemu},
79    default is to use IP scanning
80 steps refer to a method in TestPlc or to a step_* module
81 ===
82 """%(TestMain.default_config)
83         usage += self.steps_message
84         parser=OptionParser(usage=usage,version=self.subversion_id)
85         parser.add_option("-u","--url",action="store", dest="arch_rpms_url", 
86                           help="URL of the arch-dependent RPMS area - for locating what to test")
87         parser.add_option("-b","--build",action="store", dest="build_url", 
88                           help="ignored, for legacy only")
89         parser.add_option("-c","--config",action="append", dest="config", default=[],
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="append", dest="exclude", default=[],
98                           help="steps to exclude - can be set multiple times, or use quotes")
99         parser.add_option("-a","--all",action="store_true",dest="all_steps", default=False,
100                           help="Run all default steps")
101         parser.add_option("-l","--list",action="store_true",dest="list_steps", default=False,
102                           help="List known steps")
103         parser.add_option("-N","--nodes",action="append", dest="ips_vnode", default=[],
104                           help="Specify the set of hostname/IP's to use for nodes")
105         parser.add_option("-P","--plcs",action="append", dest="ips_vplc", default=[],
106                           help="Specify the set of hostname/IP's to use for plcs")
107         parser.add_option("-Q","--qemus",action="append", dest="ips_qemu", default=[],
108                           help="Specify the set of hostname/IP's to use for qemu boxes")
109         parser.add_option("-s","--size",action="store",type="int",dest="size",default=1,
110                           help="sets test size in # of plcs - default is 1")
111         parser.add_option("-q","--qualifier",action="store",type="int",dest="qualifier",default=None,
112                           help="run steps only on plc numbered <qualifier>, starting at 1")
113         parser.add_option("-k","--keep-going",action="store",dest="keep_going",default=False,
114                           help="proceeds even if some steps are failing")
115         parser.add_option("-D","--dbname",action="store",dest="dbname",default=None,
116                            help="Used by plc_db_dump and plc_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("-i","--interactive",action="store_true",dest="interactive",default=False,
120                           help="prompts before each step")
121         parser.add_option("-n","--dry-run", action="store_true", dest="dry_run", default=False,
122                           help="Show environment and exits")
123         parser.add_option("-r","--restart-nm", action="store_true", dest="forcenm", default=False, 
124                           help="Force the NM to restart in ssh_slices step")
125         parser.add_option("-t","--trace", action="store", dest="trace_file", default=None,
126                           #default="logs/trace-@TIME@.txt",
127                           help="Trace file location")
128         (self.options, self.args) = parser.parse_args()
129
130         # allow things like "run -c 'c1 c2' -c c3"
131         def flatten (x):
132             result = []
133             for el in x:
134                 if hasattr(el, "__iter__") and not isinstance(el, basestring):
135                     result.extend(flatten(el))
136                 else:
137                     result.append(el)
138             return result
139         # flatten relevant options
140         for optname in ['config','exclude','ips_vnode','ips_vplc','ips_qemu']:
141             setattr(self.options,optname, flatten ( [ arg.split() for arg in getattr(self.options,optname) ] ))
142
143         # handle defaults and option persistence
144         for (recname,filename,default,need_reverse) in (
145             ('build_url','arg-build-url',TestMain.default_build_url,None) ,
146             ('ips_vnode','arg-ips-vnode',[],True) , 
147             ('ips_vplc','arg-ips-vplc',[],True) , 
148             ('ips_qemu','arg-ips-qemu',[],True) , 
149             ('config','arg-config',TestMain.default_config,False) , 
150             ('arch_rpms_url','arg-arch-rpms-url',"",None) , 
151             ('personality','arg-personality',"linux64",None),
152             ('pldistro','arg-pldistro',"onelab",None),
153             ('fcdistro','arg-fcdistro','f14',None),
154             ) :
155 #            print 'handling',recname
156             path=filename
157             is_list = isinstance(default,list)
158             if not getattr(self.options,recname):
159                 try:
160                     parsed=file(path).readlines()
161                     if not is_list:    # strings
162                         if len(parsed) != 1:
163                             print "%s - error when parsing %s"%(sys.argv[1],path)
164                             sys.exit(1)
165                         parsed=parsed[0].strip()
166                     else:              # lists
167                         parsed=[x.strip() for x in parsed]
168                     setattr(self.options,recname,parsed)
169                 except:
170                     if default != "":
171                         setattr(self.options,recname,default)
172                     else:
173                         print "Cannot determine",recname
174                         print "Run %s --help for help"%sys.argv[0]                        
175                         sys.exit(1)
176
177             # save for next run
178             fsave=open(path,"w")
179             if not is_list:
180                 fsave.write(getattr(self.options,recname) + "\n")
181             else:
182                 for value in getattr(self.options,recname):
183                     fsave.write(value + "\n")
184             fsave.close()
185 #            utils.header('Saved %s into %s'%(recname,filename))
186
187             # lists need be reversed
188             # I suspect this is useful for the various pools but for config, it's painful
189             if isinstance(getattr(self.options,recname),list) and need_reverse:
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         # hack : if sfa is not among the published rpms, skip these tests
196         TestPlc.check_whether_build_has_sfa(self.options.arch_rpms_url)
197
198         # no step specified
199         if len(self.args) == 0:
200             self.options.steps=TestPlc.default_steps
201         else:
202             self.options.steps = self.args
203
204         if self.options.list_steps:
205             self.init_steps()
206             self.list_steps()
207             return True
208
209         # steps
210         if not self.options.steps:
211             #default (all) steps
212             #self.options.steps=['dump','clean','install','populate']
213             self.options.steps=TestPlc.default_steps
214
215         # rewrite '-' into '_' in step names
216         self.options.steps = [ step.replace('-','_') for step in self.options.steps ]
217
218         # exclude
219         selected=[]
220         for step in self.options.steps:
221             keep=True
222             for exclude in self.options.exclude:
223                 if utils.match(step,exclude):
224                     keep=False
225                     break
226             if keep: selected.append(step)
227         self.options.steps=selected
228
229         # this is useful when propagating on host boxes, to avoid conflicts
230         self.options.buildname = os.path.basename (os.path.abspath (self.path))
231
232         if self.options.verbose:
233             self.show_env(self.options,"Verbose")
234
235         # load configs
236         all_plc_specs = []
237         for config in self.options.config:
238             modulename='config_'+config
239             try:
240                 m = __import__(modulename)
241                 all_plc_specs = m.config(all_plc_specs,self.options)
242             except :
243                 traceback.print_exc()
244                 print 'Cannot load config %s -- ignored'%modulename
245                 raise
246
247         # provision on local substrate
248         all_plc_specs = LocalSubstrate.local_substrate.provision(all_plc_specs,self.options)
249
250         # remember plc IP address(es) if not specified
251         ips_vplc_file=open('arg-ips-vplc','w')
252         for plc_spec in all_plc_specs:
253             ips_vplc_file.write("%s\n"%plc_spec['PLC_API_HOST'])
254         ips_vplc_file.close()
255         # ditto for nodes
256         ips_vnode_file=open('arg-ips-vnode','w')
257         for plc_spec in all_plc_specs:
258             for site_spec in plc_spec['sites']:
259                 for node_spec in site_spec['nodes']:
260                     stripped=node_spec['node_fields']['hostname'].split('.')[0]
261                     ips_vnode_file.write("%s\n"%stripped)
262         ips_vnode_file.close()
263         # ditto for qemu boxes
264         ips_qemu_file=open('arg-ips-qemu','w')
265         for plc_spec in all_plc_specs:
266             for site_spec in plc_spec['sites']:
267                 for node_spec in site_spec['nodes']:
268                     ips_qemu_file.write("%s\n"%node_spec['host_box'])
269         ips_qemu_file.close()
270         # build a TestPlc object from the result, passing options
271         for spec in all_plc_specs:
272             spec['failed_step'] = False
273         all_plcs = [ (x, TestPlc(x,self.options)) for x in all_plc_specs]
274
275         # pass options to utils as well
276         utils.init_options(self.options)
277
278         overall_result = True
279         testplc_method_dict = __import__("TestPlc").__dict__['TestPlc'].__dict__
280         all_step_infos=[]
281         for step in self.options.steps:
282             if not TestPlc.valid_step(step):
283                 continue
284             # some steps need to be done regardless of the previous ones: we force them
285             force=False
286             if step.find("force_") == 0:
287                 step=step.replace("force_","")
288                 force=True
289             # a cross step will run a method on TestPlc that has a signature like
290             # def cross_foo (self, all_test_plcs)
291             cross=False
292             if step.find("cross_") == 0:
293                 cross=True
294             # allow for steps to specify an index like in 
295             # run checkslice@2
296             try:        (step,qualifier)=step.split('@')
297             except:     qualifier=self.options.qualifier
298
299             # try and locate a method in TestPlc
300             if testplc_method_dict.has_key(step):
301                 all_step_infos += [ (step, testplc_method_dict[step] , force, cross, qualifier)]
302             # otherwise search for the 'run' method in the step_<x> module
303             else:
304                 modulename='step_'+step
305                 try:
306                     # locate all methods named run* in the module
307                     module_dict = __import__(modulename).__dict__
308                     names = [ key for key in module_dict.keys() if key.find("run")==0 ]
309                     if not names:
310                         raise Exception,"No run* method in module %s"%modulename
311                     names.sort()
312                     all_step_infos += [ ("%s.%s"%(step,name),module_dict[name],force,cross,qualifier) for name in names ]
313                 except :
314                     utils.header("********** FAILED step %s (NOT FOUND) -- won't be run"%step)
315                     traceback.print_exc()
316                     overall_result = False
317             
318         if self.options.dry_run:
319             self.show_env(self.options,"Dry run")
320         
321         # init & open trace file if provided
322         if self.options.trace_file and not self.options.dry_run:
323             time=strftime("%H-%M")
324             date=strftime("%Y-%m-%d")
325             trace_file=self.options.trace_file
326             trace_file=trace_file.replace("@TIME@",time)
327             trace_file=trace_file.replace("@DATE@",date)
328             self.options.trace_file=trace_file
329             # create dir if needed
330             trace_dir=os.path.dirname(trace_file)
331             if trace_dir and not os.path.isdir(trace_dir):
332                 os.makedirs(trace_dir)
333             trace=open(trace_file,"w")
334
335         # do all steps on all plcs
336         TIME_FORMAT="%H-%M-%S"
337         TRACE_FORMAT="TRACE: %(plc_counter)d %(beg)s->%(end)s status=%(status)s step=%(stepname)s plc=%(plcname)s force=%(force)s\n"
338         for (stepname,method,force,cross,qualifier) in all_step_infos:
339             plc_counter=0
340             for (spec,plc_obj) in all_plcs:
341                 plc_counter+=1
342                 # skip this step if we have specified a plc_explicit
343                 if qualifier and plc_counter!=int(qualifier): continue
344
345                 plcname=spec['name']
346                 across_plcs = [ o for (s,o) in all_plcs if o!=plc_obj ]
347
348                 # run the step
349                 beg=strftime(TIME_FORMAT)
350                 if not spec['failed_step'] or force or self.options.interactive or self.options.keep_going:
351                     skip_step=False
352                     if self.options.interactive:
353                         prompting=True
354                         while prompting:
355                             msg="%d Run step %s on %s [r](un)/d(ry_run)/s(kip)/q(uit) ? "%(plc_counter,stepname,plcname)
356                             answer=raw_input(msg).strip().lower() or "r"
357                             answer=answer[0]
358                             if answer in ['s','n']:     # skip/no/next
359                                 print '%s on %s skipped'%(stepname,plcname)
360                                 prompting=False
361                                 skip_step=True
362                             elif answer in ['q','b']:   # quit/bye
363                                 print 'Exiting'
364                                 return
365                             elif answer in ['d']:       # dry_run
366                                 dry_run=self.options.dry_run
367                                 self.options.dry_run=True
368                                 plc_obj.options.dry_run=True
369                                 plc_obj.apiserver.set_dry_run(True)
370                                 if not cross:   step_result=method(plc_obj)
371                                 else:           step_result=method(plc_obj,across_plcs)
372                                 print 'dry_run step ->',step_result
373                                 self.options.dry_run=dry_run
374                                 plc_obj.options.dry_run=dry_run
375                                 plc_obj.apiserver.set_dry_run(dry_run)
376                             elif answer in ['r','y']:   # run/yes
377                                 prompting=False
378                     if skip_step:
379                         continue
380                     try:
381                         force_msg=""
382                         if force and spec['failed_step']: force_msg=" (forced after %s has failed)"%spec['failed_step']
383                         utils.header("********** %d RUNNING step %s%s on plc %s"%(plc_counter,stepname,force_msg,plcname))
384                         if not cross:   step_result = method(plc_obj)
385                         else:           step_result = method(plc_obj,across_plcs)
386                         if step_result:
387                             utils.header('********** %d SUCCESSFUL step %s on %s'%(plc_counter,stepname,plcname))
388                             status="OK"
389                         else:
390                             overall_result = False
391                             spec['failed_step'] = stepname
392                             utils.header('********** %d FAILED Step %s on %s (discarded from further steps)'\
393                                              %(plc_counter,stepname,plcname))
394                             status="KO"
395                     except:
396                         overall_result=False
397                         spec['failed_step'] = stepname
398                         traceback.print_exc()
399                         utils.header ('********** %d FAILED (exception) Step %s on %s (discarded from further steps)'\
400                                           %(plc_counter,stepname,plcname))
401                         status="KO"
402
403                 # do not run, just display it's skipped
404                 else:
405                     why="has failed %s"%spec['failed_step']
406                     utils.header("********** %d SKIPPED Step %s on %s (%s)"%(plc_counter,stepname,plcname,why))
407                     status="UNDEF"
408                 if not self.options.dry_run:
409                     end=strftime(TIME_FORMAT)
410                     # always do this on stdout
411                     print TRACE_FORMAT%locals()
412                     # duplicate on trace_file if provided
413                     if self.options.trace_file:
414                         trace.write(TRACE_FORMAT%locals())
415                         trace.flush()
416
417         if self.options.trace_file and not self.options.dry_run:
418             trace.close()
419
420         # free local substrate
421         LocalSubstrate.local_substrate.release(self.options)
422         
423         return overall_result
424
425     # wrapper to run, returns a shell-compatible result
426     def main(self):
427         try:
428             success=self.run()
429             if success:
430                 return 0
431             else:
432                 return 1 
433         except SystemExit:
434             print 'Caught SystemExit'
435             raise
436         except:
437             traceback.print_exc()
438             return 2
439
440 if __name__ == "__main__":
441     sys.exit(TestMain().main())