allow to set IP addresses - useful when running steps manually
[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 class TestMain:
14
15     subversion_id = "$Id$"
16
17     default_config = [ 'onelab' ]
18
19     default_steps = ['uninstall','install','configure', 'start', 'store_keys', 'initscripts', 
20                      'sites', 'nodes', 'slices', 'bootcd',  
21                      'nodegroups', 'start_nodes', 'check_nodes', 'check_slices' ]
22     other_steps = [ 'fresh_install', 'stop', 'install_vserver_create', 'install_vserver_native',
23                     'clean_sites', 'clean_nodes', 'clean_slices', 'clean_keys',
24                     'stop_nodes' ,  'db_dump' , 'db_restore',
25                     ]
26     default_build_url = "http://svn.planet-lab.org/svn/build/trunk"
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.split())
40         except:
41             setattr(parser.values,option.dest,value.split())
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    no default
47 build-url defaults to the last value used, as stored in BUILD-URL, 
48    or %s
49 config defaults to the last value used, as stored in CONFIG,
50    or %r
51 ips defaults to the last value used, as stored in IPS,
52    default is to use IP scanning
53 steps refer to a method in TestPlc or to a step_* module"""%(TestMain.default_build_url,TestMain.default_config)
54         usage += "\n  Defaut steps are %r"%TestMain.default_steps
55         usage += "\n  Other useful steps are %r"%TestMain.other_steps
56         parser=OptionParser(usage=usage,version=self.subversion_id)
57         parser.add_option("-u","--url",action="store", dest="myplc_url", 
58                           help="myplc URL - for locating build output")
59         parser.add_option("-b","--build",action="store", dest="build_url", 
60                           help="Build URL - for using vtest-init-vserver.sh in native mode")
61         parser.add_option("-c","--config",action="callback", callback=TestMain.optparse_list, dest="config",
62                           nargs=1,type="string",
63                           help="config module - can be set multiple times, or use quotes")
64         parser.add_option("-a","--all",action="store_true",dest="all_steps", default=False,
65                           help="Runs all default steps")
66         parser.add_option("-s","--state",action="store",dest="dbname",default=None,
67                            help="Used by db_dump and db_restore")
68         parser.add_option("-d","--display", action="store", dest="display", default='bellami.inria.fr:0.0',
69                           help="set DISPLAY for vmplayer")
70         parser.add_option("-i","--ip",action="callback", callback=TestMain.optparse_list, dest="ips",
71                           nargs=1,type="string",
72                           help="allows to specify the set of IP addresses to use in vserver mode (disable scanning)")
73         parser.add_option("-v","--verbose", action="store_true", dest="verbose", default=False, 
74                           help="Run in verbose mode")
75         parser.add_option("-n","--dry-run", action="store_true", dest="dry_run", default=False,
76                           help="Show environment and exits")
77         (self.options, self.args) = parser.parse_args()
78
79         if len(self.args) == 0:
80             if self.options.all_steps:
81                 self.options.steps=TestMain.default_steps
82             elif self.options.dry_run:
83                 self.options.steps=TestMain.default_steps
84             else:
85                 print 'No step found (do you mean -a ? )'
86                 print "Run %s --help for help"%sys.argv[0]                        
87                 sys.exit(1)
88         else:
89             self.options.steps = self.args
90
91         # display display
92         utils.header('X11 display : %s'% self.options.display)
93
94         # handle defaults and option persistence
95         for (recname,filename,default) in ( ('myplc_url','MYPLC-URL',"") , 
96                                             ('build_url','BUILD-URL',TestMain.default_build_url) ,
97                                             ('ips','IPS',[]) , 
98                                             ('config','CONFIG',TestMain.default_config) , ) :
99             print 'handling',recname
100             path="%s/%s"%(self.path,filename)
101             is_list = isinstance(default,list)
102             if not getattr(self.options,recname):
103                 try:
104                     parsed=file(path).readlines()
105                     if not is_list:    # strings
106                         if len(parsed) != 1:
107                             print "%s - error when parsing %s"%(sys.argv[1],path)
108                             sys.exit(1)
109                         parsed=parsed[0].strip()
110                     else:              # lists
111                         parsed=[x.strip() for x in parsed]
112                     setattr(self.options,recname,parsed)
113                 except:
114                     if default != "":
115                         setattr(self.options,recname,default)
116                     else:
117                         print "Cannot determine",recname
118                         print "Run %s --help for help"%sys.argv[0]                        
119                         sys.exit(1)
120             utils.header('* Using %s = %s'%(recname,getattr(self.options,recname)))
121
122             # save for next run
123             fsave=open(path,"w")
124             if not is_list:
125                 fsave.write(getattr(self.options,recname) + "\n")
126             else:
127                 for value in getattr(self.options,recname):
128                     fsave.write(value + "\n")
129             fsave.close()
130             utils.header('Saved %s into %s'%(recname,filename))
131
132         # steps
133         if not self.options.steps:
134             #default (all) steps
135             #self.options.steps=['dump','clean','install','populate']
136             self.options.steps=TestMain.default_steps
137
138         # store self.path in options.path for the various callbacks
139         self.options.path = self.path
140
141         if self.options.verbose:
142             self.show_env(self.options,"Verbose")
143
144         # load configs
145         all_plc_specs = []
146         for config in self.options.config:
147             modulename='config_'+config
148             try:
149                 m = __import__(modulename)
150                 all_plc_specs = m.config(all_plc_specs,self.options)
151             except :
152                 traceback.print_exc()
153                 print 'Cannot load config %s -- ignored'%modulename
154                 raise
155         # show config
156         utils.show_spec("Test specifications",all_plc_specs)
157         # build a TestPlc object from the result
158         for spec in all_plc_specs:
159             spec['disabled'] = False
160         all_plcs = [ (x, TestPlc(x)) for x in all_plc_specs]
161
162         overall_result = True
163         testplc_method_dict = __import__("TestPlc").__dict__['TestPlc'].__dict__
164         all_step_infos=[]
165         for step in self.options.steps:
166             # try and locate a method in TestPlc
167             if testplc_method_dict.has_key(step):
168                 all_step_infos += [ (step, testplc_method_dict[step] )]
169             # otherwise search for the 'run' method in the step_<x> module
170             else:
171                 modulename='step_'+step
172                 try:
173                     # locate all methods named run* in the module
174                     module_dict = __import__(modulename).__dict__
175                     names = [ key for key in module_dict.keys() if key.find("run")==0 ]
176                     if not names:
177                         raise Exception,"No run* method in module %s"%modulename
178                     names.sort()
179                     all_step_infos += [ ("%s.%s"%(step,name),module_dict[name]) for name in names ]
180                 except :
181                     print 'Step %s -- ignored'%(step)
182                     traceback.print_exc()
183                     overall_result = False
184             
185         if self.options.dry_run:
186             self.show_env(self.options,"Dry run")
187             return 0
188             
189         # do all steps on all plcs
190         for (name,method) in all_step_infos:
191             for (spec,obj) in all_plcs:
192                 if not spec['disabled']:
193                     try:
194                         utils.header("Running step %s on plc %s"%(name,spec['name']))
195                         step_result = method(obj,self.options)
196                         if step_result:
197                             utils.header('Successful step %s on %s'%(name,spec['name']))
198                         else:
199                             overall_result = False
200                             spec['disabled'] = True
201                             utils.header('Step %s on %s FAILED - discarding that plc from further steps'%(name,spec['name']))
202                     except:
203                         overall_result=False
204                         spec['disabled'] = True
205                         utils.header ('Step %s on plc %s FAILED (exception) - discarding this plc from further steps'%(name,spec['name']))
206                         traceback.print_exc()
207         return overall_result
208
209     # wrapper to shell
210     def main(self):
211         try:
212             success=self.test_main()
213             if success:
214                 return 0
215             else:
216                 return 1 
217         except:
218             traceback.print_exc()
219             return 2
220
221 if __name__ == "__main__":
222     sys.exit(TestMain().main())