blob: 6d8042819ebdbd67b8f59bf82e893410b15c7098 [file] [log] [blame]
mblighf1c52842007-10-16 15:21:38 +00001"""
2The main job wrapper for the server side.
3
4This is the core infrastructure. Derived from the client side job.py
5
6Copyright Martin J. Bligh, Andy Whitcroft 2007
7"""
8
9__author__ = """
10Martin J. Bligh <mbligh@google.com>
11Andy Whitcroft <apw@shadowen.org>
12"""
13
mblighf4e04152008-02-21 16:05:53 +000014import os, sys, re, time, select
mbligh03f4fc72007-11-29 20:56:14 +000015import test
mblighf1c52842007-10-16 15:21:38 +000016from utils import *
mblighf31b0c02007-11-29 18:19:22 +000017from common.error import *
mblighf1c52842007-10-16 15:21:38 +000018
mbligh3f4bced2007-11-05 17:55:53 +000019# this magic incantation should give us access to a client library
20server_dir = os.path.dirname(__file__)
21client_dir = os.path.join(server_dir, "..", "client", "bin")
22sys.path.append(client_dir)
23import fd_stack
24sys.path.pop()
25
mblighed5a4102007-11-20 00:46:41 +000026# load up a control segment
27# these are all stored in <server_dir>/control_segments
28def load_control_segment(name):
29 server_dir = os.path.dirname(os.path.abspath(__file__))
mbligh7f86e0b2007-11-24 19:45:07 +000030 script_file = os.path.join(server_dir, "control_segments", name)
mblighed5a4102007-11-20 00:46:41 +000031 if os.path.exists(script_file):
32 return file(script_file).read()
33 else:
34 return ""
35
36
mblighf1c52842007-10-16 15:21:38 +000037preamble = """\
38import os, sys
39
mblighb3c9f372008-01-14 16:39:44 +000040import hosts, autotest, kvm, git, standalone_profiler
mblighd0868ab2007-12-04 22:47:46 +000041import source_kernel, rpm_kernel, deb_kernel, git_kernel
mbligh03f4fc72007-11-29 20:56:14 +000042from common.error import *
mblighe1417fa2007-12-10 16:55:13 +000043from common import barrier
mblighf1c52842007-10-16 15:21:38 +000044from subcommand import *
45from utils import run, get_tmp_dir, sh_escape
46
mbligh119c12a2007-11-12 22:13:44 +000047autotest.Autotest.job = job
mbligh31a49de2007-11-05 18:41:19 +000048hosts.SSHHost.job = job
mblighe1417fa2007-12-10 16:55:13 +000049barrier = barrier.barrier
mblighf1c52842007-10-16 15:21:38 +000050"""
51
52client_wrapper = """
53at = autotest.Autotest()
54
55def run_client(machine):
56 host = hosts.SSHHost(machine)
57 at.run(control, host=host)
58
59if len(machines) > 1:
mbligh7b32ba32007-11-05 18:14:20 +000060 open('.machines', 'w').write('\\n'.join(machines) + '\\n')
mblighf1c52842007-10-16 15:21:38 +000061 parallel_simple(run_client, machines)
62else:
63 run_client(machines[0])
64"""
65
mbligh303ccac2007-11-05 18:07:28 +000066crashdumps = """
67def crashdumps(machine):
68 host = hosts.SSHHost(machine, initialize=False)
69 host.get_crashdumps(test_start_time)
70
71parallel_simple(crashdumps, machines, log=False)
72"""
73
mbligh98ff1462007-12-19 16:27:55 +000074reboot_segment="""\
75def reboot(machine):
mbligh17f0c662007-11-05 18:28:19 +000076 host = hosts.SSHHost(machine, initialize=False)
77 host.reboot()
mblighf1c52842007-10-16 15:21:38 +000078
mbligh98ff1462007-12-19 16:27:55 +000079parallel_simple(reboot, machines, log=False)
mblighf1c52842007-10-16 15:21:38 +000080"""
81
mblighf36243d2007-10-30 15:36:16 +000082install="""\
83def install(machine):
mbligh17f0c662007-11-05 18:28:19 +000084 host = hosts.SSHHost(machine, initialize=False)
85 host.machine_install()
mblighf36243d2007-10-30 15:36:16 +000086
mbligh009b25a2007-11-05 18:38:51 +000087parallel_simple(install, machines, log=False)
mblighf36243d2007-10-30 15:36:16 +000088"""
89
mbligh7f86e0b2007-11-24 19:45:07 +000090# load up the verifier control segment, with an optional site-specific hook
mblighed5a4102007-11-20 00:46:41 +000091verify = load_control_segment("site_verify")
92verify += load_control_segment("verify")
mbligh1d42d4e2007-11-05 22:42:00 +000093
mbligh7f86e0b2007-11-24 19:45:07 +000094# load up the repair control segment, with an optional site-specific hook
95repair = load_control_segment("site_repair")
96repair += load_control_segment("repair")
97
mbligh1d42d4e2007-11-05 22:42:00 +000098
mbligh970b94e2008-01-24 16:29:34 +000099# load up site-specific code for generating site-specific job data
100try:
101 import site_job
102 get_site_job_data = site_job.get_site_job_data
103 del site_job
104except ImportError:
105 # by default provide a stub that generates no site data
106 def get_site_job_data(job):
107 return {}
108
109
mblighf1c52842007-10-16 15:21:38 +0000110class server_job:
111 """The actual job against which we do everything.
112
113 Properties:
114 autodir
115 The top level autotest directory (/usr/local/autotest).
116 serverdir
117 <autodir>/server/
118 clientdir
119 <autodir>/client/
120 conmuxdir
121 <autodir>/conmux/
122 testdir
123 <autodir>/server/tests/
124 control
125 the control file for this job
126 """
127
mblighe8b37a92007-12-19 15:54:11 +0000128 def __init__(self, control, args, resultdir, label, user, machines,
129 client = False):
mblighf1c52842007-10-16 15:21:38 +0000130 """
131 control
132 The control file (pathname of)
133 args
134 args to pass to the control file
135 resultdir
136 where to throw the results
mbligh18420c22007-10-16 22:27:14 +0000137 label
138 label for the job
mblighf1c52842007-10-16 15:21:38 +0000139 user
140 Username for the job (email address)
141 client
142 True if a client-side control file
143 """
mbligh05269362007-10-16 16:58:11 +0000144 path = os.path.dirname(sys.modules['server_job'].__file__)
mblighf1c52842007-10-16 15:21:38 +0000145 self.autodir = os.path.abspath(os.path.join(path, '..'))
146 self.serverdir = os.path.join(self.autodir, 'server')
mbligh05269362007-10-16 16:58:11 +0000147 self.testdir = os.path.join(self.serverdir, 'tests')
148 self.tmpdir = os.path.join(self.serverdir, 'tmp')
mblighf1c52842007-10-16 15:21:38 +0000149 self.conmuxdir = os.path.join(self.autodir, 'conmux')
150 self.clientdir = os.path.join(self.autodir, 'client')
mblighe25fd5b2008-01-22 17:23:37 +0000151 if control:
152 self.control = open(control, 'r').read()
153 self.control = re.sub('\r', '', self.control)
154 else:
155 self.control = None
mblighf1c52842007-10-16 15:21:38 +0000156 self.resultdir = resultdir
157 if not os.path.exists(resultdir):
158 os.mkdir(resultdir)
mbligh3ccb8592007-11-05 18:13:40 +0000159 self.debugdir = os.path.join(resultdir, 'debug')
160 if not os.path.exists(self.debugdir):
161 os.mkdir(self.debugdir)
mbligh3dcf2c92007-10-16 22:24:00 +0000162 self.status = os.path.join(resultdir, 'status')
mbligh18420c22007-10-16 22:27:14 +0000163 self.label = label
mblighf1c52842007-10-16 15:21:38 +0000164 self.user = user
165 self.args = args
mblighe8b37a92007-12-19 15:54:11 +0000166 self.machines = machines
mblighf1c52842007-10-16 15:21:38 +0000167 self.client = client
168 self.record_prefix = ''
mblighf4e04152008-02-21 16:05:53 +0000169 self.warning_loggers = set()
mblighf1c52842007-10-16 15:21:38 +0000170
mbligh3f4bced2007-11-05 17:55:53 +0000171 self.stdout = fd_stack.fd_stack(1, sys.stdout)
172 self.stderr = fd_stack.fd_stack(2, sys.stderr)
173
mbligh3dcf2c92007-10-16 22:24:00 +0000174 if os.path.exists(self.status):
175 os.unlink(self.status)
mblighe8b37a92007-12-19 15:54:11 +0000176 job_data = { 'label' : label, 'user' : user,
177 'hostname' : ','.join(machines) }
mbligh970b94e2008-01-24 16:29:34 +0000178 job_data.update(get_site_job_data(self))
mblighf1c52842007-10-16 15:21:38 +0000179 write_keyval(self.resultdir, job_data)
180
181
mblighe25fd5b2008-01-22 17:23:37 +0000182 def verify(self):
183 if not self.machines:
184 raise AutoservError('No machines specified to verify')
185 try:
186 namespace = {'machines' : self.machines, 'job' : self}
187 exec(preamble + verify, namespace, namespace)
188 except Exception, e:
189 msg = 'Verify failed\n' + str(e) + '\n' + format_error()
190 self.record('ABORT', None, None, msg)
191 raise
192
193
194 def repair(self):
195 if not self.machines:
196 raise AutoservError('No machines specified to repair')
197 namespace = {'machines' : self.machines, 'job' : self}
198 exec(preamble + repair, namespace, namespace)
mbligh8141f862008-01-25 17:20:40 +0000199 self.verify()
mblighe25fd5b2008-01-22 17:23:37 +0000200
201
mblighe8b37a92007-12-19 15:54:11 +0000202 def run(self, reboot = False, install_before = False,
mblighf36243d2007-10-30 15:36:16 +0000203 install_after = False, namespace = {}):
mbligh60dbd502007-10-26 14:59:31 +0000204 # use a copy so changes don't affect the original dictionary
205 namespace = namespace.copy()
mblighe8b37a92007-12-19 15:54:11 +0000206 machines = self.machines
mbligh60dbd502007-10-26 14:59:31 +0000207
mblighfaf0cd42007-11-19 16:00:24 +0000208 self.aborted = False
mblighf1c52842007-10-16 15:21:38 +0000209 namespace['machines'] = machines
210 namespace['args'] = self.args
211 namespace['job'] = self
mbligh6e294382007-11-05 18:11:29 +0000212 test_start_time = int(time.time())
mblighf1c52842007-10-16 15:21:38 +0000213
mbligh87c5d882007-10-29 17:07:24 +0000214 os.chdir(self.resultdir)
215
216 status_log = os.path.join(self.resultdir, 'status.log')
mblighf1c52842007-10-16 15:21:38 +0000217 try:
mblighf36243d2007-10-30 15:36:16 +0000218 if install_before and machines:
219 exec(preamble + install, namespace, namespace)
mblighf1c52842007-10-16 15:21:38 +0000220 if self.client:
221 namespace['control'] = self.control
222 open('control', 'w').write(self.control)
223 open('control.srv', 'w').write(client_wrapper)
224 server_control = client_wrapper
225 else:
226 open('control.srv', 'w').write(self.control)
227 server_control = self.control
mblighf1c52842007-10-16 15:21:38 +0000228 exec(preamble + server_control, namespace, namespace)
229
230 finally:
mbligh6e294382007-11-05 18:11:29 +0000231 if machines:
232 namespace['test_start_time'] = test_start_time
mbligh98ff1462007-12-19 16:27:55 +0000233 exec(preamble + crashdumps,
234 namespace, namespace)
mblighf1c52842007-10-16 15:21:38 +0000235 if reboot and machines:
mbligh98ff1462007-12-19 16:27:55 +0000236 exec(preamble + reboot_segment,
237 namespace, namespace)
mblighf36243d2007-10-30 15:36:16 +0000238 if install_after and machines:
239 exec(preamble + install, namespace, namespace)
mblighf1c52842007-10-16 15:21:38 +0000240
241
242 def run_test(self, url, *args, **dargs):
243 """Summon a test object and run it.
244
245 tag
246 tag to add to testname
247 url
248 url of the test to run
249 """
250
mblighf1c52842007-10-16 15:21:38 +0000251 (group, testname) = test.testname(url)
252 tag = None
253 subdir = testname
mbligh43ac5222007-10-16 15:55:01 +0000254
mblighf1c52842007-10-16 15:21:38 +0000255 if dargs.has_key('tag'):
256 tag = dargs['tag']
257 del dargs['tag']
258 if tag:
259 subdir += '.' + tag
mblighf1c52842007-10-16 15:21:38 +0000260
mbligh43ac5222007-10-16 15:55:01 +0000261 try:
262 test.runtest(self, url, tag, args, dargs)
263 self.record('GOOD', subdir, testname, 'completed successfully')
264 except Exception, detail:
mbligh05269362007-10-16 16:58:11 +0000265 self.record('FAIL', subdir, testname, format_error())
mblighf1c52842007-10-16 15:21:38 +0000266
267
268 def run_group(self, function, *args, **dargs):
269 """\
270 function:
271 subroutine to run
272 *args:
273 arguments for the function
274 """
275
276 result = None
277 name = function.__name__
278
279 # Allow the tag for the group to be specified.
280 if dargs.has_key('tag'):
281 tag = dargs['tag']
282 del dargs['tag']
283 if tag:
284 name = tag
285
286 # if tag:
287 # name += '.' + tag
288 old_record_prefix = self.record_prefix
289 try:
290 try:
291 self.record('START', None, name)
292 self.record_prefix += '\t'
293 result = function(*args, **dargs)
294 self.record_prefix = old_record_prefix
295 self.record('END GOOD', None, name)
296 except:
297 self.record_prefix = old_record_prefix
298 self.record('END FAIL', None, name, format_error())
299 # We don't want to raise up an error higher if it's just
300 # a TestError - we want to carry on to other tests. Hence
301 # this outer try/except block.
302 except TestError:
303 pass
304 except:
305 raise TestError(name + ' failed\n' + format_error())
306
307 return result
308
309
mblighf4e04152008-02-21 16:05:53 +0000310 def record(self, status_code, subdir, operation, status=''):
mblighf1c52842007-10-16 15:21:38 +0000311 """
312 Record job-level status
313
314 The intent is to make this file both machine parseable and
315 human readable. That involves a little more complexity, but
316 really isn't all that bad ;-)
317
318 Format is <status code>\t<subdir>\t<operation>\t<status>
319
320 status code: (GOOD|WARN|FAIL|ABORT)
321 or START
322 or END (GOOD|WARN|FAIL|ABORT)
323
324 subdir: MUST be a relevant subdirectory in the results,
325 or None, which will be represented as '----'
326
327 operation: description of what you ran (e.g. "dbench", or
328 "mkfs -t foobar /dev/sda9")
329
330 status: error message or "completed sucessfully"
331
332 ------------------------------------------------------------
333
334 Initial tabs indicate indent levels for grouping, and is
335 governed by self.record_prefix
336
337 multiline messages have secondary lines prefaced by a double
338 space (' ')
mblighf4e04152008-02-21 16:05:53 +0000339
340 Executing this method will trigger the logging of all new
341 warnings to date from the various console loggers.
342 """
343 # poll the loggers for any new console warnings to log
344 warnings = []
345 while True:
346 # pull in a line of output from every logger that has
347 # output ready to be read
348 loggers, _, _ = select.select(self.warning_loggers,
349 [], [], 0)
350 closed_loggers = set()
351 for logger in loggers:
352 line = logger.readline()
353 # record any broken pipes (aka line == empty)
354 if len(line) == 0:
355 closed_loggers.add(logger)
356 continue
357 timestamp, msg = line.split('\t', 1)
358 warnings.append((int(timestamp), msg.strip()))
359
360 # stop listening to loggers that are closed
361 self.warning_loggers -= closed_loggers
362
363 # stop if none of the loggers have any output left
364 if not loggers:
365 break
366
367 # write out all of the warnings we accumulated
368 warnings.sort() # sort into timestamp order
369 for timestamp, msg in warnings:
370 self.__record("WARN", None, None, msg, timestamp)
371
372 # write out the actual status log line
373 self.__record(status_code, subdir, operation, status)
374
375
376 def __record(self, status_code, subdir, operation, status='',
377 epoch_time=None):
378 """
379 Actual function for recording a single line into the status
380 logs. Should never be called directly, only by job.record as
381 this would bypass the console monitor logging.
mblighf1c52842007-10-16 15:21:38 +0000382 """
383
384 if subdir:
385 if re.match(r'[\n\t]', subdir):
mbligh4d6feff2008-01-14 16:48:56 +0000386 raise ValueError('Invalid character in subdir string')
mblighf1c52842007-10-16 15:21:38 +0000387 substr = subdir
388 else:
389 substr = '----'
390
391 if not re.match(r'(START|(END )?(GOOD|WARN|FAIL|ABORT))$', \
392 status_code):
mbligh4d6feff2008-01-14 16:48:56 +0000393 raise ValueError('Invalid status code supplied: %s' % status_code)
mblighe25fd5b2008-01-22 17:23:37 +0000394 if not operation:
395 operation = '----'
mblighf1c52842007-10-16 15:21:38 +0000396 if re.match(r'[\n\t]', operation):
mbligh4d6feff2008-01-14 16:48:56 +0000397 raise ValueError('Invalid character in operation string')
mblighf1c52842007-10-16 15:21:38 +0000398 operation = operation.rstrip()
399 status = status.rstrip()
400 status = re.sub(r"\t", " ", status)
401 # Ensure any continuation lines are marked so we can
402 # detect them in the status file to ensure it is parsable.
403 status = re.sub(r"\n", "\n" + self.record_prefix + " ", status)
404
mbligh30270302007-11-05 20:33:52 +0000405 # Generate timestamps for inclusion in the logs
mblighf4e04152008-02-21 16:05:53 +0000406 if epoch_time is None:
407 epoch_time = int(time.time())
mbligh30270302007-11-05 20:33:52 +0000408 local_time = time.localtime(epoch_time)
409 epoch_time_str = "timestamp=%d" % (epoch_time,)
410 local_time_str = time.strftime("localtime=%b %d %H:%M:%S",
411 local_time)
412
413 msg = '\t'.join(str(x) for x in (status_code, substr, operation,
414 epoch_time_str, local_time_str,
415 status))
mblighf1c52842007-10-16 15:21:38 +0000416
mbligh31a49de2007-11-05 18:41:19 +0000417 status_file = os.path.join(self.resultdir, 'status.log')
mblighf1c52842007-10-16 15:21:38 +0000418 print msg
419 open(status_file, "a").write(self.record_prefix + msg + "\n")
420 if subdir:
mblighd56eb592008-01-22 16:36:34 +0000421 test_dir = os.path.join(self.resultdir, subdir)
422 if not os.path.exists(test_dir):
423 os.mkdir(test_dir)
424 status_file = os.path.join(test_dir, 'status')
mblighf1c52842007-10-16 15:21:38 +0000425 open(status_file, "a").write(msg + "\n")