Test framework reworked for
[tests.git] / system / TestMain.py
1 #!/usr/bin/env python
2 # $Id$
3
4 import os, sys
5 from optparse import OptionParser
6 import pprint
7 import traceback
8
9 import utils
10 from TestPlc import TestPlc
11 from TestSite import TestSite
12 from TestNode import TestNode
13
14
15 #default_steps = ['uninstall','install','configure', 'populate' , 'check_nodes' ]
16 default_steps = ['uninstall','install','configure', 'sites', 'nodes', 'initscripts', 'slices',  'bootcd', 'start_nodes', 'check-nodes', 'check-slices' ]
17 other_steps = [ 'clean_sites', 'clean_slices' , 'stop_nodes' , 'db_dump' , 'fresh-install']
18
19 class TestMain:
20
21     subversion_id = "$Id$"
22
23     def __init__ (self):
24         self.path=os.path.dirname(sys.argv[0])
25
26     @staticmethod
27     def show_env (options, message):
28         utils.header (message)
29         pprint.PrettyPrinter(indent=4,depth=2).pprint(options)
30
31     @staticmethod
32     def optparse_list (option, opt, value, parser):
33         try:
34             setattr(parser.values,option.dest,getattr(parser.values,option.dest)+[value])
35         except:
36             setattr(parser.values,option.dest,[value])
37
38     def main (self):
39         usage = """usage: %prog [options] steps
40 myplc-url defaults to the last value used, as stored in MYPLC-URL
41 build-url defaults to the last value used, as stored in BUILD-URL
42 steps refer to a method in TestPlc or to a step-* module"""
43         usage += "\n  Defaut steps are %r"%default_steps
44         usage += "\n  Other useful steps are %r"%other_steps
45         parser=OptionParser(usage=usage,version=self.subversion_id)
46         parser.add_option("-u","--url",action="store", dest="myplc_url", 
47                           help="myplc URL - for locating build output")
48         parser.add_option("-b","--build",action="store", dest="build_url", 
49                           help="Build URL - for using myplc-init-vserver.sh in native mode")
50         parser.add_option("-c","--config",action="callback", callback=TestMain.optparse_list, dest="config",
51                           nargs=1,type="string",
52                           help="config module - can be set multiple times")
53         parser.add_option("-a","--all",action="store_true",dest="all_steps", default=False,
54                           help="Runs all default steps")
55         parser.add_option("-d","--display", action="store", dest="display", default='bellami.inria.fr:0.0',
56                           help="set DISPLAY for vmplayer")
57         parser.add_option("-v","--verbose", action="store_true", dest="verbose", default=False, 
58                           help="Run in verbose mode")
59         parser.add_option("-n","--dry-run", action="store_true", dest="dry_run", default=False,
60                           help="Show environment and exits")
61         (self.options, self.args) = parser.parse_args()
62
63         if len(self.args) == 0:
64             if self.options.all_steps:
65                 self.options.steps=default_steps
66             else:
67                 parser.print_help()
68                 sys.exit(1)
69         else:
70             self.options.steps = self.args
71
72         # display display
73         utils.header('X11 display : %s'% self.options.display)
74
75         # handle defaults and option persistence
76         for (recname,filename) in ( ('myplc_url','MYPLC-URL') , ('build_url','BUILD-URL') ) :
77             if not getattr(self.options,recname):
78                 try:
79                     url_file=open("%s/%s"%(self.path,filename))
80                     url=url_file.read().strip()
81                     url_file.close()
82                     setattr(self.options,recname,url)
83                 except:
84                     print "Cannot determine",recname
85                     parser.print_help()
86                     sys.exit(1)
87             utils.header('* Using %s = %s'%(recname,getattr(self.options,recname)))
88
89             fsave=open('%s/%s'%(self.path,filename),"w")
90             fsave.write(getattr(self.options,recname))
91             fsave.write('\n')
92             fsave.close()
93             utils.header('Saved %s into %s'%(recname,filename))
94
95         # config modules
96         if not self.options.config:
97             # legacy default - do not set in optparse
98             self.options.config=['onelab-chroot']
99         # step modules
100         if not self.options.steps:
101             #default (all) steps
102             #self.options.steps=['dump','clean','install','populate']
103             self.options.steps=default_steps
104
105         # store self.path in options.path for the various callbacks
106         self.options.path = self.path
107
108         if self.options.verbose:
109             self.show_env(self.options,"Verbose")
110
111         all_plc_specs = []
112         for config in self.options.config:
113             modulename='config-'+config
114             try:
115                 m = __import__(modulename)
116                 all_plc_specs = m.config(all_plc_specs,self.options)
117             except :
118                 traceback.print_exc()
119                 print 'Cannot load config %s -- ignored'%modulename
120         # show config
121         utils.header ("Test specifications")
122         pprint.PrettyPrinter(indent=4,depth=2).pprint(all_plc_specs)
123         # build a TestPlc object from the result
124         for spec in all_plc_specs:
125             spec['disabled'] = False
126         all_plcs = [ (x, TestPlc(x)) for x in all_plc_specs]
127
128         testplc_method_dict = __import__("TestPlc").__dict__['TestPlc'].__dict__
129         all_step_infos=[]
130         for step in self.options.steps:
131             # try and locate a method in TestPlc
132             if testplc_method_dict.has_key(step):
133                 all_step_infos += [ (step, testplc_method_dict[step] )]
134             # otherwise search for the 'run' method in the step-<x> module
135             else:
136                 modulename='step-'+step
137                 try:
138                     # locate all methods named run* in the module
139                     module_dict = __import__(modulename).__dict__
140                     names = [ key for key in module_dict.keys() if key.find("run")==0 ]
141                     if not names:
142                         raise Exception,"No run* method in module %s"%modulename
143                     names.sort()
144                     all_step_infos += [ ("%s.%s"%(step,name),module_dict[name]) for name in names ]
145                 except :
146                     print 'Step %s -- ignored'%(step)
147                     traceback.print_exc()
148             
149         if self.options.dry_run:
150             self.show_env(self.options,"Dry run")
151             sys.exit(0)
152             
153         # do all steps on all plcs
154         for (name,method) in all_step_infos:
155             for (spec,obj) in all_plcs:
156                 if not spec['disabled']:
157                     try:
158                         utils.header("Running step %s on plc %s"%(name,spec['name']))
159                         if method(obj,self.options):
160                             utils.header('Successful step %s on %s'%(name,spec['name']))
161                         else:
162                             utils.header('Step %s on %s FAILED - discarding'%(name,spec['name']))
163                             spec['disabled'] = True
164                     except:
165                         spec['disabled'] = True
166                         print 'Cannot run step %s on plc %s'%(name,spec['name'])
167                         traceback.print_exc()
168
169 if __name__ == "__main__":
170     TestMain().main()