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