drop support for old chroot-based packages in tests/system
[tests.git] / system / TestMain.py
1 #!/usr/bin/env python
2 # $Id$
3
4 import sys, os, os.path
5 from optparse import OptionParser
6 import traceback
7 from time import strftime
8
9 import utils
10 from TestPlc import TestPlc
11 from TestSite import TestSite
12 from TestNode import TestNode
13
14 class TestMain:
15
16     subversion_id = "$Id$"
17
18     default_config = [ 'default' ] 
19
20     default_build_url = "http://svn.planet-lab.org/svn/build/trunk"
21
22     def __init__ (self):
23         self.path=os.path.dirname(sys.argv[0]) or "."
24         os.chdir(self.path)
25
26     @staticmethod
27     def show_env (options, message):
28         utils.header (message)
29         utils.show_options("main options",options)
30
31     @staticmethod
32     def optparse_list (option, opt, value, parser):
33         try:
34             setattr(parser.values,option.dest,getattr(parser.values,option.dest)+value.split())
35         except:
36             setattr(parser.values,option.dest,value.split())
37
38     def run (self):
39         steps_message=20*'x'+" Defaut steps are\n"+TestPlc.printable_steps(TestPlc.default_steps)
40         steps_message += "\n"+20*'x'+" Other useful steps are\n"+TestPlc.printable_steps(TestPlc.other_steps)
41         usage = """usage: %%prog [options] steps
42 arch-rpms-url defaults to the last value used, as stored in arg-arch-rpms-url,
43    no default
44 build-url defaults to the last value used, as stored in arg-build-url, 
45    or %s
46 config defaults to the last value used, as stored in arg-config,
47    or %r
48 ips defaults to the last value used, as stored in arg-ips,
49    default is to use IP scanning
50 steps refer to a method in TestPlc or to a step_* module
51 ===
52 """%(TestMain.default_build_url,TestMain.default_config)
53         usage += steps_message
54         parser=OptionParser(usage=usage,version=self.subversion_id)
55         parser.add_option("-u","--url",action="store", dest="arch_rpms_url", 
56                           help="URL of the arch-dependent RPMS area - for locating what to test")
57         parser.add_option("-b","--build",action="store", dest="build_url", 
58                           help="Build URL - for locating vtest-init-vserver.sh")
59         parser.add_option("-c","--config",action="callback", callback=TestMain.optparse_list, dest="config",
60                           nargs=1,type="string",
61                           help="Config module - can be set multiple times, or use quotes")
62         parser.add_option("-x","--exclude",action="callback", callback=TestMain.optparse_list, dest="exclude",
63                           nargs=1,type="string",default=[],
64                           help="steps to exclude - can be set multiple times, or use quotes")
65         parser.add_option("-a","--all",action="store_true",dest="all_steps", default=False,
66                           help="Run all default steps")
67         parser.add_option("-l","--list",action="store_true",dest="list_steps", default=False,
68                           help="List known steps")
69         parser.add_option("-i","--ip",action="callback", callback=TestMain.optparse_list, dest="ips",
70                           nargs=1,type="string",
71                           help="Specify the set of IP addresses to use in vserver mode (disable scanning)")
72         parser.add_option("-1","--small",action="store_true",dest="small_test",default=False,
73                           help="run a small test -- typically only one node")
74         parser.add_option("-d","--dbname",action="store",dest="dbname",default=None,
75                            help="Used by db_dump and db_restore")
76         parser.add_option("-v","--verbose", action="store_true", dest="verbose", default=False, 
77                           help="Run in verbose mode")
78         parser.add_option("-q","--quiet", action="store_true", dest="quiet", default=False, 
79                           help="Run in quiet mode")
80         parser.add_option("-n","--dry-run", action="store_true", dest="dry_run", default=False,
81                           help="Show environment and exits")
82         parser.add_option("-f","--forcenm", action="store_true", dest="forcenm", default=False, 
83                           help="Force the NM to restart in check_slices step")
84         parser.add_option("-t","--trace", action="store", dest="trace_file", default=None,
85                           #default="logs/trace-@TIME@.txt",
86                           help="Trace file location")
87         (self.options, self.args) = parser.parse_args()
88
89         if len(self.args) == 0:
90             if self.options.all_steps:
91                 self.options.steps=TestPlc.default_steps
92             elif self.options.dry_run:
93                 self.options.steps=TestPlc.default_steps
94             elif self.options.list_steps:
95                 print steps_message
96                 sys.exit(1)
97             else:
98                 print 'No step found (do you mean -a ? )'
99                 print "Run %s --help for help"%sys.argv[0]                        
100                 sys.exit(1)
101         else:
102             self.options.steps = self.args
103
104         # handle defaults and option persistence
105         for (recname,filename,default) in (
106             ('build_url','arg-build-url',TestMain.default_build_url) ,
107             ('ips','arg-ips',[]) , 
108             ('config','arg-config',TestMain.default_config) , 
109             ('arch_rpms_url','arg-arch-rpms-url',"") , 
110             ) :
111 #            print 'handling',recname
112             path=filename
113             is_list = isinstance(default,list)
114             if not getattr(self.options,recname):
115                 try:
116                     parsed=file(path).readlines()
117                     if not is_list:    # strings
118                         if len(parsed) != 1:
119                             print "%s - error when parsing %s"%(sys.argv[1],path)
120                             sys.exit(1)
121                         parsed=parsed[0].strip()
122                     else:              # lists
123                         parsed=[x.strip() for x in parsed]
124                     setattr(self.options,recname,parsed)
125                 except:
126                     if default != "":
127                         setattr(self.options,recname,default)
128                     else:
129                         print "Cannot determine",recname
130                         print "Run %s --help for help"%sys.argv[0]                        
131                         sys.exit(1)
132             if not self.options.quiet:
133                 utils.header('* Using %s = %s'%(recname,getattr(self.options,recname)))
134
135             # save for next run
136             fsave=open(path,"w")
137             if not is_list:
138                 fsave.write(getattr(self.options,recname) + "\n")
139             else:
140                 for value in getattr(self.options,recname):
141                     fsave.write(value + "\n")
142             fsave.close()
143 #            utils.header('Saved %s into %s'%(recname,filename))
144
145         self.options.arch = "i386"
146         if self.options.arch_rpms_url.find("x86_64") >= 0:
147             self.options.arch="x86_64"
148         # steps
149         if not self.options.steps:
150             #default (all) steps
151             #self.options.steps=['dump','clean','install','populate']
152             self.options.steps=TestPlc.default_steps
153
154         # exclude
155         selected=[]
156         for step in self.options.steps:
157             keep=True
158             for exclude in self.options.exclude:
159                 if utils.match(step,exclude):
160                     keep=False
161                     break
162             if keep: selected.append(step)
163         self.options.steps=selected
164
165         # this is useful when propagating on host boxes, to avoid conflicts
166         self.options.buildname = os.path.basename (os.path.abspath (self.path))
167
168         if self.options.verbose:
169             self.show_env(self.options,"Verbose")
170
171         # load configs
172         all_plc_specs = []
173         for config in self.options.config:
174             modulename='config_'+config
175             try:
176                 m = __import__(modulename)
177                 all_plc_specs = m.config(all_plc_specs,self.options)
178             except :
179                 traceback.print_exc()
180                 print 'Cannot load config %s -- ignored'%modulename
181                 raise
182         # show config
183         if not self.options.quiet:
184             utils.show_test_spec("Test specifications",all_plc_specs)
185         # build a TestPlc object from the result, passing options
186         for spec in all_plc_specs:
187             spec['disabled'] = False
188         all_plcs = [ (x, TestPlc(x,self.options)) for x in all_plc_specs]
189
190         # pass options to utils as well
191         utils.init_options(self.options)
192
193         overall_result = True
194         testplc_method_dict = __import__("TestPlc").__dict__['TestPlc'].__dict__
195         all_step_infos=[]
196         for step in self.options.steps:
197             if not TestPlc.valid_step(step):
198                 continue
199             force=False
200             # is it a forcedstep
201             if step.find("force_") == 0:
202                 step=step.replace("force_","")
203                 force=True
204             # try and locate a method in TestPlc
205             if testplc_method_dict.has_key(step):
206                 all_step_infos += [ (step, testplc_method_dict[step] , force)]
207             # otherwise search for the 'run' method in the step_<x> module
208             else:
209                 modulename='step_'+step
210                 try:
211                     # locate all methods named run* in the module
212                     module_dict = __import__(modulename).__dict__
213                     names = [ key for key in module_dict.keys() if key.find("run")==0 ]
214                     if not names:
215                         raise Exception,"No run* method in module %s"%modulename
216                     names.sort()
217                     all_step_infos += [ ("%s.%s"%(step,name),module_dict[name],force) for name in names ]
218                 except :
219                     print '********** step %s NOT FOUND -- ignored'%(step)
220                     traceback.print_exc()
221                     overall_result = False
222             
223         if self.options.dry_run:
224             self.show_env(self.options,"Dry run")
225         
226         # init & open trace file if provided
227         if self.options.trace_file and not self.options.dry_run:
228             time=strftime("%H-%M")
229             date=strftime("%Y-%m-%d")
230             trace_file=self.options.trace_file
231             trace_file=trace_file.replace("@TIME@",time)
232             trace_file=trace_file.replace("@DATE@",date)
233             self.options.trace_file=trace_file
234             # create dir if needed
235             trace_dir=os.path.dirname(trace_file)
236             if trace_dir and not os.path.isdir(trace_dir):
237                 os.makedirs(trace_dir)
238             trace=open(trace_file,"w")
239
240         # do all steps on all plcs
241         TRACE_FORMAT="TRACE: time=%(time)s plc=%(plcname)s step=%(stepname)s status=%(status)s force=%(force)s\n"
242         for (stepname,method,force) in all_step_infos:
243             for (spec,obj) in all_plcs:
244                 plcname=spec['name']
245
246                 # run the step
247                 time=strftime("%Y-%m-%d-%H-%M")
248                 if not spec['disabled'] or force:
249                     try:
250                         force_msg=""
251                         if force: force_msg=" (forced)"
252                         utils.header("********** RUNNING step %s%s on plc %s"%(stepname,force_msg,plcname))
253                         step_result = method(obj)
254                         if step_result:
255                             utils.header('********** SUCCESSFUL step %s on %s'%(stepname,plcname))
256                             status="OK"
257                         else:
258                             overall_result = False
259                             spec['disabled'] = True
260                             utils.header('********** FAILED Step %s on %s - discarding that plc from further steps'%(stepname,plcname))
261                             status="KO"
262                     except:
263                         overall_result=False
264                         spec['disabled'] = True
265                         traceback.print_exc()
266                         utils.header ('********** FAILED (exception) Step %s on plc %s - discarding this plc from further steps'%(stepname,plcname))
267                         status="KO"
268
269                 # do not run, just display it's skipped
270                 else:
271                     utils.header("********** IGNORED Plc %s is disabled - skipping step %s"%(plcname,stepname))
272                     status="UNDEF"
273                 if not self.options.dry_run:
274                     # alwas do this on stdout
275                     print TRACE_FORMAT%locals()
276                     # duplicate on trace_file if provided
277                     if self.options.trace_file:
278                         trace.write(TRACE_FORMAT%locals())
279
280         if self.options.trace_file and not self.options.dry_run:
281             trace.close()
282
283         return overall_result
284
285     # wrapper to run, returns a shell-compatible result
286     def main(self):
287         try:
288             success=self.run()
289             if success:
290                 return 0
291             else:
292                 return 1 
293         except SystemExit:
294             raise
295         except:
296             traceback.print_exc()
297             return 2
298
299 if __name__ == "__main__":
300     sys.exit(TestMain().main())