blob: be516d104cefd811ca29d5bc1cbaa6966ee87689 [file] [log] [blame]
mbligh36768f02008-02-22 18:28:33 +00001#!/usr/bin/python -u
2
3"""
4Autotest scheduler
5"""
showard909c7a62008-07-15 21:52:38 +00006
mbligh36768f02008-02-22 18:28:33 +00007
showard542e8402008-09-19 20:16:18 +00008import datetime, errno, MySQLdb, optparse, os, pwd, Queue, re, shutil, signal
9import smtplib, socket, stat, subprocess, sys, tempfile, time, traceback
mbligh70feeee2008-06-11 16:20:49 +000010import common
showard21baa452008-10-21 00:08:39 +000011from autotest_lib.frontend import setup_django_environment
showard542e8402008-09-19 20:16:18 +000012from autotest_lib.client.common_lib import global_config
showard2bab8f42008-11-12 18:15:22 +000013from autotest_lib.client.common_lib import host_protections, utils, debug
showardb1e51872008-10-07 11:08:18 +000014from autotest_lib.database import database_connection
showard21baa452008-10-21 00:08:39 +000015from autotest_lib.frontend.afe import models
mbligh70feeee2008-06-11 16:20:49 +000016
mblighb090f142008-02-27 21:33:46 +000017
mbligh36768f02008-02-22 18:28:33 +000018RESULTS_DIR = '.'
19AUTOSERV_NICE_LEVEL = 10
showardb1e51872008-10-07 11:08:18 +000020CONFIG_SECTION = 'AUTOTEST_WEB'
mbligh36768f02008-02-22 18:28:33 +000021
22AUTOTEST_PATH = os.path.join(os.path.dirname(__file__), '..')
23
24if os.environ.has_key('AUTOTEST_DIR'):
jadmanski0afbb632008-06-06 21:10:57 +000025 AUTOTEST_PATH = os.environ['AUTOTEST_DIR']
mbligh36768f02008-02-22 18:28:33 +000026AUTOTEST_SERVER_DIR = os.path.join(AUTOTEST_PATH, 'server')
27AUTOTEST_TKO_DIR = os.path.join(AUTOTEST_PATH, 'tko')
28
29if AUTOTEST_SERVER_DIR not in sys.path:
jadmanski0afbb632008-06-06 21:10:57 +000030 sys.path.insert(0, AUTOTEST_SERVER_DIR)
mbligh36768f02008-02-22 18:28:33 +000031
mblighbb421852008-03-11 22:36:16 +000032AUTOSERV_PID_FILE = '.autoserv_execute'
mbligh90a549d2008-03-25 23:52:34 +000033# how long to wait for autoserv to write a pidfile
34PIDFILE_TIMEOUT = 5 * 60 # 5 min
mblighbb421852008-03-11 22:36:16 +000035
mbligh6f8bab42008-02-29 22:45:14 +000036_db = None
mbligh36768f02008-02-22 18:28:33 +000037_shutdown = False
38_notify_email = None
mbligh4314a712008-02-29 22:44:30 +000039_autoserv_path = 'autoserv'
40_testing_mode = False
showardec113162008-05-08 00:52:49 +000041_global_config_section = 'SCHEDULER'
showard542e8402008-09-19 20:16:18 +000042_base_url = None
43# see os.getlogin() online docs
44_email_from = pwd.getpwuid(os.getuid())[0]
showardc85c21b2008-11-24 22:17:37 +000045_notify_email_statuses = []
mbligh36768f02008-02-22 18:28:33 +000046
47
48def main():
jadmanski0afbb632008-06-06 21:10:57 +000049 usage = 'usage: %prog [options] results_dir'
mbligh36768f02008-02-22 18:28:33 +000050
jadmanski0afbb632008-06-06 21:10:57 +000051 parser = optparse.OptionParser(usage)
52 parser.add_option('--recover-hosts', help='Try to recover dead hosts',
53 action='store_true')
54 parser.add_option('--logfile', help='Set a log file that all stdout ' +
55 'should be redirected to. Stderr will go to this ' +
56 'file + ".err"')
57 parser.add_option('--test', help='Indicate that scheduler is under ' +
58 'test and should use dummy autoserv and no parsing',
59 action='store_true')
60 (options, args) = parser.parse_args()
61 if len(args) != 1:
62 parser.print_usage()
63 return
mbligh36768f02008-02-22 18:28:33 +000064
jadmanski0afbb632008-06-06 21:10:57 +000065 global RESULTS_DIR
66 RESULTS_DIR = args[0]
mbligh36768f02008-02-22 18:28:33 +000067
jadmanski0afbb632008-06-06 21:10:57 +000068 # read in notify_email from global_config
69 c = global_config.global_config
70 global _notify_email
71 val = c.get_config_value(_global_config_section, "notify_email")
72 if val != "":
73 _notify_email = val
mbligh36768f02008-02-22 18:28:33 +000074
showardc85c21b2008-11-24 22:17:37 +000075 global _email_from
76 val = c.get_config_value(_global_config_section, "notify_email_from")
77 if val != "":
78 _email_from = val
79
80 global _notify_email_statuses
81 val = c.get_config_value(_global_config_section, "notify_email_statuses")
82 if val != "":
83 _notify_email_statuses = [status for status in
84 re.split(r'[\s,;:]', val.lower()) if status]
85
showard3bb499f2008-07-03 19:42:20 +000086 tick_pause = c.get_config_value(
87 _global_config_section, 'tick_pause_sec', type=int)
88
jadmanski0afbb632008-06-06 21:10:57 +000089 if options.test:
90 global _autoserv_path
91 _autoserv_path = 'autoserv_dummy'
92 global _testing_mode
93 _testing_mode = True
mbligh36768f02008-02-22 18:28:33 +000094
showard542e8402008-09-19 20:16:18 +000095 # read in base url
96 global _base_url
showardb1e51872008-10-07 11:08:18 +000097 val = c.get_config_value(CONFIG_SECTION, "base_url")
showard542e8402008-09-19 20:16:18 +000098 if val:
99 _base_url = val
100 else:
101 _base_url = "http://your_autotest_server/afe/"
102
jadmanski0afbb632008-06-06 21:10:57 +0000103 init(options.logfile)
104 dispatcher = Dispatcher()
105 dispatcher.do_initial_recovery(recover_hosts=options.recover_hosts)
106
107 try:
108 while not _shutdown:
109 dispatcher.tick()
showard3bb499f2008-07-03 19:42:20 +0000110 time.sleep(tick_pause)
jadmanski0afbb632008-06-06 21:10:57 +0000111 except:
112 log_stacktrace("Uncaught exception; terminating monitor_db")
113
114 email_manager.send_queued_emails()
115 _db.disconnect()
mbligh36768f02008-02-22 18:28:33 +0000116
117
118def handle_sigint(signum, frame):
jadmanski0afbb632008-06-06 21:10:57 +0000119 global _shutdown
120 _shutdown = True
121 print "Shutdown request received."
mbligh36768f02008-02-22 18:28:33 +0000122
123
124def init(logfile):
jadmanski0afbb632008-06-06 21:10:57 +0000125 if logfile:
126 enable_logging(logfile)
127 print "%s> dispatcher starting" % time.strftime("%X %x")
128 print "My PID is %d" % os.getpid()
mbligh36768f02008-02-22 18:28:33 +0000129
showardb1e51872008-10-07 11:08:18 +0000130 if _testing_mode:
131 global_config.global_config.override_config_value(
132 CONFIG_SECTION, 'database', 'stresstest_autotest_web')
133
jadmanski0afbb632008-06-06 21:10:57 +0000134 os.environ['PATH'] = AUTOTEST_SERVER_DIR + ':' + os.environ['PATH']
135 global _db
showardb1e51872008-10-07 11:08:18 +0000136 _db = database_connection.DatabaseConnection(CONFIG_SECTION)
jadmanski0afbb632008-06-06 21:10:57 +0000137 _db.connect()
mbligh36768f02008-02-22 18:28:33 +0000138
showardfa8629c2008-11-04 16:51:23 +0000139 # ensure Django connection is in autocommit
140 setup_django_environment.enable_autocommit()
141
showard2bab8f42008-11-12 18:15:22 +0000142 debug.configure('scheduler', format_string='%(message)s')
143
jadmanski0afbb632008-06-06 21:10:57 +0000144 print "Setting signal handler"
145 signal.signal(signal.SIGINT, handle_sigint)
146
147 print "Connected! Running..."
mbligh36768f02008-02-22 18:28:33 +0000148
149
150def enable_logging(logfile):
jadmanski0afbb632008-06-06 21:10:57 +0000151 out_file = logfile
152 err_file = "%s.err" % logfile
153 print "Enabling logging to %s (%s)" % (out_file, err_file)
154 out_fd = open(out_file, "a", buffering=0)
155 err_fd = open(err_file, "a", buffering=0)
mbligh36768f02008-02-22 18:28:33 +0000156
jadmanski0afbb632008-06-06 21:10:57 +0000157 os.dup2(out_fd.fileno(), sys.stdout.fileno())
158 os.dup2(err_fd.fileno(), sys.stderr.fileno())
mbligh36768f02008-02-22 18:28:33 +0000159
jadmanski0afbb632008-06-06 21:10:57 +0000160 sys.stdout = out_fd
161 sys.stderr = err_fd
mbligh36768f02008-02-22 18:28:33 +0000162
163
mblighd5c95802008-03-05 00:33:46 +0000164def queue_entries_to_abort():
jadmanski0afbb632008-06-06 21:10:57 +0000165 rows = _db.execute("""
166 SELECT * FROM host_queue_entries WHERE status='Abort';
167 """)
showard2bab8f42008-11-12 18:15:22 +0000168
jadmanski0afbb632008-06-06 21:10:57 +0000169 qe = [HostQueueEntry(row=i) for i in rows]
170 return qe
mbligh36768f02008-02-22 18:28:33 +0000171
mblighe2586682008-02-29 22:45:46 +0000172def remove_file_or_dir(path):
jadmanski0afbb632008-06-06 21:10:57 +0000173 if stat.S_ISDIR(os.stat(path).st_mode):
174 # directory
175 shutil.rmtree(path)
176 else:
177 # file
178 os.remove(path)
mblighe2586682008-02-29 22:45:46 +0000179
180
mbligh36768f02008-02-22 18:28:33 +0000181def log_stacktrace(reason):
jadmanski0afbb632008-06-06 21:10:57 +0000182 (type, value, tb) = sys.exc_info()
183 str = "EXCEPTION: %s\n" % reason
184 str += ''.join(traceback.format_exception(type, value, tb))
mbligh36768f02008-02-22 18:28:33 +0000185
jadmanski0afbb632008-06-06 21:10:57 +0000186 sys.stderr.write("\n%s\n" % str)
187 email_manager.enqueue_notify_email("monitor_db exception", str)
mbligh36768f02008-02-22 18:28:33 +0000188
mblighbb421852008-03-11 22:36:16 +0000189
190def get_proc_poll_fn(pid):
jadmanski0afbb632008-06-06 21:10:57 +0000191 proc_path = os.path.join('/proc', str(pid))
192 def poll_fn():
193 if os.path.exists(proc_path):
194 return None
195 return 0 # we can't get a real exit code
196 return poll_fn
mblighbb421852008-03-11 22:36:16 +0000197
198
showardc85c21b2008-11-24 22:17:37 +0000199def send_email(to_string, subject, body):
showard542e8402008-09-19 20:16:18 +0000200 """Mails out emails to the addresses listed in to_string.
201
202 to_string is split into a list which can be delimited by any of:
203 ';', ',', ':' or any whitespace
204 """
205
206 # Create list from string removing empty strings from the list.
207 to_list = [x for x in re.split('\s|,|;|:', to_string) if x]
showard7d182aa2008-09-22 16:17:24 +0000208 if not to_list:
209 return
210
showard542e8402008-09-19 20:16:18 +0000211 msg = "From: %s\nTo: %s\nSubject: %s\n\n%s" % (
showardc85c21b2008-11-24 22:17:37 +0000212 _email_from, ', '.join(to_list), subject, body)
showard7d182aa2008-09-22 16:17:24 +0000213 try:
214 mailer = smtplib.SMTP('localhost')
215 try:
showardc85c21b2008-11-24 22:17:37 +0000216 mailer.sendmail(_email_from, to_list, msg)
showard7d182aa2008-09-22 16:17:24 +0000217 finally:
218 mailer.quit()
219 except Exception, e:
220 print "Sending email failed. Reason: %s" % repr(e)
showard542e8402008-09-19 20:16:18 +0000221
222
mblighbb421852008-03-11 22:36:16 +0000223def kill_autoserv(pid, poll_fn=None):
jadmanski0afbb632008-06-06 21:10:57 +0000224 print 'killing', pid
225 if poll_fn is None:
226 poll_fn = get_proc_poll_fn(pid)
mblighd876f452008-12-03 15:09:17 +0000227 if poll_fn() is None:
jadmanski0afbb632008-06-06 21:10:57 +0000228 os.kill(pid, signal.SIGCONT)
229 os.kill(pid, signal.SIGTERM)
mbligh36768f02008-02-22 18:28:33 +0000230
231
showard2bab8f42008-11-12 18:15:22 +0000232def ensure_directory_exists(directory_path):
233 if not os.path.exists(directory_path):
234 os.makedirs(directory_path)
235
236
showard7cf9a9b2008-05-15 21:15:52 +0000237class EmailNotificationManager(object):
jadmanski0afbb632008-06-06 21:10:57 +0000238 def __init__(self):
239 self._emails = []
showard7cf9a9b2008-05-15 21:15:52 +0000240
jadmanski0afbb632008-06-06 21:10:57 +0000241 def enqueue_notify_email(self, subject, message):
242 if not _notify_email:
243 return
showard7cf9a9b2008-05-15 21:15:52 +0000244
jadmanski0afbb632008-06-06 21:10:57 +0000245 body = 'Subject: ' + subject + '\n'
246 body += "%s / %s / %s\n%s" % (socket.gethostname(),
247 os.getpid(),
248 time.strftime("%X %x"), message)
249 self._emails.append(body)
showard7cf9a9b2008-05-15 21:15:52 +0000250
251
jadmanski0afbb632008-06-06 21:10:57 +0000252 def send_queued_emails(self):
253 if not self._emails:
254 return
255 subject = 'Scheduler notifications from ' + socket.gethostname()
256 separator = '\n' + '-' * 40 + '\n'
257 body = separator.join(self._emails)
showard7cf9a9b2008-05-15 21:15:52 +0000258
showardc85c21b2008-11-24 22:17:37 +0000259 send_email(_notify_email, subject, body)
jadmanski0afbb632008-06-06 21:10:57 +0000260 self._emails = []
showard7cf9a9b2008-05-15 21:15:52 +0000261
262email_manager = EmailNotificationManager()
263
264
showard63a34772008-08-18 19:32:50 +0000265class HostScheduler(object):
266 def _get_ready_hosts(self):
267 # avoid any host with a currently active queue entry against it
268 hosts = Host.fetch(
269 joins='LEFT JOIN host_queue_entries AS active_hqe '
270 'ON (hosts.id = active_hqe.host_id AND '
showardb1e51872008-10-07 11:08:18 +0000271 'active_hqe.active)',
showard63a34772008-08-18 19:32:50 +0000272 where="active_hqe.host_id IS NULL "
showardb1e51872008-10-07 11:08:18 +0000273 "AND NOT hosts.locked "
showard63a34772008-08-18 19:32:50 +0000274 "AND (hosts.status IS NULL OR hosts.status = 'Ready')")
275 return dict((host.id, host) for host in hosts)
276
277
278 @staticmethod
279 def _get_sql_id_list(id_list):
280 return ','.join(str(item_id) for item_id in id_list)
281
282
283 @classmethod
showard989f25d2008-10-01 11:38:11 +0000284 def _get_many2many_dict(cls, query, id_list, flip=False):
mbligh849a0f62008-08-28 20:12:19 +0000285 if not id_list:
286 return {}
showard63a34772008-08-18 19:32:50 +0000287 query %= cls._get_sql_id_list(id_list)
288 rows = _db.execute(query)
showard989f25d2008-10-01 11:38:11 +0000289 return cls._process_many2many_dict(rows, flip)
290
291
292 @staticmethod
293 def _process_many2many_dict(rows, flip=False):
showard63a34772008-08-18 19:32:50 +0000294 result = {}
295 for row in rows:
296 left_id, right_id = long(row[0]), long(row[1])
showard989f25d2008-10-01 11:38:11 +0000297 if flip:
298 left_id, right_id = right_id, left_id
showard63a34772008-08-18 19:32:50 +0000299 result.setdefault(left_id, set()).add(right_id)
300 return result
301
302
303 @classmethod
304 def _get_job_acl_groups(cls, job_ids):
305 query = """
306 SELECT jobs.id, acl_groups_users.acl_group_id
307 FROM jobs
308 INNER JOIN users ON users.login = jobs.owner
309 INNER JOIN acl_groups_users ON acl_groups_users.user_id = users.id
310 WHERE jobs.id IN (%s)
311 """
312 return cls._get_many2many_dict(query, job_ids)
313
314
315 @classmethod
316 def _get_job_ineligible_hosts(cls, job_ids):
317 query = """
318 SELECT job_id, host_id
319 FROM ineligible_host_queues
320 WHERE job_id IN (%s)
321 """
322 return cls._get_many2many_dict(query, job_ids)
323
324
325 @classmethod
showard989f25d2008-10-01 11:38:11 +0000326 def _get_job_dependencies(cls, job_ids):
327 query = """
328 SELECT job_id, label_id
329 FROM jobs_dependency_labels
330 WHERE job_id IN (%s)
331 """
332 return cls._get_many2many_dict(query, job_ids)
333
334
335 @classmethod
showard63a34772008-08-18 19:32:50 +0000336 def _get_host_acls(cls, host_ids):
337 query = """
338 SELECT host_id, acl_group_id
339 FROM acl_groups_hosts
340 WHERE host_id IN (%s)
341 """
342 return cls._get_many2many_dict(query, host_ids)
343
344
345 @classmethod
346 def _get_label_hosts(cls, host_ids):
showardfa8629c2008-11-04 16:51:23 +0000347 if not host_ids:
348 return {}, {}
showard63a34772008-08-18 19:32:50 +0000349 query = """
350 SELECT label_id, host_id
351 FROM hosts_labels
352 WHERE host_id IN (%s)
showard989f25d2008-10-01 11:38:11 +0000353 """ % cls._get_sql_id_list(host_ids)
354 rows = _db.execute(query)
355 labels_to_hosts = cls._process_many2many_dict(rows)
356 hosts_to_labels = cls._process_many2many_dict(rows, flip=True)
357 return labels_to_hosts, hosts_to_labels
358
359
360 @classmethod
361 def _get_labels(cls):
362 return dict((label.id, label) for label in Label.fetch())
showard63a34772008-08-18 19:32:50 +0000363
364
365 def refresh(self, pending_queue_entries):
366 self._hosts_available = self._get_ready_hosts()
367
368 relevant_jobs = [queue_entry.job_id
369 for queue_entry in pending_queue_entries]
370 self._job_acls = self._get_job_acl_groups(relevant_jobs)
371 self._ineligible_hosts = self._get_job_ineligible_hosts(relevant_jobs)
showard989f25d2008-10-01 11:38:11 +0000372 self._job_dependencies = self._get_job_dependencies(relevant_jobs)
showard63a34772008-08-18 19:32:50 +0000373
374 host_ids = self._hosts_available.keys()
375 self._host_acls = self._get_host_acls(host_ids)
showard989f25d2008-10-01 11:38:11 +0000376 self._label_hosts, self._host_labels = self._get_label_hosts(host_ids)
377
378 self._labels = self._get_labels()
showard63a34772008-08-18 19:32:50 +0000379
380
381 def _is_acl_accessible(self, host_id, queue_entry):
382 job_acls = self._job_acls.get(queue_entry.job_id, set())
383 host_acls = self._host_acls.get(host_id, set())
384 return len(host_acls.intersection(job_acls)) > 0
385
386
showard989f25d2008-10-01 11:38:11 +0000387 def _check_job_dependencies(self, job_dependencies, host_labels):
388 missing = job_dependencies - host_labels
389 return len(job_dependencies - host_labels) == 0
390
391
392 def _check_only_if_needed_labels(self, job_dependencies, host_labels,
393 queue_entry):
394 for label_id in host_labels:
395 label = self._labels[label_id]
396 if not label.only_if_needed:
397 # we don't care about non-only_if_needed labels
398 continue
399 if queue_entry.meta_host == label_id:
400 # if the label was requested in a metahost it's OK
401 continue
402 if label_id not in job_dependencies:
403 return False
404 return True
405
406
407 def _is_host_eligible_for_job(self, host_id, queue_entry):
408 job_dependencies = self._job_dependencies.get(queue_entry.job_id, set())
409 host_labels = self._host_labels.get(host_id, set())
mblighc993bee2008-10-03 03:42:34 +0000410
411 acl = self._is_acl_accessible(host_id, queue_entry)
412 deps = self._check_job_dependencies(job_dependencies, host_labels)
413 only_if = self._check_only_if_needed_labels(job_dependencies,
414 host_labels, queue_entry)
415 return acl and deps and only_if
showard989f25d2008-10-01 11:38:11 +0000416
417
showard63a34772008-08-18 19:32:50 +0000418 def _schedule_non_metahost(self, queue_entry):
showard989f25d2008-10-01 11:38:11 +0000419 if not self._is_host_eligible_for_job(queue_entry.host_id, queue_entry):
showard63a34772008-08-18 19:32:50 +0000420 return None
421 return self._hosts_available.pop(queue_entry.host_id, None)
422
423
424 def _is_host_usable(self, host_id):
425 if host_id not in self._hosts_available:
426 # host was already used during this scheduling cycle
427 return False
428 if self._hosts_available[host_id].invalid:
429 # Invalid hosts cannot be used for metahosts. They're included in
430 # the original query because they can be used by non-metahosts.
431 return False
432 return True
433
434
435 def _schedule_metahost(self, queue_entry):
436 label_id = queue_entry.meta_host
437 hosts_in_label = self._label_hosts.get(label_id, set())
438 ineligible_host_ids = self._ineligible_hosts.get(queue_entry.job_id,
439 set())
440
441 # must iterate over a copy so we can mutate the original while iterating
442 for host_id in list(hosts_in_label):
443 if not self._is_host_usable(host_id):
444 hosts_in_label.remove(host_id)
445 continue
446 if host_id in ineligible_host_ids:
447 continue
showard989f25d2008-10-01 11:38:11 +0000448 if not self._is_host_eligible_for_job(host_id, queue_entry):
showard63a34772008-08-18 19:32:50 +0000449 continue
450
451 hosts_in_label.remove(host_id)
452 return self._hosts_available.pop(host_id)
453 return None
454
455
456 def find_eligible_host(self, queue_entry):
457 if not queue_entry.meta_host:
458 return self._schedule_non_metahost(queue_entry)
459 return self._schedule_metahost(queue_entry)
460
461
mbligh36768f02008-02-22 18:28:33 +0000462class Dispatcher:
jadmanski0afbb632008-06-06 21:10:57 +0000463 autoserv_procs_cache = None
showard4c5374f2008-09-04 17:02:56 +0000464 max_running_processes = global_config.global_config.get_config_value(
jadmanski0afbb632008-06-06 21:10:57 +0000465 _global_config_section, 'max_running_jobs', type=int)
showard4c5374f2008-09-04 17:02:56 +0000466 max_processes_started_per_cycle = (
jadmanski0afbb632008-06-06 21:10:57 +0000467 global_config.global_config.get_config_value(
468 _global_config_section, 'max_jobs_started_per_cycle', type=int))
showard3bb499f2008-07-03 19:42:20 +0000469 clean_interval = (
470 global_config.global_config.get_config_value(
471 _global_config_section, 'clean_interval_minutes', type=int))
showard98863972008-10-29 21:14:56 +0000472 synch_job_start_timeout_minutes = (
473 global_config.global_config.get_config_value(
474 _global_config_section, 'synch_job_start_timeout_minutes',
475 type=int))
mbligh90a549d2008-03-25 23:52:34 +0000476
jadmanski0afbb632008-06-06 21:10:57 +0000477 def __init__(self):
478 self._agents = []
showard3bb499f2008-07-03 19:42:20 +0000479 self._last_clean_time = time.time()
showard63a34772008-08-18 19:32:50 +0000480 self._host_scheduler = HostScheduler()
mbligh36768f02008-02-22 18:28:33 +0000481
mbligh36768f02008-02-22 18:28:33 +0000482
jadmanski0afbb632008-06-06 21:10:57 +0000483 def do_initial_recovery(self, recover_hosts=True):
484 # always recover processes
485 self._recover_processes()
mblighbb421852008-03-11 22:36:16 +0000486
jadmanski0afbb632008-06-06 21:10:57 +0000487 if recover_hosts:
488 self._recover_hosts()
mbligh36768f02008-02-22 18:28:33 +0000489
490
jadmanski0afbb632008-06-06 21:10:57 +0000491 def tick(self):
492 Dispatcher.autoserv_procs_cache = None
showarda3ab0d52008-11-03 19:03:47 +0000493 self._run_cleanup_maybe()
jadmanski0afbb632008-06-06 21:10:57 +0000494 self._find_aborting()
495 self._schedule_new_jobs()
496 self._handle_agents()
jadmanski0afbb632008-06-06 21:10:57 +0000497 email_manager.send_queued_emails()
mbligh36768f02008-02-22 18:28:33 +0000498
showard97aed502008-11-04 02:01:24 +0000499
showarda3ab0d52008-11-03 19:03:47 +0000500 def _run_cleanup_maybe(self):
501 if self._last_clean_time + self.clean_interval * 60 < time.time():
502 print 'Running cleanup'
503 self._abort_timed_out_jobs()
504 self._abort_jobs_past_synch_start_timeout()
505 self._clear_inactive_blocks()
showardfa8629c2008-11-04 16:51:23 +0000506 self._check_for_db_inconsistencies()
showarda3ab0d52008-11-03 19:03:47 +0000507 self._last_clean_time = time.time()
508
mbligh36768f02008-02-22 18:28:33 +0000509
jadmanski0afbb632008-06-06 21:10:57 +0000510 def add_agent(self, agent):
511 self._agents.append(agent)
512 agent.dispatcher = self
mblighd5c95802008-03-05 00:33:46 +0000513
jadmanski0afbb632008-06-06 21:10:57 +0000514 # Find agent corresponding to the specified queue_entry
515 def get_agents(self, queue_entry):
516 res_agents = []
517 for agent in self._agents:
518 if queue_entry.id in agent.queue_entry_ids:
519 res_agents.append(agent)
520 return res_agents
mbligh36768f02008-02-22 18:28:33 +0000521
522
jadmanski0afbb632008-06-06 21:10:57 +0000523 def remove_agent(self, agent):
524 self._agents.remove(agent)
showardec113162008-05-08 00:52:49 +0000525
526
showard4c5374f2008-09-04 17:02:56 +0000527 def num_running_processes(self):
528 return sum(agent.num_processes for agent in self._agents
529 if agent.is_running())
mblighbb421852008-03-11 22:36:16 +0000530
531
jadmanski0afbb632008-06-06 21:10:57 +0000532 @classmethod
533 def find_autoservs(cls, orphans_only=False):
534 """\
535 Returns a dict mapping pids to command lines for root autoserv
536 processes. If orphans_only=True, return only processes that
537 have been orphaned (i.e. parent pid = 1).
538 """
539 if cls.autoserv_procs_cache is not None:
540 return cls.autoserv_procs_cache
541
542 proc = subprocess.Popen(
543 ['/bin/ps', 'x', '-o', 'pid,pgid,ppid,comm,args'],
544 stdout=subprocess.PIPE)
545 # split each line into the four columns output by ps
546 procs = [line.split(None, 4) for line in
547 proc.communicate()[0].splitlines()]
548 autoserv_procs = {}
549 for proc in procs:
550 # check ppid == 1 for orphans
551 if orphans_only and proc[2] != 1:
552 continue
553 # only root autoserv processes have pgid == pid
554 if (proc[3] == 'autoserv' and # comm
555 proc[1] == proc[0]): # pgid == pid
556 # map pid to args
557 autoserv_procs[int(proc[0])] = proc[4]
558 cls.autoserv_procs_cache = autoserv_procs
559 return autoserv_procs
mblighbb421852008-03-11 22:36:16 +0000560
561
showard2bab8f42008-11-12 18:15:22 +0000562 def _recover_queue_entries(self, queue_entries, run_monitor):
563 assert len(queue_entries) > 0
564 queue_entry_ids = [entry.id for entry in queue_entries]
565 queue_task = RecoveryQueueTask(job=queue_entries[0].job,
566 queue_entries=queue_entries,
567 run_monitor=run_monitor)
jadmanski0afbb632008-06-06 21:10:57 +0000568 self.add_agent(Agent(tasks=[queue_task],
showard2bab8f42008-11-12 18:15:22 +0000569 queue_entry_ids=queue_entry_ids))
mblighbb421852008-03-11 22:36:16 +0000570
571
jadmanski0afbb632008-06-06 21:10:57 +0000572 def _recover_processes(self):
573 orphans = self.find_autoservs(orphans_only=True)
mblighbb421852008-03-11 22:36:16 +0000574
jadmanski0afbb632008-06-06 21:10:57 +0000575 # first, recover running queue entries
576 rows = _db.execute("""SELECT * FROM host_queue_entries
577 WHERE status = 'Running'""")
578 queue_entries = [HostQueueEntry(row=i) for i in rows]
579 requeue_entries = []
580 recovered_entry_ids = set()
581 for queue_entry in queue_entries:
showard2bab8f42008-11-12 18:15:22 +0000582 run_monitor = PidfileRunMonitor(queue_entry.results_dir())
showard21baa452008-10-21 00:08:39 +0000583 if not run_monitor.has_pid():
jadmanski0afbb632008-06-06 21:10:57 +0000584 # autoserv apparently never got run, so requeue
585 requeue_entries.append(queue_entry)
586 continue
587 if queue_entry.id in recovered_entry_ids:
588 # synchronous job we've already recovered
589 continue
showard2bab8f42008-11-12 18:15:22 +0000590 job_tag = queue_entry.job.get_job_tag([queue_entry])
showard21baa452008-10-21 00:08:39 +0000591 pid = run_monitor.get_pid()
showard2bab8f42008-11-12 18:15:22 +0000592 print 'Recovering %s (pid %d)' % (queue_entry.id, pid)
showarde788ea62008-11-17 21:02:47 +0000593 queue_entries = queue_entry.job.get_group_entries(queue_entry)
showard2bab8f42008-11-12 18:15:22 +0000594 recovered_entry_ids.union(entry.id for entry in queue_entries)
595 self._recover_queue_entries(queue_entries, run_monitor)
jadmanski0afbb632008-06-06 21:10:57 +0000596 orphans.pop(pid, None)
mblighd5c95802008-03-05 00:33:46 +0000597
jadmanski0afbb632008-06-06 21:10:57 +0000598 # and requeue other active queue entries
599 rows = _db.execute("""SELECT * FROM host_queue_entries
600 WHERE active AND NOT complete
601 AND status != 'Running'
602 AND status != 'Pending'
603 AND status != 'Abort'
604 AND status != 'Aborting'""")
605 queue_entries = [HostQueueEntry(row=i) for i in rows]
606 for queue_entry in queue_entries + requeue_entries:
607 print 'Requeuing running QE %d' % queue_entry.id
608 queue_entry.clear_results_dir(dont_delete_files=True)
609 queue_entry.requeue()
mbligh90a549d2008-03-25 23:52:34 +0000610
611
jadmanski0afbb632008-06-06 21:10:57 +0000612 # now kill any remaining autoserv processes
613 for pid in orphans.keys():
614 print 'Killing orphan %d (%s)' % (pid, orphans[pid])
615 kill_autoserv(pid)
616
617 # recover aborting tasks
618 rebooting_host_ids = set()
619 rows = _db.execute("""SELECT * FROM host_queue_entries
620 WHERE status='Abort' or status='Aborting'""")
621 queue_entries = [HostQueueEntry(row=i) for i in rows]
622 for queue_entry in queue_entries:
623 print 'Recovering aborting QE %d' % queue_entry.id
showard1be97432008-10-17 15:30:45 +0000624 agent = queue_entry.abort()
625 self.add_agent(agent)
626 if queue_entry.get_host():
627 rebooting_host_ids.add(queue_entry.get_host().id)
jadmanski0afbb632008-06-06 21:10:57 +0000628
showard97aed502008-11-04 02:01:24 +0000629 self._recover_parsing_entries()
630
showard45ae8192008-11-05 19:32:53 +0000631 # reverify hosts that were in the middle of verify, repair or cleanup
jadmanski0afbb632008-06-06 21:10:57 +0000632 self._reverify_hosts_where("""(status = 'Repairing' OR
633 status = 'Verifying' OR
showard45ae8192008-11-05 19:32:53 +0000634 status = 'Cleaning')""",
jadmanski0afbb632008-06-06 21:10:57 +0000635 exclude_ids=rebooting_host_ids)
636
637 # finally, recover "Running" hosts with no active queue entries,
638 # although this should never happen
639 message = ('Recovering running host %s - this probably '
640 'indicates a scheduler bug')
641 self._reverify_hosts_where("""status = 'Running' AND
642 id NOT IN (SELECT host_id
643 FROM host_queue_entries
644 WHERE active)""",
645 print_message=message)
mblighbb421852008-03-11 22:36:16 +0000646
647
jadmanski0afbb632008-06-06 21:10:57 +0000648 def _reverify_hosts_where(self, where,
649 print_message='Reverifying host %s',
650 exclude_ids=set()):
651 rows = _db.execute('SELECT * FROM hosts WHERE locked = 0 AND '
652 'invalid = 0 AND ' + where)
653 hosts = [Host(row=i) for i in rows]
654 for host in hosts:
655 if host.id in exclude_ids:
656 continue
657 if print_message is not None:
658 print print_message % host.hostname
659 verify_task = VerifyTask(host = host)
660 self.add_agent(Agent(tasks = [verify_task]))
mbligh36768f02008-02-22 18:28:33 +0000661
662
showard97aed502008-11-04 02:01:24 +0000663 def _recover_parsing_entries(self):
664 # make sure there are no old parsers running
665 os.system('killall parse')
666
showard2bab8f42008-11-12 18:15:22 +0000667 recovered_entry_ids = set()
showard97aed502008-11-04 02:01:24 +0000668 for entry in HostQueueEntry.fetch(where='status = "Parsing"'):
showard2bab8f42008-11-12 18:15:22 +0000669 if entry.id in recovered_entry_ids:
670 continue
671 queue_entries = entry.job.get_group_entries(entry)
672 recovered_entry_ids.union(entry.id for entry in queue_entries)
showard97aed502008-11-04 02:01:24 +0000673
674 reparse_task = FinalReparseTask(queue_entries)
675 self.add_agent(Agent([reparse_task]))
676
677
jadmanski0afbb632008-06-06 21:10:57 +0000678 def _recover_hosts(self):
679 # recover "Repair Failed" hosts
680 message = 'Reverifying dead host %s'
681 self._reverify_hosts_where("status = 'Repair Failed'",
682 print_message=message)
mbligh62ba2ed2008-04-30 17:09:25 +0000683
684
showard3bb499f2008-07-03 19:42:20 +0000685 def _abort_timed_out_jobs(self):
686 """
687 Aborts all jobs that have timed out and not completed
688 """
showarda3ab0d52008-11-03 19:03:47 +0000689 query = models.Job.objects.filter(hostqueueentry__complete=False).extra(
690 where=['created_on + INTERVAL timeout HOUR < NOW()'])
691 for job in query.distinct():
692 print 'Aborting job %d due to job timeout' % job.id
693 job.abort(None)
showard3bb499f2008-07-03 19:42:20 +0000694
695
showard98863972008-10-29 21:14:56 +0000696 def _abort_jobs_past_synch_start_timeout(self):
697 """
698 Abort synchronous jobs that are past the start timeout (from global
699 config) and are holding a machine that's in everyone.
700 """
701 timeout_delta = datetime.timedelta(
702 minutes=self.synch_job_start_timeout_minutes)
703 timeout_start = datetime.datetime.now() - timeout_delta
704 query = models.Job.objects.filter(
showard98863972008-10-29 21:14:56 +0000705 created_on__lt=timeout_start,
706 hostqueueentry__status='Pending',
707 hostqueueentry__host__acl_group__name='Everyone')
708 for job in query.distinct():
709 print 'Aborting job %d due to start timeout' % job.id
showardff059d72008-12-03 18:18:53 +0000710 entries_to_abort = job.hostqueueentry_set.exclude(
711 status=models.HostQueueEntry.Status.RUNNING)
712 for queue_entry in entries_to_abort:
713 queue_entry.abort(None)
showard98863972008-10-29 21:14:56 +0000714
715
jadmanski0afbb632008-06-06 21:10:57 +0000716 def _clear_inactive_blocks(self):
717 """
718 Clear out blocks for all completed jobs.
719 """
720 # this would be simpler using NOT IN (subquery), but MySQL
721 # treats all IN subqueries as dependent, so this optimizes much
722 # better
723 _db.execute("""
724 DELETE ihq FROM ineligible_host_queues ihq
showard4eaaf522008-06-06 22:28:07 +0000725 LEFT JOIN (SELECT DISTINCT job_id FROM host_queue_entries
jadmanski0afbb632008-06-06 21:10:57 +0000726 WHERE NOT complete) hqe
727 USING (job_id) WHERE hqe.job_id IS NULL""")
showard04c82c52008-05-29 19:38:12 +0000728
729
showardb95b1bd2008-08-15 18:11:04 +0000730 def _get_pending_queue_entries(self):
showard63a34772008-08-18 19:32:50 +0000731 # prioritize by job priority, then non-metahost over metahost, then FIFO
732 return list(HostQueueEntry.fetch(
733 where='NOT complete AND NOT active',
showard3dd6b882008-10-27 19:21:39 +0000734 order_by='priority DESC, meta_host, job_id'))
mbligh36768f02008-02-22 18:28:33 +0000735
736
jadmanski0afbb632008-06-06 21:10:57 +0000737 def _schedule_new_jobs(self):
738 print "finding work"
739
showard63a34772008-08-18 19:32:50 +0000740 queue_entries = self._get_pending_queue_entries()
741 if not queue_entries:
showardb95b1bd2008-08-15 18:11:04 +0000742 return
showardb95b1bd2008-08-15 18:11:04 +0000743
showard63a34772008-08-18 19:32:50 +0000744 self._host_scheduler.refresh(queue_entries)
showardb95b1bd2008-08-15 18:11:04 +0000745
showard63a34772008-08-18 19:32:50 +0000746 for queue_entry in queue_entries:
747 assigned_host = self._host_scheduler.find_eligible_host(queue_entry)
showardb95b1bd2008-08-15 18:11:04 +0000748 if not assigned_host:
jadmanski0afbb632008-06-06 21:10:57 +0000749 continue
showardb95b1bd2008-08-15 18:11:04 +0000750 self._run_queue_entry(queue_entry, assigned_host)
751
752
753 def _run_queue_entry(self, queue_entry, host):
754 agent = queue_entry.run(assigned_host=host)
showard9976ce92008-10-15 20:28:13 +0000755 # in some cases (synchronous jobs with run_verify=False), agent may be None
756 if agent:
757 self.add_agent(agent)
mblighd5c95802008-03-05 00:33:46 +0000758
759
jadmanski0afbb632008-06-06 21:10:57 +0000760 def _find_aborting(self):
761 num_aborted = 0
762 # Find jobs that are aborting
763 for entry in queue_entries_to_abort():
764 agents_to_abort = self.get_agents(entry)
showard1be97432008-10-17 15:30:45 +0000765 for agent in agents_to_abort:
766 self.remove_agent(agent)
767
768 agent = entry.abort(agents_to_abort)
769 self.add_agent(agent)
jadmanski0afbb632008-06-06 21:10:57 +0000770 num_aborted += 1
771 if num_aborted >= 50:
772 break
773
774
showard4c5374f2008-09-04 17:02:56 +0000775 def _can_start_agent(self, agent, num_running_processes,
776 num_started_this_cycle, have_reached_limit):
777 # always allow zero-process agents to run
778 if agent.num_processes == 0:
779 return True
780 # don't allow any nonzero-process agents to run after we've reached a
781 # limit (this avoids starvation of many-process agents)
782 if have_reached_limit:
783 return False
784 # total process throttling
785 if (num_running_processes + agent.num_processes >
786 self.max_running_processes):
787 return False
788 # if a single agent exceeds the per-cycle throttling, still allow it to
789 # run when it's the first agent in the cycle
790 if num_started_this_cycle == 0:
791 return True
792 # per-cycle throttling
793 if (num_started_this_cycle + agent.num_processes >
794 self.max_processes_started_per_cycle):
795 return False
796 return True
797
798
jadmanski0afbb632008-06-06 21:10:57 +0000799 def _handle_agents(self):
showard4c5374f2008-09-04 17:02:56 +0000800 num_running_processes = self.num_running_processes()
jadmanski0afbb632008-06-06 21:10:57 +0000801 num_started_this_cycle = 0
showard4c5374f2008-09-04 17:02:56 +0000802 have_reached_limit = False
803 # iterate over copy, so we can remove agents during iteration
804 for agent in list(self._agents):
805 if agent.is_done():
jadmanski0afbb632008-06-06 21:10:57 +0000806 print "agent finished"
showard4c5374f2008-09-04 17:02:56 +0000807 self._agents.remove(agent)
showard4c5374f2008-09-04 17:02:56 +0000808 continue
809 if not agent.is_running():
810 if not self._can_start_agent(agent, num_running_processes,
811 num_started_this_cycle,
812 have_reached_limit):
813 have_reached_limit = True
814 continue
815 num_running_processes += agent.num_processes
816 num_started_this_cycle += agent.num_processes
817 agent.tick()
818 print num_running_processes, 'running processes'
mbligh36768f02008-02-22 18:28:33 +0000819
820
showardfa8629c2008-11-04 16:51:23 +0000821 def _check_for_db_inconsistencies(self):
822 query = models.HostQueueEntry.objects.filter(active=True, complete=True)
823 if query.count() != 0:
824 subject = ('%d queue entries found with active=complete=1'
825 % query.count())
826 message = '\n'.join(str(entry.get_object_dict())
827 for entry in query[:50])
828 if len(query) > 50:
829 message += '\n(truncated)\n'
830
831 print subject
832 email_manager.enqueue_notify_email(subject, message)
833
834
mbligh36768f02008-02-22 18:28:33 +0000835class RunMonitor(object):
jadmanski0afbb632008-06-06 21:10:57 +0000836 def __init__(self, cmd, nice_level = None, log_file = None):
837 self.nice_level = nice_level
838 self.log_file = log_file
839 self.cmd = cmd
showard2bab8f42008-11-12 18:15:22 +0000840 self.proc = None
mbligh36768f02008-02-22 18:28:33 +0000841
jadmanski0afbb632008-06-06 21:10:57 +0000842 def run(self):
843 if self.nice_level:
844 nice_cmd = ['nice','-n', str(self.nice_level)]
845 nice_cmd.extend(self.cmd)
846 self.cmd = nice_cmd
mbligh36768f02008-02-22 18:28:33 +0000847
jadmanski0afbb632008-06-06 21:10:57 +0000848 out_file = None
849 if self.log_file:
850 try:
851 os.makedirs(os.path.dirname(self.log_file))
852 except OSError, exc:
853 if exc.errno != errno.EEXIST:
854 log_stacktrace(
855 'Unexpected error creating logfile '
856 'directory for %s' % self.log_file)
857 try:
858 out_file = open(self.log_file, 'a')
859 out_file.write("\n%s\n" % ('*'*80))
860 out_file.write("%s> %s\n" %
861 (time.strftime("%X %x"),
862 self.cmd))
863 out_file.write("%s\n" % ('*'*80))
864 except (OSError, IOError):
865 log_stacktrace('Error opening log file %s' %
866 self.log_file)
mblighcadb3532008-04-15 17:46:26 +0000867
jadmanski0afbb632008-06-06 21:10:57 +0000868 if not out_file:
869 out_file = open('/dev/null', 'w')
mblighcadb3532008-04-15 17:46:26 +0000870
jadmanski0afbb632008-06-06 21:10:57 +0000871 in_devnull = open('/dev/null', 'r')
872 print "cmd = %s" % self.cmd
873 print "path = %s" % os.getcwd()
mbligh36768f02008-02-22 18:28:33 +0000874
jadmanski0afbb632008-06-06 21:10:57 +0000875 self.proc = subprocess.Popen(self.cmd, stdout=out_file,
876 stderr=subprocess.STDOUT,
877 stdin=in_devnull)
878 out_file.close()
879 in_devnull.close()
mbligh36768f02008-02-22 18:28:33 +0000880
881
showard2bab8f42008-11-12 18:15:22 +0000882 def has_pid(self):
883 return self.proc is not None
884
885
jadmanski0afbb632008-06-06 21:10:57 +0000886 def get_pid(self):
887 return self.proc.pid
mblighbb421852008-03-11 22:36:16 +0000888
889
jadmanski0afbb632008-06-06 21:10:57 +0000890 def kill(self):
showard2bab8f42008-11-12 18:15:22 +0000891 if self.has_pid():
892 kill_autoserv(self.get_pid(), self.exit_code)
mblighbb421852008-03-11 22:36:16 +0000893
mbligh36768f02008-02-22 18:28:33 +0000894
jadmanski0afbb632008-06-06 21:10:57 +0000895 def exit_code(self):
896 return self.proc.poll()
mbligh36768f02008-02-22 18:28:33 +0000897
898
mblighbb421852008-03-11 22:36:16 +0000899class PidfileException(Exception):
jadmanski0afbb632008-06-06 21:10:57 +0000900 """\
901 Raised when there's some unexpected behavior with the pid file.
902 """
mblighbb421852008-03-11 22:36:16 +0000903
904
905class PidfileRunMonitor(RunMonitor):
showard21baa452008-10-21 00:08:39 +0000906 class PidfileState(object):
907 pid = None
908 exit_status = None
909 num_tests_failed = None
910
911 def reset(self):
912 self.pid = self.exit_status = self.all_tests_passed = None
913
914
jadmanski0afbb632008-06-06 21:10:57 +0000915 def __init__(self, results_dir, cmd=None, nice_level=None,
916 log_file=None):
917 self.results_dir = os.path.abspath(results_dir)
918 self.pid_file = os.path.join(results_dir, AUTOSERV_PID_FILE)
919 self.lost_process = False
920 self.start_time = time.time()
showard21baa452008-10-21 00:08:39 +0000921 self._state = self.PidfileState()
showardb376bc52008-06-13 20:48:45 +0000922 super(PidfileRunMonitor, self).__init__(cmd, nice_level, log_file)
mblighbb421852008-03-11 22:36:16 +0000923
924
showard21baa452008-10-21 00:08:39 +0000925 def has_pid(self):
926 self._get_pidfile_info()
927 return self._state.pid is not None
928
929
jadmanski0afbb632008-06-06 21:10:57 +0000930 def get_pid(self):
showard21baa452008-10-21 00:08:39 +0000931 self._get_pidfile_info()
932 assert self._state.pid is not None
933 return self._state.pid
mblighbb421852008-03-11 22:36:16 +0000934
935
jadmanski0afbb632008-06-06 21:10:57 +0000936 def _check_command_line(self, command_line, spacer=' ',
937 print_error=False):
938 results_dir_arg = spacer.join(('', '-r', self.results_dir, ''))
939 match = results_dir_arg in command_line
940 if print_error and not match:
941 print '%s not found in %s' % (repr(results_dir_arg),
942 repr(command_line))
943 return match
mbligh90a549d2008-03-25 23:52:34 +0000944
945
showard21baa452008-10-21 00:08:39 +0000946 def _check_proc_fs(self):
947 cmdline_path = os.path.join('/proc', str(self._state.pid), 'cmdline')
jadmanski0afbb632008-06-06 21:10:57 +0000948 try:
949 cmdline_file = open(cmdline_path, 'r')
950 cmdline = cmdline_file.read().strip()
951 cmdline_file.close()
952 except IOError:
953 return False
954 # /proc/.../cmdline has \x00 separating args
955 return self._check_command_line(cmdline, spacer='\x00',
956 print_error=True)
mblighbb421852008-03-11 22:36:16 +0000957
958
showard21baa452008-10-21 00:08:39 +0000959 def _read_pidfile(self):
960 self._state.reset()
jadmanski0afbb632008-06-06 21:10:57 +0000961 if not os.path.exists(self.pid_file):
showard21baa452008-10-21 00:08:39 +0000962 return
jadmanski0afbb632008-06-06 21:10:57 +0000963 file_obj = open(self.pid_file, 'r')
964 lines = file_obj.readlines()
965 file_obj.close()
showard3dd6b882008-10-27 19:21:39 +0000966 if not lines:
967 return
968 if len(lines) > 3:
showard21baa452008-10-21 00:08:39 +0000969 raise PidfileException('Corrupt pid file (%d lines) at %s:\n%s' %
970 (len(lines), self.pid_file, lines))
jadmanski0afbb632008-06-06 21:10:57 +0000971 try:
showard21baa452008-10-21 00:08:39 +0000972 self._state.pid = int(lines[0])
973 if len(lines) > 1:
974 self._state.exit_status = int(lines[1])
975 if len(lines) == 3:
976 self._state.num_tests_failed = int(lines[2])
977 else:
978 # maintain backwards-compatibility with two-line pidfiles
979 self._state.num_tests_failed = 0
jadmanski0afbb632008-06-06 21:10:57 +0000980 except ValueError, exc:
showard3dd6b882008-10-27 19:21:39 +0000981 raise PidfileException('Corrupt pid file: ' + str(exc.args))
mblighbb421852008-03-11 22:36:16 +0000982
mblighbb421852008-03-11 22:36:16 +0000983
jadmanski0afbb632008-06-06 21:10:57 +0000984 def _find_autoserv_proc(self):
985 autoserv_procs = Dispatcher.find_autoservs()
986 for pid, args in autoserv_procs.iteritems():
987 if self._check_command_line(args):
988 return pid, args
989 return None, None
mbligh90a549d2008-03-25 23:52:34 +0000990
991
showard21baa452008-10-21 00:08:39 +0000992 def _handle_pidfile_error(self, error, message=''):
993 message = error + '\nPid: %s\nPidfile: %s\n%s' % (self._state.pid,
994 self.pid_file,
995 message)
996 print message
997 email_manager.enqueue_notify_email(error, message)
998 if self._state.pid is not None:
999 pid = self._state.pid
1000 else:
1001 pid = 0
1002 self.on_lost_process(pid)
1003
1004
1005 def _get_pidfile_info_helper(self):
jadmanski0afbb632008-06-06 21:10:57 +00001006 if self.lost_process:
showard21baa452008-10-21 00:08:39 +00001007 return
mblighbb421852008-03-11 22:36:16 +00001008
showard21baa452008-10-21 00:08:39 +00001009 self._read_pidfile()
mblighbb421852008-03-11 22:36:16 +00001010
showard21baa452008-10-21 00:08:39 +00001011 if self._state.pid is None:
1012 self._handle_no_pid()
1013 return
mbligh90a549d2008-03-25 23:52:34 +00001014
showard21baa452008-10-21 00:08:39 +00001015 if self._state.exit_status is None:
jadmanski0afbb632008-06-06 21:10:57 +00001016 # double check whether or not autoserv is running
showard21baa452008-10-21 00:08:39 +00001017 proc_running = self._check_proc_fs()
jadmanski0afbb632008-06-06 21:10:57 +00001018 if proc_running:
showard21baa452008-10-21 00:08:39 +00001019 return
mbligh90a549d2008-03-25 23:52:34 +00001020
jadmanski0afbb632008-06-06 21:10:57 +00001021 # pid but no process - maybe process *just* exited
showard21baa452008-10-21 00:08:39 +00001022 self._read_pidfile()
1023 if self._state.exit_status is None:
jadmanski0afbb632008-06-06 21:10:57 +00001024 # autoserv exited without writing an exit code
1025 # to the pidfile
showard21baa452008-10-21 00:08:39 +00001026 self._handle_pidfile_error(
1027 'autoserv died without writing exit code')
mblighbb421852008-03-11 22:36:16 +00001028
showard21baa452008-10-21 00:08:39 +00001029
1030 def _get_pidfile_info(self):
1031 """\
1032 After completion, self._state will contain:
1033 pid=None, exit_status=None if autoserv has not yet run
1034 pid!=None, exit_status=None if autoserv is running
1035 pid!=None, exit_status!=None if autoserv has completed
1036 """
1037 try:
1038 self._get_pidfile_info_helper()
1039 except PidfileException, exc:
1040 self._handle_pidfile_error('Pidfile error', traceback.format_exc())
mblighbb421852008-03-11 22:36:16 +00001041
1042
jadmanski0afbb632008-06-06 21:10:57 +00001043 def _handle_no_pid(self):
1044 """\
1045 Called when no pidfile is found or no pid is in the pidfile.
1046 """
1047 # is autoserv running?
1048 pid, args = self._find_autoserv_proc()
1049 if pid is None:
1050 # no autoserv process running
1051 message = 'No pid found at ' + self.pid_file
1052 else:
1053 message = ("Process %d (%s) hasn't written pidfile %s" %
1054 (pid, args, self.pid_file))
mbligh90a549d2008-03-25 23:52:34 +00001055
jadmanski0afbb632008-06-06 21:10:57 +00001056 print message
1057 if time.time() - self.start_time > PIDFILE_TIMEOUT:
1058 email_manager.enqueue_notify_email(
1059 'Process has failed to write pidfile', message)
1060 if pid is not None:
1061 kill_autoserv(pid)
1062 else:
1063 pid = 0
1064 self.on_lost_process(pid)
showard21baa452008-10-21 00:08:39 +00001065 return
mbligh90a549d2008-03-25 23:52:34 +00001066
1067
jadmanski0afbb632008-06-06 21:10:57 +00001068 def on_lost_process(self, pid):
1069 """\
1070 Called when autoserv has exited without writing an exit status,
1071 or we've timed out waiting for autoserv to write a pid to the
1072 pidfile. In either case, we just return failure and the caller
1073 should signal some kind of warning.
mbligh90a549d2008-03-25 23:52:34 +00001074
jadmanski0afbb632008-06-06 21:10:57 +00001075 pid is unimportant here, as it shouldn't be used by anyone.
1076 """
1077 self.lost_process = True
showard21baa452008-10-21 00:08:39 +00001078 self._state.pid = pid
1079 self._state.exit_status = 1
1080 self._state.num_tests_failed = 0
mbligh90a549d2008-03-25 23:52:34 +00001081
1082
jadmanski0afbb632008-06-06 21:10:57 +00001083 def exit_code(self):
showard21baa452008-10-21 00:08:39 +00001084 self._get_pidfile_info()
1085 return self._state.exit_status
1086
1087
1088 def num_tests_failed(self):
1089 self._get_pidfile_info()
1090 assert self._state.num_tests_failed is not None
1091 return self._state.num_tests_failed
mblighbb421852008-03-11 22:36:16 +00001092
1093
mbligh36768f02008-02-22 18:28:33 +00001094class Agent(object):
showard4c5374f2008-09-04 17:02:56 +00001095 def __init__(self, tasks, queue_entry_ids=[], num_processes=1):
jadmanski0afbb632008-06-06 21:10:57 +00001096 self.active_task = None
1097 self.queue = Queue.Queue(0)
1098 self.dispatcher = None
1099 self.queue_entry_ids = queue_entry_ids
showard4c5374f2008-09-04 17:02:56 +00001100 self.num_processes = num_processes
jadmanski0afbb632008-06-06 21:10:57 +00001101
1102 for task in tasks:
1103 self.add_task(task)
mbligh36768f02008-02-22 18:28:33 +00001104
1105
jadmanski0afbb632008-06-06 21:10:57 +00001106 def add_task(self, task):
1107 self.queue.put_nowait(task)
1108 task.agent = self
mbligh36768f02008-02-22 18:28:33 +00001109
1110
jadmanski0afbb632008-06-06 21:10:57 +00001111 def tick(self):
showard21baa452008-10-21 00:08:39 +00001112 while not self.is_done():
1113 if self.active_task and not self.active_task.is_done():
1114 self.active_task.poll()
1115 if not self.active_task.is_done():
1116 return
1117 self._next_task()
mbligh36768f02008-02-22 18:28:33 +00001118
1119
jadmanski0afbb632008-06-06 21:10:57 +00001120 def _next_task(self):
1121 print "agent picking task"
1122 if self.active_task:
1123 assert self.active_task.is_done()
mbligh36768f02008-02-22 18:28:33 +00001124
jadmanski0afbb632008-06-06 21:10:57 +00001125 if not self.active_task.success:
1126 self.on_task_failure()
mblighe2586682008-02-29 22:45:46 +00001127
jadmanski0afbb632008-06-06 21:10:57 +00001128 self.active_task = None
1129 if not self.is_done():
1130 self.active_task = self.queue.get_nowait()
1131 if self.active_task:
1132 self.active_task.start()
mbligh36768f02008-02-22 18:28:33 +00001133
1134
jadmanski0afbb632008-06-06 21:10:57 +00001135 def on_task_failure(self):
1136 self.queue = Queue.Queue(0)
1137 for task in self.active_task.failure_tasks:
1138 self.add_task(task)
mbligh16c722d2008-03-05 00:58:44 +00001139
mblighe2586682008-02-29 22:45:46 +00001140
showard4c5374f2008-09-04 17:02:56 +00001141 def is_running(self):
jadmanski0afbb632008-06-06 21:10:57 +00001142 return self.active_task is not None
showardec113162008-05-08 00:52:49 +00001143
1144
jadmanski0afbb632008-06-06 21:10:57 +00001145 def is_done(self):
mblighd876f452008-12-03 15:09:17 +00001146 return self.active_task is None and self.queue.empty()
mbligh36768f02008-02-22 18:28:33 +00001147
1148
jadmanski0afbb632008-06-06 21:10:57 +00001149 def start(self):
1150 assert self.dispatcher
mbligh36768f02008-02-22 18:28:33 +00001151
jadmanski0afbb632008-06-06 21:10:57 +00001152 self._next_task()
mbligh36768f02008-02-22 18:28:33 +00001153
jadmanski0afbb632008-06-06 21:10:57 +00001154
mbligh36768f02008-02-22 18:28:33 +00001155class AgentTask(object):
jadmanski0afbb632008-06-06 21:10:57 +00001156 def __init__(self, cmd, failure_tasks = []):
1157 self.done = False
1158 self.failure_tasks = failure_tasks
1159 self.started = False
1160 self.cmd = cmd
1161 self.task = None
1162 self.agent = None
1163 self.monitor = None
1164 self.success = None
mbligh36768f02008-02-22 18:28:33 +00001165
1166
jadmanski0afbb632008-06-06 21:10:57 +00001167 def poll(self):
1168 print "poll"
1169 if self.monitor:
1170 self.tick(self.monitor.exit_code())
1171 else:
1172 self.finished(False)
mbligh36768f02008-02-22 18:28:33 +00001173
1174
jadmanski0afbb632008-06-06 21:10:57 +00001175 def tick(self, exit_code):
1176 if exit_code==None:
1177 return
1178# print "exit_code was %d" % exit_code
1179 if exit_code == 0:
1180 success = True
1181 else:
1182 success = False
mbligh36768f02008-02-22 18:28:33 +00001183
jadmanski0afbb632008-06-06 21:10:57 +00001184 self.finished(success)
mbligh36768f02008-02-22 18:28:33 +00001185
1186
jadmanski0afbb632008-06-06 21:10:57 +00001187 def is_done(self):
1188 return self.done
mbligh36768f02008-02-22 18:28:33 +00001189
1190
jadmanski0afbb632008-06-06 21:10:57 +00001191 def finished(self, success):
1192 self.done = True
1193 self.success = success
1194 self.epilog()
mbligh36768f02008-02-22 18:28:33 +00001195
1196
jadmanski0afbb632008-06-06 21:10:57 +00001197 def prolog(self):
1198 pass
mblighd64e5702008-04-04 21:39:28 +00001199
1200
jadmanski0afbb632008-06-06 21:10:57 +00001201 def create_temp_resultsdir(self, suffix=''):
1202 self.temp_results_dir = tempfile.mkdtemp(suffix=suffix)
mblighd64e5702008-04-04 21:39:28 +00001203
mbligh36768f02008-02-22 18:28:33 +00001204
jadmanski0afbb632008-06-06 21:10:57 +00001205 def cleanup(self):
1206 if (hasattr(self, 'temp_results_dir') and
1207 os.path.exists(self.temp_results_dir)):
1208 shutil.rmtree(self.temp_results_dir)
mbligh36768f02008-02-22 18:28:33 +00001209
1210
jadmanski0afbb632008-06-06 21:10:57 +00001211 def epilog(self):
1212 self.cleanup()
mbligh36768f02008-02-22 18:28:33 +00001213
1214
jadmanski0afbb632008-06-06 21:10:57 +00001215 def start(self):
1216 assert self.agent
1217
1218 if not self.started:
1219 self.prolog()
1220 self.run()
1221
1222 self.started = True
1223
1224
1225 def abort(self):
1226 if self.monitor:
1227 self.monitor.kill()
1228 self.done = True
1229 self.cleanup()
1230
1231
1232 def run(self):
1233 if self.cmd:
1234 print "agent starting monitor"
1235 log_file = None
showard97aed502008-11-04 02:01:24 +00001236 if hasattr(self, 'log_file'):
1237 log_file = self.log_file
1238 elif hasattr(self, 'host'):
jadmanski0afbb632008-06-06 21:10:57 +00001239 log_file = os.path.join(RESULTS_DIR, 'hosts',
1240 self.host.hostname)
1241 self.monitor = RunMonitor(
showard97aed502008-11-04 02:01:24 +00001242 self.cmd, nice_level=AUTOSERV_NICE_LEVEL, log_file=log_file)
jadmanski0afbb632008-06-06 21:10:57 +00001243 self.monitor.run()
mbligh36768f02008-02-22 18:28:33 +00001244
1245
1246class RepairTask(AgentTask):
showarde788ea62008-11-17 21:02:47 +00001247 def __init__(self, host, queue_entry=None):
jadmanski0afbb632008-06-06 21:10:57 +00001248 """\
1249 fail_queue_entry: queue entry to mark failed if this repair
1250 fails.
1251 """
jadmanskifb7cfb12008-07-09 14:13:21 +00001252 protection = host_protections.Protection.get_string(host.protection)
jadmanski542537f2008-07-24 14:14:56 +00001253 # normalize the protection name
1254 protection = host_protections.Protection.get_attr_name(protection)
jadmanski0afbb632008-06-06 21:10:57 +00001255 self.create_temp_resultsdir('.repair')
1256 cmd = [_autoserv_path , '-R', '-m', host.hostname,
jadmanskifb7cfb12008-07-09 14:13:21 +00001257 '-r', self.temp_results_dir, '--host-protection', protection]
jadmanski0afbb632008-06-06 21:10:57 +00001258 self.host = host
showarde788ea62008-11-17 21:02:47 +00001259 self.queue_entry = queue_entry
jadmanski0afbb632008-06-06 21:10:57 +00001260 super(RepairTask, self).__init__(cmd)
mblighe2586682008-02-29 22:45:46 +00001261
mbligh36768f02008-02-22 18:28:33 +00001262
jadmanski0afbb632008-06-06 21:10:57 +00001263 def prolog(self):
1264 print "repair_task starting"
1265 self.host.set_status('Repairing')
showarde788ea62008-11-17 21:02:47 +00001266 if self.queue_entry:
1267 self.queue_entry.requeue()
mbligh36768f02008-02-22 18:28:33 +00001268
1269
jadmanski0afbb632008-06-06 21:10:57 +00001270 def epilog(self):
1271 super(RepairTask, self).epilog()
1272 if self.success:
1273 self.host.set_status('Ready')
1274 else:
1275 self.host.set_status('Repair Failed')
showarde788ea62008-11-17 21:02:47 +00001276 if self.queue_entry and not self.queue_entry.meta_host:
1277 self.queue_entry.handle_host_failure()
mbligh36768f02008-02-22 18:28:33 +00001278
1279
showard8fe93b52008-11-18 17:53:22 +00001280class PreJobTask(AgentTask):
1281 def prolog(self):
1282 super(PreJobTask, self).prolog()
1283 if self.queue_entry:
1284 # clear any possibly existing results, could be a previously failed
1285 # verify or a previous execution that crashed
1286 self.queue_entry.clear_results_dir()
1287
1288
1289 def cleanup(self):
1290 if not os.path.exists(self.temp_results_dir):
1291 return
1292 should_copy_results = (self.queue_entry and not self.success
1293 and not self.queue_entry.meta_host)
1294 if should_copy_results:
1295 self.queue_entry.set_execution_subdir()
1296 self._move_results()
1297 super(PreJobTask, self).cleanup()
1298
1299
1300 def _move_results(self):
1301 assert self.queue_entry is not None
1302 target_dir = self.queue_entry.results_dir()
1303 ensure_directory_exists(target_dir)
1304 files = os.listdir(self.temp_results_dir)
1305 for filename in files:
1306 if filename == AUTOSERV_PID_FILE:
1307 continue
1308 self._force_move(os.path.join(self.temp_results_dir, filename),
1309 os.path.join(target_dir, filename))
1310
1311
1312 @staticmethod
1313 def _force_move(source, dest):
1314 """\
1315 Replacement for shutil.move() that will delete the destination
1316 if it exists, even if it's a directory.
1317 """
1318 if os.path.exists(dest):
1319 warning = 'Warning: removing existing destination file ' + dest
1320 print warning
1321 email_manager.enqueue_notify_email(warning, warning)
1322 remove_file_or_dir(dest)
1323 shutil.move(source, dest)
1324
1325
1326class VerifyTask(PreJobTask):
showard9976ce92008-10-15 20:28:13 +00001327 def __init__(self, queue_entry=None, host=None):
jadmanski0afbb632008-06-06 21:10:57 +00001328 assert bool(queue_entry) != bool(host)
mbligh36768f02008-02-22 18:28:33 +00001329
jadmanski0afbb632008-06-06 21:10:57 +00001330 self.host = host or queue_entry.host
1331 self.queue_entry = queue_entry
mbligh36768f02008-02-22 18:28:33 +00001332
jadmanski0afbb632008-06-06 21:10:57 +00001333 self.create_temp_resultsdir('.verify')
showard3d9899a2008-07-31 02:11:58 +00001334
showard2bab8f42008-11-12 18:15:22 +00001335 cmd = [_autoserv_path, '-v', '-m', self.host.hostname, '-r',
1336 self.temp_results_dir]
mbligh36768f02008-02-22 18:28:33 +00001337
showarde788ea62008-11-17 21:02:47 +00001338 failure_tasks = [RepairTask(self.host, queue_entry=queue_entry)]
mblighe2586682008-02-29 22:45:46 +00001339
showard2bab8f42008-11-12 18:15:22 +00001340 super(VerifyTask, self).__init__(cmd, failure_tasks=failure_tasks)
mblighe2586682008-02-29 22:45:46 +00001341
1342
jadmanski0afbb632008-06-06 21:10:57 +00001343 def prolog(self):
showard8fe93b52008-11-18 17:53:22 +00001344 super(VerifyTask, self).prolog()
jadmanski0afbb632008-06-06 21:10:57 +00001345 print "starting verify on %s" % (self.host.hostname)
1346 if self.queue_entry:
1347 self.queue_entry.set_status('Verifying')
jadmanski0afbb632008-06-06 21:10:57 +00001348 self.host.set_status('Verifying')
mbligh36768f02008-02-22 18:28:33 +00001349
1350
jadmanski0afbb632008-06-06 21:10:57 +00001351 def epilog(self):
1352 super(VerifyTask, self).epilog()
mbligh36768f02008-02-22 18:28:33 +00001353
jadmanski0afbb632008-06-06 21:10:57 +00001354 if self.success:
1355 self.host.set_status('Ready')
showard2bab8f42008-11-12 18:15:22 +00001356 if self.queue_entry:
1357 agent = self.queue_entry.on_pending()
1358 if agent:
1359 self.agent.dispatcher.add_agent(agent)
mbligh36768f02008-02-22 18:28:33 +00001360
1361
mbligh36768f02008-02-22 18:28:33 +00001362class QueueTask(AgentTask):
jadmanski0afbb632008-06-06 21:10:57 +00001363 def __init__(self, job, queue_entries, cmd):
1364 super(QueueTask, self).__init__(cmd)
1365 self.job = job
1366 self.queue_entries = queue_entries
mbligh36768f02008-02-22 18:28:33 +00001367
1368
jadmanski0afbb632008-06-06 21:10:57 +00001369 @staticmethod
showardd8e548a2008-09-09 03:04:57 +00001370 def _write_keyval(keyval_dir, field, value, keyval_filename='keyval'):
1371 key_path = os.path.join(keyval_dir, keyval_filename)
jadmanski0afbb632008-06-06 21:10:57 +00001372 keyval_file = open(key_path, 'a')
showardd8e548a2008-09-09 03:04:57 +00001373 print >> keyval_file, '%s=%s' % (field, str(value))
jadmanski0afbb632008-06-06 21:10:57 +00001374 keyval_file.close()
mbligh36768f02008-02-22 18:28:33 +00001375
1376
showardd8e548a2008-09-09 03:04:57 +00001377 def _host_keyval_dir(self):
1378 return os.path.join(self.results_dir(), 'host_keyvals')
1379
1380
1381 def _write_host_keyval(self, host):
1382 labels = ','.join(host.labels())
1383 self._write_keyval(self._host_keyval_dir(), 'labels', labels,
1384 keyval_filename=host.hostname)
1385
1386 def _create_host_keyval_dir(self):
1387 directory = self._host_keyval_dir()
showard2bab8f42008-11-12 18:15:22 +00001388 ensure_directory_exists(directory)
showardd8e548a2008-09-09 03:04:57 +00001389
1390
jadmanski0afbb632008-06-06 21:10:57 +00001391 def results_dir(self):
1392 return self.queue_entries[0].results_dir()
mblighbb421852008-03-11 22:36:16 +00001393
1394
jadmanski0afbb632008-06-06 21:10:57 +00001395 def run(self):
1396 """\
1397 Override AgentTask.run() so we can use a PidfileRunMonitor.
1398 """
1399 self.monitor = PidfileRunMonitor(self.results_dir(),
1400 cmd=self.cmd,
1401 nice_level=AUTOSERV_NICE_LEVEL)
1402 self.monitor.run()
mblighbb421852008-03-11 22:36:16 +00001403
1404
jadmanski0afbb632008-06-06 21:10:57 +00001405 def prolog(self):
1406 # write some job timestamps into the job keyval file
1407 queued = time.mktime(self.job.created_on.timetuple())
1408 started = time.time()
showardd8e548a2008-09-09 03:04:57 +00001409 self._write_keyval(self.results_dir(), "job_queued", int(queued))
1410 self._write_keyval(self.results_dir(), "job_started", int(started))
1411 self._create_host_keyval_dir()
jadmanski0afbb632008-06-06 21:10:57 +00001412 for queue_entry in self.queue_entries:
showardd8e548a2008-09-09 03:04:57 +00001413 self._write_host_keyval(queue_entry.host)
jadmanski0afbb632008-06-06 21:10:57 +00001414 queue_entry.set_status('Running')
1415 queue_entry.host.set_status('Running')
showard21baa452008-10-21 00:08:39 +00001416 queue_entry.host.update_field('dirty', 1)
showard2bab8f42008-11-12 18:15:22 +00001417 if self.job.synch_count == 1:
jadmanski0afbb632008-06-06 21:10:57 +00001418 assert len(self.queue_entries) == 1
1419 self.job.write_to_machines_file(self.queue_entries[0])
mbligh36768f02008-02-22 18:28:33 +00001420
1421
showard97aed502008-11-04 02:01:24 +00001422 def _finish_task(self, success):
jadmanski0afbb632008-06-06 21:10:57 +00001423 # write out the finished time into the results keyval
1424 finished = time.time()
jadmanskif7fa2cc2008-10-01 14:13:23 +00001425 self._write_keyval(self.results_dir(), "job_finished", int(finished))
jadmanskic2ac77f2008-05-16 21:44:04 +00001426
jadmanski0afbb632008-06-06 21:10:57 +00001427 # parse the results of the job
showard97aed502008-11-04 02:01:24 +00001428 reparse_task = FinalReparseTask(self.queue_entries)
1429 self.agent.dispatcher.add_agent(Agent([reparse_task]))
jadmanskif7fa2cc2008-10-01 14:13:23 +00001430
1431
showardcbd74612008-11-19 21:42:02 +00001432 def _write_status_comment(self, comment):
1433 status_log = open(os.path.join(self.results_dir(), 'status.log'), 'a')
1434 status_log.write('INFO\t----\t----\t' + comment)
1435 status_log.close()
1436
1437
jadmanskif7fa2cc2008-10-01 14:13:23 +00001438 def _log_abort(self):
1439 # build up sets of all the aborted_by and aborted_on values
1440 aborted_by, aborted_on = set(), set()
1441 for queue_entry in self.queue_entries:
1442 if queue_entry.aborted_by:
1443 aborted_by.add(queue_entry.aborted_by)
1444 t = int(time.mktime(queue_entry.aborted_on.timetuple()))
1445 aborted_on.add(t)
1446
1447 # extract some actual, unique aborted by value and write it out
1448 assert len(aborted_by) <= 1
1449 if len(aborted_by) == 1:
showardcbd74612008-11-19 21:42:02 +00001450 aborted_by_value = aborted_by.pop()
1451 aborted_on_value = max(aborted_on)
1452 else:
1453 aborted_by_value = 'autotest_system'
1454 aborted_on_value = int(time.time())
1455 results_dir = self.results_dir()
1456 self._write_keyval(results_dir, "aborted_by", aborted_by_value)
1457 self._write_keyval(results_dir, "aborted_on", aborted_on_value)
1458 aborted_on_string = str(datetime.datetime.fromtimestamp(
1459 aborted_on_value))
1460 self._write_status_comment('Job aborted by %s on %s' %
1461 (aborted_by_value, aborted_on_string))
jadmanskic2ac77f2008-05-16 21:44:04 +00001462
1463
jadmanski0afbb632008-06-06 21:10:57 +00001464 def abort(self):
1465 super(QueueTask, self).abort()
jadmanskif7fa2cc2008-10-01 14:13:23 +00001466 self._log_abort()
showard97aed502008-11-04 02:01:24 +00001467 self._finish_task(False)
jadmanskic2ac77f2008-05-16 21:44:04 +00001468
1469
showard21baa452008-10-21 00:08:39 +00001470 def _reboot_hosts(self):
1471 reboot_after = self.job.reboot_after
1472 do_reboot = False
showard0fc38302008-10-23 00:44:07 +00001473 if reboot_after == models.RebootAfter.ALWAYS:
showard21baa452008-10-21 00:08:39 +00001474 do_reboot = True
showard0fc38302008-10-23 00:44:07 +00001475 elif reboot_after == models.RebootAfter.IF_ALL_TESTS_PASSED:
showard21baa452008-10-21 00:08:39 +00001476 num_tests_failed = self.monitor.num_tests_failed()
1477 do_reboot = (self.success and num_tests_failed == 0)
1478
showard8ebca792008-11-04 21:54:22 +00001479 for queue_entry in self.queue_entries:
1480 if do_reboot:
showard45ae8192008-11-05 19:32:53 +00001481 # don't pass the queue entry to the CleanupTask. if the cleanup
showardfa8629c2008-11-04 16:51:23 +00001482 # fails, the job doesn't care -- it's over.
showard45ae8192008-11-05 19:32:53 +00001483 cleanup_task = CleanupTask(host=queue_entry.get_host())
1484 self.agent.dispatcher.add_agent(Agent([cleanup_task]))
showard8ebca792008-11-04 21:54:22 +00001485 else:
1486 queue_entry.host.set_status('Ready')
showard21baa452008-10-21 00:08:39 +00001487
1488
jadmanski0afbb632008-06-06 21:10:57 +00001489 def epilog(self):
1490 super(QueueTask, self).epilog()
jadmanski0afbb632008-06-06 21:10:57 +00001491 for queue_entry in self.queue_entries:
showard97aed502008-11-04 02:01:24 +00001492 # set status to PARSING here so queue entry is marked complete
1493 queue_entry.set_status(models.HostQueueEntry.Status.PARSING)
mbligh36768f02008-02-22 18:28:33 +00001494
showard97aed502008-11-04 02:01:24 +00001495 self._finish_task(self.success)
showard21baa452008-10-21 00:08:39 +00001496 self._reboot_hosts()
mblighbb421852008-03-11 22:36:16 +00001497
showard97aed502008-11-04 02:01:24 +00001498 print "queue_task finished with succes=%s" % self.success
mbligh36768f02008-02-22 18:28:33 +00001499
1500
mblighbb421852008-03-11 22:36:16 +00001501class RecoveryQueueTask(QueueTask):
jadmanski0afbb632008-06-06 21:10:57 +00001502 def __init__(self, job, queue_entries, run_monitor):
1503 super(RecoveryQueueTask, self).__init__(job,
1504 queue_entries, cmd=None)
1505 self.run_monitor = run_monitor
mblighbb421852008-03-11 22:36:16 +00001506
1507
jadmanski0afbb632008-06-06 21:10:57 +00001508 def run(self):
1509 self.monitor = self.run_monitor
mblighbb421852008-03-11 22:36:16 +00001510
1511
jadmanski0afbb632008-06-06 21:10:57 +00001512 def prolog(self):
1513 # recovering an existing process - don't do prolog
1514 pass
mblighbb421852008-03-11 22:36:16 +00001515
1516
showard8fe93b52008-11-18 17:53:22 +00001517class CleanupTask(PreJobTask):
showardfa8629c2008-11-04 16:51:23 +00001518 def __init__(self, host=None, queue_entry=None):
1519 assert bool(host) ^ bool(queue_entry)
1520 if queue_entry:
1521 host = queue_entry.get_host()
jadmanski0afbb632008-06-06 21:10:57 +00001522
showard45ae8192008-11-05 19:32:53 +00001523 self.create_temp_resultsdir('.cleanup')
1524 self.cmd = [_autoserv_path, '--cleanup', '-m', host.hostname,
1525 '-r', self.temp_results_dir]
showardfa8629c2008-11-04 16:51:23 +00001526 self.queue_entry = queue_entry
jadmanski0afbb632008-06-06 21:10:57 +00001527 self.host = host
showarde788ea62008-11-17 21:02:47 +00001528 repair_task = RepairTask(host, queue_entry=queue_entry)
showard45ae8192008-11-05 19:32:53 +00001529 super(CleanupTask, self).__init__(self.cmd, failure_tasks=[repair_task])
mbligh16c722d2008-03-05 00:58:44 +00001530
mblighd5c95802008-03-05 00:33:46 +00001531
jadmanski0afbb632008-06-06 21:10:57 +00001532 def prolog(self):
showard8fe93b52008-11-18 17:53:22 +00001533 super(CleanupTask, self).prolog()
showard45ae8192008-11-05 19:32:53 +00001534 print "starting cleanup task for host: %s" % self.host.hostname
1535 self.host.set_status("Cleaning")
mblighd5c95802008-03-05 00:33:46 +00001536
mblighd5c95802008-03-05 00:33:46 +00001537
showard21baa452008-10-21 00:08:39 +00001538 def epilog(self):
showard45ae8192008-11-05 19:32:53 +00001539 super(CleanupTask, self).epilog()
showard21baa452008-10-21 00:08:39 +00001540 if self.success:
showardfa8629c2008-11-04 16:51:23 +00001541 self.host.set_status('Ready')
showard21baa452008-10-21 00:08:39 +00001542 self.host.update_field('dirty', 0)
1543
1544
mblighd5c95802008-03-05 00:33:46 +00001545class AbortTask(AgentTask):
jadmanski0afbb632008-06-06 21:10:57 +00001546 def __init__(self, queue_entry, agents_to_abort):
1547 self.queue_entry = queue_entry
1548 self.agents_to_abort = agents_to_abort
jadmanski0afbb632008-06-06 21:10:57 +00001549 super(AbortTask, self).__init__('')
mbligh36768f02008-02-22 18:28:33 +00001550
1551
jadmanski0afbb632008-06-06 21:10:57 +00001552 def prolog(self):
1553 print "starting abort on host %s, job %s" % (
1554 self.queue_entry.host_id, self.queue_entry.job_id)
mbligh36768f02008-02-22 18:28:33 +00001555
mblighd64e5702008-04-04 21:39:28 +00001556
jadmanski0afbb632008-06-06 21:10:57 +00001557 def epilog(self):
1558 super(AbortTask, self).epilog()
1559 self.queue_entry.set_status('Aborted')
1560 self.success = True
1561
1562
1563 def run(self):
1564 for agent in self.agents_to_abort:
1565 if (agent.active_task):
1566 agent.active_task.abort()
mbligh36768f02008-02-22 18:28:33 +00001567
1568
showard97aed502008-11-04 02:01:24 +00001569class FinalReparseTask(AgentTask):
1570 MAX_PARSE_PROCESSES = (
1571 global_config.global_config.get_config_value(
1572 _global_config_section, 'max_parse_processes', type=int))
1573 _num_running_parses = 0
1574
1575 def __init__(self, queue_entries):
1576 self._queue_entries = queue_entries
1577 self._parse_started = False
1578
1579 assert len(queue_entries) > 0
1580 queue_entry = queue_entries[0]
showard97aed502008-11-04 02:01:24 +00001581
1582 if _testing_mode:
1583 self.cmd = 'true'
1584 return
1585
1586 self._results_dir = queue_entry.results_dir()
1587 self.log_file = os.path.abspath(os.path.join(self._results_dir,
1588 '.parse.log'))
1589 super(FinalReparseTask, self).__init__(
showard2bab8f42008-11-12 18:15:22 +00001590 cmd=self._generate_parse_command())
showard97aed502008-11-04 02:01:24 +00001591
1592
1593 @classmethod
1594 def _increment_running_parses(cls):
1595 cls._num_running_parses += 1
1596
1597
1598 @classmethod
1599 def _decrement_running_parses(cls):
1600 cls._num_running_parses -= 1
1601
1602
1603 @classmethod
1604 def _can_run_new_parse(cls):
1605 return cls._num_running_parses < cls.MAX_PARSE_PROCESSES
1606
1607
1608 def prolog(self):
1609 super(FinalReparseTask, self).prolog()
1610 for queue_entry in self._queue_entries:
1611 queue_entry.set_status(models.HostQueueEntry.Status.PARSING)
1612
1613
1614 def epilog(self):
1615 super(FinalReparseTask, self).epilog()
1616 final_status = self._determine_final_status()
1617 for queue_entry in self._queue_entries:
1618 queue_entry.set_status(final_status)
1619
1620
1621 def _determine_final_status(self):
1622 # use a PidfileRunMonitor to read the autoserv exit status
1623 monitor = PidfileRunMonitor(self._results_dir)
1624 if monitor.exit_code() == 0:
1625 return models.HostQueueEntry.Status.COMPLETED
1626 return models.HostQueueEntry.Status.FAILED
1627
1628
showard2bab8f42008-11-12 18:15:22 +00001629 def _generate_parse_command(self):
showard97aed502008-11-04 02:01:24 +00001630 parse = os.path.abspath(os.path.join(AUTOTEST_TKO_DIR, 'parse'))
showard2bab8f42008-11-12 18:15:22 +00001631 return [parse, '-l', '2', '-r', '-o', self._results_dir]
showard97aed502008-11-04 02:01:24 +00001632
1633
1634 def poll(self):
1635 # override poll to keep trying to start until the parse count goes down
1636 # and we can, at which point we revert to default behavior
1637 if self._parse_started:
1638 super(FinalReparseTask, self).poll()
1639 else:
1640 self._try_starting_parse()
1641
1642
1643 def run(self):
1644 # override run() to not actually run unless we can
1645 self._try_starting_parse()
1646
1647
1648 def _try_starting_parse(self):
1649 if not self._can_run_new_parse():
1650 return
1651 # actually run the parse command
1652 super(FinalReparseTask, self).run()
1653 self._increment_running_parses()
1654 self._parse_started = True
1655
1656
1657 def finished(self, success):
1658 super(FinalReparseTask, self).finished(success)
1659 self._decrement_running_parses()
1660
1661
mbligh36768f02008-02-22 18:28:33 +00001662class DBObject(object):
jadmanski0afbb632008-06-06 21:10:57 +00001663 def __init__(self, id=None, row=None, new_record=False):
1664 assert (bool(id) != bool(row))
mbligh36768f02008-02-22 18:28:33 +00001665
jadmanski0afbb632008-06-06 21:10:57 +00001666 self.__table = self._get_table()
mbligh36768f02008-02-22 18:28:33 +00001667
jadmanski0afbb632008-06-06 21:10:57 +00001668 self.__new_record = new_record
mbligh36768f02008-02-22 18:28:33 +00001669
jadmanski0afbb632008-06-06 21:10:57 +00001670 if row is None:
1671 sql = 'SELECT * FROM %s WHERE ID=%%s' % self.__table
1672 rows = _db.execute(sql, (id,))
1673 if len(rows) == 0:
1674 raise "row not found (table=%s, id=%s)" % \
1675 (self.__table, id)
1676 row = rows[0]
mbligh36768f02008-02-22 18:28:33 +00001677
showard2bab8f42008-11-12 18:15:22 +00001678 self._update_fields_from_row(row)
1679
1680
1681 def _update_fields_from_row(self, row):
jadmanski0afbb632008-06-06 21:10:57 +00001682 assert len(row) == self.num_cols(), (
1683 "table = %s, row = %s/%d, fields = %s/%d" % (
showard2bab8f42008-11-12 18:15:22 +00001684 self.__table, row, len(row), self._fields(), self.num_cols()))
mbligh36768f02008-02-22 18:28:33 +00001685
showard2bab8f42008-11-12 18:15:22 +00001686 self._valid_fields = set()
1687 for field, value in zip(self._fields(), row):
1688 setattr(self, field, value)
1689 self._valid_fields.add(field)
mbligh36768f02008-02-22 18:28:33 +00001690
showard2bab8f42008-11-12 18:15:22 +00001691 self._valid_fields.remove('id')
mbligh36768f02008-02-22 18:28:33 +00001692
mblighe2586682008-02-29 22:45:46 +00001693
jadmanski0afbb632008-06-06 21:10:57 +00001694 @classmethod
1695 def _get_table(cls):
1696 raise NotImplementedError('Subclasses must override this')
mblighe2586682008-02-29 22:45:46 +00001697
1698
jadmanski0afbb632008-06-06 21:10:57 +00001699 @classmethod
1700 def _fields(cls):
1701 raise NotImplementedError('Subclasses must override this')
showard04c82c52008-05-29 19:38:12 +00001702
1703
jadmanski0afbb632008-06-06 21:10:57 +00001704 @classmethod
1705 def num_cols(cls):
1706 return len(cls._fields())
showard04c82c52008-05-29 19:38:12 +00001707
1708
jadmanski0afbb632008-06-06 21:10:57 +00001709 def count(self, where, table = None):
1710 if not table:
1711 table = self.__table
mbligh36768f02008-02-22 18:28:33 +00001712
jadmanski0afbb632008-06-06 21:10:57 +00001713 rows = _db.execute("""
1714 SELECT count(*) FROM %s
1715 WHERE %s
1716 """ % (table, where))
mbligh6f8bab42008-02-29 22:45:14 +00001717
jadmanski0afbb632008-06-06 21:10:57 +00001718 assert len(rows) == 1
1719
1720 return int(rows[0][0])
mbligh36768f02008-02-22 18:28:33 +00001721
1722
mblighf8c624d2008-07-03 16:58:45 +00001723 def update_field(self, field, value, condition=''):
showard2bab8f42008-11-12 18:15:22 +00001724 assert field in self._valid_fields
mbligh36768f02008-02-22 18:28:33 +00001725
showard2bab8f42008-11-12 18:15:22 +00001726 if getattr(self, field) == value:
jadmanski0afbb632008-06-06 21:10:57 +00001727 return
mbligh36768f02008-02-22 18:28:33 +00001728
mblighf8c624d2008-07-03 16:58:45 +00001729 query = "UPDATE %s SET %s = %%s WHERE id = %%s" % (self.__table, field)
1730 if condition:
1731 query += ' AND (%s)' % condition
jadmanski0afbb632008-06-06 21:10:57 +00001732 _db.execute(query, (value, self.id))
1733
showard2bab8f42008-11-12 18:15:22 +00001734 setattr(self, field, value)
mbligh36768f02008-02-22 18:28:33 +00001735
1736
jadmanski0afbb632008-06-06 21:10:57 +00001737 def save(self):
1738 if self.__new_record:
1739 keys = self._fields()[1:] # avoid id
1740 columns = ','.join([str(key) for key in keys])
1741 values = ['"%s"' % self.__dict__[key] for key in keys]
1742 values = ','.join(values)
1743 query = """INSERT INTO %s (%s) VALUES (%s)""" % \
1744 (self.__table, columns, values)
1745 _db.execute(query)
mbligh36768f02008-02-22 18:28:33 +00001746
1747
jadmanski0afbb632008-06-06 21:10:57 +00001748 def delete(self):
1749 query = 'DELETE FROM %s WHERE id=%%s' % self.__table
1750 _db.execute(query, (self.id,))
mblighe2586682008-02-29 22:45:46 +00001751
1752
showard63a34772008-08-18 19:32:50 +00001753 @staticmethod
1754 def _prefix_with(string, prefix):
1755 if string:
1756 string = prefix + string
1757 return string
1758
1759
jadmanski0afbb632008-06-06 21:10:57 +00001760 @classmethod
showard989f25d2008-10-01 11:38:11 +00001761 def fetch(cls, where='', params=(), joins='', order_by=''):
showard63a34772008-08-18 19:32:50 +00001762 order_by = cls._prefix_with(order_by, 'ORDER BY ')
1763 where = cls._prefix_with(where, 'WHERE ')
1764 query = ('SELECT %(table)s.* FROM %(table)s %(joins)s '
1765 '%(where)s %(order_by)s' % {'table' : cls._get_table(),
1766 'joins' : joins,
1767 'where' : where,
1768 'order_by' : order_by})
1769 rows = _db.execute(query, params)
jadmanski0afbb632008-06-06 21:10:57 +00001770 for row in rows:
1771 yield cls(row=row)
mblighe2586682008-02-29 22:45:46 +00001772
mbligh36768f02008-02-22 18:28:33 +00001773
1774class IneligibleHostQueue(DBObject):
jadmanski0afbb632008-06-06 21:10:57 +00001775 def __init__(self, id=None, row=None, new_record=None):
1776 super(IneligibleHostQueue, self).__init__(id=id, row=row,
1777 new_record=new_record)
mblighe2586682008-02-29 22:45:46 +00001778
1779
jadmanski0afbb632008-06-06 21:10:57 +00001780 @classmethod
1781 def _get_table(cls):
1782 return 'ineligible_host_queues'
mbligh36768f02008-02-22 18:28:33 +00001783
1784
jadmanski0afbb632008-06-06 21:10:57 +00001785 @classmethod
1786 def _fields(cls):
1787 return ['id', 'job_id', 'host_id']
showard04c82c52008-05-29 19:38:12 +00001788
1789
showard989f25d2008-10-01 11:38:11 +00001790class Label(DBObject):
1791 @classmethod
1792 def _get_table(cls):
1793 return 'labels'
1794
1795
1796 @classmethod
1797 def _fields(cls):
1798 return ['id', 'name', 'kernel_config', 'platform', 'invalid',
1799 'only_if_needed']
1800
1801
mbligh36768f02008-02-22 18:28:33 +00001802class Host(DBObject):
jadmanski0afbb632008-06-06 21:10:57 +00001803 def __init__(self, id=None, row=None):
1804 super(Host, self).__init__(id=id, row=row)
mblighe2586682008-02-29 22:45:46 +00001805
1806
jadmanski0afbb632008-06-06 21:10:57 +00001807 @classmethod
1808 def _get_table(cls):
1809 return 'hosts'
mbligh36768f02008-02-22 18:28:33 +00001810
1811
jadmanski0afbb632008-06-06 21:10:57 +00001812 @classmethod
1813 def _fields(cls):
1814 return ['id', 'hostname', 'locked', 'synch_id','status',
showard21baa452008-10-21 00:08:39 +00001815 'invalid', 'protection', 'locked_by_id', 'lock_time', 'dirty']
showard04c82c52008-05-29 19:38:12 +00001816
1817
jadmanski0afbb632008-06-06 21:10:57 +00001818 def current_task(self):
1819 rows = _db.execute("""
1820 SELECT * FROM host_queue_entries WHERE host_id=%s AND NOT complete AND active
1821 """, (self.id,))
1822
1823 if len(rows) == 0:
1824 return None
1825 else:
1826 assert len(rows) == 1
1827 results = rows[0];
mblighf8c624d2008-07-03 16:58:45 +00001828# print "current = %s" % results
jadmanski0afbb632008-06-06 21:10:57 +00001829 return HostQueueEntry(row=results)
mbligh36768f02008-02-22 18:28:33 +00001830
1831
jadmanski0afbb632008-06-06 21:10:57 +00001832 def yield_work(self):
1833 print "%s yielding work" % self.hostname
1834 if self.current_task():
1835 self.current_task().requeue()
1836
1837 def set_status(self,status):
1838 print '%s -> %s' % (self.hostname, status)
1839 self.update_field('status',status)
mbligh36768f02008-02-22 18:28:33 +00001840
1841
showardd8e548a2008-09-09 03:04:57 +00001842 def labels(self):
1843 """
1844 Fetch a list of names of all non-platform labels associated with this
1845 host.
1846 """
1847 rows = _db.execute("""
1848 SELECT labels.name
1849 FROM labels
1850 INNER JOIN hosts_labels ON labels.id = hosts_labels.label_id
1851 WHERE NOT labels.platform AND hosts_labels.host_id = %s
1852 ORDER BY labels.name
1853 """, (self.id,))
1854 return [row[0] for row in rows]
1855
1856
mbligh36768f02008-02-22 18:28:33 +00001857class HostQueueEntry(DBObject):
jadmanski0afbb632008-06-06 21:10:57 +00001858 def __init__(self, id=None, row=None):
1859 assert id or row
1860 super(HostQueueEntry, self).__init__(id=id, row=row)
1861 self.job = Job(self.job_id)
mbligh36768f02008-02-22 18:28:33 +00001862
jadmanski0afbb632008-06-06 21:10:57 +00001863 if self.host_id:
1864 self.host = Host(self.host_id)
1865 else:
1866 self.host = None
mbligh36768f02008-02-22 18:28:33 +00001867
jadmanski0afbb632008-06-06 21:10:57 +00001868 self.queue_log_path = os.path.join(self.job.results_dir(),
1869 'queue.log.' + str(self.id))
mbligh36768f02008-02-22 18:28:33 +00001870
1871
jadmanski0afbb632008-06-06 21:10:57 +00001872 @classmethod
1873 def _get_table(cls):
1874 return 'host_queue_entries'
mblighe2586682008-02-29 22:45:46 +00001875
1876
jadmanski0afbb632008-06-06 21:10:57 +00001877 @classmethod
1878 def _fields(cls):
showard2bab8f42008-11-12 18:15:22 +00001879 return ['id', 'job_id', 'host_id', 'priority', 'status', 'meta_host',
1880 'active', 'complete', 'deleted', 'execution_subdir']
showard04c82c52008-05-29 19:38:12 +00001881
1882
showardc85c21b2008-11-24 22:17:37 +00001883 def _view_job_url(self):
1884 return "%s#tab_id=view_job&object_id=%s" % (_base_url, self.job.id)
1885
1886
jadmanski0afbb632008-06-06 21:10:57 +00001887 def set_host(self, host):
1888 if host:
1889 self.queue_log_record('Assigning host ' + host.hostname)
1890 self.update_field('host_id', host.id)
1891 self.update_field('active', True)
1892 self.block_host(host.id)
1893 else:
1894 self.queue_log_record('Releasing host')
1895 self.unblock_host(self.host.id)
1896 self.update_field('host_id', None)
mbligh36768f02008-02-22 18:28:33 +00001897
jadmanski0afbb632008-06-06 21:10:57 +00001898 self.host = host
mbligh36768f02008-02-22 18:28:33 +00001899
1900
jadmanski0afbb632008-06-06 21:10:57 +00001901 def get_host(self):
1902 return self.host
mbligh36768f02008-02-22 18:28:33 +00001903
1904
jadmanski0afbb632008-06-06 21:10:57 +00001905 def queue_log_record(self, log_line):
1906 now = str(datetime.datetime.now())
1907 queue_log = open(self.queue_log_path, 'a', 0)
1908 queue_log.write(now + ' ' + log_line + '\n')
1909 queue_log.close()
mbligh36768f02008-02-22 18:28:33 +00001910
1911
jadmanski0afbb632008-06-06 21:10:57 +00001912 def block_host(self, host_id):
1913 print "creating block %s/%s" % (self.job.id, host_id)
1914 row = [0, self.job.id, host_id]
1915 block = IneligibleHostQueue(row=row, new_record=True)
1916 block.save()
mblighe2586682008-02-29 22:45:46 +00001917
1918
jadmanski0afbb632008-06-06 21:10:57 +00001919 def unblock_host(self, host_id):
1920 print "removing block %s/%s" % (self.job.id, host_id)
1921 blocks = IneligibleHostQueue.fetch(
1922 'job_id=%d and host_id=%d' % (self.job.id, host_id))
1923 for block in blocks:
1924 block.delete()
mblighe2586682008-02-29 22:45:46 +00001925
1926
jadmanski0afbb632008-06-06 21:10:57 +00001927 def results_dir(self):
showard2bab8f42008-11-12 18:15:22 +00001928 return os.path.join(self.job.job_dir, self.execution_subdir)
mbligh36768f02008-02-22 18:28:33 +00001929
mblighe2586682008-02-29 22:45:46 +00001930
showard2bab8f42008-11-12 18:15:22 +00001931 def set_execution_subdir(self, subdir=None):
1932 if subdir is None:
1933 assert self.get_host()
1934 subdir = self.get_host().hostname
1935 self.update_field('execution_subdir', subdir)
mbligh36768f02008-02-22 18:28:33 +00001936
1937
jadmanski0afbb632008-06-06 21:10:57 +00001938 def set_status(self, status):
mblighf8c624d2008-07-03 16:58:45 +00001939 abort_statuses = ['Abort', 'Aborting', 'Aborted']
1940 if status not in abort_statuses:
1941 condition = ' AND '.join(['status <> "%s"' % x
1942 for x in abort_statuses])
1943 else:
1944 condition = ''
1945 self.update_field('status', status, condition=condition)
1946
jadmanski0afbb632008-06-06 21:10:57 +00001947 if self.host:
1948 hostname = self.host.hostname
1949 else:
showard2bab8f42008-11-12 18:15:22 +00001950 hostname = 'None'
1951 print "%s/%d (%d) -> %s" % (hostname, self.job.id, self.id, self.status)
mblighf8c624d2008-07-03 16:58:45 +00001952
showardc85c21b2008-11-24 22:17:37 +00001953 if status in ['Queued', 'Parsing']:
jadmanski0afbb632008-06-06 21:10:57 +00001954 self.update_field('complete', False)
1955 self.update_field('active', False)
mbligh36768f02008-02-22 18:28:33 +00001956
jadmanski0afbb632008-06-06 21:10:57 +00001957 if status in ['Pending', 'Running', 'Verifying', 'Starting',
showarde58e3f82008-11-20 19:04:59 +00001958 'Aborting']:
jadmanski0afbb632008-06-06 21:10:57 +00001959 self.update_field('complete', False)
1960 self.update_field('active', True)
mbligh36768f02008-02-22 18:28:33 +00001961
showardc85c21b2008-11-24 22:17:37 +00001962 if status in ['Failed', 'Completed', 'Stopped', 'Aborted']:
jadmanski0afbb632008-06-06 21:10:57 +00001963 self.update_field('complete', True)
1964 self.update_field('active', False)
showardc85c21b2008-11-24 22:17:37 +00001965
1966 should_email_status = (status.lower() in _notify_email_statuses or
1967 'all' in _notify_email_statuses)
1968 if should_email_status:
1969 self._email_on_status(status)
1970
1971 self._email_on_job_complete()
1972
1973
1974 def _email_on_status(self, status):
1975 hostname = 'no host'
1976 if self.host:
1977 hostname = self.host.hostname
1978
1979 subject = 'Autotest: Job ID: %s "%s" Host: %s %s' % (
1980 self.job.id, self.job.name, hostname, status)
1981 body = "Job ID: %s\nJob Name: %s\nHost: %s\nStatus: %s\n%s\n" % (
1982 self.job.id, self.job.name, hostname, status,
1983 self._view_job_url())
1984 send_email(self.job.email_list, subject, body)
showard542e8402008-09-19 20:16:18 +00001985
1986
1987 def _email_on_job_complete(self):
showardc85c21b2008-11-24 22:17:37 +00001988 if not self.job.is_finished():
1989 return
showard542e8402008-09-19 20:16:18 +00001990
showardc85c21b2008-11-24 22:17:37 +00001991 summary_text = []
1992 hosts_queue = models.Job.objects.get(
1993 id=self.job.id).hostqueueentry_set.all()
1994 for queue_entry in hosts_queue:
1995 summary_text.append("Host: %s Status: %s" %
1996 (queue_entry.host.hostname,
1997 queue_entry.status))
1998
1999 summary_text = "\n".join(summary_text)
2000 status_counts = models.Job.objects.get_status_counts(
2001 [self.job.id])[self.job.id]
2002 status = ', '.join('%d %s' % (count, status) for status, count
2003 in status_counts.iteritems())
2004
2005 subject = 'Autotest: Job ID: %s "%s" %s' % (
2006 self.job.id, self.job.name, status)
2007 body = "Job ID: %s\nJob Name: %s\nStatus: %s\n%s\nSummary:\n%s" % (
2008 self.job.id, self.job.name, status, self._view_job_url(),
2009 summary_text)
2010 send_email(self.job.email_list, subject, body)
mbligh36768f02008-02-22 18:28:33 +00002011
2012
jadmanski0afbb632008-06-06 21:10:57 +00002013 def run(self,assigned_host=None):
2014 if self.meta_host:
2015 assert assigned_host
2016 # ensure results dir exists for the queue log
2017 self.job.create_results_dir()
2018 self.set_host(assigned_host)
mbligh36768f02008-02-22 18:28:33 +00002019
jadmanski0afbb632008-06-06 21:10:57 +00002020 print "%s/%s scheduled on %s, status=%s" % (self.job.name,
2021 self.meta_host, self.host.hostname, self.status)
mbligh36768f02008-02-22 18:28:33 +00002022
jadmanski0afbb632008-06-06 21:10:57 +00002023 return self.job.run(queue_entry=self)
mblighe2586682008-02-29 22:45:46 +00002024
jadmanski0afbb632008-06-06 21:10:57 +00002025 def requeue(self):
2026 self.set_status('Queued')
mblighe2586682008-02-29 22:45:46 +00002027
jadmanski0afbb632008-06-06 21:10:57 +00002028 if self.meta_host:
2029 self.set_host(None)
mbligh36768f02008-02-22 18:28:33 +00002030
2031
jadmanski0afbb632008-06-06 21:10:57 +00002032 def handle_host_failure(self):
2033 """\
2034 Called when this queue entry's host has failed verification and
2035 repair.
2036 """
2037 assert not self.meta_host
2038 self.set_status('Failed')
showard2bab8f42008-11-12 18:15:22 +00002039 self.job.stop_if_necessary()
mblighe2586682008-02-29 22:45:46 +00002040
2041
showard2bab8f42008-11-12 18:15:22 +00002042 def clear_results_dir(self, dont_delete_files=False):
2043 if not self.execution_subdir:
2044 return
2045 results_dir = self.results_dir()
jadmanski0afbb632008-06-06 21:10:57 +00002046 if not os.path.exists(results_dir):
2047 return
2048 if dont_delete_files:
2049 temp_dir = tempfile.mkdtemp(suffix='.clear_results')
showard2bab8f42008-11-12 18:15:22 +00002050 print 'Moving results from %s to %s' % (results_dir, temp_dir)
jadmanski0afbb632008-06-06 21:10:57 +00002051 for filename in os.listdir(results_dir):
2052 path = os.path.join(results_dir, filename)
2053 if dont_delete_files:
showard2bab8f42008-11-12 18:15:22 +00002054 shutil.move(path, os.path.join(temp_dir, filename))
jadmanski0afbb632008-06-06 21:10:57 +00002055 else:
2056 remove_file_or_dir(path)
showard2bab8f42008-11-12 18:15:22 +00002057 remove_file_or_dir(results_dir)
mbligh36768f02008-02-22 18:28:33 +00002058
2059
jadmanskif7fa2cc2008-10-01 14:13:23 +00002060 @property
2061 def aborted_by(self):
2062 self._load_abort_info()
2063 return self._aborted_by
2064
2065
2066 @property
2067 def aborted_on(self):
2068 self._load_abort_info()
2069 return self._aborted_on
2070
2071
2072 def _load_abort_info(self):
2073 """ Fetch info about who aborted the job. """
2074 if hasattr(self, "_aborted_by"):
2075 return
2076 rows = _db.execute("""
2077 SELECT users.login, aborted_host_queue_entries.aborted_on
2078 FROM aborted_host_queue_entries
2079 INNER JOIN users
2080 ON users.id = aborted_host_queue_entries.aborted_by_id
2081 WHERE aborted_host_queue_entries.queue_entry_id = %s
2082 """, (self.id,))
2083 if rows:
2084 self._aborted_by, self._aborted_on = rows[0]
2085 else:
2086 self._aborted_by = self._aborted_on = None
2087
2088
showardb2e2c322008-10-14 17:33:55 +00002089 def on_pending(self):
2090 """
2091 Called when an entry in a synchronous job has passed verify. If the
2092 job is ready to run, returns an agent to run the job. Returns None
2093 otherwise.
2094 """
2095 self.set_status('Pending')
showardcfd66a32008-10-15 20:31:48 +00002096 self.get_host().set_status('Pending')
showardb2e2c322008-10-14 17:33:55 +00002097 if self.job.is_ready():
2098 return self.job.run(self)
showard2bab8f42008-11-12 18:15:22 +00002099 self.job.stop_if_necessary()
showardb2e2c322008-10-14 17:33:55 +00002100 return None
2101
2102
showard1be97432008-10-17 15:30:45 +00002103 def abort(self, agents_to_abort=[]):
2104 abort_task = AbortTask(self, agents_to_abort)
2105 tasks = [abort_task]
2106
2107 host = self.get_host()
showard9d9ffd52008-11-09 23:14:35 +00002108 if self.active and host:
showard45ae8192008-11-05 19:32:53 +00002109 cleanup_task = CleanupTask(host=host)
showard1be97432008-10-17 15:30:45 +00002110 verify_task = VerifyTask(host=host)
2111 # just to make sure this host does not get taken away
showard45ae8192008-11-05 19:32:53 +00002112 host.set_status('Cleaning')
2113 tasks += [cleanup_task, verify_task]
showard1be97432008-10-17 15:30:45 +00002114
2115 self.set_status('Aborting')
2116 return Agent(tasks=tasks, queue_entry_ids=[self.id])
2117
2118
mbligh36768f02008-02-22 18:28:33 +00002119class Job(DBObject):
jadmanski0afbb632008-06-06 21:10:57 +00002120 def __init__(self, id=None, row=None):
2121 assert id or row
2122 super(Job, self).__init__(id=id, row=row)
mbligh36768f02008-02-22 18:28:33 +00002123
jadmanski0afbb632008-06-06 21:10:57 +00002124 self.job_dir = os.path.join(RESULTS_DIR, "%s-%s" % (self.id,
2125 self.owner))
mblighe2586682008-02-29 22:45:46 +00002126
2127
jadmanski0afbb632008-06-06 21:10:57 +00002128 @classmethod
2129 def _get_table(cls):
2130 return 'jobs'
mbligh36768f02008-02-22 18:28:33 +00002131
2132
jadmanski0afbb632008-06-06 21:10:57 +00002133 @classmethod
2134 def _fields(cls):
2135 return ['id', 'owner', 'name', 'priority', 'control_file',
showard2bab8f42008-11-12 18:15:22 +00002136 'control_type', 'created_on', 'synch_count', 'timeout',
showard21baa452008-10-21 00:08:39 +00002137 'run_verify', 'email_list', 'reboot_before', 'reboot_after']
showard04c82c52008-05-29 19:38:12 +00002138
2139
jadmanski0afbb632008-06-06 21:10:57 +00002140 def is_server_job(self):
2141 return self.control_type != 2
mbligh36768f02008-02-22 18:28:33 +00002142
2143
jadmanski0afbb632008-06-06 21:10:57 +00002144 def get_host_queue_entries(self):
2145 rows = _db.execute("""
2146 SELECT * FROM host_queue_entries
2147 WHERE job_id= %s
2148 """, (self.id,))
2149 entries = [HostQueueEntry(row=i) for i in rows]
mbligh36768f02008-02-22 18:28:33 +00002150
jadmanski0afbb632008-06-06 21:10:57 +00002151 assert len(entries)>0
mbligh36768f02008-02-22 18:28:33 +00002152
jadmanski0afbb632008-06-06 21:10:57 +00002153 return entries
mbligh36768f02008-02-22 18:28:33 +00002154
2155
jadmanski0afbb632008-06-06 21:10:57 +00002156 def set_status(self, status, update_queues=False):
2157 self.update_field('status',status)
2158
2159 if update_queues:
2160 for queue_entry in self.get_host_queue_entries():
2161 queue_entry.set_status(status)
mbligh36768f02008-02-22 18:28:33 +00002162
2163
jadmanski0afbb632008-06-06 21:10:57 +00002164 def is_ready(self):
showard2bab8f42008-11-12 18:15:22 +00002165 pending_entries = models.HostQueueEntry.objects.filter(job=self.id,
2166 status='Pending')
2167 return (pending_entries.count() >= self.synch_count)
mbligh36768f02008-02-22 18:28:33 +00002168
2169
jadmanski0afbb632008-06-06 21:10:57 +00002170 def results_dir(self):
2171 return self.job_dir
mbligh36768f02008-02-22 18:28:33 +00002172
jadmanski0afbb632008-06-06 21:10:57 +00002173 def num_machines(self, clause = None):
2174 sql = "job_id=%s" % self.id
2175 if clause:
2176 sql += " AND (%s)" % clause
2177 return self.count(sql, table='host_queue_entries')
mbligh36768f02008-02-22 18:28:33 +00002178
2179
jadmanski0afbb632008-06-06 21:10:57 +00002180 def num_queued(self):
2181 return self.num_machines('not complete')
mbligh36768f02008-02-22 18:28:33 +00002182
2183
jadmanski0afbb632008-06-06 21:10:57 +00002184 def num_active(self):
2185 return self.num_machines('active')
mbligh36768f02008-02-22 18:28:33 +00002186
2187
jadmanski0afbb632008-06-06 21:10:57 +00002188 def num_complete(self):
2189 return self.num_machines('complete')
mbligh36768f02008-02-22 18:28:33 +00002190
2191
jadmanski0afbb632008-06-06 21:10:57 +00002192 def is_finished(self):
showardc85c21b2008-11-24 22:17:37 +00002193 return self.num_complete() == self.num_machines()
mbligh36768f02008-02-22 18:28:33 +00002194
mbligh36768f02008-02-22 18:28:33 +00002195
showard2bab8f42008-11-12 18:15:22 +00002196 def _stop_all_entries(self, entries_to_abort):
2197 """
2198 queue_entries: sequence of models.HostQueueEntry objects
2199 """
2200 for child_entry in entries_to_abort:
2201 assert not child_entry.complete
2202 if child_entry.status == models.HostQueueEntry.Status.PENDING:
2203 child_entry.host.status = models.Host.Status.READY
2204 child_entry.host.save()
2205 child_entry.status = models.HostQueueEntry.Status.STOPPED
2206 child_entry.save()
2207
2208
2209 def stop_if_necessary(self):
2210 not_yet_run = models.HostQueueEntry.objects.filter(
2211 job=self.id, status__in=(models.HostQueueEntry.Status.QUEUED,
2212 models.HostQueueEntry.Status.VERIFYING,
2213 models.HostQueueEntry.Status.PENDING))
2214 if not_yet_run.count() < self.synch_count:
2215 self._stop_all_entries(not_yet_run)
mblighe2586682008-02-29 22:45:46 +00002216
2217
jadmanski0afbb632008-06-06 21:10:57 +00002218 def write_to_machines_file(self, queue_entry):
2219 hostname = queue_entry.get_host().hostname
2220 print "writing %s to job %s machines file" % (hostname, self.id)
2221 file_path = os.path.join(self.job_dir, '.machines')
2222 mf = open(file_path, 'a')
showard2bab8f42008-11-12 18:15:22 +00002223 mf.write(hostname + '\n')
jadmanski0afbb632008-06-06 21:10:57 +00002224 mf.close()
mbligh36768f02008-02-22 18:28:33 +00002225
2226
jadmanski0afbb632008-06-06 21:10:57 +00002227 def create_results_dir(self, queue_entry=None):
showard2bab8f42008-11-12 18:15:22 +00002228 ensure_directory_exists(self.job_dir)
mbligh36768f02008-02-22 18:28:33 +00002229
jadmanski0afbb632008-06-06 21:10:57 +00002230 if queue_entry:
showarde05654d2008-10-28 20:38:40 +00002231 results_dir = queue_entry.results_dir()
showarde788ea62008-11-17 21:02:47 +00002232 if os.path.exists(results_dir):
2233 warning = 'QE results dir ' + results_dir + ' already exists'
2234 print warning
2235 email_manager.enqueue_notify_email(warning, warning)
showard2bab8f42008-11-12 18:15:22 +00002236 ensure_directory_exists(results_dir)
showarde05654d2008-10-28 20:38:40 +00002237 return results_dir
jadmanski0afbb632008-06-06 21:10:57 +00002238 return self.job_dir
mbligh36768f02008-02-22 18:28:33 +00002239
2240
showard2bab8f42008-11-12 18:15:22 +00002241 def _next_group_name(self):
2242 query = models.HostQueueEntry.objects.filter(
2243 job=self.id).values('execution_subdir').distinct()
2244 subdirs = (entry['execution_subdir'] for entry in query)
2245 groups = (re.match(r'group(\d+)', subdir) for subdir in subdirs)
2246 ids = [int(match.group(1)) for match in groups if match]
2247 if ids:
2248 next_id = max(ids) + 1
2249 else:
2250 next_id = 0
2251 return "group%d" % next_id
2252
2253
showardb2e2c322008-10-14 17:33:55 +00002254 def _write_control_file(self):
2255 'Writes control file out to disk, returns a filename'
2256 control_fd, control_filename = tempfile.mkstemp(suffix='.control_file')
2257 control_file = os.fdopen(control_fd, 'w')
jadmanski0afbb632008-06-06 21:10:57 +00002258 if self.control_file:
showardb2e2c322008-10-14 17:33:55 +00002259 control_file.write(self.control_file)
2260 control_file.close()
2261 return control_filename
mbligh36768f02008-02-22 18:28:33 +00002262
showardb2e2c322008-10-14 17:33:55 +00002263
showard2bab8f42008-11-12 18:15:22 +00002264 def get_group_entries(self, queue_entry_from_group):
2265 execution_subdir = queue_entry_from_group.execution_subdir
showarde788ea62008-11-17 21:02:47 +00002266 return list(HostQueueEntry.fetch(
2267 where='job_id=%s AND execution_subdir=%s',
2268 params=(self.id, execution_subdir)))
showard2bab8f42008-11-12 18:15:22 +00002269
2270
2271 def get_job_tag(self, queue_entries):
2272 assert len(queue_entries) > 0
2273 execution_subdir = queue_entries[0].execution_subdir
2274 assert execution_subdir
2275 return "%s-%s/%s" % (self.id, self.owner, execution_subdir)
showardb2e2c322008-10-14 17:33:55 +00002276
2277
2278 def _get_autoserv_params(self, queue_entries):
2279 results_dir = self.create_results_dir(queue_entries[0])
2280 control_filename = self._write_control_file()
jadmanski0afbb632008-06-06 21:10:57 +00002281 hostnames = ','.join([entry.get_host().hostname
2282 for entry in queue_entries])
showard2bab8f42008-11-12 18:15:22 +00002283 job_tag = self.get_job_tag(queue_entries)
mbligh36768f02008-02-22 18:28:33 +00002284
showardb2e2c322008-10-14 17:33:55 +00002285 params = [_autoserv_path, '-P', job_tag, '-p', '-n',
showard21baa452008-10-21 00:08:39 +00002286 '-r', os.path.abspath(results_dir), '-u', self.owner,
2287 '-l', self.name, '-m', hostnames, control_filename]
mbligh36768f02008-02-22 18:28:33 +00002288
jadmanski0afbb632008-06-06 21:10:57 +00002289 if not self.is_server_job():
2290 params.append('-c')
mbligh36768f02008-02-22 18:28:33 +00002291
showardb2e2c322008-10-14 17:33:55 +00002292 return params
mblighe2586682008-02-29 22:45:46 +00002293
mbligh36768f02008-02-22 18:28:33 +00002294
showard2bab8f42008-11-12 18:15:22 +00002295 def _get_pre_job_tasks(self, queue_entry):
showard21baa452008-10-21 00:08:39 +00002296 do_reboot = False
showard0fc38302008-10-23 00:44:07 +00002297 if self.reboot_before == models.RebootBefore.ALWAYS:
showard21baa452008-10-21 00:08:39 +00002298 do_reboot = True
showard0fc38302008-10-23 00:44:07 +00002299 elif self.reboot_before == models.RebootBefore.IF_DIRTY:
showard21baa452008-10-21 00:08:39 +00002300 do_reboot = queue_entry.get_host().dirty
2301
2302 tasks = []
2303 if do_reboot:
showard45ae8192008-11-05 19:32:53 +00002304 tasks.append(CleanupTask(queue_entry=queue_entry))
showard2bab8f42008-11-12 18:15:22 +00002305 tasks.append(VerifyTask(queue_entry=queue_entry))
showard21baa452008-10-21 00:08:39 +00002306 return tasks
2307
2308
showard2bab8f42008-11-12 18:15:22 +00002309 def _assign_new_group(self, queue_entries):
2310 if len(queue_entries) == 1:
2311 group_name = queue_entries[0].get_host().hostname
2312 else:
2313 group_name = self._next_group_name()
2314 print 'Running synchronous job %d hosts %s as %s' % (
2315 self.id, [entry.host.hostname for entry in queue_entries],
2316 group_name)
2317
2318 for queue_entry in queue_entries:
2319 queue_entry.set_execution_subdir(group_name)
2320
2321
2322 def _choose_group_to_run(self, include_queue_entry):
2323 chosen_entries = [include_queue_entry]
2324
2325 num_entries_needed = self.synch_count - 1
2326 if num_entries_needed > 0:
2327 pending_entries = HostQueueEntry.fetch(
2328 where='job_id = %s AND status = "Pending" AND id != %s',
2329 params=(self.id, include_queue_entry.id))
2330 chosen_entries += list(pending_entries)[:num_entries_needed]
2331
2332 self._assign_new_group(chosen_entries)
2333 return chosen_entries
2334
2335
2336 def run(self, queue_entry):
showardb2e2c322008-10-14 17:33:55 +00002337 if not self.is_ready():
showard9976ce92008-10-15 20:28:13 +00002338 if self.run_verify:
showarde58e3f82008-11-20 19:04:59 +00002339 queue_entry.set_status(models.HostQueueEntry.Status.VERIFYING)
showard2bab8f42008-11-12 18:15:22 +00002340 return Agent(self._get_pre_job_tasks(queue_entry),
showard21baa452008-10-21 00:08:39 +00002341 [queue_entry.id])
showard9976ce92008-10-15 20:28:13 +00002342 else:
2343 return queue_entry.on_pending()
mbligh36768f02008-02-22 18:28:33 +00002344
showard2bab8f42008-11-12 18:15:22 +00002345 queue_entries = self._choose_group_to_run(queue_entry)
2346 return self._finish_run(queue_entries)
showardb2e2c322008-10-14 17:33:55 +00002347
2348
2349 def _finish_run(self, queue_entries, initial_tasks=[]):
showardb2ccdda2008-10-28 20:39:05 +00002350 for queue_entry in queue_entries:
2351 queue_entry.set_status('Starting')
showardb2e2c322008-10-14 17:33:55 +00002352 params = self._get_autoserv_params(queue_entries)
2353 queue_task = QueueTask(job=self, queue_entries=queue_entries,
2354 cmd=params)
2355 tasks = initial_tasks + [queue_task]
2356 entry_ids = [entry.id for entry in queue_entries]
2357
2358 return Agent(tasks, entry_ids, num_processes=len(queue_entries))
2359
2360
mbligh36768f02008-02-22 18:28:33 +00002361if __name__ == '__main__':
jadmanski0afbb632008-06-06 21:10:57 +00002362 main()