blob: 2059fc4950ed90efefb390435e090462d7fd4bd7 [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
mbligh7dd510c2007-11-13 17:11:22 +00009import os, sys, re, pickle, shutil, time, traceback
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
20class job:
mblighc86b0b42006-07-28 17:35:28 +000021 """The actual job against which we do everything.
22
23 Properties:
mbligh72b88fc2006-12-16 18:41:35 +000024 autodir
mblighc86b0b42006-07-28 17:35:28 +000025 The top level autotest directory (/usr/local/autotest).
26 Comes from os.environ['AUTODIR'].
mbligh72b88fc2006-12-16 18:41:35 +000027 bindir
mblighc86b0b42006-07-28 17:35:28 +000028 <autodir>/bin/
mblighd5a38832008-01-25 18:15:39 +000029 libdir
30 <autodir>/lib/
mbligh72b88fc2006-12-16 18:41:35 +000031 testdir
mblighc86b0b42006-07-28 17:35:28 +000032 <autodir>/tests/
mbligh84bafdb2008-01-26 19:43:34 +000033 site_testdir
34 <autodir>/site_tests/
mblighc86b0b42006-07-28 17:35:28 +000035 profdir
36 <autodir>/profilers/
37 tmpdir
38 <autodir>/tmp/
39 resultdir
40 <autodir>/results/<jobtag>
41 stdout
42 fd_stack object for stdout
43 stderr
44 fd_stack object for stderr
45 profilers
46 the profilers object for this job
apw504a7dd2006-10-12 17:18:37 +000047 harness
48 the server harness object for this job
apw059e1b12006-10-12 17:18:26 +000049 config
50 the job configuration for this job
mblighc86b0b42006-07-28 17:35:28 +000051 """
52
mblighd528d302007-12-19 16:19:05 +000053 DEFAULT_LOG_FILENAME = "status"
54
mbligh362ab3d2007-08-30 11:24:04 +000055 def __init__(self, control, jobtag, cont, harness_type=None):
mblighc86b0b42006-07-28 17:35:28 +000056 """
57 control
58 The control file (pathname of)
59 jobtag
60 The job tag string (eg "default")
apw96da1a42006-11-02 00:23:18 +000061 cont
62 If this is the continuation of this job
apwe68a7132006-12-01 11:21:37 +000063 harness_type
64 An alternative server harness
mblighc86b0b42006-07-28 17:35:28 +000065 """
mblighf4c35322006-03-13 01:01:10 +000066 self.autodir = os.environ['AUTODIR']
apw870988b2007-09-25 16:50:53 +000067 self.bindir = os.path.join(self.autodir, 'bin')
mblighd5a38832008-01-25 18:15:39 +000068 self.libdir = os.path.join(self.autodir, 'lib')
apw870988b2007-09-25 16:50:53 +000069 self.testdir = os.path.join(self.autodir, 'tests')
mbligh84bafdb2008-01-26 19:43:34 +000070 self.site_testdir = os.path.join(self.autodir, 'site_tests')
apw870988b2007-09-25 16:50:53 +000071 self.profdir = os.path.join(self.autodir, 'profilers')
72 self.tmpdir = os.path.join(self.autodir, 'tmp')
73 self.resultdir = os.path.join(self.autodir, 'results', jobtag)
mbligh0fb83972008-01-10 16:30:02 +000074 self.sysinfodir = os.path.join(self.resultdir, 'sysinfo')
mbligh8d83cdc2007-12-03 18:09:18 +000075 self.control = os.path.abspath(control)
mbligha2508052006-05-28 21:29:53 +000076
apw96da1a42006-11-02 00:23:18 +000077 if not cont:
78 if os.path.exists(self.tmpdir):
mbligh09f288a2007-09-18 21:34:57 +000079 system('umount -f %s > /dev/null 2> /dev/null'%\
80 self.tmpdir, ignorestatus=True)
apw96da1a42006-11-02 00:23:18 +000081 system('rm -rf ' + self.tmpdir)
82 os.mkdir(self.tmpdir)
83
apw870988b2007-09-25 16:50:53 +000084 results = os.path.join(self.autodir, 'results')
85 if not os.path.exists(results):
86 os.mkdir(results)
mblighfbfb77d2007-02-15 18:54:03 +000087
apwf3d28622007-09-25 16:49:17 +000088 download = os.path.join(self.testdir, 'download')
89 if os.path.exists(download):
90 system('rm -rf ' + download)
91 os.mkdir(download)
92
apw96da1a42006-11-02 00:23:18 +000093 if os.path.exists(self.resultdir):
94 system('rm -rf ' + self.resultdir)
95 os.mkdir(self.resultdir)
mbligh0fb83972008-01-10 16:30:02 +000096 os.mkdir(self.sysinfodir)
apw96da1a42006-11-02 00:23:18 +000097
apw870988b2007-09-25 16:50:53 +000098 os.mkdir(os.path.join(self.resultdir, 'debug'))
99 os.mkdir(os.path.join(self.resultdir, 'analysis'))
apw870988b2007-09-25 16:50:53 +0000100
mbligh8d83cdc2007-12-03 18:09:18 +0000101 shutil.copyfile(self.control,
102 os.path.join(self.resultdir, 'control'))
mbligh4b089662006-06-14 22:34:58 +0000103
apwecf41b72006-03-31 14:00:55 +0000104 self.control = control
mbligh27113602007-10-31 21:07:51 +0000105 self.jobtag = jobtag
mblighd528d302007-12-19 16:19:05 +0000106 self.log_filename = self.DEFAULT_LOG_FILENAME
mbligh68119582008-01-25 18:16:41 +0000107 self.container = None
mblighf4c35322006-03-13 01:01:10 +0000108
mbligh56f1fbb2006-10-01 15:10:56 +0000109 self.stdout = fd_stack.fd_stack(1, sys.stdout)
110 self.stderr = fd_stack.fd_stack(2, sys.stderr)
mbligh7dd510c2007-11-13 17:11:22 +0000111 self.group_level = 0
mblighf4c35322006-03-13 01:01:10 +0000112
apw059e1b12006-10-12 17:18:26 +0000113 self.config = config.config(self)
114
apwd27e55f2006-12-01 11:22:08 +0000115 self.harness = harness.select(harness_type, self)
116
mbligha35553b2006-04-23 15:52:25 +0000117 self.profilers = profilers.profilers(self)
mbligh72905562006-05-25 01:30:49 +0000118
mblighcaa605c2006-10-02 00:37:35 +0000119 try:
apw90154af2006-12-01 11:23:36 +0000120 tool = self.config_get('boottool.executable')
121 self.bootloader = boottool.boottool(tool)
mblighcaa605c2006-10-02 00:37:35 +0000122 except:
123 pass
124
mbligh0fb83972008-01-10 16:30:02 +0000125 sysinfo.log_per_reboot_data(self.sysinfodir)
mbligh3a6d6ca2006-04-23 15:50:24 +0000126
mbligh30270302007-11-05 20:33:52 +0000127 if not cont:
mblighc3430162007-11-14 23:57:19 +0000128 self.record('START', None, None)
mblighc3430162007-11-14 23:57:19 +0000129 self.group_level = 1
apw357f50f2006-12-01 11:22:39 +0000130
apwf91efaf2007-11-24 17:32:13 +0000131 self.harness.run_start()
132
mbligh0692e472007-08-30 16:07:53 +0000133
134 def relative_path(self, path):
135 """\
136 Return a patch relative to the job results directory
137 """
mbligh1c250ca2007-08-30 16:31:38 +0000138 head = len(self.resultdir) + 1 # remove the / inbetween
139 return path[head:]
mbligh0692e472007-08-30 16:07:53 +0000140
141
mbligh362ab3d2007-08-30 11:24:04 +0000142 def control_get(self):
143 return self.control
144
mblighcaa605c2006-10-02 00:37:35 +0000145
mbligh8d83cdc2007-12-03 18:09:18 +0000146 def control_set(self, control):
147 self.control = os.path.abspath(control)
148
149
apwde1503a2006-10-10 08:34:21 +0000150 def harness_select(self, which):
151 self.harness = harness.select(which, self)
152
153
apw059e1b12006-10-12 17:18:26 +0000154 def config_set(self, name, value):
155 self.config.set(name, value)
156
157
158 def config_get(self, name):
159 return self.config.get(name)
160
mbligh8baa2ea2006-12-17 23:01:24 +0000161 def setup_dirs(self, results_dir, tmp_dir):
mbligh1e8858e2006-11-24 22:18:35 +0000162 if not tmp_dir:
apw870988b2007-09-25 16:50:53 +0000163 tmp_dir = os.path.join(self.tmpdir, 'build')
mbligh1e8858e2006-11-24 22:18:35 +0000164 if not os.path.exists(tmp_dir):
165 os.mkdir(tmp_dir)
166 if not os.path.isdir(tmp_dir):
mbligh642b03e2008-01-14 16:53:15 +0000167 e_msg = "Temp dir (%s) is not a dir - args backwards?" % self.tmpdir
168 raise ValueError(e_msg)
mbligh1e8858e2006-11-24 22:18:35 +0000169
170 # We label the first build "build" and then subsequent ones
171 # as "build.2", "build.3", etc. Whilst this is a little bit
172 # inconsistent, 99.9% of jobs will only have one build
173 # (that's not done as kernbench, sparse, or buildtest),
174 # so it works out much cleaner. One of life's comprimises.
175 if not results_dir:
176 results_dir = os.path.join(self.resultdir, 'build')
177 i = 2
178 while os.path.exists(results_dir):
179 results_dir = os.path.join(self.resultdir, 'build.%d' % i)
mblighd9223fc2006-11-26 17:19:54 +0000180 i += 1
mbligh1e8858e2006-11-24 22:18:35 +0000181 if not os.path.exists(results_dir):
182 os.mkdir(results_dir)
mbligh72b88fc2006-12-16 18:41:35 +0000183
mbligh8baa2ea2006-12-17 23:01:24 +0000184 return (results_dir, tmp_dir)
185
186
187 def xen(self, base_tree, results_dir = '', tmp_dir = '', leave = False, \
188 kjob = None ):
189 """Summon a xen object"""
190 (results_dir, tmp_dir) = self.setup_dirs(results_dir, tmp_dir)
191 build_dir = 'xen'
192 return xen.xen(self, base_tree, results_dir, tmp_dir, build_dir, leave, kjob)
193
194
195 def kernel(self, base_tree, results_dir = '', tmp_dir = '', leave = False):
196 """Summon a kernel object"""
mbligh669caa12007-11-05 18:32:13 +0000197 (results_dir, tmp_dir) = self.setup_dirs(results_dir, tmp_dir)
mbligh8baa2ea2006-12-17 23:01:24 +0000198 build_dir = 'linux'
mbligh6ee7ee02007-11-13 23:49:05 +0000199 return kernel.auto_kernel(self, base_tree, results_dir,
200 tmp_dir, build_dir, leave)
mblighf4c35322006-03-13 01:01:10 +0000201
mblighcaa605c2006-10-02 00:37:35 +0000202
mbligh6b504ff2007-12-12 21:03:49 +0000203 def barrier(self, *args, **kwds):
mblighfadca202006-09-23 04:40:01 +0000204 """Create a barrier object"""
mbligh6b504ff2007-12-12 21:03:49 +0000205 return barrier.barrier(*args, **kwds)
mblighfadca202006-09-23 04:40:01 +0000206
mblighcaa605c2006-10-02 00:37:35 +0000207
mbligh4b089662006-06-14 22:34:58 +0000208 def setup_dep(self, deps):
mblighc86b0b42006-07-28 17:35:28 +0000209 """Set up the dependencies for this test.
210
211 deps is a list of libraries required for this test.
212 """
mbligh4b089662006-06-14 22:34:58 +0000213 for dep in deps:
214 try:
apw870988b2007-09-25 16:50:53 +0000215 os.chdir(os.path.join(self.autodir, 'deps', dep))
mbligh4b089662006-06-14 22:34:58 +0000216 system('./' + dep + '.py')
217 except:
218 error = "setting up dependency " + dep + "\n"
mbligh72b88fc2006-12-16 18:41:35 +0000219 raise UnhandledError(error)
mbligh4b089662006-06-14 22:34:58 +0000220
221
mbligh72b88fc2006-12-16 18:41:35 +0000222 def __runtest(self, url, tag, args, dargs):
223 try:
mbligh53c41502007-10-23 20:45:04 +0000224 l = lambda : test.runtest(self, url, tag, args, dargs)
225 pid = fork_start(self.resultdir, l)
226 fork_waitfor(self.resultdir, pid)
mbligh72b88fc2006-12-16 18:41:35 +0000227 except AutotestError:
228 raise
229 except:
230 raise UnhandledError('running test ' + \
231 self.__class__.__name__ + "\n")
apwf1a81162006-04-25 10:10:29 +0000232
mblighcaa605c2006-10-02 00:37:35 +0000233
mblighd016ecc2006-11-25 21:41:07 +0000234 def run_test(self, url, *args, **dargs):
mblighc86b0b42006-07-28 17:35:28 +0000235 """Summon a test object and run it.
236
237 tag
238 tag to add to testname
mbligh12a7df72006-10-06 03:54:33 +0000239 url
240 url of the test to run
mblighc86b0b42006-07-28 17:35:28 +0000241 """
mbligh12a7df72006-10-06 03:54:33 +0000242
mblighd016ecc2006-11-25 21:41:07 +0000243 if not url:
mbligh642b03e2008-01-14 16:53:15 +0000244 raise TypeError("Test name is invalid. Switched arguments?")
mbligh09f288a2007-09-18 21:34:57 +0000245 (group, testname) = test.testname(url)
mbligh7dd510c2007-11-13 17:11:22 +0000246 tag = dargs.pop('tag', None)
mbligh65938a22007-12-10 16:58:52 +0000247 container = dargs.pop('container', None)
mbligh09f288a2007-09-18 21:34:57 +0000248 subdir = testname
mbligh7dd510c2007-11-13 17:11:22 +0000249 if tag:
250 subdir += '.' + tag
251
mbligh65938a22007-12-10 16:58:52 +0000252 if container:
mbligh68119582008-01-25 18:16:41 +0000253 cname = container.get('name', None)
254 if not cname: # get old name
255 cname = container.get('container_name', None)
256 mbytes = container.get('mbytes', None)
257 if not mbytes: # get old name
258 mbytes = container.get('mem', None)
259 cpus = container.get('cpus', None)
260 if not cpus: # get old name
261 cpus = container.get('cpu', None)
262 root = container.get('root', None)
263 self.new_container(mbytes=mbytes, cpus=cpus,
264 root=root, name=cname)
mbligh65938a22007-12-10 16:58:52 +0000265 # We are running in a container now...
266
mbligh7dd510c2007-11-13 17:11:22 +0000267 def group_func():
apwf1a81162006-04-25 10:10:29 +0000268 try:
mblighd016ecc2006-11-25 21:41:07 +0000269 self.__runtest(url, tag, args, dargs)
apwf1a81162006-04-25 10:10:29 +0000270 except Exception, detail:
mbligh7dd510c2007-11-13 17:11:22 +0000271 self.record('FAIL', subdir, testname,
272 str(detail))
apwf1a81162006-04-25 10:10:29 +0000273 raise
274 else:
mbligh7dd510c2007-11-13 17:11:22 +0000275 self.record('GOOD', subdir, testname,
276 'completed successfully')
mblighcfc6dd32007-11-20 00:44:35 +0000277 result, exc_info = self.__rungroup(subdir, group_func)
mbligh68119582008-01-25 18:16:41 +0000278 if container:
279 self.release_container()
mbligh7dd510c2007-11-13 17:11:22 +0000280 if exc_info and isinstance(exc_info[1], TestError):
281 return False
282 elif exc_info:
mbligh71ea2492008-01-15 20:35:52 +0000283 raise exc_info[0], exc_info[1], exc_info[2]
apwf1a81162006-04-25 10:10:29 +0000284 else:
mbligh7dd510c2007-11-13 17:11:22 +0000285 return True
286
287
288 def __rungroup(self, name, function, *args, **dargs):
289 """\
290 name:
291 name of the group
292 function:
293 subroutine to run
294 *args:
295 arguments for the function
296
297 Returns a 2-tuple (result, exc_info) where result
298 is the return value of function, and exc_info is
299 the sys.exc_info() of the exception thrown by the
300 function (which may be None).
301 """
302
303 result, exc_info = None, None
304 try:
305 self.record('START', None, name)
306 self.group_level += 1
307 result = function(*args, **dargs)
308 self.group_level -= 1
309 self.record('END GOOD', None, name)
310 except Exception, e:
311 exc_info = sys.exc_info()
312 self.group_level -= 1
mbligh51144e02007-11-20 20:38:18 +0000313 err_msg = str(e) + '\n' + format_error()
314 self.record('END FAIL', None, name, err_msg)
mbligh7dd510c2007-11-13 17:11:22 +0000315
316 return result, exc_info
apw0865f482006-03-30 18:50:19 +0000317
mblighd7fb4a62006-10-01 00:57:53 +0000318
apw1da244b2007-09-27 17:18:01 +0000319 def run_group(self, function, *args, **dargs):
mbligh88ab90f2007-08-29 15:52:49 +0000320 """\
321 function:
322 subroutine to run
323 *args:
324 arguments for the function
325 """
326
mbligh7dd510c2007-11-13 17:11:22 +0000327 # Allow the tag for the group to be specified
mbligh88ab90f2007-08-29 15:52:49 +0000328 name = function.__name__
mbligh7dd510c2007-11-13 17:11:22 +0000329 tag = dargs.pop('tag', None)
330 if tag:
331 name = tag
apw1da244b2007-09-27 17:18:01 +0000332
mbligh7dd510c2007-11-13 17:11:22 +0000333 result, exc_info = self.__rungroup(name, function,
334 *args, **dargs)
apw1da244b2007-09-27 17:18:01 +0000335
mbligh7dd510c2007-11-13 17:11:22 +0000336 # if there was a non-TestError exception, raise it
mbligh71ea2492008-01-15 20:35:52 +0000337 if exc_info and not isinstance(exc_info[1], TestError):
mbligh7dd510c2007-11-13 17:11:22 +0000338 err = ''.join(traceback.format_exception(*exc_info))
339 raise TestError(name + ' failed\n' + err)
mbligh88ab90f2007-08-29 15:52:49 +0000340
mbligh7dd510c2007-11-13 17:11:22 +0000341 # pass back the actual return value from the function
apw08403ca2007-09-27 17:17:22 +0000342 return result
343
mbligh88ab90f2007-08-29 15:52:49 +0000344
mbligh68119582008-01-25 18:16:41 +0000345 def new_container(self, mbytes=None, cpus=None, root=None, name=None):
346 if grep('cpusets', '/proc/filesystems'):
347 print "Containers not enabled by latest reboot"
348 return # containers weren't enabled in this kernel boot
349 pid = os.getpid()
350 if not root:
351 root = 'sys'
352 if not name:
353 name = 'test%d' % pid # make arbitrary unique name
354 self.container = cpuset.cpuset(name, job_size=mbytes,
355 job_pid=pid, cpus=cpus, root=root, cleanup=1)
356 # This job's python shell is now running in the new container
357 # and all forked test processes will inherit that container
358
359
360 def release_container(self):
361 if self.container:
362 self.container.release(job_pid=os.getpid())
363 self.container = None
364
365
366 def cpu_count(self):
367 if self.container:
368 return len(self.container.cpus)
369 return count_cpus() # use total system count
370
371
apwce73d892007-09-25 16:53:05 +0000372 # Check the passed kernel identifier against the command line
373 # and the running kernel, abort the job on missmatch.
mblighda0311e2007-10-25 16:03:33 +0000374 def kernel_check_ident(self, expected_when, expected_id, expected_cl, subdir, type = 'src'):
375 print "POST BOOT: checking booted kernel mark=%d identity='%s' changelist=%s type='%s'" \
376 % (expected_when, expected_id, expected_cl, type)
apwce73d892007-09-25 16:53:05 +0000377
378 running_id = running_os_ident()
379
380 cmdline = read_one_line("/proc/cmdline")
381
382 find_sum = re.compile(r'.*IDENT=(\d+)')
383 m = find_sum.match(cmdline)
384 cmdline_when = -1
385 if m:
386 cmdline_when = int(m.groups()[0])
387
mblighda0311e2007-10-25 16:03:33 +0000388 cl_re = re.compile(r'\d{7,}')
389 cl_match = cl_re.search(system_output('uname -v').split()[1])
390 if cl_match:
391 current_cl = cl_match.group()
392 else:
393 current_cl = None
394
apwce73d892007-09-25 16:53:05 +0000395 # We have all the facts, see if they indicate we
396 # booted the requested kernel or not.
397 bad = False
mblighda0311e2007-10-25 16:03:33 +0000398 if (type == 'src' and expected_id != running_id or
399 type == 'rpm' and not running_id.startswith(expected_id + '::')):
apwce73d892007-09-25 16:53:05 +0000400 print "check_kernel_ident: kernel identifier mismatch"
401 bad = True
402 if expected_when != cmdline_when:
403 print "check_kernel_ident: kernel command line mismatch"
404 bad = True
mblighda0311e2007-10-25 16:03:33 +0000405 if expected_cl and current_cl and str(expected_cl) != current_cl:
406 print 'check_kernel_ident: kernel changelist mismatch'
407 bad = True
apwce73d892007-09-25 16:53:05 +0000408
409 if bad:
410 print " Expected Ident: " + expected_id
411 print " Running Ident: " + running_id
412 print " Expected Mark: %d" % (expected_when)
413 print "Command Line Mark: %d" % (cmdline_when)
mblighda0311e2007-10-25 16:03:33 +0000414 print " Expected P4 CL: %s" % expected_cl
415 print " P4 CL: %s" % current_cl
apwce73d892007-09-25 16:53:05 +0000416 print " Command Line: " + cmdline
417
mbligh30270302007-11-05 20:33:52 +0000418 raise JobError("boot failure", "reboot.verify")
apwce73d892007-09-25 16:53:05 +0000419
mbligh30270302007-11-05 20:33:52 +0000420 self.record('GOOD', subdir, 'reboot.verify')
apwce73d892007-09-25 16:53:05 +0000421
422
mblighc2359852007-08-28 18:11:48 +0000423 def filesystem(self, device, mountpoint = None, loop_size = 0):
mblighd7fb4a62006-10-01 00:57:53 +0000424 if not mountpoint:
425 mountpoint = self.tmpdir
mblighc2359852007-08-28 18:11:48 +0000426 return filesystem.filesystem(self, device, mountpoint,loop_size)
mblighd7fb4a62006-10-01 00:57:53 +0000427
mblighcaa605c2006-10-02 00:37:35 +0000428
429 def reboot(self, tag='autotest'):
mbligh30270302007-11-05 20:33:52 +0000430 self.record('GOOD', None, 'reboot.start')
apwde1503a2006-10-10 08:34:21 +0000431 self.harness.run_reboot()
apw11985b72007-10-04 15:44:47 +0000432 default = self.config_get('boot.set_default')
433 if default:
434 self.bootloader.set_default(tag)
435 else:
436 self.bootloader.boot_once(tag)
mblighf3b78932007-11-07 16:52:47 +0000437 system("(sleep 5; reboot) </dev/null >/dev/null 2>&1 &")
apw0778a2f2006-10-06 03:11:40 +0000438 self.quit()
mblighcaa605c2006-10-02 00:37:35 +0000439
440
apw0865f482006-03-30 18:50:19 +0000441 def noop(self, text):
442 print "job: noop: " + text
443
mblighcaa605c2006-10-02 00:37:35 +0000444
mblighc86b0b42006-07-28 17:35:28 +0000445 def parallel(self, *tasklist):
446 """Run tasks in parallel"""
apw8fef4ac2006-10-10 22:53:37 +0000447
448 pids = []
mblighd528d302007-12-19 16:19:05 +0000449 old_log_filename = self.log_filename
450 for i, task in enumerate(tasklist):
451 self.log_filename = old_log_filename + (".%d" % i)
452 task_func = lambda: task[0](*task[1:])
453 pids.append(fork_start(self.resultdir, task_func))
454
455 old_log_path = os.path.join(self.resultdir, old_log_filename)
456 old_log = open(old_log_path, "a")
mblighd509b712008-01-14 17:41:25 +0000457 exceptions = []
mblighd528d302007-12-19 16:19:05 +0000458 for i, pid in enumerate(pids):
459 # wait for the task to finish
mblighd509b712008-01-14 17:41:25 +0000460 try:
461 fork_waitfor(self.resultdir, pid)
462 except Exception, e:
463 exceptions.append(e)
mblighd528d302007-12-19 16:19:05 +0000464 # copy the logs from the subtask into the main log
465 new_log_path = old_log_path + (".%d" % i)
466 if os.path.exists(new_log_path):
467 new_log = open(new_log_path)
468 old_log.write(new_log.read())
469 new_log.close()
470 old_log.flush()
471 os.remove(new_log_path)
472 old_log.close()
473
474 self.log_filename = old_log_filename
apw0865f482006-03-30 18:50:19 +0000475
mblighd509b712008-01-14 17:41:25 +0000476 # handle any exceptions raised by the parallel tasks
477 if exceptions:
478 msg = "%d task(s) failed" % len(exceptions)
479 raise JobError(msg, str(exceptions), exceptions)
480
mblighcaa605c2006-10-02 00:37:35 +0000481
apw0865f482006-03-30 18:50:19 +0000482 def quit(self):
mblighc86b0b42006-07-28 17:35:28 +0000483 # XXX: should have a better name.
apwde1503a2006-10-10 08:34:21 +0000484 self.harness.run_pause()
apwf2c66602006-04-27 14:11:25 +0000485 raise JobContinue("more to come")
apw0865f482006-03-30 18:50:19 +0000486
mblighcaa605c2006-10-02 00:37:35 +0000487
apw0865f482006-03-30 18:50:19 +0000488 def complete(self, status):
mblighc86b0b42006-07-28 17:35:28 +0000489 """Clean up and exit"""
apw0865f482006-03-30 18:50:19 +0000490 # We are about to exit 'complete' so clean up the control file.
491 try:
apwecf41b72006-03-31 14:00:55 +0000492 os.unlink(self.control + '.state')
apw0865f482006-03-30 18:50:19 +0000493 except:
494 pass
mbligh61a6c1a2006-12-25 01:26:38 +0000495 self.harness.run_complete()
apw1b021902006-04-03 17:02:56 +0000496 sys.exit(status)
apw0865f482006-03-30 18:50:19 +0000497
mblighcaa605c2006-10-02 00:37:35 +0000498
apw0865f482006-03-30 18:50:19 +0000499 steps = []
500 def next_step(self, step):
mblighc86b0b42006-07-28 17:35:28 +0000501 """Define the next step"""
apwce73d892007-09-25 16:53:05 +0000502 if not isinstance(step[0], basestring):
503 step[0] = step[0].__name__
apw0865f482006-03-30 18:50:19 +0000504 self.steps.append(step)
apwecf41b72006-03-31 14:00:55 +0000505 pickle.dump(self.steps, open(self.control + '.state', 'w'))
apw0865f482006-03-30 18:50:19 +0000506
mblighcaa605c2006-10-02 00:37:35 +0000507
mbligh237bed32007-09-05 13:05:57 +0000508 def next_step_prepend(self, step):
509 """Insert a new step, executing first"""
apwce73d892007-09-25 16:53:05 +0000510 if not isinstance(step[0], basestring):
511 step[0] = step[0].__name__
mbligh237bed32007-09-05 13:05:57 +0000512 self.steps.insert(0, step)
513 pickle.dump(self.steps, open(self.control + '.state', 'w'))
514
515
apw83f8d772006-04-27 14:12:56 +0000516 def step_engine(self):
mblighc86b0b42006-07-28 17:35:28 +0000517 """the stepping engine -- if the control file defines
518 step_init we will be using this engine to drive multiple runs.
519 """
520 """Do the next step"""
apw83f8d772006-04-27 14:12:56 +0000521 lcl = dict({'job': self})
522
523 str = """
mblighf31b0c02007-11-29 18:19:22 +0000524from common.error import *
apw83f8d772006-04-27 14:12:56 +0000525from autotest_utils import *
526"""
527 exec(str, lcl, lcl)
528 execfile(self.control, lcl, lcl)
529
mblighd9223fc2006-11-26 17:19:54 +0000530 state = self.control + '.state'
apw0865f482006-03-30 18:50:19 +0000531 # If there is a mid-job state file load that in and continue
532 # where it indicates. Otherwise start stepping at the passed
533 # entry.
534 try:
mblighd9223fc2006-11-26 17:19:54 +0000535 self.steps = pickle.load(open(state, 'r'))
apw0865f482006-03-30 18:50:19 +0000536 except:
apw83f8d772006-04-27 14:12:56 +0000537 if lcl.has_key('step_init'):
538 self.next_step([lcl['step_init']])
apw0865f482006-03-30 18:50:19 +0000539
540 # Run the step list.
541 while len(self.steps) > 0:
apwfd922bb2006-04-04 07:47:00 +0000542 step = self.steps.pop(0)
mblighd9223fc2006-11-26 17:19:54 +0000543 pickle.dump(self.steps, open(state, 'w'))
apw0865f482006-03-30 18:50:19 +0000544
545 cmd = step.pop(0)
apw83f8d772006-04-27 14:12:56 +0000546 lcl['__args'] = step
apwce73d892007-09-25 16:53:05 +0000547 exec(cmd + "(*__args)", lcl, lcl)
apw0865f482006-03-30 18:50:19 +0000548
mblighcaa605c2006-10-02 00:37:35 +0000549
mbligh09f288a2007-09-18 21:34:57 +0000550 def record(self, status_code, subdir, operation, status = ''):
551 """
552 Record job-level status
apw7db8d0b2006-10-09 08:10:25 +0000553
mbligh09f288a2007-09-18 21:34:57 +0000554 The intent is to make this file both machine parseable and
555 human readable. That involves a little more complexity, but
556 really isn't all that bad ;-)
557
558 Format is <status code>\t<subdir>\t<operation>\t<status>
559
560 status code: (GOOD|WARN|FAIL|ABORT)
561 or START
562 or END (GOOD|WARN|FAIL|ABORT)
563
564 subdir: MUST be a relevant subdirectory in the results,
565 or None, which will be represented as '----'
566
567 operation: description of what you ran (e.g. "dbench", or
568 "mkfs -t foobar /dev/sda9")
569
570 status: error message or "completed sucessfully"
571
572 ------------------------------------------------------------
573
574 Initial tabs indicate indent levels for grouping, and is
mbligh7dd510c2007-11-13 17:11:22 +0000575 governed by self.group_level
mbligh09f288a2007-09-18 21:34:57 +0000576
577 multiline messages have secondary lines prefaced by a double
578 space (' ')
579 """
580
mblighb0570ad2007-09-19 18:18:11 +0000581 if subdir:
582 if re.match(r'[\n\t]', subdir):
mbligh642b03e2008-01-14 16:53:15 +0000583 raise ValueError("Invalid character in subdir string")
mblighb0570ad2007-09-19 18:18:11 +0000584 substr = subdir
585 else:
586 substr = '----'
mbligh09f288a2007-09-18 21:34:57 +0000587
588 if not re.match(r'(START|(END )?(GOOD|WARN|FAIL|ABORT))$', \
589 status_code):
mbligh642b03e2008-01-14 16:53:15 +0000590 raise ValueError("Invalid status code supplied: %s" % status_code)
mbligh9c5ac322007-10-31 18:01:59 +0000591 if not operation:
592 operation = '----'
mbligh09f288a2007-09-18 21:34:57 +0000593 if re.match(r'[\n\t]', operation):
mbligh642b03e2008-01-14 16:53:15 +0000594 raise ValueError("Invalid character in operation string")
mbligh09f288a2007-09-18 21:34:57 +0000595 operation = operation.rstrip()
596 status = status.rstrip()
597 status = re.sub(r"\t", " ", status)
apw7db8d0b2006-10-09 08:10:25 +0000598 # Ensure any continuation lines are marked so we can
599 # detect them in the status file to ensure it is parsable.
mbligh7dd510c2007-11-13 17:11:22 +0000600 status = re.sub(r"\n", "\n" + "\t" * self.group_level + " ", status)
mbligh09f288a2007-09-18 21:34:57 +0000601
mbligh30270302007-11-05 20:33:52 +0000602 # Generate timestamps for inclusion in the logs
603 epoch_time = int(time.time()) # seconds since epoch, in UTC
604 local_time = time.localtime(epoch_time)
605 epoch_time_str = "timestamp=%d" % (epoch_time,)
606 local_time_str = time.strftime("localtime=%b %d %H:%M:%S",
607 local_time)
608
609 msg = '\t'.join(str(x) for x in (status_code, substr, operation,
610 epoch_time_str, local_time_str,
611 status))
mbligh7dd510c2007-11-13 17:11:22 +0000612 msg = '\t' * self.group_level + msg
apw7db8d0b2006-10-09 08:10:25 +0000613
mblighd528d302007-12-19 16:19:05 +0000614 msg_tag = ""
615 if "." in self.log_filename:
616 msg_tag = self.log_filename.split(".", 1)[1]
617
618 self.harness.test_status_detail(status_code, substr, operation,
619 status, msg_tag)
620 self.harness.test_status(msg, msg_tag)
621
622 # log to stdout (if enabled)
623 #if self.log_filename == self.DEFAULT_LOG_FILENAME:
apwf1a81162006-04-25 10:10:29 +0000624 print msg
mblighd528d302007-12-19 16:19:05 +0000625
626 # log to the "root" status log
627 status_file = os.path.join(self.resultdir, self.log_filename)
mbligh7dd510c2007-11-13 17:11:22 +0000628 open(status_file, "a").write(msg + "\n")
mblighd528d302007-12-19 16:19:05 +0000629
630 # log to the subdir status log (if subdir is set)
mblighb0570ad2007-09-19 18:18:11 +0000631 if subdir:
mblighadff6ca2008-01-22 16:38:25 +0000632 dir = os.path.join(self.resultdir, subdir)
633 if not os.path.exists(dir):
634 os.mkdir(dir)
635
636 status_file = os.path.join(dir,
mblighd528d302007-12-19 16:19:05 +0000637 self.DEFAULT_LOG_FILENAME)
mblighb0570ad2007-09-19 18:18:11 +0000638 open(status_file, "a").write(msg + "\n")
apwce9abe92006-04-27 14:14:04 +0000639
640
mbligh570e93e2006-11-26 05:15:56 +0000641def runjob(control, cont = False, tag = "default", harness_type = ''):
mblighc86b0b42006-07-28 17:35:28 +0000642 """The main interface to this module
643
mbligh72b88fc2006-12-16 18:41:35 +0000644 control
mblighc86b0b42006-07-28 17:35:28 +0000645 The control file to use for this job.
646 cont
647 Whether this is the continuation of a previously started job
648 """
mblighb4eef242007-07-23 18:22:49 +0000649 control = os.path.abspath(control)
apwce9abe92006-04-27 14:14:04 +0000650 state = control + '.state'
651
652 # instantiate the job object ready for the control file.
653 myjob = None
654 try:
655 # Check that the control file is valid
656 if not os.path.exists(control):
657 raise JobError(control + ": control file not found")
658
659 # When continuing, the job is complete when there is no
660 # state file, ensure we don't try and continue.
mblighf3fef462006-09-13 16:05:05 +0000661 if cont and not os.path.exists(state):
apwb832e1b2007-11-24 20:24:38 +0000662 raise JobComplete("all done")
mblighf3fef462006-09-13 16:05:05 +0000663 if cont == False and os.path.exists(state):
apwce9abe92006-04-27 14:14:04 +0000664 os.unlink(state)
665
mbligh570e93e2006-11-26 05:15:56 +0000666 myjob = job(control, tag, cont, harness_type)
apwce9abe92006-04-27 14:14:04 +0000667
668 # Load in the users control file, may do any one of:
669 # 1) execute in toto
670 # 2) define steps, and select the first via next_step()
671 myjob.step_engine()
672
apwce9abe92006-04-27 14:14:04 +0000673 except JobContinue:
674 sys.exit(5)
675
apwb832e1b2007-11-24 20:24:38 +0000676 except JobComplete:
677 sys.exit(1)
678
mbligh47681712007-11-16 21:41:51 +0000679 except JobError, instance:
apwce9abe92006-04-27 14:14:04 +0000680 print "JOB ERROR: " + instance.args[0]
mbligh9c5ac322007-10-31 18:01:59 +0000681 if myjob:
mbligh30270302007-11-05 20:33:52 +0000682 command = None
683 if len(instance.args) > 1:
684 command = instance.args[1]
mblighc3430162007-11-14 23:57:19 +0000685 myjob.group_level = 0
mbligh30270302007-11-05 20:33:52 +0000686 myjob.record('ABORT', None, command, instance.args[0])
mblighc3430162007-11-14 23:57:19 +0000687 myjob.record('END ABORT', None, None)
apwce9abe92006-04-27 14:14:04 +0000688 myjob.complete(1)
apwb832e1b2007-11-24 20:24:38 +0000689 else:
690 sys.exit(1)
apwce9abe92006-04-27 14:14:04 +0000691
mblighc3430162007-11-14 23:57:19 +0000692 except Exception, e:
mbligh51144e02007-11-20 20:38:18 +0000693 msg = str(e) + '\n' + format_error()
mblighc3430162007-11-14 23:57:19 +0000694 print "JOB ERROR: " + msg
mblighfbfb77d2007-02-15 18:54:03 +0000695 if myjob:
mblighc3430162007-11-14 23:57:19 +0000696 myjob.group_level = 0
697 myjob.record('ABORT', None, None, msg)
698 myjob.record('END ABORT', None, None)
mbligh9c5ac322007-10-31 18:01:59 +0000699 myjob.complete(1)
apwb832e1b2007-11-24 20:24:38 +0000700 else:
701 sys.exit(1)
mbligh892d37f2007-03-01 17:03:25 +0000702
703 # If we get here, then we assume the job is complete and good.
mblighc3430162007-11-14 23:57:19 +0000704 myjob.group_level = 0
705 myjob.record('END GOOD', None, None)
mbligh892d37f2007-03-01 17:03:25 +0000706 myjob.complete(0)
mbligh68119582008-01-25 18:16:41 +0000707