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