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