blob: 0b5ee3051b419cd04343819392be526f07a6dc36 [file] [log] [blame]
mblighc86b0b42006-07-28 17:35:28 +00001"""The main job wrapper
mbligha2508052006-05-28 21:29:53 +00002
mblighc86b0b42006-07-28 17:35:28 +00003This is the core infrastructure.
4"""
5
6__author__ = """Copyright Andy Whitcroft, Martin J. Bligh 2006"""
mbligha2508052006-05-28 21:29:53 +00007
mbligh8f243ec2006-10-10 05:55:49 +00008# standard stuff
mbligh366ff1b2008-04-25 16:07:56 +00009import os, sys, re, pickle, shutil, time, traceback, types, copy
mbligh8f243ec2006-10-10 05:55:49 +000010# autotest stuff
mblighf4c35322006-03-13 01:01:10 +000011from autotest_utils import *
apw8fef4ac2006-10-10 22:53:37 +000012from parallel import *
mblighf31b0c02007-11-29 18:19:22 +000013from common.error import *
mbligh65938a22007-12-10 16:58:52 +000014from common import barrier
mblighe1417fa2007-12-10 16:55:13 +000015import kernel, xen, test, profilers, filesystem, fd_stack, boottool
apw059e1b12006-10-12 17:18:26 +000016import harness, config
mbligh83ac9942007-11-05 18:59:37 +000017import sysinfo
mbligh65938a22007-12-10 16:58:52 +000018import cpuset
mblighf4c35322006-03-13 01:01:10 +000019
mbligh12a04cb2008-04-25 16:07:20 +000020
mbligh366ff1b2008-04-25 16:07:56 +000021JOB_PREAMBLE = """
22from common.error import *
23from autotest_utils import *
24"""
25
26
mbligh12a04cb2008-04-25 16:07:20 +000027class StepError(AutotestError):
28 pass
29
30
mblighcaa62c22008-04-07 21:51:17 +000031class base_job:
mblighc86b0b42006-07-28 17:35:28 +000032 """The actual job against which we do everything.
33
34 Properties:
mbligh72b88fc2006-12-16 18:41:35 +000035 autodir
mblighc86b0b42006-07-28 17:35:28 +000036 The top level autotest directory (/usr/local/autotest).
37 Comes from os.environ['AUTODIR'].
mbligh72b88fc2006-12-16 18:41:35 +000038 bindir
mblighc86b0b42006-07-28 17:35:28 +000039 <autodir>/bin/
mblighd5a38832008-01-25 18:15:39 +000040 libdir
41 <autodir>/lib/
mbligh72b88fc2006-12-16 18:41:35 +000042 testdir
mblighc86b0b42006-07-28 17:35:28 +000043 <autodir>/tests/
mbligh84bafdb2008-01-26 19:43:34 +000044 site_testdir
45 <autodir>/site_tests/
mblighc86b0b42006-07-28 17:35:28 +000046 profdir
47 <autodir>/profilers/
48 tmpdir
49 <autodir>/tmp/
50 resultdir
51 <autodir>/results/<jobtag>
52 stdout
53 fd_stack object for stdout
54 stderr
55 fd_stack object for stderr
56 profilers
57 the profilers object for this job
apw504a7dd2006-10-12 17:18:37 +000058 harness
59 the server harness object for this job
apw059e1b12006-10-12 17:18:26 +000060 config
61 the job configuration for this job
mblighc86b0b42006-07-28 17:35:28 +000062 """
63
mblighd528d302007-12-19 16:19:05 +000064 DEFAULT_LOG_FILENAME = "status"
65
mblighcaa62c22008-04-07 21:51:17 +000066 def __init__(self, control, jobtag, cont, harness_type=None,
67 use_external_logging = False):
mblighc86b0b42006-07-28 17:35:28 +000068 """
69 control
70 The control file (pathname of)
71 jobtag
72 The job tag string (eg "default")
apw96da1a42006-11-02 00:23:18 +000073 cont
74 If this is the continuation of this job
apwe68a7132006-12-01 11:21:37 +000075 harness_type
76 An alternative server harness
mblighc86b0b42006-07-28 17:35:28 +000077 """
mblighf4c35322006-03-13 01:01:10 +000078 self.autodir = os.environ['AUTODIR']
apw870988b2007-09-25 16:50:53 +000079 self.bindir = os.path.join(self.autodir, 'bin')
mblighd5a38832008-01-25 18:15:39 +000080 self.libdir = os.path.join(self.autodir, 'lib')
apw870988b2007-09-25 16:50:53 +000081 self.testdir = os.path.join(self.autodir, 'tests')
mbligh84bafdb2008-01-26 19:43:34 +000082 self.site_testdir = os.path.join(self.autodir, 'site_tests')
apw870988b2007-09-25 16:50:53 +000083 self.profdir = os.path.join(self.autodir, 'profilers')
84 self.tmpdir = os.path.join(self.autodir, 'tmp')
85 self.resultdir = os.path.join(self.autodir, 'results', jobtag)
mbligh0fb83972008-01-10 16:30:02 +000086 self.sysinfodir = os.path.join(self.resultdir, 'sysinfo')
mbligh8d83cdc2007-12-03 18:09:18 +000087 self.control = os.path.abspath(control)
mbligh366ff1b2008-04-25 16:07:56 +000088 self.state_file = self.control + '.state'
89 self.state = None
mbligha2508052006-05-28 21:29:53 +000090
apw96da1a42006-11-02 00:23:18 +000091 if not cont:
92 if os.path.exists(self.tmpdir):
mbligh09f288a2007-09-18 21:34:57 +000093 system('umount -f %s > /dev/null 2> /dev/null'%\
94 self.tmpdir, ignorestatus=True)
apw96da1a42006-11-02 00:23:18 +000095 system('rm -rf ' + self.tmpdir)
96 os.mkdir(self.tmpdir)
97
apw870988b2007-09-25 16:50:53 +000098 results = os.path.join(self.autodir, 'results')
99 if not os.path.exists(results):
100 os.mkdir(results)
mblighfbfb77d2007-02-15 18:54:03 +0000101
apwf3d28622007-09-25 16:49:17 +0000102 download = os.path.join(self.testdir, 'download')
103 if os.path.exists(download):
104 system('rm -rf ' + download)
105 os.mkdir(download)
106
apw96da1a42006-11-02 00:23:18 +0000107 if os.path.exists(self.resultdir):
108 system('rm -rf ' + self.resultdir)
109 os.mkdir(self.resultdir)
mbligh0fb83972008-01-10 16:30:02 +0000110 os.mkdir(self.sysinfodir)
apw96da1a42006-11-02 00:23:18 +0000111
apw870988b2007-09-25 16:50:53 +0000112 os.mkdir(os.path.join(self.resultdir, 'debug'))
113 os.mkdir(os.path.join(self.resultdir, 'analysis'))
apw870988b2007-09-25 16:50:53 +0000114
mbligh8d83cdc2007-12-03 18:09:18 +0000115 shutil.copyfile(self.control,
116 os.path.join(self.resultdir, 'control'))
mblighf4ca14f2008-03-03 16:03:05 +0000117
mbligh4b089662006-06-14 22:34:58 +0000118
apwecf41b72006-03-31 14:00:55 +0000119 self.control = control
mbligh27113602007-10-31 21:07:51 +0000120 self.jobtag = jobtag
mblighd528d302007-12-19 16:19:05 +0000121 self.log_filename = self.DEFAULT_LOG_FILENAME
mbligh68119582008-01-25 18:16:41 +0000122 self.container = None
mblighf4c35322006-03-13 01:01:10 +0000123
mbligh56f1fbb2006-10-01 15:10:56 +0000124 self.stdout = fd_stack.fd_stack(1, sys.stdout)
125 self.stderr = fd_stack.fd_stack(2, sys.stderr)
mbligh7dd510c2007-11-13 17:11:22 +0000126 self.group_level = 0
mblighf4c35322006-03-13 01:01:10 +0000127
apw059e1b12006-10-12 17:18:26 +0000128 self.config = config.config(self)
129
apwd27e55f2006-12-01 11:22:08 +0000130 self.harness = harness.select(harness_type, self)
131
mbligha35553b2006-04-23 15:52:25 +0000132 self.profilers = profilers.profilers(self)
mbligh72905562006-05-25 01:30:49 +0000133
mblighcaa605c2006-10-02 00:37:35 +0000134 try:
apw90154af2006-12-01 11:23:36 +0000135 tool = self.config_get('boottool.executable')
136 self.bootloader = boottool.boottool(tool)
mblighcaa605c2006-10-02 00:37:35 +0000137 except:
138 pass
139
mbligh0fb83972008-01-10 16:30:02 +0000140 sysinfo.log_per_reboot_data(self.sysinfodir)
mbligh3a6d6ca2006-04-23 15:50:24 +0000141
mbligh30270302007-11-05 20:33:52 +0000142 if not cont:
mblighc3430162007-11-14 23:57:19 +0000143 self.record('START', None, None)
mblighc3430162007-11-14 23:57:19 +0000144 self.group_level = 1
apw357f50f2006-12-01 11:22:39 +0000145
apwf91efaf2007-11-24 17:32:13 +0000146 self.harness.run_start()
mblighcaa62c22008-04-07 21:51:17 +0000147
148 if use_external_logging:
149 self.enable_external_logging()
apwf91efaf2007-11-24 17:32:13 +0000150
mbligh0692e472007-08-30 16:07:53 +0000151
152 def relative_path(self, path):
153 """\
154 Return a patch relative to the job results directory
155 """
mbligh1c250ca2007-08-30 16:31:38 +0000156 head = len(self.resultdir) + 1 # remove the / inbetween
157 return path[head:]
mbligh0692e472007-08-30 16:07:53 +0000158
159
mbligh362ab3d2007-08-30 11:24:04 +0000160 def control_get(self):
161 return self.control
162
mblighcaa605c2006-10-02 00:37:35 +0000163
mbligh8d83cdc2007-12-03 18:09:18 +0000164 def control_set(self, control):
165 self.control = os.path.abspath(control)
166
167
apwde1503a2006-10-10 08:34:21 +0000168 def harness_select(self, which):
169 self.harness = harness.select(which, self)
170
171
apw059e1b12006-10-12 17:18:26 +0000172 def config_set(self, name, value):
173 self.config.set(name, value)
174
175
176 def config_get(self, name):
177 return self.config.get(name)
178
mbligh8baa2ea2006-12-17 23:01:24 +0000179 def setup_dirs(self, results_dir, tmp_dir):
mbligh1e8858e2006-11-24 22:18:35 +0000180 if not tmp_dir:
apw870988b2007-09-25 16:50:53 +0000181 tmp_dir = os.path.join(self.tmpdir, 'build')
mbligh1e8858e2006-11-24 22:18:35 +0000182 if not os.path.exists(tmp_dir):
183 os.mkdir(tmp_dir)
184 if not os.path.isdir(tmp_dir):
mbligh642b03e2008-01-14 16:53:15 +0000185 e_msg = "Temp dir (%s) is not a dir - args backwards?" % self.tmpdir
186 raise ValueError(e_msg)
mbligh1e8858e2006-11-24 22:18:35 +0000187
188 # We label the first build "build" and then subsequent ones
189 # as "build.2", "build.3", etc. Whilst this is a little bit
190 # inconsistent, 99.9% of jobs will only have one build
191 # (that's not done as kernbench, sparse, or buildtest),
192 # so it works out much cleaner. One of life's comprimises.
193 if not results_dir:
194 results_dir = os.path.join(self.resultdir, 'build')
195 i = 2
196 while os.path.exists(results_dir):
197 results_dir = os.path.join(self.resultdir, 'build.%d' % i)
mblighd9223fc2006-11-26 17:19:54 +0000198 i += 1
mbligh1e8858e2006-11-24 22:18:35 +0000199 if not os.path.exists(results_dir):
200 os.mkdir(results_dir)
mbligh72b88fc2006-12-16 18:41:35 +0000201
mbligh8baa2ea2006-12-17 23:01:24 +0000202 return (results_dir, tmp_dir)
203
204
205 def xen(self, base_tree, results_dir = '', tmp_dir = '', leave = False, \
206 kjob = None ):
207 """Summon a xen object"""
208 (results_dir, tmp_dir) = self.setup_dirs(results_dir, tmp_dir)
209 build_dir = 'xen'
210 return xen.xen(self, base_tree, results_dir, tmp_dir, build_dir, leave, kjob)
211
212
213 def kernel(self, base_tree, results_dir = '', tmp_dir = '', leave = False):
214 """Summon a kernel object"""
mbligh669caa12007-11-05 18:32:13 +0000215 (results_dir, tmp_dir) = self.setup_dirs(results_dir, tmp_dir)
mbligh8baa2ea2006-12-17 23:01:24 +0000216 build_dir = 'linux'
mbligh6ee7ee02007-11-13 23:49:05 +0000217 return kernel.auto_kernel(self, base_tree, results_dir,
218 tmp_dir, build_dir, leave)
mblighf4c35322006-03-13 01:01:10 +0000219
mblighcaa605c2006-10-02 00:37:35 +0000220
mbligh6b504ff2007-12-12 21:03:49 +0000221 def barrier(self, *args, **kwds):
mblighfadca202006-09-23 04:40:01 +0000222 """Create a barrier object"""
mbligh6b504ff2007-12-12 21:03:49 +0000223 return barrier.barrier(*args, **kwds)
mblighfadca202006-09-23 04:40:01 +0000224
mblighcaa605c2006-10-02 00:37:35 +0000225
mbligh4b089662006-06-14 22:34:58 +0000226 def setup_dep(self, deps):
mblighc86b0b42006-07-28 17:35:28 +0000227 """Set up the dependencies for this test.
228
229 deps is a list of libraries required for this test.
230 """
mbligh4b089662006-06-14 22:34:58 +0000231 for dep in deps:
232 try:
apw870988b2007-09-25 16:50:53 +0000233 os.chdir(os.path.join(self.autodir, 'deps', dep))
mbligh4b089662006-06-14 22:34:58 +0000234 system('./' + dep + '.py')
235 except:
236 error = "setting up dependency " + dep + "\n"
mbligh72b88fc2006-12-16 18:41:35 +0000237 raise UnhandledError(error)
mbligh4b089662006-06-14 22:34:58 +0000238
239
mbligh72b88fc2006-12-16 18:41:35 +0000240 def __runtest(self, url, tag, args, dargs):
241 try:
mbligh53c41502007-10-23 20:45:04 +0000242 l = lambda : test.runtest(self, url, tag, args, dargs)
243 pid = fork_start(self.resultdir, l)
244 fork_waitfor(self.resultdir, pid)
mbligh72b88fc2006-12-16 18:41:35 +0000245 except AutotestError:
246 raise
247 except:
248 raise UnhandledError('running test ' + \
249 self.__class__.__name__ + "\n")
apwf1a81162006-04-25 10:10:29 +0000250
mblighcaa605c2006-10-02 00:37:35 +0000251
mblighd016ecc2006-11-25 21:41:07 +0000252 def run_test(self, url, *args, **dargs):
mblighc86b0b42006-07-28 17:35:28 +0000253 """Summon a test object and run it.
254
255 tag
256 tag to add to testname
mbligh12a7df72006-10-06 03:54:33 +0000257 url
258 url of the test to run
mblighc86b0b42006-07-28 17:35:28 +0000259 """
mbligh12a7df72006-10-06 03:54:33 +0000260
mblighd016ecc2006-11-25 21:41:07 +0000261 if not url:
mbligh642b03e2008-01-14 16:53:15 +0000262 raise TypeError("Test name is invalid. Switched arguments?")
mbligh09f288a2007-09-18 21:34:57 +0000263 (group, testname) = test.testname(url)
mbligh7dd510c2007-11-13 17:11:22 +0000264 tag = dargs.pop('tag', None)
mbligh65938a22007-12-10 16:58:52 +0000265 container = dargs.pop('container', None)
mbligh09f288a2007-09-18 21:34:57 +0000266 subdir = testname
mbligh7dd510c2007-11-13 17:11:22 +0000267 if tag:
268 subdir += '.' + tag
269
mbligh65938a22007-12-10 16:58:52 +0000270 if container:
mbligh68119582008-01-25 18:16:41 +0000271 cname = container.get('name', None)
272 if not cname: # get old name
273 cname = container.get('container_name', None)
274 mbytes = container.get('mbytes', None)
275 if not mbytes: # get old name
276 mbytes = container.get('mem', None)
277 cpus = container.get('cpus', None)
278 if not cpus: # get old name
279 cpus = container.get('cpu', None)
mbligh9ea52602008-04-02 00:15:35 +0000280 root = container.get('root', '')
mbligh68119582008-01-25 18:16:41 +0000281 self.new_container(mbytes=mbytes, cpus=cpus,
282 root=root, name=cname)
mbligh65938a22007-12-10 16:58:52 +0000283 # We are running in a container now...
284
mbligh7dd510c2007-11-13 17:11:22 +0000285 def group_func():
apwf1a81162006-04-25 10:10:29 +0000286 try:
mblighd016ecc2006-11-25 21:41:07 +0000287 self.__runtest(url, tag, args, dargs)
apwf1a81162006-04-25 10:10:29 +0000288 except Exception, detail:
mbligh7dd510c2007-11-13 17:11:22 +0000289 self.record('FAIL', subdir, testname,
290 str(detail))
apwf1a81162006-04-25 10:10:29 +0000291 raise
292 else:
mbligh7dd510c2007-11-13 17:11:22 +0000293 self.record('GOOD', subdir, testname,
294 'completed successfully')
mblighcfc6dd32007-11-20 00:44:35 +0000295 result, exc_info = self.__rungroup(subdir, group_func)
mbligh68119582008-01-25 18:16:41 +0000296 if container:
297 self.release_container()
mbligh7dd510c2007-11-13 17:11:22 +0000298 if exc_info and isinstance(exc_info[1], TestError):
299 return False
300 elif exc_info:
mbligh71ea2492008-01-15 20:35:52 +0000301 raise exc_info[0], exc_info[1], exc_info[2]
apwf1a81162006-04-25 10:10:29 +0000302 else:
mbligh7dd510c2007-11-13 17:11:22 +0000303 return True
304
305
306 def __rungroup(self, name, function, *args, **dargs):
307 """\
308 name:
309 name of the group
310 function:
311 subroutine to run
312 *args:
313 arguments for the function
314
315 Returns a 2-tuple (result, exc_info) where result
316 is the return value of function, and exc_info is
317 the sys.exc_info() of the exception thrown by the
318 function (which may be None).
319 """
320
321 result, exc_info = None, None
322 try:
323 self.record('START', None, name)
324 self.group_level += 1
325 result = function(*args, **dargs)
326 self.group_level -= 1
327 self.record('END GOOD', None, name)
328 except Exception, e:
329 exc_info = sys.exc_info()
330 self.group_level -= 1
mbligh51144e02007-11-20 20:38:18 +0000331 err_msg = str(e) + '\n' + format_error()
332 self.record('END FAIL', None, name, err_msg)
mbligh7dd510c2007-11-13 17:11:22 +0000333
334 return result, exc_info
apw0865f482006-03-30 18:50:19 +0000335
mblighd7fb4a62006-10-01 00:57:53 +0000336
apw1da244b2007-09-27 17:18:01 +0000337 def run_group(self, function, *args, **dargs):
mbligh88ab90f2007-08-29 15:52:49 +0000338 """\
339 function:
340 subroutine to run
341 *args:
342 arguments for the function
343 """
344
mbligh7dd510c2007-11-13 17:11:22 +0000345 # Allow the tag for the group to be specified
mbligh88ab90f2007-08-29 15:52:49 +0000346 name = function.__name__
mbligh7dd510c2007-11-13 17:11:22 +0000347 tag = dargs.pop('tag', None)
348 if tag:
349 name = tag
apw1da244b2007-09-27 17:18:01 +0000350
mbligh7dd510c2007-11-13 17:11:22 +0000351 result, exc_info = self.__rungroup(name, function,
352 *args, **dargs)
apw1da244b2007-09-27 17:18:01 +0000353
mbligh7dd510c2007-11-13 17:11:22 +0000354 # if there was a non-TestError exception, raise it
mbligh71ea2492008-01-15 20:35:52 +0000355 if exc_info and not isinstance(exc_info[1], TestError):
mbligh7dd510c2007-11-13 17:11:22 +0000356 err = ''.join(traceback.format_exception(*exc_info))
357 raise TestError(name + ' failed\n' + err)
mbligh88ab90f2007-08-29 15:52:49 +0000358
mbligh7dd510c2007-11-13 17:11:22 +0000359 # pass back the actual return value from the function
apw08403ca2007-09-27 17:17:22 +0000360 return result
361
mbligh88ab90f2007-08-29 15:52:49 +0000362
mbligh1fc7ba12008-03-31 17:50:53 +0000363 def new_container(self, mbytes=None, cpus=None, root='', name=None):
mbligh6ca0d6a2008-03-03 16:22:13 +0000364 if not grep('cpuset', '/proc/filesystems'):
mbligh68119582008-01-25 18:16:41 +0000365 print "Containers not enabled by latest reboot"
366 return # containers weren't enabled in this kernel boot
367 pid = os.getpid()
mbligh68119582008-01-25 18:16:41 +0000368 if not name:
369 name = 'test%d' % pid # make arbitrary unique name
370 self.container = cpuset.cpuset(name, job_size=mbytes,
mbligh337bb762008-04-16 21:23:10 +0000371 job_pid=pid, cpus=cpus, root=root)
mbligh68119582008-01-25 18:16:41 +0000372 # This job's python shell is now running in the new container
373 # and all forked test processes will inherit that container
374
375
376 def release_container(self):
377 if self.container:
mbligh337bb762008-04-16 21:23:10 +0000378 self.container.release()
mbligh68119582008-01-25 18:16:41 +0000379 self.container = None
380
381
382 def cpu_count(self):
383 if self.container:
384 return len(self.container.cpus)
385 return count_cpus() # use total system count
386
387
apwce73d892007-09-25 16:53:05 +0000388 # Check the passed kernel identifier against the command line
389 # and the running kernel, abort the job on missmatch.
mbligh38a4a112008-03-19 13:11:34 +0000390 def kernel_check_ident(self, expected_when, expected_id, subdir,
391 type = 'src'):
392 print (("POST BOOT: checking booted kernel " +
393 "mark=%d identity='%s' type='%s'") %
394 (expected_when, expected_id, type))
apwce73d892007-09-25 16:53:05 +0000395
396 running_id = running_os_ident()
397
398 cmdline = read_one_line("/proc/cmdline")
399
400 find_sum = re.compile(r'.*IDENT=(\d+)')
401 m = find_sum.match(cmdline)
402 cmdline_when = -1
403 if m:
404 cmdline_when = int(m.groups()[0])
405
406 # We have all the facts, see if they indicate we
407 # booted the requested kernel or not.
408 bad = False
mblighda0311e2007-10-25 16:03:33 +0000409 if (type == 'src' and expected_id != running_id or
410 type == 'rpm' and not running_id.startswith(expected_id + '::')):
apwce73d892007-09-25 16:53:05 +0000411 print "check_kernel_ident: kernel identifier mismatch"
412 bad = True
413 if expected_when != cmdline_when:
414 print "check_kernel_ident: kernel command line mismatch"
415 bad = True
416
417 if bad:
418 print " Expected Ident: " + expected_id
419 print " Running Ident: " + running_id
420 print " Expected Mark: %d" % (expected_when)
421 print "Command Line Mark: %d" % (cmdline_when)
422 print " Command Line: " + cmdline
423
mbligh30270302007-11-05 20:33:52 +0000424 raise JobError("boot failure", "reboot.verify")
apwce73d892007-09-25 16:53:05 +0000425
mblighb7fd2702008-03-25 14:57:08 +0000426 self.record('GOOD', subdir, 'reboot.verify', expected_id)
apwce73d892007-09-25 16:53:05 +0000427
428
mblighc2359852007-08-28 18:11:48 +0000429 def filesystem(self, device, mountpoint = None, loop_size = 0):
mblighd7fb4a62006-10-01 00:57:53 +0000430 if not mountpoint:
431 mountpoint = self.tmpdir
mblighc2359852007-08-28 18:11:48 +0000432 return filesystem.filesystem(self, device, mountpoint,loop_size)
mblighd7fb4a62006-10-01 00:57:53 +0000433
mblighcaa62c22008-04-07 21:51:17 +0000434
435 def enable_external_logging(self):
436 pass
437
438
439 def disable_external_logging(self):
440 pass
441
442
443 def reboot_setup(self):
444 pass
445
mblighcaa605c2006-10-02 00:37:35 +0000446
447 def reboot(self, tag='autotest'):
mblighcaa62c22008-04-07 21:51:17 +0000448 self.reboot_setup()
mbligh30270302007-11-05 20:33:52 +0000449 self.record('GOOD', None, 'reboot.start')
apwde1503a2006-10-10 08:34:21 +0000450 self.harness.run_reboot()
apw11985b72007-10-04 15:44:47 +0000451 default = self.config_get('boot.set_default')
452 if default:
453 self.bootloader.set_default(tag)
454 else:
455 self.bootloader.boot_once(tag)
mblighf3b78932007-11-07 16:52:47 +0000456 system("(sleep 5; reboot) </dev/null >/dev/null 2>&1 &")
apw0778a2f2006-10-06 03:11:40 +0000457 self.quit()
mblighcaa605c2006-10-02 00:37:35 +0000458
459
apw0865f482006-03-30 18:50:19 +0000460 def noop(self, text):
461 print "job: noop: " + text
462
mblighcaa605c2006-10-02 00:37:35 +0000463
mblighc86b0b42006-07-28 17:35:28 +0000464 def parallel(self, *tasklist):
465 """Run tasks in parallel"""
apw8fef4ac2006-10-10 22:53:37 +0000466
467 pids = []
mblighd528d302007-12-19 16:19:05 +0000468 old_log_filename = self.log_filename
469 for i, task in enumerate(tasklist):
470 self.log_filename = old_log_filename + (".%d" % i)
471 task_func = lambda: task[0](*task[1:])
472 pids.append(fork_start(self.resultdir, task_func))
473
474 old_log_path = os.path.join(self.resultdir, old_log_filename)
475 old_log = open(old_log_path, "a")
mblighd509b712008-01-14 17:41:25 +0000476 exceptions = []
mblighd528d302007-12-19 16:19:05 +0000477 for i, pid in enumerate(pids):
478 # wait for the task to finish
mblighd509b712008-01-14 17:41:25 +0000479 try:
480 fork_waitfor(self.resultdir, pid)
481 except Exception, e:
482 exceptions.append(e)
mblighd528d302007-12-19 16:19:05 +0000483 # copy the logs from the subtask into the main log
484 new_log_path = old_log_path + (".%d" % i)
485 if os.path.exists(new_log_path):
486 new_log = open(new_log_path)
487 old_log.write(new_log.read())
488 new_log.close()
489 old_log.flush()
490 os.remove(new_log_path)
491 old_log.close()
492
493 self.log_filename = old_log_filename
apw0865f482006-03-30 18:50:19 +0000494
mblighd509b712008-01-14 17:41:25 +0000495 # handle any exceptions raised by the parallel tasks
496 if exceptions:
497 msg = "%d task(s) failed" % len(exceptions)
498 raise JobError(msg, str(exceptions), exceptions)
499
mblighcaa605c2006-10-02 00:37:35 +0000500
apw0865f482006-03-30 18:50:19 +0000501 def quit(self):
mblighc86b0b42006-07-28 17:35:28 +0000502 # XXX: should have a better name.
apwde1503a2006-10-10 08:34:21 +0000503 self.harness.run_pause()
apwf2c66602006-04-27 14:11:25 +0000504 raise JobContinue("more to come")
apw0865f482006-03-30 18:50:19 +0000505
mblighcaa605c2006-10-02 00:37:35 +0000506
apw0865f482006-03-30 18:50:19 +0000507 def complete(self, status):
mblighc86b0b42006-07-28 17:35:28 +0000508 """Clean up and exit"""
apw0865f482006-03-30 18:50:19 +0000509 # We are about to exit 'complete' so clean up the control file.
510 try:
mbligh366ff1b2008-04-25 16:07:56 +0000511 os.unlink(self.state_file)
apw0865f482006-03-30 18:50:19 +0000512 except:
513 pass
mblighc0b10d32008-03-03 16:03:28 +0000514
mbligh61a6c1a2006-12-25 01:26:38 +0000515 self.harness.run_complete()
mblighcaa62c22008-04-07 21:51:17 +0000516 self.disable_external_logging()
apw1b021902006-04-03 17:02:56 +0000517 sys.exit(status)
apw0865f482006-03-30 18:50:19 +0000518
mblighcaa605c2006-10-02 00:37:35 +0000519
mbligh366ff1b2008-04-25 16:07:56 +0000520 def set_state(self, var, val):
521 # Deep copies make sure that the state can't be altered
522 # without it being re-written. Perf wise, deep copies
523 # are overshadowed by pickling/loading.
524 self.state[var] = copy.deepcopy(val)
525 pickle.dump(self.state, open(self.state_file, 'w'))
526
527
528 def __load_state(self):
529 assert(self.state == None)
530 try:
531 self.state = pickle.load(open(self.state_file, 'r'))
532 return True
533 except Exception:
534 print "Initializing the state engine."
535 self.state = {}
536 self.set_state('steps', []) # writes pickle file
537 return False
538
539
540 def get_state(self, var, default=None):
541 if var in self.state or default == None:
542 val = self.state[var]
543 else:
544 val = default
545 return copy.deepcopy(val)
546
547
mbligh12a04cb2008-04-25 16:07:20 +0000548 def __create_step_tuple(self, fn, args, dargs):
549 # Legacy code passes in an array where the first arg is
550 # the function or its name.
551 if isinstance(fn, list):
552 assert(len(args) == 0)
553 assert(len(dargs) == 0)
554 args = fn[1:]
555 fn = fn[0]
556 # Pickling actual functions is harry, thus we have to call
557 # them by name. Unfortunately, this means only functions
558 # defined globally can be used as a next step.
559 if isinstance(fn, types.FunctionType):
560 fn = fn.__name__
561 if not isinstance(fn, types.StringTypes):
562 raise StepError("Next steps must be functions or "
563 "strings containing the function name")
564 return (fn, args, dargs)
565
566
mbligh12a04cb2008-04-25 16:07:20 +0000567 def next_step(self, fn, *args, **dargs):
mblighc86b0b42006-07-28 17:35:28 +0000568 """Define the next step"""
mbligh366ff1b2008-04-25 16:07:56 +0000569 steps = self.get_state('steps')
570 steps.append(self.__create_step_tuple(fn, args, dargs))
571 self.set_state('steps', steps)
apw0865f482006-03-30 18:50:19 +0000572
mblighcaa605c2006-10-02 00:37:35 +0000573
mbligh12a04cb2008-04-25 16:07:20 +0000574 def next_step_prepend(self, fn, *args, **dargs):
mbligh237bed32007-09-05 13:05:57 +0000575 """Insert a new step, executing first"""
mbligh366ff1b2008-04-25 16:07:56 +0000576 steps = self.get_state('steps')
577 steps.insert(0, self.__create_step_tuple(fn, args, dargs))
578 self.set_state('steps', steps)
mbligh237bed32007-09-05 13:05:57 +0000579
580
apw83f8d772006-04-27 14:12:56 +0000581 def step_engine(self):
mblighc86b0b42006-07-28 17:35:28 +0000582 """the stepping engine -- if the control file defines
583 step_init we will be using this engine to drive multiple runs.
584 """
585 """Do the next step"""
apw83f8d772006-04-27 14:12:56 +0000586
mbligh366ff1b2008-04-25 16:07:56 +0000587 # Set up the environment and then interpret the control file.
588 # Some control files will have code outside of functions,
589 # which means we need to have our state engine initialized
590 # before reading in the file.
591 state_existed = self.__load_state()
592 lcl = {'job': self}
593 exec(JOB_PREAMBLE, lcl, lcl)
apw83f8d772006-04-27 14:12:56 +0000594 execfile(self.control, lcl, lcl)
595
mbligh366ff1b2008-04-25 16:07:56 +0000596 # If we loaded in a mid-job state file, then we presumably
597 # know what steps we have yet to run.
598 if not state_existed:
apw83f8d772006-04-27 14:12:56 +0000599 if lcl.has_key('step_init'):
600 self.next_step([lcl['step_init']])
apw0865f482006-03-30 18:50:19 +0000601
mbligh366ff1b2008-04-25 16:07:56 +0000602 # Iterate through the steps. If we reboot, we'll simply
603 # continue iterating on the next step.
604 while len(self.get_state('steps')) > 0:
605 steps = self.get_state('steps')
606 (fn, args, dargs) = steps.pop(0)
607 self.set_state('steps', steps)
apw0865f482006-03-30 18:50:19 +0000608
mbligh12a04cb2008-04-25 16:07:20 +0000609 lcl['__args'] = args
610 lcl['__dargs'] = dargs
611 exec(fn + "(*__args, **__dargs)", lcl, lcl)
apw0865f482006-03-30 18:50:19 +0000612
mblighcaa605c2006-10-02 00:37:35 +0000613
mbligh09f288a2007-09-18 21:34:57 +0000614 def record(self, status_code, subdir, operation, status = ''):
615 """
616 Record job-level status
apw7db8d0b2006-10-09 08:10:25 +0000617
mbligh09f288a2007-09-18 21:34:57 +0000618 The intent is to make this file both machine parseable and
619 human readable. That involves a little more complexity, but
620 really isn't all that bad ;-)
621
622 Format is <status code>\t<subdir>\t<operation>\t<status>
623
624 status code: (GOOD|WARN|FAIL|ABORT)
625 or START
626 or END (GOOD|WARN|FAIL|ABORT)
627
628 subdir: MUST be a relevant subdirectory in the results,
629 or None, which will be represented as '----'
630
631 operation: description of what you ran (e.g. "dbench", or
632 "mkfs -t foobar /dev/sda9")
633
634 status: error message or "completed sucessfully"
635
636 ------------------------------------------------------------
637
638 Initial tabs indicate indent levels for grouping, and is
mbligh7dd510c2007-11-13 17:11:22 +0000639 governed by self.group_level
mbligh09f288a2007-09-18 21:34:57 +0000640
641 multiline messages have secondary lines prefaced by a double
642 space (' ')
643 """
644
mblighb0570ad2007-09-19 18:18:11 +0000645 if subdir:
646 if re.match(r'[\n\t]', subdir):
mbligh642b03e2008-01-14 16:53:15 +0000647 raise ValueError("Invalid character in subdir string")
mblighb0570ad2007-09-19 18:18:11 +0000648 substr = subdir
649 else:
650 substr = '----'
mbligh09f288a2007-09-18 21:34:57 +0000651
652 if not re.match(r'(START|(END )?(GOOD|WARN|FAIL|ABORT))$', \
653 status_code):
mbligh642b03e2008-01-14 16:53:15 +0000654 raise ValueError("Invalid status code supplied: %s" % status_code)
mbligh9c5ac322007-10-31 18:01:59 +0000655 if not operation:
656 operation = '----'
mbligh09f288a2007-09-18 21:34:57 +0000657 if re.match(r'[\n\t]', operation):
mbligh642b03e2008-01-14 16:53:15 +0000658 raise ValueError("Invalid character in operation string")
mbligh09f288a2007-09-18 21:34:57 +0000659 operation = operation.rstrip()
660 status = status.rstrip()
661 status = re.sub(r"\t", " ", status)
apw7db8d0b2006-10-09 08:10:25 +0000662 # Ensure any continuation lines are marked so we can
663 # detect them in the status file to ensure it is parsable.
mbligh7dd510c2007-11-13 17:11:22 +0000664 status = re.sub(r"\n", "\n" + "\t" * self.group_level + " ", status)
mbligh09f288a2007-09-18 21:34:57 +0000665
mbligh30270302007-11-05 20:33:52 +0000666 # Generate timestamps for inclusion in the logs
667 epoch_time = int(time.time()) # seconds since epoch, in UTC
668 local_time = time.localtime(epoch_time)
669 epoch_time_str = "timestamp=%d" % (epoch_time,)
670 local_time_str = time.strftime("localtime=%b %d %H:%M:%S",
671 local_time)
672
673 msg = '\t'.join(str(x) for x in (status_code, substr, operation,
674 epoch_time_str, local_time_str,
675 status))
mbligh7dd510c2007-11-13 17:11:22 +0000676 msg = '\t' * self.group_level + msg
apw7db8d0b2006-10-09 08:10:25 +0000677
mblighd528d302007-12-19 16:19:05 +0000678 msg_tag = ""
679 if "." in self.log_filename:
680 msg_tag = self.log_filename.split(".", 1)[1]
681
682 self.harness.test_status_detail(status_code, substr, operation,
683 status, msg_tag)
684 self.harness.test_status(msg, msg_tag)
685
686 # log to stdout (if enabled)
687 #if self.log_filename == self.DEFAULT_LOG_FILENAME:
apwf1a81162006-04-25 10:10:29 +0000688 print msg
mblighd528d302007-12-19 16:19:05 +0000689
690 # log to the "root" status log
691 status_file = os.path.join(self.resultdir, self.log_filename)
mbligh7dd510c2007-11-13 17:11:22 +0000692 open(status_file, "a").write(msg + "\n")
mblighd528d302007-12-19 16:19:05 +0000693
694 # log to the subdir status log (if subdir is set)
mblighb0570ad2007-09-19 18:18:11 +0000695 if subdir:
mblighadff6ca2008-01-22 16:38:25 +0000696 dir = os.path.join(self.resultdir, subdir)
697 if not os.path.exists(dir):
698 os.mkdir(dir)
699
700 status_file = os.path.join(dir,
mblighd528d302007-12-19 16:19:05 +0000701 self.DEFAULT_LOG_FILENAME)
mblighb0570ad2007-09-19 18:18:11 +0000702 open(status_file, "a").write(msg + "\n")
apwce9abe92006-04-27 14:14:04 +0000703
704
mblighcaa62c22008-04-07 21:51:17 +0000705def runjob(control, cont = False, tag = "default", harness_type = '',
706 use_external_logging = False):
mblighc86b0b42006-07-28 17:35:28 +0000707 """The main interface to this module
708
mbligh72b88fc2006-12-16 18:41:35 +0000709 control
mblighc86b0b42006-07-28 17:35:28 +0000710 The control file to use for this job.
711 cont
712 Whether this is the continuation of a previously started job
713 """
mblighb4eef242007-07-23 18:22:49 +0000714 control = os.path.abspath(control)
apwce9abe92006-04-27 14:14:04 +0000715 state = control + '.state'
716
717 # instantiate the job object ready for the control file.
718 myjob = None
719 try:
720 # Check that the control file is valid
721 if not os.path.exists(control):
722 raise JobError(control + ": control file not found")
723
724 # When continuing, the job is complete when there is no
725 # state file, ensure we don't try and continue.
mblighf3fef462006-09-13 16:05:05 +0000726 if cont and not os.path.exists(state):
apwb832e1b2007-11-24 20:24:38 +0000727 raise JobComplete("all done")
mblighf3fef462006-09-13 16:05:05 +0000728 if cont == False and os.path.exists(state):
apwce9abe92006-04-27 14:14:04 +0000729 os.unlink(state)
730
mblighcaa62c22008-04-07 21:51:17 +0000731 myjob = job(control, tag, cont, harness_type,
732 use_external_logging)
apwce9abe92006-04-27 14:14:04 +0000733
734 # Load in the users control file, may do any one of:
735 # 1) execute in toto
736 # 2) define steps, and select the first via next_step()
737 myjob.step_engine()
738
apwce9abe92006-04-27 14:14:04 +0000739 except JobContinue:
740 sys.exit(5)
741
apwb832e1b2007-11-24 20:24:38 +0000742 except JobComplete:
743 sys.exit(1)
744
mbligh47681712007-11-16 21:41:51 +0000745 except JobError, instance:
apwce9abe92006-04-27 14:14:04 +0000746 print "JOB ERROR: " + instance.args[0]
mbligh9c5ac322007-10-31 18:01:59 +0000747 if myjob:
mbligh30270302007-11-05 20:33:52 +0000748 command = None
749 if len(instance.args) > 1:
750 command = instance.args[1]
mblighc3430162007-11-14 23:57:19 +0000751 myjob.group_level = 0
mbligh30270302007-11-05 20:33:52 +0000752 myjob.record('ABORT', None, command, instance.args[0])
mblighc3430162007-11-14 23:57:19 +0000753 myjob.record('END ABORT', None, None)
apwce9abe92006-04-27 14:14:04 +0000754 myjob.complete(1)
apwb832e1b2007-11-24 20:24:38 +0000755 else:
756 sys.exit(1)
apwce9abe92006-04-27 14:14:04 +0000757
mblighc3430162007-11-14 23:57:19 +0000758 except Exception, e:
mbligh51144e02007-11-20 20:38:18 +0000759 msg = str(e) + '\n' + format_error()
mblighc3430162007-11-14 23:57:19 +0000760 print "JOB ERROR: " + msg
mblighfbfb77d2007-02-15 18:54:03 +0000761 if myjob:
mblighc3430162007-11-14 23:57:19 +0000762 myjob.group_level = 0
763 myjob.record('ABORT', None, None, msg)
764 myjob.record('END ABORT', None, None)
mbligh9c5ac322007-10-31 18:01:59 +0000765 myjob.complete(1)
apwb832e1b2007-11-24 20:24:38 +0000766 else:
767 sys.exit(1)
mbligh892d37f2007-03-01 17:03:25 +0000768
mbligh0144e5a2008-03-07 18:17:53 +0000769 # If we get here, then we assume the job is complete and good.
770 myjob.group_level = 0
771 myjob.record('END GOOD', None, None)
772
mbligh892d37f2007-03-01 17:03:25 +0000773 myjob.complete(0)
mblighcaa62c22008-04-07 21:51:17 +0000774
775
776# site_job.py may be non-existant or empty, make sure that an appropriate
777# site_job class is created nevertheless
778try:
779 from site_job import site_job
780except ImportError:
781 class site_job(base_job):
782 pass
783
784class job(site_job):
785 pass