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