new step 'free_all' to cleanup everything about plc-vservers, qemus and trackers
[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                     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_node, ips_plc and ips_qemu defaults to the last value used, as stored in arg-ips-{node,plc,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_node", default=[],
104                           help="Specify the set of hostname/IP's to use for nodes")
105         parser.add_option("-P","--plcs",action="append", dest="ips_plc", 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_node','ips_plc','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) in (
145             ('build_url','arg-build-url',TestMain.default_build_url) ,
146             ('ips_node','arg-ips-node',[]) , 
147             ('ips_plc','arg-ips-plc',[]) , 
148             ('ips_qemu','arg-ips-qemu',[]) , 
149             ('config','arg-config',TestMain.default_config) , 
150             ('arch_rpms_url','arg-arch-rpms-url',"") , 
151             ('personality','arg-personality',"linux32"),
152             ('pldistro','arg-pldistro',"planetlab"),
153             ('fcdistro','arg-fcdistro','centos5'),
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             if isinstance(getattr(self.options,recname),list):
189                 getattr(self.options,recname).reverse()
190
191             if self.options.verbose:
192                 utils.header('* Using %s = %s'%(recname,getattr(self.options,recname)))
193
194         # hack : if sfa is not among the published rpms, skip these tests
195         TestPlc.check_whether_build_has_sfa(self.options.arch_rpms_url)
196
197         # no step specified
198         if len(self.args) == 0:
199             self.options.steps=TestPlc.default_steps
200         else:
201             self.options.steps = self.args
202
203         if self.options.list_steps:
204             self.init_steps()
205             self.list_steps()
206             return True
207
208         # steps
209         if not self.options.steps:
210             #default (all) steps
211             #self.options.steps=['dump','clean','install','populate']
212             self.options.steps=TestPlc.default_steps
213
214         # rewrite '-' into '_' in step names
215         self.options.steps = [ step.replace('-','_') for step in self.options.steps ]
216
217         # exclude
218         selected=[]
219         for step in self.options.steps:
220             keep=True
221             for exclude in self.options.exclude:
222                 if utils.match(step,exclude):
223                     keep=False
224                     break
225             if keep: selected.append(step)
226         self.options.steps=selected
227
228         # this is useful when propagating on host boxes, to avoid conflicts
229         self.options.buildname = os.path.basename (os.path.abspath (self.path))
230
231         if self.options.verbose:
232             self.show_env(self.options,"Verbose")
233
234         # load configs
235         all_plc_specs = []
236         for config in self.options.config:
237             modulename='config_'+config
238             try:
239                 m = __import__(modulename)
240                 all_plc_specs = m.config(all_plc_specs,self.options)
241             except :
242                 traceback.print_exc()
243                 print 'Cannot load config %s -- ignored'%modulename
244                 raise
245
246         # run localize as defined by local_resources
247         all_plc_specs = LocalTestResources.local_resources.localize(all_plc_specs,self.options)
248
249         # remember plc IP address(es) if not specified
250         ips_plc_file=open('arg-ips-plc','w')
251         for plc_spec in all_plc_specs:
252             ips_plc_file.write("%s\n"%plc_spec['PLC_API_HOST'])
253         ips_plc_file.close()
254         # ditto for nodes
255         ips_node_file=open('arg-ips-node','w')
256         for plc_spec in all_plc_specs:
257             for site_spec in plc_spec['sites']:
258                 for node_spec in site_spec['nodes']:
259                     ips_node_file.write("%s\n"%node_spec['node_fields']['hostname'])
260         ips_node_file.close()
261         # ditto for qemu boxes
262         ips_qemu_file=open('arg-ips-qemu','w')
263         for plc_spec in all_plc_specs:
264             for site_spec in plc_spec['sites']:
265                 for node_spec in site_spec['nodes']:
266                     ips_qemu_file.write("%s\n"%node_spec['host_box'])
267         ips_qemu_file.close()
268         # build a TestPlc object from the result, passing options
269         for spec in all_plc_specs:
270             spec['failed_step'] = False
271         all_plcs = [ (x, TestPlc(x,self.options)) for x in all_plc_specs]
272
273         # pass options to utils as well
274         utils.init_options(self.options)
275
276         overall_result = True
277         testplc_method_dict = __import__("TestPlc").__dict__['TestPlc'].__dict__
278         all_step_infos=[]
279         for step in self.options.steps:
280             if not TestPlc.valid_step(step):
281                 continue
282             # some steps need to be done regardless of the previous ones: we force them
283             force=False
284             if step.find("force_") == 0:
285                 step=step.replace("force_","")
286                 force=True
287             # a cross step will run a method on TestPlc that has a signature like
288             # def cross_foo (self, all_test_plcs)
289             cross=False
290             if step.find("cross_") == 0:
291                 cross=True
292             # allow for steps to specify an index like in 
293             # run checkslice@2
294             try:        (step,qualifier)=step.split('@')
295             except:     qualifier=self.options.qualifier
296
297             # try and locate a method in TestPlc
298             if testplc_method_dict.has_key(step):
299                 all_step_infos += [ (step, testplc_method_dict[step] , force, cross, qualifier)]
300             # otherwise search for the 'run' method in the step_<x> module
301             else:
302                 modulename='step_'+step
303                 try:
304                     # locate all methods named run* in the module
305                     module_dict = __import__(modulename).__dict__
306                     names = [ key for key in module_dict.keys() if key.find("run")==0 ]
307                     if not names:
308                         raise Exception,"No run* method in module %s"%modulename
309                     names.sort()
310                     all_step_infos += [ ("%s.%s"%(step,name),module_dict[name],force,cross,qualifier) for name in names ]
311                 except :
312                     utils.header("********** FAILED step %s (NOT FOUND) -- won't be run"%step)
313                     traceback.print_exc()
314                     overall_result = False
315             
316         if self.options.dry_run:
317             self.show_env(self.options,"Dry run")
318         
319         # init & open trace file if provided
320         if self.options.trace_file and not self.options.dry_run:
321             time=strftime("%H-%M")
322             date=strftime("%Y-%m-%d")
323             trace_file=self.options.trace_file
324             trace_file=trace_file.replace("@TIME@",time)
325             trace_file=trace_file.replace("@DATE@",date)
326             self.options.trace_file=trace_file
327             # create dir if needed
328             trace_dir=os.path.dirname(trace_file)
329             if trace_dir and not os.path.isdir(trace_dir):
330                 os.makedirs(trace_dir)
331             trace=open(trace_file,"w")
332
333         # do all steps on all plcs
334         TIME_FORMAT="%H-%M-%S"
335         TRACE_FORMAT="TRACE: %(plc_counter)d %(beg)s->%(end)s status=%(status)s step=%(stepname)s plc=%(plcname)s force=%(force)s\n"
336         for (stepname,method,force,cross,qualifier) in all_step_infos:
337             plc_counter=0
338             for (spec,plc_obj) in all_plcs:
339                 plc_counter+=1
340                 # skip this step if we have specified a plc_explicit
341                 if qualifier and plc_counter!=int(qualifier): continue
342
343                 plcname=spec['name']
344                 across_plcs = [ o for (s,o) in all_plcs if o!=plc_obj ]
345
346                 # run the step
347                 beg=strftime(TIME_FORMAT)
348                 if not spec['failed_step'] or force or self.options.interactive or self.options.keep_going:
349                     skip_step=False
350                     if self.options.interactive:
351                         prompting=True
352                         while prompting:
353                             msg="%d Run step %s on %s [r](un)/d(ry_run)/s(kip)/q(uit) ? "%(plc_counter,stepname,plcname)
354                             answer=raw_input(msg).strip().lower() or "r"
355                             answer=answer[0]
356                             if answer in ['s','n']:     # skip/no/next
357                                 print '%s on %s skipped'%(stepname,plcname)
358                                 prompting=False
359                                 skip_step=True
360                             elif answer in ['q','b']:   # quit/bye
361                                 print 'Exiting'
362                                 return
363                             elif answer in ['d']:       # dry_run
364                                 dry_run=self.options.dry_run
365                                 self.options.dry_run=True
366                                 plc_obj.options.dry_run=True
367                                 plc_obj.apiserver.set_dry_run(True)
368                                 if not cross:   step_result=method(plc_obj)
369                                 else:           step_result=method(plc_obj,across_plcs)
370                                 print 'dry_run step ->',step_result
371                                 self.options.dry_run=dry_run
372                                 plc_obj.options.dry_run=dry_run
373                                 plc_obj.apiserver.set_dry_run(dry_run)
374                             elif answer in ['r','y']:   # run/yes
375                                 prompting=False
376                     if skip_step:
377                         continue
378                     try:
379                         force_msg=""
380                         if force and spec['failed_step']: force_msg=" (forced after %s has failed)"%spec['failed_step']
381                         utils.header("********** %d RUNNING step %s%s on plc %s"%(plc_counter,stepname,force_msg,plcname))
382                         if not cross:   step_result = method(plc_obj)
383                         else:           step_result = method(plc_obj,across_plcs)
384                         if step_result:
385                             utils.header('********** %d SUCCESSFUL step %s on %s'%(plc_counter,stepname,plcname))
386                             status="OK"
387                         else:
388                             overall_result = False
389                             spec['failed_step'] = stepname
390                             utils.header('********** %d FAILED Step %s on %s (discarded from further steps)'\
391                                              %(plc_counter,stepname,plcname))
392                             status="KO"
393                     except:
394                         overall_result=False
395                         spec['failed_step'] = stepname
396                         traceback.print_exc()
397                         utils.header ('********** %d FAILED (exception) Step %s on %s (discarded from further steps)'\
398                                           %(plc_counter,stepname,plcname))
399                         status="KO"
400
401                 # do not run, just display it's skipped
402                 else:
403                     why="has failed %s"%spec['failed_step']
404                     utils.header("********** %d SKIPPED Step %s on %s (%s)"%(plc_counter,stepname,plcname,why))
405                     status="UNDEF"
406                 if not self.options.dry_run:
407                     end=strftime(TIME_FORMAT)
408                     # always do this on stdout
409                     print TRACE_FORMAT%locals()
410                     # duplicate on trace_file if provided
411                     if self.options.trace_file:
412                         trace.write(TRACE_FORMAT%locals())
413                         trace.flush()
414
415         if self.options.trace_file and not self.options.dry_run:
416             trace.close()
417
418         return overall_result
419
420     # wrapper to run, returns a shell-compatible result
421     def main(self):
422         try:
423             success=self.run()
424             if success:
425                 return 0
426             else:
427                 return 1 
428         except SystemExit:
429             print 'Caught SystemExit'
430             raise
431         except:
432             traceback.print_exc()
433             return 2
434
435 if __name__ == "__main__":
436     sys.exit(TestMain().main())