blob: e8ceb37e98726ed002df2729f1427a6e11a653ab [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:
mblighbf79bba2008-03-03 16:02:37 +000078 df_root = system_output('df -m / | tail -1').split()
79 self.free_space_mb_root_before = int(df_root[3])
80 self.usage_percent_root_before = int(df_root[4].rstrip('%'))
81 if (self.free_space_mb_root_before < 100 or
82 self.usage_percent_root_before > 90):
83 self.record('WARN', 'check free space on root', 'free space is less than 100Mb or 10%')
84
apw96da1a42006-11-02 00:23:18 +000085 if os.path.exists(self.tmpdir):
mbligh09f288a2007-09-18 21:34:57 +000086 system('umount -f %s > /dev/null 2> /dev/null'%\
87 self.tmpdir, ignorestatus=True)
apw96da1a42006-11-02 00:23:18 +000088 system('rm -rf ' + self.tmpdir)
89 os.mkdir(self.tmpdir)
90
apw870988b2007-09-25 16:50:53 +000091 results = os.path.join(self.autodir, 'results')
92 if not os.path.exists(results):
93 os.mkdir(results)
mblighfbfb77d2007-02-15 18:54:03 +000094
apwf3d28622007-09-25 16:49:17 +000095 download = os.path.join(self.testdir, 'download')
96 if os.path.exists(download):
97 system('rm -rf ' + download)
98 os.mkdir(download)
99
apw96da1a42006-11-02 00:23:18 +0000100 if os.path.exists(self.resultdir):
101 system('rm -rf ' + self.resultdir)
102 os.mkdir(self.resultdir)
mbligh0fb83972008-01-10 16:30:02 +0000103 os.mkdir(self.sysinfodir)
apw96da1a42006-11-02 00:23:18 +0000104
apw870988b2007-09-25 16:50:53 +0000105 os.mkdir(os.path.join(self.resultdir, 'debug'))
106 os.mkdir(os.path.join(self.resultdir, 'analysis'))
apw870988b2007-09-25 16:50:53 +0000107
mbligh8d83cdc2007-12-03 18:09:18 +0000108 shutil.copyfile(self.control,
109 os.path.join(self.resultdir, 'control'))
mbligh4b089662006-06-14 22:34:58 +0000110
apwecf41b72006-03-31 14:00:55 +0000111 self.control = control
mbligh27113602007-10-31 21:07:51 +0000112 self.jobtag = jobtag
mblighd528d302007-12-19 16:19:05 +0000113 self.log_filename = self.DEFAULT_LOG_FILENAME
mbligh68119582008-01-25 18:16:41 +0000114 self.container = None
mblighf4c35322006-03-13 01:01:10 +0000115
mbligh56f1fbb2006-10-01 15:10:56 +0000116 self.stdout = fd_stack.fd_stack(1, sys.stdout)
117 self.stderr = fd_stack.fd_stack(2, sys.stderr)
mbligh7dd510c2007-11-13 17:11:22 +0000118 self.group_level = 0
mblighf4c35322006-03-13 01:01:10 +0000119
apw059e1b12006-10-12 17:18:26 +0000120 self.config = config.config(self)
121
apwd27e55f2006-12-01 11:22:08 +0000122 self.harness = harness.select(harness_type, self)
123
mbligha35553b2006-04-23 15:52:25 +0000124 self.profilers = profilers.profilers(self)
mbligh72905562006-05-25 01:30:49 +0000125
mblighcaa605c2006-10-02 00:37:35 +0000126 try:
apw90154af2006-12-01 11:23:36 +0000127 tool = self.config_get('boottool.executable')
128 self.bootloader = boottool.boottool(tool)
mblighcaa605c2006-10-02 00:37:35 +0000129 except:
130 pass
131
mbligh0fb83972008-01-10 16:30:02 +0000132 sysinfo.log_per_reboot_data(self.sysinfodir)
mbligh3a6d6ca2006-04-23 15:50:24 +0000133
mbligh30270302007-11-05 20:33:52 +0000134 if not cont:
mblighc3430162007-11-14 23:57:19 +0000135 self.record('START', None, None)
mblighc3430162007-11-14 23:57:19 +0000136 self.group_level = 1
apw357f50f2006-12-01 11:22:39 +0000137
apwf91efaf2007-11-24 17:32:13 +0000138 self.harness.run_start()
139
mbligh0692e472007-08-30 16:07:53 +0000140
141 def relative_path(self, path):
142 """\
143 Return a patch relative to the job results directory
144 """
mbligh1c250ca2007-08-30 16:31:38 +0000145 head = len(self.resultdir) + 1 # remove the / inbetween
146 return path[head:]
mbligh0692e472007-08-30 16:07:53 +0000147
148
mbligh362ab3d2007-08-30 11:24:04 +0000149 def control_get(self):
150 return self.control
151
mblighcaa605c2006-10-02 00:37:35 +0000152
mbligh8d83cdc2007-12-03 18:09:18 +0000153 def control_set(self, control):
154 self.control = os.path.abspath(control)
155
156
apwde1503a2006-10-10 08:34:21 +0000157 def harness_select(self, which):
158 self.harness = harness.select(which, self)
159
160
apw059e1b12006-10-12 17:18:26 +0000161 def config_set(self, name, value):
162 self.config.set(name, value)
163
164
165 def config_get(self, name):
166 return self.config.get(name)
167
mbligh8baa2ea2006-12-17 23:01:24 +0000168 def setup_dirs(self, results_dir, tmp_dir):
mbligh1e8858e2006-11-24 22:18:35 +0000169 if not tmp_dir:
apw870988b2007-09-25 16:50:53 +0000170 tmp_dir = os.path.join(self.tmpdir, 'build')
mbligh1e8858e2006-11-24 22:18:35 +0000171 if not os.path.exists(tmp_dir):
172 os.mkdir(tmp_dir)
173 if not os.path.isdir(tmp_dir):
mbligh642b03e2008-01-14 16:53:15 +0000174 e_msg = "Temp dir (%s) is not a dir - args backwards?" % self.tmpdir
175 raise ValueError(e_msg)
mbligh1e8858e2006-11-24 22:18:35 +0000176
177 # We label the first build "build" and then subsequent ones
178 # as "build.2", "build.3", etc. Whilst this is a little bit
179 # inconsistent, 99.9% of jobs will only have one build
180 # (that's not done as kernbench, sparse, or buildtest),
181 # so it works out much cleaner. One of life's comprimises.
182 if not results_dir:
183 results_dir = os.path.join(self.resultdir, 'build')
184 i = 2
185 while os.path.exists(results_dir):
186 results_dir = os.path.join(self.resultdir, 'build.%d' % i)
mblighd9223fc2006-11-26 17:19:54 +0000187 i += 1
mbligh1e8858e2006-11-24 22:18:35 +0000188 if not os.path.exists(results_dir):
189 os.mkdir(results_dir)
mbligh72b88fc2006-12-16 18:41:35 +0000190
mbligh8baa2ea2006-12-17 23:01:24 +0000191 return (results_dir, tmp_dir)
192
193
194 def xen(self, base_tree, results_dir = '', tmp_dir = '', leave = False, \
195 kjob = None ):
196 """Summon a xen object"""
197 (results_dir, tmp_dir) = self.setup_dirs(results_dir, tmp_dir)
198 build_dir = 'xen'
199 return xen.xen(self, base_tree, results_dir, tmp_dir, build_dir, leave, kjob)
200
201
202 def kernel(self, base_tree, results_dir = '', tmp_dir = '', leave = False):
203 """Summon a kernel object"""
mbligh669caa12007-11-05 18:32:13 +0000204 (results_dir, tmp_dir) = self.setup_dirs(results_dir, tmp_dir)
mbligh8baa2ea2006-12-17 23:01:24 +0000205 build_dir = 'linux'
mbligh6ee7ee02007-11-13 23:49:05 +0000206 return kernel.auto_kernel(self, base_tree, results_dir,
207 tmp_dir, build_dir, leave)
mblighf4c35322006-03-13 01:01:10 +0000208
mblighcaa605c2006-10-02 00:37:35 +0000209
mbligh6b504ff2007-12-12 21:03:49 +0000210 def barrier(self, *args, **kwds):
mblighfadca202006-09-23 04:40:01 +0000211 """Create a barrier object"""
mbligh6b504ff2007-12-12 21:03:49 +0000212 return barrier.barrier(*args, **kwds)
mblighfadca202006-09-23 04:40:01 +0000213
mblighcaa605c2006-10-02 00:37:35 +0000214
mbligh4b089662006-06-14 22:34:58 +0000215 def setup_dep(self, deps):
mblighc86b0b42006-07-28 17:35:28 +0000216 """Set up the dependencies for this test.
217
218 deps is a list of libraries required for this test.
219 """
mbligh4b089662006-06-14 22:34:58 +0000220 for dep in deps:
221 try:
apw870988b2007-09-25 16:50:53 +0000222 os.chdir(os.path.join(self.autodir, 'deps', dep))
mbligh4b089662006-06-14 22:34:58 +0000223 system('./' + dep + '.py')
224 except:
225 error = "setting up dependency " + dep + "\n"
mbligh72b88fc2006-12-16 18:41:35 +0000226 raise UnhandledError(error)
mbligh4b089662006-06-14 22:34:58 +0000227
228
mbligh72b88fc2006-12-16 18:41:35 +0000229 def __runtest(self, url, tag, args, dargs):
230 try:
mbligh53c41502007-10-23 20:45:04 +0000231 l = lambda : test.runtest(self, url, tag, args, dargs)
232 pid = fork_start(self.resultdir, l)
233 fork_waitfor(self.resultdir, pid)
mbligh72b88fc2006-12-16 18:41:35 +0000234 except AutotestError:
235 raise
236 except:
237 raise UnhandledError('running test ' + \
238 self.__class__.__name__ + "\n")
apwf1a81162006-04-25 10:10:29 +0000239
mblighcaa605c2006-10-02 00:37:35 +0000240
mblighd016ecc2006-11-25 21:41:07 +0000241 def run_test(self, url, *args, **dargs):
mblighc86b0b42006-07-28 17:35:28 +0000242 """Summon a test object and run it.
243
244 tag
245 tag to add to testname
mbligh12a7df72006-10-06 03:54:33 +0000246 url
247 url of the test to run
mblighc86b0b42006-07-28 17:35:28 +0000248 """
mbligh12a7df72006-10-06 03:54:33 +0000249
mblighd016ecc2006-11-25 21:41:07 +0000250 if not url:
mbligh642b03e2008-01-14 16:53:15 +0000251 raise TypeError("Test name is invalid. Switched arguments?")
mbligh09f288a2007-09-18 21:34:57 +0000252 (group, testname) = test.testname(url)
mbligh7dd510c2007-11-13 17:11:22 +0000253 tag = dargs.pop('tag', None)
mbligh65938a22007-12-10 16:58:52 +0000254 container = dargs.pop('container', None)
mbligh09f288a2007-09-18 21:34:57 +0000255 subdir = testname
mbligh7dd510c2007-11-13 17:11:22 +0000256 if tag:
257 subdir += '.' + tag
258
mbligh65938a22007-12-10 16:58:52 +0000259 if container:
mbligh68119582008-01-25 18:16:41 +0000260 cname = container.get('name', None)
261 if not cname: # get old name
262 cname = container.get('container_name', None)
263 mbytes = container.get('mbytes', None)
264 if not mbytes: # get old name
265 mbytes = container.get('mem', None)
266 cpus = container.get('cpus', None)
267 if not cpus: # get old name
268 cpus = container.get('cpu', None)
269 root = container.get('root', None)
270 self.new_container(mbytes=mbytes, cpus=cpus,
271 root=root, name=cname)
mbligh65938a22007-12-10 16:58:52 +0000272 # We are running in a container now...
273
mbligh7dd510c2007-11-13 17:11:22 +0000274 def group_func():
apwf1a81162006-04-25 10:10:29 +0000275 try:
mblighd016ecc2006-11-25 21:41:07 +0000276 self.__runtest(url, tag, args, dargs)
apwf1a81162006-04-25 10:10:29 +0000277 except Exception, detail:
mbligh7dd510c2007-11-13 17:11:22 +0000278 self.record('FAIL', subdir, testname,
279 str(detail))
apwf1a81162006-04-25 10:10:29 +0000280 raise
281 else:
mbligh7dd510c2007-11-13 17:11:22 +0000282 self.record('GOOD', subdir, testname,
283 'completed successfully')
mblighcfc6dd32007-11-20 00:44:35 +0000284 result, exc_info = self.__rungroup(subdir, group_func)
mbligh68119582008-01-25 18:16:41 +0000285 if container:
286 self.release_container()
mbligh7dd510c2007-11-13 17:11:22 +0000287 if exc_info and isinstance(exc_info[1], TestError):
288 return False
289 elif exc_info:
mbligh71ea2492008-01-15 20:35:52 +0000290 raise exc_info[0], exc_info[1], exc_info[2]
apwf1a81162006-04-25 10:10:29 +0000291 else:
mbligh7dd510c2007-11-13 17:11:22 +0000292 return True
293
294
295 def __rungroup(self, name, function, *args, **dargs):
296 """\
297 name:
298 name of the group
299 function:
300 subroutine to run
301 *args:
302 arguments for the function
303
304 Returns a 2-tuple (result, exc_info) where result
305 is the return value of function, and exc_info is
306 the sys.exc_info() of the exception thrown by the
307 function (which may be None).
308 """
309
310 result, exc_info = None, None
311 try:
312 self.record('START', None, name)
313 self.group_level += 1
314 result = function(*args, **dargs)
315 self.group_level -= 1
316 self.record('END GOOD', None, name)
317 except Exception, e:
318 exc_info = sys.exc_info()
319 self.group_level -= 1
mbligh51144e02007-11-20 20:38:18 +0000320 err_msg = str(e) + '\n' + format_error()
321 self.record('END FAIL', None, name, err_msg)
mbligh7dd510c2007-11-13 17:11:22 +0000322
323 return result, exc_info
apw0865f482006-03-30 18:50:19 +0000324
mblighd7fb4a62006-10-01 00:57:53 +0000325
apw1da244b2007-09-27 17:18:01 +0000326 def run_group(self, function, *args, **dargs):
mbligh88ab90f2007-08-29 15:52:49 +0000327 """\
328 function:
329 subroutine to run
330 *args:
331 arguments for the function
332 """
333
mbligh7dd510c2007-11-13 17:11:22 +0000334 # Allow the tag for the group to be specified
mbligh88ab90f2007-08-29 15:52:49 +0000335 name = function.__name__
mbligh7dd510c2007-11-13 17:11:22 +0000336 tag = dargs.pop('tag', None)
337 if tag:
338 name = tag
apw1da244b2007-09-27 17:18:01 +0000339
mbligh7dd510c2007-11-13 17:11:22 +0000340 result, exc_info = self.__rungroup(name, function,
341 *args, **dargs)
apw1da244b2007-09-27 17:18:01 +0000342
mbligh7dd510c2007-11-13 17:11:22 +0000343 # if there was a non-TestError exception, raise it
mbligh71ea2492008-01-15 20:35:52 +0000344 if exc_info and not isinstance(exc_info[1], TestError):
mbligh7dd510c2007-11-13 17:11:22 +0000345 err = ''.join(traceback.format_exception(*exc_info))
346 raise TestError(name + ' failed\n' + err)
mbligh88ab90f2007-08-29 15:52:49 +0000347
mbligh7dd510c2007-11-13 17:11:22 +0000348 # pass back the actual return value from the function
apw08403ca2007-09-27 17:17:22 +0000349 return result
350
mbligh88ab90f2007-08-29 15:52:49 +0000351
mbligh68119582008-01-25 18:16:41 +0000352 def new_container(self, mbytes=None, cpus=None, root=None, name=None):
353 if grep('cpusets', '/proc/filesystems'):
354 print "Containers not enabled by latest reboot"
355 return # containers weren't enabled in this kernel boot
356 pid = os.getpid()
357 if not root:
358 root = 'sys'
359 if not name:
360 name = 'test%d' % pid # make arbitrary unique name
361 self.container = cpuset.cpuset(name, job_size=mbytes,
362 job_pid=pid, cpus=cpus, root=root, cleanup=1)
363 # This job's python shell is now running in the new container
364 # and all forked test processes will inherit that container
365
366
367 def release_container(self):
368 if self.container:
369 self.container.release(job_pid=os.getpid())
370 self.container = None
371
372
373 def cpu_count(self):
374 if self.container:
375 return len(self.container.cpus)
376 return count_cpus() # use total system count
377
378
apwce73d892007-09-25 16:53:05 +0000379 # Check the passed kernel identifier against the command line
380 # and the running kernel, abort the job on missmatch.
mblighda0311e2007-10-25 16:03:33 +0000381 def kernel_check_ident(self, expected_when, expected_id, expected_cl, subdir, type = 'src'):
382 print "POST BOOT: checking booted kernel mark=%d identity='%s' changelist=%s type='%s'" \
383 % (expected_when, expected_id, expected_cl, type)
apwce73d892007-09-25 16:53:05 +0000384
385 running_id = running_os_ident()
386
387 cmdline = read_one_line("/proc/cmdline")
388
389 find_sum = re.compile(r'.*IDENT=(\d+)')
390 m = find_sum.match(cmdline)
391 cmdline_when = -1
392 if m:
393 cmdline_when = int(m.groups()[0])
394
mblighda0311e2007-10-25 16:03:33 +0000395 cl_re = re.compile(r'\d{7,}')
396 cl_match = cl_re.search(system_output('uname -v').split()[1])
397 if cl_match:
398 current_cl = cl_match.group()
399 else:
400 current_cl = None
401
apwce73d892007-09-25 16:53:05 +0000402 # We have all the facts, see if they indicate we
403 # booted the requested kernel or not.
404 bad = False
mblighda0311e2007-10-25 16:03:33 +0000405 if (type == 'src' and expected_id != running_id or
406 type == 'rpm' and not running_id.startswith(expected_id + '::')):
apwce73d892007-09-25 16:53:05 +0000407 print "check_kernel_ident: kernel identifier mismatch"
408 bad = True
409 if expected_when != cmdline_when:
410 print "check_kernel_ident: kernel command line mismatch"
411 bad = True
mblighda0311e2007-10-25 16:03:33 +0000412 if expected_cl and current_cl and str(expected_cl) != current_cl:
413 print 'check_kernel_ident: kernel changelist mismatch'
414 bad = True
apwce73d892007-09-25 16:53:05 +0000415
416 if bad:
417 print " Expected Ident: " + expected_id
418 print " Running Ident: " + running_id
419 print " Expected Mark: %d" % (expected_when)
420 print "Command Line Mark: %d" % (cmdline_when)
mblighda0311e2007-10-25 16:03:33 +0000421 print " Expected P4 CL: %s" % expected_cl
422 print " P4 CL: %s" % current_cl
apwce73d892007-09-25 16:53:05 +0000423 print " Command Line: " + cmdline
424
mbligh30270302007-11-05 20:33:52 +0000425 raise JobError("boot failure", "reboot.verify")
apwce73d892007-09-25 16:53:05 +0000426
mbligh30270302007-11-05 20:33:52 +0000427 self.record('GOOD', subdir, 'reboot.verify')
apwce73d892007-09-25 16:53:05 +0000428
429
mblighc2359852007-08-28 18:11:48 +0000430 def filesystem(self, device, mountpoint = None, loop_size = 0):
mblighd7fb4a62006-10-01 00:57:53 +0000431 if not mountpoint:
432 mountpoint = self.tmpdir
mblighc2359852007-08-28 18:11:48 +0000433 return filesystem.filesystem(self, device, mountpoint,loop_size)
mblighd7fb4a62006-10-01 00:57:53 +0000434
mblighcaa605c2006-10-02 00:37:35 +0000435
436 def reboot(self, tag='autotest'):
mbligh30270302007-11-05 20:33:52 +0000437 self.record('GOOD', None, 'reboot.start')
apwde1503a2006-10-10 08:34:21 +0000438 self.harness.run_reboot()
apw11985b72007-10-04 15:44:47 +0000439 default = self.config_get('boot.set_default')
440 if default:
441 self.bootloader.set_default(tag)
442 else:
443 self.bootloader.boot_once(tag)
mblighf3b78932007-11-07 16:52:47 +0000444 system("(sleep 5; reboot) </dev/null >/dev/null 2>&1 &")
apw0778a2f2006-10-06 03:11:40 +0000445 self.quit()
mblighcaa605c2006-10-02 00:37:35 +0000446
447
apw0865f482006-03-30 18:50:19 +0000448 def noop(self, text):
449 print "job: noop: " + text
450
mblighcaa605c2006-10-02 00:37:35 +0000451
mblighc86b0b42006-07-28 17:35:28 +0000452 def parallel(self, *tasklist):
453 """Run tasks in parallel"""
apw8fef4ac2006-10-10 22:53:37 +0000454
455 pids = []
mblighd528d302007-12-19 16:19:05 +0000456 old_log_filename = self.log_filename
457 for i, task in enumerate(tasklist):
458 self.log_filename = old_log_filename + (".%d" % i)
459 task_func = lambda: task[0](*task[1:])
460 pids.append(fork_start(self.resultdir, task_func))
461
462 old_log_path = os.path.join(self.resultdir, old_log_filename)
463 old_log = open(old_log_path, "a")
mblighd509b712008-01-14 17:41:25 +0000464 exceptions = []
mblighd528d302007-12-19 16:19:05 +0000465 for i, pid in enumerate(pids):
466 # wait for the task to finish
mblighd509b712008-01-14 17:41:25 +0000467 try:
468 fork_waitfor(self.resultdir, pid)
469 except Exception, e:
470 exceptions.append(e)
mblighd528d302007-12-19 16:19:05 +0000471 # copy the logs from the subtask into the main log
472 new_log_path = old_log_path + (".%d" % i)
473 if os.path.exists(new_log_path):
474 new_log = open(new_log_path)
475 old_log.write(new_log.read())
476 new_log.close()
477 old_log.flush()
478 os.remove(new_log_path)
479 old_log.close()
480
481 self.log_filename = old_log_filename
apw0865f482006-03-30 18:50:19 +0000482
mblighd509b712008-01-14 17:41:25 +0000483 # handle any exceptions raised by the parallel tasks
484 if exceptions:
485 msg = "%d task(s) failed" % len(exceptions)
486 raise JobError(msg, str(exceptions), exceptions)
487
mblighcaa605c2006-10-02 00:37:35 +0000488
apw0865f482006-03-30 18:50:19 +0000489 def quit(self):
mblighc86b0b42006-07-28 17:35:28 +0000490 # XXX: should have a better name.
apwde1503a2006-10-10 08:34:21 +0000491 self.harness.run_pause()
apwf2c66602006-04-27 14:11:25 +0000492 raise JobContinue("more to come")
apw0865f482006-03-30 18:50:19 +0000493
mblighcaa605c2006-10-02 00:37:35 +0000494
apw0865f482006-03-30 18:50:19 +0000495 def complete(self, status):
mblighc86b0b42006-07-28 17:35:28 +0000496 """Clean up and exit"""
apw0865f482006-03-30 18:50:19 +0000497 # We are about to exit 'complete' so clean up the control file.
498 try:
apwecf41b72006-03-31 14:00:55 +0000499 os.unlink(self.control + '.state')
apw0865f482006-03-30 18:50:19 +0000500 except:
501 pass
mbligh61a6c1a2006-12-25 01:26:38 +0000502 self.harness.run_complete()
apw1b021902006-04-03 17:02:56 +0000503 sys.exit(status)
apw0865f482006-03-30 18:50:19 +0000504
mblighcaa605c2006-10-02 00:37:35 +0000505
apw0865f482006-03-30 18:50:19 +0000506 steps = []
507 def next_step(self, step):
mblighc86b0b42006-07-28 17:35:28 +0000508 """Define the next step"""
apwce73d892007-09-25 16:53:05 +0000509 if not isinstance(step[0], basestring):
510 step[0] = step[0].__name__
apw0865f482006-03-30 18:50:19 +0000511 self.steps.append(step)
apwecf41b72006-03-31 14:00:55 +0000512 pickle.dump(self.steps, open(self.control + '.state', 'w'))
apw0865f482006-03-30 18:50:19 +0000513
mblighcaa605c2006-10-02 00:37:35 +0000514
mbligh237bed32007-09-05 13:05:57 +0000515 def next_step_prepend(self, step):
516 """Insert a new step, executing first"""
apwce73d892007-09-25 16:53:05 +0000517 if not isinstance(step[0], basestring):
518 step[0] = step[0].__name__
mbligh237bed32007-09-05 13:05:57 +0000519 self.steps.insert(0, step)
520 pickle.dump(self.steps, open(self.control + '.state', 'w'))
521
522
apw83f8d772006-04-27 14:12:56 +0000523 def step_engine(self):
mblighc86b0b42006-07-28 17:35:28 +0000524 """the stepping engine -- if the control file defines
525 step_init we will be using this engine to drive multiple runs.
526 """
527 """Do the next step"""
apw83f8d772006-04-27 14:12:56 +0000528 lcl = dict({'job': self})
529
530 str = """
mblighf31b0c02007-11-29 18:19:22 +0000531from common.error import *
apw83f8d772006-04-27 14:12:56 +0000532from autotest_utils import *
533"""
534 exec(str, lcl, lcl)
535 execfile(self.control, lcl, lcl)
536
mblighd9223fc2006-11-26 17:19:54 +0000537 state = self.control + '.state'
apw0865f482006-03-30 18:50:19 +0000538 # If there is a mid-job state file load that in and continue
539 # where it indicates. Otherwise start stepping at the passed
540 # entry.
541 try:
mblighd9223fc2006-11-26 17:19:54 +0000542 self.steps = pickle.load(open(state, 'r'))
apw0865f482006-03-30 18:50:19 +0000543 except:
apw83f8d772006-04-27 14:12:56 +0000544 if lcl.has_key('step_init'):
545 self.next_step([lcl['step_init']])
apw0865f482006-03-30 18:50:19 +0000546
547 # Run the step list.
548 while len(self.steps) > 0:
apwfd922bb2006-04-04 07:47:00 +0000549 step = self.steps.pop(0)
mblighd9223fc2006-11-26 17:19:54 +0000550 pickle.dump(self.steps, open(state, 'w'))
apw0865f482006-03-30 18:50:19 +0000551
552 cmd = step.pop(0)
apw83f8d772006-04-27 14:12:56 +0000553 lcl['__args'] = step
apwce73d892007-09-25 16:53:05 +0000554 exec(cmd + "(*__args)", lcl, lcl)
apw0865f482006-03-30 18:50:19 +0000555
mblighcaa605c2006-10-02 00:37:35 +0000556
mbligh09f288a2007-09-18 21:34:57 +0000557 def record(self, status_code, subdir, operation, status = ''):
558 """
559 Record job-level status
apw7db8d0b2006-10-09 08:10:25 +0000560
mbligh09f288a2007-09-18 21:34:57 +0000561 The intent is to make this file both machine parseable and
562 human readable. That involves a little more complexity, but
563 really isn't all that bad ;-)
564
565 Format is <status code>\t<subdir>\t<operation>\t<status>
566
567 status code: (GOOD|WARN|FAIL|ABORT)
568 or START
569 or END (GOOD|WARN|FAIL|ABORT)
570
571 subdir: MUST be a relevant subdirectory in the results,
572 or None, which will be represented as '----'
573
574 operation: description of what you ran (e.g. "dbench", or
575 "mkfs -t foobar /dev/sda9")
576
577 status: error message or "completed sucessfully"
578
579 ------------------------------------------------------------
580
581 Initial tabs indicate indent levels for grouping, and is
mbligh7dd510c2007-11-13 17:11:22 +0000582 governed by self.group_level
mbligh09f288a2007-09-18 21:34:57 +0000583
584 multiline messages have secondary lines prefaced by a double
585 space (' ')
586 """
587
mblighb0570ad2007-09-19 18:18:11 +0000588 if subdir:
589 if re.match(r'[\n\t]', subdir):
mbligh642b03e2008-01-14 16:53:15 +0000590 raise ValueError("Invalid character in subdir string")
mblighb0570ad2007-09-19 18:18:11 +0000591 substr = subdir
592 else:
593 substr = '----'
mbligh09f288a2007-09-18 21:34:57 +0000594
595 if not re.match(r'(START|(END )?(GOOD|WARN|FAIL|ABORT))$', \
596 status_code):
mbligh642b03e2008-01-14 16:53:15 +0000597 raise ValueError("Invalid status code supplied: %s" % status_code)
mbligh9c5ac322007-10-31 18:01:59 +0000598 if not operation:
599 operation = '----'
mbligh09f288a2007-09-18 21:34:57 +0000600 if re.match(r'[\n\t]', operation):
mbligh642b03e2008-01-14 16:53:15 +0000601 raise ValueError("Invalid character in operation string")
mbligh09f288a2007-09-18 21:34:57 +0000602 operation = operation.rstrip()
603 status = status.rstrip()
604 status = re.sub(r"\t", " ", status)
apw7db8d0b2006-10-09 08:10:25 +0000605 # Ensure any continuation lines are marked so we can
606 # detect them in the status file to ensure it is parsable.
mbligh7dd510c2007-11-13 17:11:22 +0000607 status = re.sub(r"\n", "\n" + "\t" * self.group_level + " ", status)
mbligh09f288a2007-09-18 21:34:57 +0000608
mbligh30270302007-11-05 20:33:52 +0000609 # Generate timestamps for inclusion in the logs
610 epoch_time = int(time.time()) # seconds since epoch, in UTC
611 local_time = time.localtime(epoch_time)
612 epoch_time_str = "timestamp=%d" % (epoch_time,)
613 local_time_str = time.strftime("localtime=%b %d %H:%M:%S",
614 local_time)
615
616 msg = '\t'.join(str(x) for x in (status_code, substr, operation,
617 epoch_time_str, local_time_str,
618 status))
mbligh7dd510c2007-11-13 17:11:22 +0000619 msg = '\t' * self.group_level + msg
apw7db8d0b2006-10-09 08:10:25 +0000620
mblighd528d302007-12-19 16:19:05 +0000621 msg_tag = ""
622 if "." in self.log_filename:
623 msg_tag = self.log_filename.split(".", 1)[1]
624
625 self.harness.test_status_detail(status_code, substr, operation,
626 status, msg_tag)
627 self.harness.test_status(msg, msg_tag)
628
629 # log to stdout (if enabled)
630 #if self.log_filename == self.DEFAULT_LOG_FILENAME:
apwf1a81162006-04-25 10:10:29 +0000631 print msg
mblighd528d302007-12-19 16:19:05 +0000632
633 # log to the "root" status log
634 status_file = os.path.join(self.resultdir, self.log_filename)
mbligh7dd510c2007-11-13 17:11:22 +0000635 open(status_file, "a").write(msg + "\n")
mblighd528d302007-12-19 16:19:05 +0000636
637 # log to the subdir status log (if subdir is set)
mblighb0570ad2007-09-19 18:18:11 +0000638 if subdir:
mblighadff6ca2008-01-22 16:38:25 +0000639 dir = os.path.join(self.resultdir, subdir)
640 if not os.path.exists(dir):
641 os.mkdir(dir)
642
643 status_file = os.path.join(dir,
mblighd528d302007-12-19 16:19:05 +0000644 self.DEFAULT_LOG_FILENAME)
mblighb0570ad2007-09-19 18:18:11 +0000645 open(status_file, "a").write(msg + "\n")
apwce9abe92006-04-27 14:14:04 +0000646
647
mbligh570e93e2006-11-26 05:15:56 +0000648def runjob(control, cont = False, tag = "default", harness_type = ''):
mblighc86b0b42006-07-28 17:35:28 +0000649 """The main interface to this module
650
mbligh72b88fc2006-12-16 18:41:35 +0000651 control
mblighc86b0b42006-07-28 17:35:28 +0000652 The control file to use for this job.
653 cont
654 Whether this is the continuation of a previously started job
655 """
mblighb4eef242007-07-23 18:22:49 +0000656 control = os.path.abspath(control)
apwce9abe92006-04-27 14:14:04 +0000657 state = control + '.state'
658
659 # instantiate the job object ready for the control file.
660 myjob = None
661 try:
662 # Check that the control file is valid
663 if not os.path.exists(control):
664 raise JobError(control + ": control file not found")
665
666 # When continuing, the job is complete when there is no
667 # state file, ensure we don't try and continue.
mblighf3fef462006-09-13 16:05:05 +0000668 if cont and not os.path.exists(state):
apwb832e1b2007-11-24 20:24:38 +0000669 raise JobComplete("all done")
mblighf3fef462006-09-13 16:05:05 +0000670 if cont == False and os.path.exists(state):
apwce9abe92006-04-27 14:14:04 +0000671 os.unlink(state)
672
mbligh570e93e2006-11-26 05:15:56 +0000673 myjob = job(control, tag, cont, harness_type)
apwce9abe92006-04-27 14:14:04 +0000674
675 # Load in the users control file, may do any one of:
676 # 1) execute in toto
677 # 2) define steps, and select the first via next_step()
678 myjob.step_engine()
679
apwce9abe92006-04-27 14:14:04 +0000680 except JobContinue:
681 sys.exit(5)
682
apwb832e1b2007-11-24 20:24:38 +0000683 except JobComplete:
684 sys.exit(1)
685
mbligh47681712007-11-16 21:41:51 +0000686 except JobError, instance:
apwce9abe92006-04-27 14:14:04 +0000687 print "JOB ERROR: " + instance.args[0]
mbligh9c5ac322007-10-31 18:01:59 +0000688 if myjob:
mbligh30270302007-11-05 20:33:52 +0000689 command = None
690 if len(instance.args) > 1:
691 command = instance.args[1]
mblighc3430162007-11-14 23:57:19 +0000692 myjob.group_level = 0
mbligh30270302007-11-05 20:33:52 +0000693 myjob.record('ABORT', None, command, instance.args[0])
mblighc3430162007-11-14 23:57:19 +0000694 myjob.record('END ABORT', None, None)
apwce9abe92006-04-27 14:14:04 +0000695 myjob.complete(1)
apwb832e1b2007-11-24 20:24:38 +0000696 else:
697 sys.exit(1)
apwce9abe92006-04-27 14:14:04 +0000698
mblighc3430162007-11-14 23:57:19 +0000699 except Exception, e:
mbligh51144e02007-11-20 20:38:18 +0000700 msg = str(e) + '\n' + format_error()
mblighc3430162007-11-14 23:57:19 +0000701 print "JOB ERROR: " + msg
mblighfbfb77d2007-02-15 18:54:03 +0000702 if myjob:
mblighc3430162007-11-14 23:57:19 +0000703 myjob.group_level = 0
704 myjob.record('ABORT', None, None, msg)
705 myjob.record('END ABORT', None, None)
mbligh9c5ac322007-10-31 18:01:59 +0000706 myjob.complete(1)
apwb832e1b2007-11-24 20:24:38 +0000707 else:
708 sys.exit(1)
mbligh892d37f2007-03-01 17:03:25 +0000709
710 # If we get here, then we assume the job is complete and good.
mblighc3430162007-11-14 23:57:19 +0000711 myjob.group_level = 0
712 myjob.record('END GOOD', None, None)
mblighbf79bba2008-03-03 16:02:37 +0000713 df_root = system_output('df -m / | tail -1').split()
714 free_space_mb_root_after = int(df_root[3])
715 if myjob.free_space_mb_root_before - free_space_mb_root_after > 5:
716 myjob.record('WARN', 'Check disk usage', 'disk usage on root is greater than 5Mb')
mbligh892d37f2007-03-01 17:03:25 +0000717 myjob.complete(0)
mbligh68119582008-01-25 18:16:41 +0000718