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