blob: db492219ed75df567aa14a58d401b9900bfa0168 [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)
227 if poll_fn() == None:
228 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
710 job.abort(None)
711
712
jadmanski0afbb632008-06-06 21:10:57 +0000713 def _clear_inactive_blocks(self):
714 """
715 Clear out blocks for all completed jobs.
716 """
717 # this would be simpler using NOT IN (subquery), but MySQL
718 # treats all IN subqueries as dependent, so this optimizes much
719 # better
720 _db.execute("""
721 DELETE ihq FROM ineligible_host_queues ihq
showard4eaaf522008-06-06 22:28:07 +0000722 LEFT JOIN (SELECT DISTINCT job_id FROM host_queue_entries
jadmanski0afbb632008-06-06 21:10:57 +0000723 WHERE NOT complete) hqe
724 USING (job_id) WHERE hqe.job_id IS NULL""")
showard04c82c52008-05-29 19:38:12 +0000725
726
showardb95b1bd2008-08-15 18:11:04 +0000727 def _get_pending_queue_entries(self):
showard63a34772008-08-18 19:32:50 +0000728 # prioritize by job priority, then non-metahost over metahost, then FIFO
729 return list(HostQueueEntry.fetch(
730 where='NOT complete AND NOT active',
showard3dd6b882008-10-27 19:21:39 +0000731 order_by='priority DESC, meta_host, job_id'))
mbligh36768f02008-02-22 18:28:33 +0000732
733
jadmanski0afbb632008-06-06 21:10:57 +0000734 def _schedule_new_jobs(self):
735 print "finding work"
736
showard63a34772008-08-18 19:32:50 +0000737 queue_entries = self._get_pending_queue_entries()
738 if not queue_entries:
showardb95b1bd2008-08-15 18:11:04 +0000739 return
showardb95b1bd2008-08-15 18:11:04 +0000740
showard63a34772008-08-18 19:32:50 +0000741 self._host_scheduler.refresh(queue_entries)
showardb95b1bd2008-08-15 18:11:04 +0000742
showard63a34772008-08-18 19:32:50 +0000743 for queue_entry in queue_entries:
744 assigned_host = self._host_scheduler.find_eligible_host(queue_entry)
showardb95b1bd2008-08-15 18:11:04 +0000745 if not assigned_host:
jadmanski0afbb632008-06-06 21:10:57 +0000746 continue
showardb95b1bd2008-08-15 18:11:04 +0000747 self._run_queue_entry(queue_entry, assigned_host)
748
749
750 def _run_queue_entry(self, queue_entry, host):
751 agent = queue_entry.run(assigned_host=host)
showard9976ce92008-10-15 20:28:13 +0000752 # in some cases (synchronous jobs with run_verify=False), agent may be None
753 if agent:
754 self.add_agent(agent)
mblighd5c95802008-03-05 00:33:46 +0000755
756
jadmanski0afbb632008-06-06 21:10:57 +0000757 def _find_aborting(self):
758 num_aborted = 0
759 # Find jobs that are aborting
760 for entry in queue_entries_to_abort():
761 agents_to_abort = self.get_agents(entry)
showard1be97432008-10-17 15:30:45 +0000762 for agent in agents_to_abort:
763 self.remove_agent(agent)
764
765 agent = entry.abort(agents_to_abort)
766 self.add_agent(agent)
jadmanski0afbb632008-06-06 21:10:57 +0000767 num_aborted += 1
768 if num_aborted >= 50:
769 break
770
771
showard4c5374f2008-09-04 17:02:56 +0000772 def _can_start_agent(self, agent, num_running_processes,
773 num_started_this_cycle, have_reached_limit):
774 # always allow zero-process agents to run
775 if agent.num_processes == 0:
776 return True
777 # don't allow any nonzero-process agents to run after we've reached a
778 # limit (this avoids starvation of many-process agents)
779 if have_reached_limit:
780 return False
781 # total process throttling
782 if (num_running_processes + agent.num_processes >
783 self.max_running_processes):
784 return False
785 # if a single agent exceeds the per-cycle throttling, still allow it to
786 # run when it's the first agent in the cycle
787 if num_started_this_cycle == 0:
788 return True
789 # per-cycle throttling
790 if (num_started_this_cycle + agent.num_processes >
791 self.max_processes_started_per_cycle):
792 return False
793 return True
794
795
jadmanski0afbb632008-06-06 21:10:57 +0000796 def _handle_agents(self):
showard4c5374f2008-09-04 17:02:56 +0000797 num_running_processes = self.num_running_processes()
jadmanski0afbb632008-06-06 21:10:57 +0000798 num_started_this_cycle = 0
showard4c5374f2008-09-04 17:02:56 +0000799 have_reached_limit = False
800 # iterate over copy, so we can remove agents during iteration
801 for agent in list(self._agents):
802 if agent.is_done():
jadmanski0afbb632008-06-06 21:10:57 +0000803 print "agent finished"
showard4c5374f2008-09-04 17:02:56 +0000804 self._agents.remove(agent)
showard4c5374f2008-09-04 17:02:56 +0000805 continue
806 if not agent.is_running():
807 if not self._can_start_agent(agent, num_running_processes,
808 num_started_this_cycle,
809 have_reached_limit):
810 have_reached_limit = True
811 continue
812 num_running_processes += agent.num_processes
813 num_started_this_cycle += agent.num_processes
814 agent.tick()
815 print num_running_processes, 'running processes'
mbligh36768f02008-02-22 18:28:33 +0000816
817
showardfa8629c2008-11-04 16:51:23 +0000818 def _check_for_db_inconsistencies(self):
819 query = models.HostQueueEntry.objects.filter(active=True, complete=True)
820 if query.count() != 0:
821 subject = ('%d queue entries found with active=complete=1'
822 % query.count())
823 message = '\n'.join(str(entry.get_object_dict())
824 for entry in query[:50])
825 if len(query) > 50:
826 message += '\n(truncated)\n'
827
828 print subject
829 email_manager.enqueue_notify_email(subject, message)
830
831
mbligh36768f02008-02-22 18:28:33 +0000832class RunMonitor(object):
jadmanski0afbb632008-06-06 21:10:57 +0000833 def __init__(self, cmd, nice_level = None, log_file = None):
834 self.nice_level = nice_level
835 self.log_file = log_file
836 self.cmd = cmd
showard2bab8f42008-11-12 18:15:22 +0000837 self.proc = None
mbligh36768f02008-02-22 18:28:33 +0000838
jadmanski0afbb632008-06-06 21:10:57 +0000839 def run(self):
840 if self.nice_level:
841 nice_cmd = ['nice','-n', str(self.nice_level)]
842 nice_cmd.extend(self.cmd)
843 self.cmd = nice_cmd
mbligh36768f02008-02-22 18:28:33 +0000844
jadmanski0afbb632008-06-06 21:10:57 +0000845 out_file = None
846 if self.log_file:
847 try:
848 os.makedirs(os.path.dirname(self.log_file))
849 except OSError, exc:
850 if exc.errno != errno.EEXIST:
851 log_stacktrace(
852 'Unexpected error creating logfile '
853 'directory for %s' % self.log_file)
854 try:
855 out_file = open(self.log_file, 'a')
856 out_file.write("\n%s\n" % ('*'*80))
857 out_file.write("%s> %s\n" %
858 (time.strftime("%X %x"),
859 self.cmd))
860 out_file.write("%s\n" % ('*'*80))
861 except (OSError, IOError):
862 log_stacktrace('Error opening log file %s' %
863 self.log_file)
mblighcadb3532008-04-15 17:46:26 +0000864
jadmanski0afbb632008-06-06 21:10:57 +0000865 if not out_file:
866 out_file = open('/dev/null', 'w')
mblighcadb3532008-04-15 17:46:26 +0000867
jadmanski0afbb632008-06-06 21:10:57 +0000868 in_devnull = open('/dev/null', 'r')
869 print "cmd = %s" % self.cmd
870 print "path = %s" % os.getcwd()
mbligh36768f02008-02-22 18:28:33 +0000871
jadmanski0afbb632008-06-06 21:10:57 +0000872 self.proc = subprocess.Popen(self.cmd, stdout=out_file,
873 stderr=subprocess.STDOUT,
874 stdin=in_devnull)
875 out_file.close()
876 in_devnull.close()
mbligh36768f02008-02-22 18:28:33 +0000877
878
showard2bab8f42008-11-12 18:15:22 +0000879 def has_pid(self):
880 return self.proc is not None
881
882
jadmanski0afbb632008-06-06 21:10:57 +0000883 def get_pid(self):
884 return self.proc.pid
mblighbb421852008-03-11 22:36:16 +0000885
886
jadmanski0afbb632008-06-06 21:10:57 +0000887 def kill(self):
showard2bab8f42008-11-12 18:15:22 +0000888 if self.has_pid():
889 kill_autoserv(self.get_pid(), self.exit_code)
mblighbb421852008-03-11 22:36:16 +0000890
mbligh36768f02008-02-22 18:28:33 +0000891
jadmanski0afbb632008-06-06 21:10:57 +0000892 def exit_code(self):
893 return self.proc.poll()
mbligh36768f02008-02-22 18:28:33 +0000894
895
mblighbb421852008-03-11 22:36:16 +0000896class PidfileException(Exception):
jadmanski0afbb632008-06-06 21:10:57 +0000897 """\
898 Raised when there's some unexpected behavior with the pid file.
899 """
mblighbb421852008-03-11 22:36:16 +0000900
901
902class PidfileRunMonitor(RunMonitor):
showard21baa452008-10-21 00:08:39 +0000903 class PidfileState(object):
904 pid = None
905 exit_status = None
906 num_tests_failed = None
907
908 def reset(self):
909 self.pid = self.exit_status = self.all_tests_passed = None
910
911
jadmanski0afbb632008-06-06 21:10:57 +0000912 def __init__(self, results_dir, cmd=None, nice_level=None,
913 log_file=None):
914 self.results_dir = os.path.abspath(results_dir)
915 self.pid_file = os.path.join(results_dir, AUTOSERV_PID_FILE)
916 self.lost_process = False
917 self.start_time = time.time()
showard21baa452008-10-21 00:08:39 +0000918 self._state = self.PidfileState()
showardb376bc52008-06-13 20:48:45 +0000919 super(PidfileRunMonitor, self).__init__(cmd, nice_level, log_file)
mblighbb421852008-03-11 22:36:16 +0000920
921
showard21baa452008-10-21 00:08:39 +0000922 def has_pid(self):
923 self._get_pidfile_info()
924 return self._state.pid is not None
925
926
jadmanski0afbb632008-06-06 21:10:57 +0000927 def get_pid(self):
showard21baa452008-10-21 00:08:39 +0000928 self._get_pidfile_info()
929 assert self._state.pid is not None
930 return self._state.pid
mblighbb421852008-03-11 22:36:16 +0000931
932
jadmanski0afbb632008-06-06 21:10:57 +0000933 def _check_command_line(self, command_line, spacer=' ',
934 print_error=False):
935 results_dir_arg = spacer.join(('', '-r', self.results_dir, ''))
936 match = results_dir_arg in command_line
937 if print_error and not match:
938 print '%s not found in %s' % (repr(results_dir_arg),
939 repr(command_line))
940 return match
mbligh90a549d2008-03-25 23:52:34 +0000941
942
showard21baa452008-10-21 00:08:39 +0000943 def _check_proc_fs(self):
944 cmdline_path = os.path.join('/proc', str(self._state.pid), 'cmdline')
jadmanski0afbb632008-06-06 21:10:57 +0000945 try:
946 cmdline_file = open(cmdline_path, 'r')
947 cmdline = cmdline_file.read().strip()
948 cmdline_file.close()
949 except IOError:
950 return False
951 # /proc/.../cmdline has \x00 separating args
952 return self._check_command_line(cmdline, spacer='\x00',
953 print_error=True)
mblighbb421852008-03-11 22:36:16 +0000954
955
showard21baa452008-10-21 00:08:39 +0000956 def _read_pidfile(self):
957 self._state.reset()
jadmanski0afbb632008-06-06 21:10:57 +0000958 if not os.path.exists(self.pid_file):
showard21baa452008-10-21 00:08:39 +0000959 return
jadmanski0afbb632008-06-06 21:10:57 +0000960 file_obj = open(self.pid_file, 'r')
961 lines = file_obj.readlines()
962 file_obj.close()
showard3dd6b882008-10-27 19:21:39 +0000963 if not lines:
964 return
965 if len(lines) > 3:
showard21baa452008-10-21 00:08:39 +0000966 raise PidfileException('Corrupt pid file (%d lines) at %s:\n%s' %
967 (len(lines), self.pid_file, lines))
jadmanski0afbb632008-06-06 21:10:57 +0000968 try:
showard21baa452008-10-21 00:08:39 +0000969 self._state.pid = int(lines[0])
970 if len(lines) > 1:
971 self._state.exit_status = int(lines[1])
972 if len(lines) == 3:
973 self._state.num_tests_failed = int(lines[2])
974 else:
975 # maintain backwards-compatibility with two-line pidfiles
976 self._state.num_tests_failed = 0
jadmanski0afbb632008-06-06 21:10:57 +0000977 except ValueError, exc:
showard3dd6b882008-10-27 19:21:39 +0000978 raise PidfileException('Corrupt pid file: ' + str(exc.args))
mblighbb421852008-03-11 22:36:16 +0000979
mblighbb421852008-03-11 22:36:16 +0000980
jadmanski0afbb632008-06-06 21:10:57 +0000981 def _find_autoserv_proc(self):
982 autoserv_procs = Dispatcher.find_autoservs()
983 for pid, args in autoserv_procs.iteritems():
984 if self._check_command_line(args):
985 return pid, args
986 return None, None
mbligh90a549d2008-03-25 23:52:34 +0000987
988
showard21baa452008-10-21 00:08:39 +0000989 def _handle_pidfile_error(self, error, message=''):
990 message = error + '\nPid: %s\nPidfile: %s\n%s' % (self._state.pid,
991 self.pid_file,
992 message)
993 print message
994 email_manager.enqueue_notify_email(error, message)
995 if self._state.pid is not None:
996 pid = self._state.pid
997 else:
998 pid = 0
999 self.on_lost_process(pid)
1000
1001
1002 def _get_pidfile_info_helper(self):
jadmanski0afbb632008-06-06 21:10:57 +00001003 if self.lost_process:
showard21baa452008-10-21 00:08:39 +00001004 return
mblighbb421852008-03-11 22:36:16 +00001005
showard21baa452008-10-21 00:08:39 +00001006 self._read_pidfile()
mblighbb421852008-03-11 22:36:16 +00001007
showard21baa452008-10-21 00:08:39 +00001008 if self._state.pid is None:
1009 self._handle_no_pid()
1010 return
mbligh90a549d2008-03-25 23:52:34 +00001011
showard21baa452008-10-21 00:08:39 +00001012 if self._state.exit_status is None:
jadmanski0afbb632008-06-06 21:10:57 +00001013 # double check whether or not autoserv is running
showard21baa452008-10-21 00:08:39 +00001014 proc_running = self._check_proc_fs()
jadmanski0afbb632008-06-06 21:10:57 +00001015 if proc_running:
showard21baa452008-10-21 00:08:39 +00001016 return
mbligh90a549d2008-03-25 23:52:34 +00001017
jadmanski0afbb632008-06-06 21:10:57 +00001018 # pid but no process - maybe process *just* exited
showard21baa452008-10-21 00:08:39 +00001019 self._read_pidfile()
1020 if self._state.exit_status is None:
jadmanski0afbb632008-06-06 21:10:57 +00001021 # autoserv exited without writing an exit code
1022 # to the pidfile
showard21baa452008-10-21 00:08:39 +00001023 self._handle_pidfile_error(
1024 'autoserv died without writing exit code')
mblighbb421852008-03-11 22:36:16 +00001025
showard21baa452008-10-21 00:08:39 +00001026
1027 def _get_pidfile_info(self):
1028 """\
1029 After completion, self._state will contain:
1030 pid=None, exit_status=None if autoserv has not yet run
1031 pid!=None, exit_status=None if autoserv is running
1032 pid!=None, exit_status!=None if autoserv has completed
1033 """
1034 try:
1035 self._get_pidfile_info_helper()
1036 except PidfileException, exc:
1037 self._handle_pidfile_error('Pidfile error', traceback.format_exc())
mblighbb421852008-03-11 22:36:16 +00001038
1039
jadmanski0afbb632008-06-06 21:10:57 +00001040 def _handle_no_pid(self):
1041 """\
1042 Called when no pidfile is found or no pid is in the pidfile.
1043 """
1044 # is autoserv running?
1045 pid, args = self._find_autoserv_proc()
1046 if pid is None:
1047 # no autoserv process running
1048 message = 'No pid found at ' + self.pid_file
1049 else:
1050 message = ("Process %d (%s) hasn't written pidfile %s" %
1051 (pid, args, self.pid_file))
mbligh90a549d2008-03-25 23:52:34 +00001052
jadmanski0afbb632008-06-06 21:10:57 +00001053 print message
1054 if time.time() - self.start_time > PIDFILE_TIMEOUT:
1055 email_manager.enqueue_notify_email(
1056 'Process has failed to write pidfile', message)
1057 if pid is not None:
1058 kill_autoserv(pid)
1059 else:
1060 pid = 0
1061 self.on_lost_process(pid)
showard21baa452008-10-21 00:08:39 +00001062 return
mbligh90a549d2008-03-25 23:52:34 +00001063
1064
jadmanski0afbb632008-06-06 21:10:57 +00001065 def on_lost_process(self, pid):
1066 """\
1067 Called when autoserv has exited without writing an exit status,
1068 or we've timed out waiting for autoserv to write a pid to the
1069 pidfile. In either case, we just return failure and the caller
1070 should signal some kind of warning.
mbligh90a549d2008-03-25 23:52:34 +00001071
jadmanski0afbb632008-06-06 21:10:57 +00001072 pid is unimportant here, as it shouldn't be used by anyone.
1073 """
1074 self.lost_process = True
showard21baa452008-10-21 00:08:39 +00001075 self._state.pid = pid
1076 self._state.exit_status = 1
1077 self._state.num_tests_failed = 0
mbligh90a549d2008-03-25 23:52:34 +00001078
1079
jadmanski0afbb632008-06-06 21:10:57 +00001080 def exit_code(self):
showard21baa452008-10-21 00:08:39 +00001081 self._get_pidfile_info()
1082 return self._state.exit_status
1083
1084
1085 def num_tests_failed(self):
1086 self._get_pidfile_info()
1087 assert self._state.num_tests_failed is not None
1088 return self._state.num_tests_failed
mblighbb421852008-03-11 22:36:16 +00001089
1090
mbligh36768f02008-02-22 18:28:33 +00001091class Agent(object):
showard4c5374f2008-09-04 17:02:56 +00001092 def __init__(self, tasks, queue_entry_ids=[], num_processes=1):
jadmanski0afbb632008-06-06 21:10:57 +00001093 self.active_task = None
1094 self.queue = Queue.Queue(0)
1095 self.dispatcher = None
1096 self.queue_entry_ids = queue_entry_ids
showard4c5374f2008-09-04 17:02:56 +00001097 self.num_processes = num_processes
jadmanski0afbb632008-06-06 21:10:57 +00001098
1099 for task in tasks:
1100 self.add_task(task)
mbligh36768f02008-02-22 18:28:33 +00001101
1102
jadmanski0afbb632008-06-06 21:10:57 +00001103 def add_task(self, task):
1104 self.queue.put_nowait(task)
1105 task.agent = self
mbligh36768f02008-02-22 18:28:33 +00001106
1107
jadmanski0afbb632008-06-06 21:10:57 +00001108 def tick(self):
showard21baa452008-10-21 00:08:39 +00001109 while not self.is_done():
1110 if self.active_task and not self.active_task.is_done():
1111 self.active_task.poll()
1112 if not self.active_task.is_done():
1113 return
1114 self._next_task()
mbligh36768f02008-02-22 18:28:33 +00001115
1116
jadmanski0afbb632008-06-06 21:10:57 +00001117 def _next_task(self):
1118 print "agent picking task"
1119 if self.active_task:
1120 assert self.active_task.is_done()
mbligh36768f02008-02-22 18:28:33 +00001121
jadmanski0afbb632008-06-06 21:10:57 +00001122 if not self.active_task.success:
1123 self.on_task_failure()
mblighe2586682008-02-29 22:45:46 +00001124
jadmanski0afbb632008-06-06 21:10:57 +00001125 self.active_task = None
1126 if not self.is_done():
1127 self.active_task = self.queue.get_nowait()
1128 if self.active_task:
1129 self.active_task.start()
mbligh36768f02008-02-22 18:28:33 +00001130
1131
jadmanski0afbb632008-06-06 21:10:57 +00001132 def on_task_failure(self):
1133 self.queue = Queue.Queue(0)
1134 for task in self.active_task.failure_tasks:
1135 self.add_task(task)
mbligh16c722d2008-03-05 00:58:44 +00001136
mblighe2586682008-02-29 22:45:46 +00001137
showard4c5374f2008-09-04 17:02:56 +00001138 def is_running(self):
jadmanski0afbb632008-06-06 21:10:57 +00001139 return self.active_task is not None
showardec113162008-05-08 00:52:49 +00001140
1141
jadmanski0afbb632008-06-06 21:10:57 +00001142 def is_done(self):
1143 return self.active_task == None and self.queue.empty()
mbligh36768f02008-02-22 18:28:33 +00001144
1145
jadmanski0afbb632008-06-06 21:10:57 +00001146 def start(self):
1147 assert self.dispatcher
mbligh36768f02008-02-22 18:28:33 +00001148
jadmanski0afbb632008-06-06 21:10:57 +00001149 self._next_task()
mbligh36768f02008-02-22 18:28:33 +00001150
jadmanski0afbb632008-06-06 21:10:57 +00001151
mbligh36768f02008-02-22 18:28:33 +00001152class AgentTask(object):
jadmanski0afbb632008-06-06 21:10:57 +00001153 def __init__(self, cmd, failure_tasks = []):
1154 self.done = False
1155 self.failure_tasks = failure_tasks
1156 self.started = False
1157 self.cmd = cmd
1158 self.task = None
1159 self.agent = None
1160 self.monitor = None
1161 self.success = None
mbligh36768f02008-02-22 18:28:33 +00001162
1163
jadmanski0afbb632008-06-06 21:10:57 +00001164 def poll(self):
1165 print "poll"
1166 if self.monitor:
1167 self.tick(self.monitor.exit_code())
1168 else:
1169 self.finished(False)
mbligh36768f02008-02-22 18:28:33 +00001170
1171
jadmanski0afbb632008-06-06 21:10:57 +00001172 def tick(self, exit_code):
1173 if exit_code==None:
1174 return
1175# print "exit_code was %d" % exit_code
1176 if exit_code == 0:
1177 success = True
1178 else:
1179 success = False
mbligh36768f02008-02-22 18:28:33 +00001180
jadmanski0afbb632008-06-06 21:10:57 +00001181 self.finished(success)
mbligh36768f02008-02-22 18:28:33 +00001182
1183
jadmanski0afbb632008-06-06 21:10:57 +00001184 def is_done(self):
1185 return self.done
mbligh36768f02008-02-22 18:28:33 +00001186
1187
jadmanski0afbb632008-06-06 21:10:57 +00001188 def finished(self, success):
1189 self.done = True
1190 self.success = success
1191 self.epilog()
mbligh36768f02008-02-22 18:28:33 +00001192
1193
jadmanski0afbb632008-06-06 21:10:57 +00001194 def prolog(self):
1195 pass
mblighd64e5702008-04-04 21:39:28 +00001196
1197
jadmanski0afbb632008-06-06 21:10:57 +00001198 def create_temp_resultsdir(self, suffix=''):
1199 self.temp_results_dir = tempfile.mkdtemp(suffix=suffix)
mblighd64e5702008-04-04 21:39:28 +00001200
mbligh36768f02008-02-22 18:28:33 +00001201
jadmanski0afbb632008-06-06 21:10:57 +00001202 def cleanup(self):
1203 if (hasattr(self, 'temp_results_dir') and
1204 os.path.exists(self.temp_results_dir)):
1205 shutil.rmtree(self.temp_results_dir)
mbligh36768f02008-02-22 18:28:33 +00001206
1207
jadmanski0afbb632008-06-06 21:10:57 +00001208 def epilog(self):
1209 self.cleanup()
mbligh36768f02008-02-22 18:28:33 +00001210
1211
jadmanski0afbb632008-06-06 21:10:57 +00001212 def start(self):
1213 assert self.agent
1214
1215 if not self.started:
1216 self.prolog()
1217 self.run()
1218
1219 self.started = True
1220
1221
1222 def abort(self):
1223 if self.monitor:
1224 self.monitor.kill()
1225 self.done = True
1226 self.cleanup()
1227
1228
1229 def run(self):
1230 if self.cmd:
1231 print "agent starting monitor"
1232 log_file = None
showard97aed502008-11-04 02:01:24 +00001233 if hasattr(self, 'log_file'):
1234 log_file = self.log_file
1235 elif hasattr(self, 'host'):
jadmanski0afbb632008-06-06 21:10:57 +00001236 log_file = os.path.join(RESULTS_DIR, 'hosts',
1237 self.host.hostname)
1238 self.monitor = RunMonitor(
showard97aed502008-11-04 02:01:24 +00001239 self.cmd, nice_level=AUTOSERV_NICE_LEVEL, log_file=log_file)
jadmanski0afbb632008-06-06 21:10:57 +00001240 self.monitor.run()
mbligh36768f02008-02-22 18:28:33 +00001241
1242
1243class RepairTask(AgentTask):
showarde788ea62008-11-17 21:02:47 +00001244 def __init__(self, host, queue_entry=None):
jadmanski0afbb632008-06-06 21:10:57 +00001245 """\
1246 fail_queue_entry: queue entry to mark failed if this repair
1247 fails.
1248 """
jadmanskifb7cfb12008-07-09 14:13:21 +00001249 protection = host_protections.Protection.get_string(host.protection)
jadmanski542537f2008-07-24 14:14:56 +00001250 # normalize the protection name
1251 protection = host_protections.Protection.get_attr_name(protection)
jadmanski0afbb632008-06-06 21:10:57 +00001252 self.create_temp_resultsdir('.repair')
1253 cmd = [_autoserv_path , '-R', '-m', host.hostname,
jadmanskifb7cfb12008-07-09 14:13:21 +00001254 '-r', self.temp_results_dir, '--host-protection', protection]
jadmanski0afbb632008-06-06 21:10:57 +00001255 self.host = host
showarde788ea62008-11-17 21:02:47 +00001256 self.queue_entry = queue_entry
jadmanski0afbb632008-06-06 21:10:57 +00001257 super(RepairTask, self).__init__(cmd)
mblighe2586682008-02-29 22:45:46 +00001258
mbligh36768f02008-02-22 18:28:33 +00001259
jadmanski0afbb632008-06-06 21:10:57 +00001260 def prolog(self):
1261 print "repair_task starting"
1262 self.host.set_status('Repairing')
showarde788ea62008-11-17 21:02:47 +00001263 if self.queue_entry:
1264 self.queue_entry.requeue()
mbligh36768f02008-02-22 18:28:33 +00001265
1266
jadmanski0afbb632008-06-06 21:10:57 +00001267 def epilog(self):
1268 super(RepairTask, self).epilog()
1269 if self.success:
1270 self.host.set_status('Ready')
1271 else:
1272 self.host.set_status('Repair Failed')
showarde788ea62008-11-17 21:02:47 +00001273 if self.queue_entry and not self.queue_entry.meta_host:
1274 self.queue_entry.handle_host_failure()
mbligh36768f02008-02-22 18:28:33 +00001275
1276
showard8fe93b52008-11-18 17:53:22 +00001277class PreJobTask(AgentTask):
1278 def prolog(self):
1279 super(PreJobTask, self).prolog()
1280 if self.queue_entry:
1281 # clear any possibly existing results, could be a previously failed
1282 # verify or a previous execution that crashed
1283 self.queue_entry.clear_results_dir()
1284
1285
1286 def cleanup(self):
1287 if not os.path.exists(self.temp_results_dir):
1288 return
1289 should_copy_results = (self.queue_entry and not self.success
1290 and not self.queue_entry.meta_host)
1291 if should_copy_results:
1292 self.queue_entry.set_execution_subdir()
1293 self._move_results()
1294 super(PreJobTask, self).cleanup()
1295
1296
1297 def _move_results(self):
1298 assert self.queue_entry is not None
1299 target_dir = self.queue_entry.results_dir()
1300 ensure_directory_exists(target_dir)
1301 files = os.listdir(self.temp_results_dir)
1302 for filename in files:
1303 if filename == AUTOSERV_PID_FILE:
1304 continue
1305 self._force_move(os.path.join(self.temp_results_dir, filename),
1306 os.path.join(target_dir, filename))
1307
1308
1309 @staticmethod
1310 def _force_move(source, dest):
1311 """\
1312 Replacement for shutil.move() that will delete the destination
1313 if it exists, even if it's a directory.
1314 """
1315 if os.path.exists(dest):
1316 warning = 'Warning: removing existing destination file ' + dest
1317 print warning
1318 email_manager.enqueue_notify_email(warning, warning)
1319 remove_file_or_dir(dest)
1320 shutil.move(source, dest)
1321
1322
1323class VerifyTask(PreJobTask):
showard9976ce92008-10-15 20:28:13 +00001324 def __init__(self, queue_entry=None, host=None):
jadmanski0afbb632008-06-06 21:10:57 +00001325 assert bool(queue_entry) != bool(host)
mbligh36768f02008-02-22 18:28:33 +00001326
jadmanski0afbb632008-06-06 21:10:57 +00001327 self.host = host or queue_entry.host
1328 self.queue_entry = queue_entry
mbligh36768f02008-02-22 18:28:33 +00001329
jadmanski0afbb632008-06-06 21:10:57 +00001330 self.create_temp_resultsdir('.verify')
showard3d9899a2008-07-31 02:11:58 +00001331
showard2bab8f42008-11-12 18:15:22 +00001332 cmd = [_autoserv_path, '-v', '-m', self.host.hostname, '-r',
1333 self.temp_results_dir]
mbligh36768f02008-02-22 18:28:33 +00001334
showarde788ea62008-11-17 21:02:47 +00001335 failure_tasks = [RepairTask(self.host, queue_entry=queue_entry)]
mblighe2586682008-02-29 22:45:46 +00001336
showard2bab8f42008-11-12 18:15:22 +00001337 super(VerifyTask, self).__init__(cmd, failure_tasks=failure_tasks)
mblighe2586682008-02-29 22:45:46 +00001338
1339
jadmanski0afbb632008-06-06 21:10:57 +00001340 def prolog(self):
showard8fe93b52008-11-18 17:53:22 +00001341 super(VerifyTask, self).prolog()
jadmanski0afbb632008-06-06 21:10:57 +00001342 print "starting verify on %s" % (self.host.hostname)
1343 if self.queue_entry:
1344 self.queue_entry.set_status('Verifying')
jadmanski0afbb632008-06-06 21:10:57 +00001345 self.host.set_status('Verifying')
mbligh36768f02008-02-22 18:28:33 +00001346
1347
jadmanski0afbb632008-06-06 21:10:57 +00001348 def epilog(self):
1349 super(VerifyTask, self).epilog()
mbligh36768f02008-02-22 18:28:33 +00001350
jadmanski0afbb632008-06-06 21:10:57 +00001351 if self.success:
1352 self.host.set_status('Ready')
showard2bab8f42008-11-12 18:15:22 +00001353 if self.queue_entry:
1354 agent = self.queue_entry.on_pending()
1355 if agent:
1356 self.agent.dispatcher.add_agent(agent)
mbligh36768f02008-02-22 18:28:33 +00001357
1358
mbligh36768f02008-02-22 18:28:33 +00001359class QueueTask(AgentTask):
jadmanski0afbb632008-06-06 21:10:57 +00001360 def __init__(self, job, queue_entries, cmd):
1361 super(QueueTask, self).__init__(cmd)
1362 self.job = job
1363 self.queue_entries = queue_entries
mbligh36768f02008-02-22 18:28:33 +00001364
1365
jadmanski0afbb632008-06-06 21:10:57 +00001366 @staticmethod
showardd8e548a2008-09-09 03:04:57 +00001367 def _write_keyval(keyval_dir, field, value, keyval_filename='keyval'):
1368 key_path = os.path.join(keyval_dir, keyval_filename)
jadmanski0afbb632008-06-06 21:10:57 +00001369 keyval_file = open(key_path, 'a')
showardd8e548a2008-09-09 03:04:57 +00001370 print >> keyval_file, '%s=%s' % (field, str(value))
jadmanski0afbb632008-06-06 21:10:57 +00001371 keyval_file.close()
mbligh36768f02008-02-22 18:28:33 +00001372
1373
showardd8e548a2008-09-09 03:04:57 +00001374 def _host_keyval_dir(self):
1375 return os.path.join(self.results_dir(), 'host_keyvals')
1376
1377
1378 def _write_host_keyval(self, host):
1379 labels = ','.join(host.labels())
1380 self._write_keyval(self._host_keyval_dir(), 'labels', labels,
1381 keyval_filename=host.hostname)
1382
1383 def _create_host_keyval_dir(self):
1384 directory = self._host_keyval_dir()
showard2bab8f42008-11-12 18:15:22 +00001385 ensure_directory_exists(directory)
showardd8e548a2008-09-09 03:04:57 +00001386
1387
jadmanski0afbb632008-06-06 21:10:57 +00001388 def results_dir(self):
1389 return self.queue_entries[0].results_dir()
mblighbb421852008-03-11 22:36:16 +00001390
1391
jadmanski0afbb632008-06-06 21:10:57 +00001392 def run(self):
1393 """\
1394 Override AgentTask.run() so we can use a PidfileRunMonitor.
1395 """
1396 self.monitor = PidfileRunMonitor(self.results_dir(),
1397 cmd=self.cmd,
1398 nice_level=AUTOSERV_NICE_LEVEL)
1399 self.monitor.run()
mblighbb421852008-03-11 22:36:16 +00001400
1401
jadmanski0afbb632008-06-06 21:10:57 +00001402 def prolog(self):
1403 # write some job timestamps into the job keyval file
1404 queued = time.mktime(self.job.created_on.timetuple())
1405 started = time.time()
showardd8e548a2008-09-09 03:04:57 +00001406 self._write_keyval(self.results_dir(), "job_queued", int(queued))
1407 self._write_keyval(self.results_dir(), "job_started", int(started))
1408 self._create_host_keyval_dir()
jadmanski0afbb632008-06-06 21:10:57 +00001409 for queue_entry in self.queue_entries:
showardd8e548a2008-09-09 03:04:57 +00001410 self._write_host_keyval(queue_entry.host)
jadmanski0afbb632008-06-06 21:10:57 +00001411 queue_entry.set_status('Running')
1412 queue_entry.host.set_status('Running')
showard21baa452008-10-21 00:08:39 +00001413 queue_entry.host.update_field('dirty', 1)
showard2bab8f42008-11-12 18:15:22 +00001414 if self.job.synch_count == 1:
jadmanski0afbb632008-06-06 21:10:57 +00001415 assert len(self.queue_entries) == 1
1416 self.job.write_to_machines_file(self.queue_entries[0])
mbligh36768f02008-02-22 18:28:33 +00001417
1418
showard97aed502008-11-04 02:01:24 +00001419 def _finish_task(self, success):
jadmanski0afbb632008-06-06 21:10:57 +00001420 # write out the finished time into the results keyval
1421 finished = time.time()
jadmanskif7fa2cc2008-10-01 14:13:23 +00001422 self._write_keyval(self.results_dir(), "job_finished", int(finished))
jadmanskic2ac77f2008-05-16 21:44:04 +00001423
jadmanski0afbb632008-06-06 21:10:57 +00001424 # parse the results of the job
showard97aed502008-11-04 02:01:24 +00001425 reparse_task = FinalReparseTask(self.queue_entries)
1426 self.agent.dispatcher.add_agent(Agent([reparse_task]))
jadmanskif7fa2cc2008-10-01 14:13:23 +00001427
1428
showardcbd74612008-11-19 21:42:02 +00001429 def _write_status_comment(self, comment):
1430 status_log = open(os.path.join(self.results_dir(), 'status.log'), 'a')
1431 status_log.write('INFO\t----\t----\t' + comment)
1432 status_log.close()
1433
1434
jadmanskif7fa2cc2008-10-01 14:13:23 +00001435 def _log_abort(self):
1436 # build up sets of all the aborted_by and aborted_on values
1437 aborted_by, aborted_on = set(), set()
1438 for queue_entry in self.queue_entries:
1439 if queue_entry.aborted_by:
1440 aborted_by.add(queue_entry.aborted_by)
1441 t = int(time.mktime(queue_entry.aborted_on.timetuple()))
1442 aborted_on.add(t)
1443
1444 # extract some actual, unique aborted by value and write it out
1445 assert len(aborted_by) <= 1
1446 if len(aborted_by) == 1:
showardcbd74612008-11-19 21:42:02 +00001447 aborted_by_value = aborted_by.pop()
1448 aborted_on_value = max(aborted_on)
1449 else:
1450 aborted_by_value = 'autotest_system'
1451 aborted_on_value = int(time.time())
1452 results_dir = self.results_dir()
1453 self._write_keyval(results_dir, "aborted_by", aborted_by_value)
1454 self._write_keyval(results_dir, "aborted_on", aborted_on_value)
1455 aborted_on_string = str(datetime.datetime.fromtimestamp(
1456 aborted_on_value))
1457 self._write_status_comment('Job aborted by %s on %s' %
1458 (aborted_by_value, aborted_on_string))
jadmanskic2ac77f2008-05-16 21:44:04 +00001459
1460
jadmanski0afbb632008-06-06 21:10:57 +00001461 def abort(self):
1462 super(QueueTask, self).abort()
jadmanskif7fa2cc2008-10-01 14:13:23 +00001463 self._log_abort()
showard97aed502008-11-04 02:01:24 +00001464 self._finish_task(False)
jadmanskic2ac77f2008-05-16 21:44:04 +00001465
1466
showard21baa452008-10-21 00:08:39 +00001467 def _reboot_hosts(self):
1468 reboot_after = self.job.reboot_after
1469 do_reboot = False
showard0fc38302008-10-23 00:44:07 +00001470 if reboot_after == models.RebootAfter.ALWAYS:
showard21baa452008-10-21 00:08:39 +00001471 do_reboot = True
showard0fc38302008-10-23 00:44:07 +00001472 elif reboot_after == models.RebootAfter.IF_ALL_TESTS_PASSED:
showard21baa452008-10-21 00:08:39 +00001473 num_tests_failed = self.monitor.num_tests_failed()
1474 do_reboot = (self.success and num_tests_failed == 0)
1475
showard8ebca792008-11-04 21:54:22 +00001476 for queue_entry in self.queue_entries:
1477 if do_reboot:
showard45ae8192008-11-05 19:32:53 +00001478 # don't pass the queue entry to the CleanupTask. if the cleanup
showardfa8629c2008-11-04 16:51:23 +00001479 # fails, the job doesn't care -- it's over.
showard45ae8192008-11-05 19:32:53 +00001480 cleanup_task = CleanupTask(host=queue_entry.get_host())
1481 self.agent.dispatcher.add_agent(Agent([cleanup_task]))
showard8ebca792008-11-04 21:54:22 +00001482 else:
1483 queue_entry.host.set_status('Ready')
showard21baa452008-10-21 00:08:39 +00001484
1485
jadmanski0afbb632008-06-06 21:10:57 +00001486 def epilog(self):
1487 super(QueueTask, self).epilog()
jadmanski0afbb632008-06-06 21:10:57 +00001488 for queue_entry in self.queue_entries:
showard97aed502008-11-04 02:01:24 +00001489 # set status to PARSING here so queue entry is marked complete
1490 queue_entry.set_status(models.HostQueueEntry.Status.PARSING)
mbligh36768f02008-02-22 18:28:33 +00001491
showard97aed502008-11-04 02:01:24 +00001492 self._finish_task(self.success)
showard21baa452008-10-21 00:08:39 +00001493 self._reboot_hosts()
mblighbb421852008-03-11 22:36:16 +00001494
showard97aed502008-11-04 02:01:24 +00001495 print "queue_task finished with succes=%s" % self.success
mbligh36768f02008-02-22 18:28:33 +00001496
1497
mblighbb421852008-03-11 22:36:16 +00001498class RecoveryQueueTask(QueueTask):
jadmanski0afbb632008-06-06 21:10:57 +00001499 def __init__(self, job, queue_entries, run_monitor):
1500 super(RecoveryQueueTask, self).__init__(job,
1501 queue_entries, cmd=None)
1502 self.run_monitor = run_monitor
mblighbb421852008-03-11 22:36:16 +00001503
1504
jadmanski0afbb632008-06-06 21:10:57 +00001505 def run(self):
1506 self.monitor = self.run_monitor
mblighbb421852008-03-11 22:36:16 +00001507
1508
jadmanski0afbb632008-06-06 21:10:57 +00001509 def prolog(self):
1510 # recovering an existing process - don't do prolog
1511 pass
mblighbb421852008-03-11 22:36:16 +00001512
1513
showard8fe93b52008-11-18 17:53:22 +00001514class CleanupTask(PreJobTask):
showardfa8629c2008-11-04 16:51:23 +00001515 def __init__(self, host=None, queue_entry=None):
1516 assert bool(host) ^ bool(queue_entry)
1517 if queue_entry:
1518 host = queue_entry.get_host()
jadmanski0afbb632008-06-06 21:10:57 +00001519
showard45ae8192008-11-05 19:32:53 +00001520 self.create_temp_resultsdir('.cleanup')
1521 self.cmd = [_autoserv_path, '--cleanup', '-m', host.hostname,
1522 '-r', self.temp_results_dir]
showardfa8629c2008-11-04 16:51:23 +00001523 self.queue_entry = queue_entry
jadmanski0afbb632008-06-06 21:10:57 +00001524 self.host = host
showarde788ea62008-11-17 21:02:47 +00001525 repair_task = RepairTask(host, queue_entry=queue_entry)
showard45ae8192008-11-05 19:32:53 +00001526 super(CleanupTask, self).__init__(self.cmd, failure_tasks=[repair_task])
mbligh16c722d2008-03-05 00:58:44 +00001527
mblighd5c95802008-03-05 00:33:46 +00001528
jadmanski0afbb632008-06-06 21:10:57 +00001529 def prolog(self):
showard8fe93b52008-11-18 17:53:22 +00001530 super(CleanupTask, self).prolog()
showard45ae8192008-11-05 19:32:53 +00001531 print "starting cleanup task for host: %s" % self.host.hostname
1532 self.host.set_status("Cleaning")
mblighd5c95802008-03-05 00:33:46 +00001533
mblighd5c95802008-03-05 00:33:46 +00001534
showard21baa452008-10-21 00:08:39 +00001535 def epilog(self):
showard45ae8192008-11-05 19:32:53 +00001536 super(CleanupTask, self).epilog()
showard21baa452008-10-21 00:08:39 +00001537 if self.success:
showardfa8629c2008-11-04 16:51:23 +00001538 self.host.set_status('Ready')
showard21baa452008-10-21 00:08:39 +00001539 self.host.update_field('dirty', 0)
1540
1541
mblighd5c95802008-03-05 00:33:46 +00001542class AbortTask(AgentTask):
jadmanski0afbb632008-06-06 21:10:57 +00001543 def __init__(self, queue_entry, agents_to_abort):
1544 self.queue_entry = queue_entry
1545 self.agents_to_abort = agents_to_abort
jadmanski0afbb632008-06-06 21:10:57 +00001546 super(AbortTask, self).__init__('')
mbligh36768f02008-02-22 18:28:33 +00001547
1548
jadmanski0afbb632008-06-06 21:10:57 +00001549 def prolog(self):
1550 print "starting abort on host %s, job %s" % (
1551 self.queue_entry.host_id, self.queue_entry.job_id)
mbligh36768f02008-02-22 18:28:33 +00001552
mblighd64e5702008-04-04 21:39:28 +00001553
jadmanski0afbb632008-06-06 21:10:57 +00001554 def epilog(self):
1555 super(AbortTask, self).epilog()
1556 self.queue_entry.set_status('Aborted')
1557 self.success = True
1558
1559
1560 def run(self):
1561 for agent in self.agents_to_abort:
1562 if (agent.active_task):
1563 agent.active_task.abort()
mbligh36768f02008-02-22 18:28:33 +00001564
1565
showard97aed502008-11-04 02:01:24 +00001566class FinalReparseTask(AgentTask):
1567 MAX_PARSE_PROCESSES = (
1568 global_config.global_config.get_config_value(
1569 _global_config_section, 'max_parse_processes', type=int))
1570 _num_running_parses = 0
1571
1572 def __init__(self, queue_entries):
1573 self._queue_entries = queue_entries
1574 self._parse_started = False
1575
1576 assert len(queue_entries) > 0
1577 queue_entry = queue_entries[0]
showard97aed502008-11-04 02:01:24 +00001578
1579 if _testing_mode:
1580 self.cmd = 'true'
1581 return
1582
1583 self._results_dir = queue_entry.results_dir()
1584 self.log_file = os.path.abspath(os.path.join(self._results_dir,
1585 '.parse.log'))
1586 super(FinalReparseTask, self).__init__(
showard2bab8f42008-11-12 18:15:22 +00001587 cmd=self._generate_parse_command())
showard97aed502008-11-04 02:01:24 +00001588
1589
1590 @classmethod
1591 def _increment_running_parses(cls):
1592 cls._num_running_parses += 1
1593
1594
1595 @classmethod
1596 def _decrement_running_parses(cls):
1597 cls._num_running_parses -= 1
1598
1599
1600 @classmethod
1601 def _can_run_new_parse(cls):
1602 return cls._num_running_parses < cls.MAX_PARSE_PROCESSES
1603
1604
1605 def prolog(self):
1606 super(FinalReparseTask, self).prolog()
1607 for queue_entry in self._queue_entries:
1608 queue_entry.set_status(models.HostQueueEntry.Status.PARSING)
1609
1610
1611 def epilog(self):
1612 super(FinalReparseTask, self).epilog()
1613 final_status = self._determine_final_status()
1614 for queue_entry in self._queue_entries:
1615 queue_entry.set_status(final_status)
1616
1617
1618 def _determine_final_status(self):
1619 # use a PidfileRunMonitor to read the autoserv exit status
1620 monitor = PidfileRunMonitor(self._results_dir)
1621 if monitor.exit_code() == 0:
1622 return models.HostQueueEntry.Status.COMPLETED
1623 return models.HostQueueEntry.Status.FAILED
1624
1625
showard2bab8f42008-11-12 18:15:22 +00001626 def _generate_parse_command(self):
showard97aed502008-11-04 02:01:24 +00001627 parse = os.path.abspath(os.path.join(AUTOTEST_TKO_DIR, 'parse'))
showard2bab8f42008-11-12 18:15:22 +00001628 return [parse, '-l', '2', '-r', '-o', self._results_dir]
showard97aed502008-11-04 02:01:24 +00001629
1630
1631 def poll(self):
1632 # override poll to keep trying to start until the parse count goes down
1633 # and we can, at which point we revert to default behavior
1634 if self._parse_started:
1635 super(FinalReparseTask, self).poll()
1636 else:
1637 self._try_starting_parse()
1638
1639
1640 def run(self):
1641 # override run() to not actually run unless we can
1642 self._try_starting_parse()
1643
1644
1645 def _try_starting_parse(self):
1646 if not self._can_run_new_parse():
1647 return
1648 # actually run the parse command
1649 super(FinalReparseTask, self).run()
1650 self._increment_running_parses()
1651 self._parse_started = True
1652
1653
1654 def finished(self, success):
1655 super(FinalReparseTask, self).finished(success)
1656 self._decrement_running_parses()
1657
1658
mbligh36768f02008-02-22 18:28:33 +00001659class DBObject(object):
jadmanski0afbb632008-06-06 21:10:57 +00001660 def __init__(self, id=None, row=None, new_record=False):
1661 assert (bool(id) != bool(row))
mbligh36768f02008-02-22 18:28:33 +00001662
jadmanski0afbb632008-06-06 21:10:57 +00001663 self.__table = self._get_table()
mbligh36768f02008-02-22 18:28:33 +00001664
jadmanski0afbb632008-06-06 21:10:57 +00001665 self.__new_record = new_record
mbligh36768f02008-02-22 18:28:33 +00001666
jadmanski0afbb632008-06-06 21:10:57 +00001667 if row is None:
1668 sql = 'SELECT * FROM %s WHERE ID=%%s' % self.__table
1669 rows = _db.execute(sql, (id,))
1670 if len(rows) == 0:
1671 raise "row not found (table=%s, id=%s)" % \
1672 (self.__table, id)
1673 row = rows[0]
mbligh36768f02008-02-22 18:28:33 +00001674
showard2bab8f42008-11-12 18:15:22 +00001675 self._update_fields_from_row(row)
1676
1677
1678 def _update_fields_from_row(self, row):
jadmanski0afbb632008-06-06 21:10:57 +00001679 assert len(row) == self.num_cols(), (
1680 "table = %s, row = %s/%d, fields = %s/%d" % (
showard2bab8f42008-11-12 18:15:22 +00001681 self.__table, row, len(row), self._fields(), self.num_cols()))
mbligh36768f02008-02-22 18:28:33 +00001682
showard2bab8f42008-11-12 18:15:22 +00001683 self._valid_fields = set()
1684 for field, value in zip(self._fields(), row):
1685 setattr(self, field, value)
1686 self._valid_fields.add(field)
mbligh36768f02008-02-22 18:28:33 +00001687
showard2bab8f42008-11-12 18:15:22 +00001688 self._valid_fields.remove('id')
mbligh36768f02008-02-22 18:28:33 +00001689
mblighe2586682008-02-29 22:45:46 +00001690
jadmanski0afbb632008-06-06 21:10:57 +00001691 @classmethod
1692 def _get_table(cls):
1693 raise NotImplementedError('Subclasses must override this')
mblighe2586682008-02-29 22:45:46 +00001694
1695
jadmanski0afbb632008-06-06 21:10:57 +00001696 @classmethod
1697 def _fields(cls):
1698 raise NotImplementedError('Subclasses must override this')
showard04c82c52008-05-29 19:38:12 +00001699
1700
jadmanski0afbb632008-06-06 21:10:57 +00001701 @classmethod
1702 def num_cols(cls):
1703 return len(cls._fields())
showard04c82c52008-05-29 19:38:12 +00001704
1705
jadmanski0afbb632008-06-06 21:10:57 +00001706 def count(self, where, table = None):
1707 if not table:
1708 table = self.__table
mbligh36768f02008-02-22 18:28:33 +00001709
jadmanski0afbb632008-06-06 21:10:57 +00001710 rows = _db.execute("""
1711 SELECT count(*) FROM %s
1712 WHERE %s
1713 """ % (table, where))
mbligh6f8bab42008-02-29 22:45:14 +00001714
jadmanski0afbb632008-06-06 21:10:57 +00001715 assert len(rows) == 1
1716
1717 return int(rows[0][0])
mbligh36768f02008-02-22 18:28:33 +00001718
1719
mblighf8c624d2008-07-03 16:58:45 +00001720 def update_field(self, field, value, condition=''):
showard2bab8f42008-11-12 18:15:22 +00001721 assert field in self._valid_fields
mbligh36768f02008-02-22 18:28:33 +00001722
showard2bab8f42008-11-12 18:15:22 +00001723 if getattr(self, field) == value:
jadmanski0afbb632008-06-06 21:10:57 +00001724 return
mbligh36768f02008-02-22 18:28:33 +00001725
mblighf8c624d2008-07-03 16:58:45 +00001726 query = "UPDATE %s SET %s = %%s WHERE id = %%s" % (self.__table, field)
1727 if condition:
1728 query += ' AND (%s)' % condition
jadmanski0afbb632008-06-06 21:10:57 +00001729 _db.execute(query, (value, self.id))
1730
showard2bab8f42008-11-12 18:15:22 +00001731 setattr(self, field, value)
mbligh36768f02008-02-22 18:28:33 +00001732
1733
jadmanski0afbb632008-06-06 21:10:57 +00001734 def save(self):
1735 if self.__new_record:
1736 keys = self._fields()[1:] # avoid id
1737 columns = ','.join([str(key) for key in keys])
1738 values = ['"%s"' % self.__dict__[key] for key in keys]
1739 values = ','.join(values)
1740 query = """INSERT INTO %s (%s) VALUES (%s)""" % \
1741 (self.__table, columns, values)
1742 _db.execute(query)
mbligh36768f02008-02-22 18:28:33 +00001743
1744
jadmanski0afbb632008-06-06 21:10:57 +00001745 def delete(self):
1746 query = 'DELETE FROM %s WHERE id=%%s' % self.__table
1747 _db.execute(query, (self.id,))
mblighe2586682008-02-29 22:45:46 +00001748
1749
showard63a34772008-08-18 19:32:50 +00001750 @staticmethod
1751 def _prefix_with(string, prefix):
1752 if string:
1753 string = prefix + string
1754 return string
1755
1756
jadmanski0afbb632008-06-06 21:10:57 +00001757 @classmethod
showard989f25d2008-10-01 11:38:11 +00001758 def fetch(cls, where='', params=(), joins='', order_by=''):
showard63a34772008-08-18 19:32:50 +00001759 order_by = cls._prefix_with(order_by, 'ORDER BY ')
1760 where = cls._prefix_with(where, 'WHERE ')
1761 query = ('SELECT %(table)s.* FROM %(table)s %(joins)s '
1762 '%(where)s %(order_by)s' % {'table' : cls._get_table(),
1763 'joins' : joins,
1764 'where' : where,
1765 'order_by' : order_by})
1766 rows = _db.execute(query, params)
jadmanski0afbb632008-06-06 21:10:57 +00001767 for row in rows:
1768 yield cls(row=row)
mblighe2586682008-02-29 22:45:46 +00001769
mbligh36768f02008-02-22 18:28:33 +00001770
1771class IneligibleHostQueue(DBObject):
jadmanski0afbb632008-06-06 21:10:57 +00001772 def __init__(self, id=None, row=None, new_record=None):
1773 super(IneligibleHostQueue, self).__init__(id=id, row=row,
1774 new_record=new_record)
mblighe2586682008-02-29 22:45:46 +00001775
1776
jadmanski0afbb632008-06-06 21:10:57 +00001777 @classmethod
1778 def _get_table(cls):
1779 return 'ineligible_host_queues'
mbligh36768f02008-02-22 18:28:33 +00001780
1781
jadmanski0afbb632008-06-06 21:10:57 +00001782 @classmethod
1783 def _fields(cls):
1784 return ['id', 'job_id', 'host_id']
showard04c82c52008-05-29 19:38:12 +00001785
1786
showard989f25d2008-10-01 11:38:11 +00001787class Label(DBObject):
1788 @classmethod
1789 def _get_table(cls):
1790 return 'labels'
1791
1792
1793 @classmethod
1794 def _fields(cls):
1795 return ['id', 'name', 'kernel_config', 'platform', 'invalid',
1796 'only_if_needed']
1797
1798
mbligh36768f02008-02-22 18:28:33 +00001799class Host(DBObject):
jadmanski0afbb632008-06-06 21:10:57 +00001800 def __init__(self, id=None, row=None):
1801 super(Host, self).__init__(id=id, row=row)
mblighe2586682008-02-29 22:45:46 +00001802
1803
jadmanski0afbb632008-06-06 21:10:57 +00001804 @classmethod
1805 def _get_table(cls):
1806 return 'hosts'
mbligh36768f02008-02-22 18:28:33 +00001807
1808
jadmanski0afbb632008-06-06 21:10:57 +00001809 @classmethod
1810 def _fields(cls):
1811 return ['id', 'hostname', 'locked', 'synch_id','status',
showard21baa452008-10-21 00:08:39 +00001812 'invalid', 'protection', 'locked_by_id', 'lock_time', 'dirty']
showard04c82c52008-05-29 19:38:12 +00001813
1814
jadmanski0afbb632008-06-06 21:10:57 +00001815 def current_task(self):
1816 rows = _db.execute("""
1817 SELECT * FROM host_queue_entries WHERE host_id=%s AND NOT complete AND active
1818 """, (self.id,))
1819
1820 if len(rows) == 0:
1821 return None
1822 else:
1823 assert len(rows) == 1
1824 results = rows[0];
mblighf8c624d2008-07-03 16:58:45 +00001825# print "current = %s" % results
jadmanski0afbb632008-06-06 21:10:57 +00001826 return HostQueueEntry(row=results)
mbligh36768f02008-02-22 18:28:33 +00001827
1828
jadmanski0afbb632008-06-06 21:10:57 +00001829 def yield_work(self):
1830 print "%s yielding work" % self.hostname
1831 if self.current_task():
1832 self.current_task().requeue()
1833
1834 def set_status(self,status):
1835 print '%s -> %s' % (self.hostname, status)
1836 self.update_field('status',status)
mbligh36768f02008-02-22 18:28:33 +00001837
1838
showardd8e548a2008-09-09 03:04:57 +00001839 def labels(self):
1840 """
1841 Fetch a list of names of all non-platform labels associated with this
1842 host.
1843 """
1844 rows = _db.execute("""
1845 SELECT labels.name
1846 FROM labels
1847 INNER JOIN hosts_labels ON labels.id = hosts_labels.label_id
1848 WHERE NOT labels.platform AND hosts_labels.host_id = %s
1849 ORDER BY labels.name
1850 """, (self.id,))
1851 return [row[0] for row in rows]
1852
1853
mbligh36768f02008-02-22 18:28:33 +00001854class HostQueueEntry(DBObject):
jadmanski0afbb632008-06-06 21:10:57 +00001855 def __init__(self, id=None, row=None):
1856 assert id or row
1857 super(HostQueueEntry, self).__init__(id=id, row=row)
1858 self.job = Job(self.job_id)
mbligh36768f02008-02-22 18:28:33 +00001859
jadmanski0afbb632008-06-06 21:10:57 +00001860 if self.host_id:
1861 self.host = Host(self.host_id)
1862 else:
1863 self.host = None
mbligh36768f02008-02-22 18:28:33 +00001864
jadmanski0afbb632008-06-06 21:10:57 +00001865 self.queue_log_path = os.path.join(self.job.results_dir(),
1866 'queue.log.' + str(self.id))
mbligh36768f02008-02-22 18:28:33 +00001867
1868
jadmanski0afbb632008-06-06 21:10:57 +00001869 @classmethod
1870 def _get_table(cls):
1871 return 'host_queue_entries'
mblighe2586682008-02-29 22:45:46 +00001872
1873
jadmanski0afbb632008-06-06 21:10:57 +00001874 @classmethod
1875 def _fields(cls):
showard2bab8f42008-11-12 18:15:22 +00001876 return ['id', 'job_id', 'host_id', 'priority', 'status', 'meta_host',
1877 'active', 'complete', 'deleted', 'execution_subdir']
showard04c82c52008-05-29 19:38:12 +00001878
1879
showardc85c21b2008-11-24 22:17:37 +00001880 def _view_job_url(self):
1881 return "%s#tab_id=view_job&object_id=%s" % (_base_url, self.job.id)
1882
1883
jadmanski0afbb632008-06-06 21:10:57 +00001884 def set_host(self, host):
1885 if host:
1886 self.queue_log_record('Assigning host ' + host.hostname)
1887 self.update_field('host_id', host.id)
1888 self.update_field('active', True)
1889 self.block_host(host.id)
1890 else:
1891 self.queue_log_record('Releasing host')
1892 self.unblock_host(self.host.id)
1893 self.update_field('host_id', None)
mbligh36768f02008-02-22 18:28:33 +00001894
jadmanski0afbb632008-06-06 21:10:57 +00001895 self.host = host
mbligh36768f02008-02-22 18:28:33 +00001896
1897
jadmanski0afbb632008-06-06 21:10:57 +00001898 def get_host(self):
1899 return self.host
mbligh36768f02008-02-22 18:28:33 +00001900
1901
jadmanski0afbb632008-06-06 21:10:57 +00001902 def queue_log_record(self, log_line):
1903 now = str(datetime.datetime.now())
1904 queue_log = open(self.queue_log_path, 'a', 0)
1905 queue_log.write(now + ' ' + log_line + '\n')
1906 queue_log.close()
mbligh36768f02008-02-22 18:28:33 +00001907
1908
jadmanski0afbb632008-06-06 21:10:57 +00001909 def block_host(self, host_id):
1910 print "creating block %s/%s" % (self.job.id, host_id)
1911 row = [0, self.job.id, host_id]
1912 block = IneligibleHostQueue(row=row, new_record=True)
1913 block.save()
mblighe2586682008-02-29 22:45:46 +00001914
1915
jadmanski0afbb632008-06-06 21:10:57 +00001916 def unblock_host(self, host_id):
1917 print "removing block %s/%s" % (self.job.id, host_id)
1918 blocks = IneligibleHostQueue.fetch(
1919 'job_id=%d and host_id=%d' % (self.job.id, host_id))
1920 for block in blocks:
1921 block.delete()
mblighe2586682008-02-29 22:45:46 +00001922
1923
jadmanski0afbb632008-06-06 21:10:57 +00001924 def results_dir(self):
showard2bab8f42008-11-12 18:15:22 +00001925 return os.path.join(self.job.job_dir, self.execution_subdir)
mbligh36768f02008-02-22 18:28:33 +00001926
mblighe2586682008-02-29 22:45:46 +00001927
showard2bab8f42008-11-12 18:15:22 +00001928 def set_execution_subdir(self, subdir=None):
1929 if subdir is None:
1930 assert self.get_host()
1931 subdir = self.get_host().hostname
1932 self.update_field('execution_subdir', subdir)
mbligh36768f02008-02-22 18:28:33 +00001933
1934
jadmanski0afbb632008-06-06 21:10:57 +00001935 def set_status(self, status):
mblighf8c624d2008-07-03 16:58:45 +00001936 abort_statuses = ['Abort', 'Aborting', 'Aborted']
1937 if status not in abort_statuses:
1938 condition = ' AND '.join(['status <> "%s"' % x
1939 for x in abort_statuses])
1940 else:
1941 condition = ''
1942 self.update_field('status', status, condition=condition)
1943
jadmanski0afbb632008-06-06 21:10:57 +00001944 if self.host:
1945 hostname = self.host.hostname
1946 else:
showard2bab8f42008-11-12 18:15:22 +00001947 hostname = 'None'
1948 print "%s/%d (%d) -> %s" % (hostname, self.job.id, self.id, self.status)
mblighf8c624d2008-07-03 16:58:45 +00001949
showardc85c21b2008-11-24 22:17:37 +00001950 if status in ['Queued', 'Parsing']:
jadmanski0afbb632008-06-06 21:10:57 +00001951 self.update_field('complete', False)
1952 self.update_field('active', False)
mbligh36768f02008-02-22 18:28:33 +00001953
jadmanski0afbb632008-06-06 21:10:57 +00001954 if status in ['Pending', 'Running', 'Verifying', 'Starting',
showarde58e3f82008-11-20 19:04:59 +00001955 'Aborting']:
jadmanski0afbb632008-06-06 21:10:57 +00001956 self.update_field('complete', False)
1957 self.update_field('active', True)
mbligh36768f02008-02-22 18:28:33 +00001958
showardc85c21b2008-11-24 22:17:37 +00001959 if status in ['Failed', 'Completed', 'Stopped', 'Aborted']:
jadmanski0afbb632008-06-06 21:10:57 +00001960 self.update_field('complete', True)
1961 self.update_field('active', False)
showardc85c21b2008-11-24 22:17:37 +00001962
1963 should_email_status = (status.lower() in _notify_email_statuses or
1964 'all' in _notify_email_statuses)
1965 if should_email_status:
1966 self._email_on_status(status)
1967
1968 self._email_on_job_complete()
1969
1970
1971 def _email_on_status(self, status):
1972 hostname = 'no host'
1973 if self.host:
1974 hostname = self.host.hostname
1975
1976 subject = 'Autotest: Job ID: %s "%s" Host: %s %s' % (
1977 self.job.id, self.job.name, hostname, status)
1978 body = "Job ID: %s\nJob Name: %s\nHost: %s\nStatus: %s\n%s\n" % (
1979 self.job.id, self.job.name, hostname, status,
1980 self._view_job_url())
1981 send_email(self.job.email_list, subject, body)
showard542e8402008-09-19 20:16:18 +00001982
1983
1984 def _email_on_job_complete(self):
showardc85c21b2008-11-24 22:17:37 +00001985 if not self.job.is_finished():
1986 return
showard542e8402008-09-19 20:16:18 +00001987
showardc85c21b2008-11-24 22:17:37 +00001988 summary_text = []
1989 hosts_queue = models.Job.objects.get(
1990 id=self.job.id).hostqueueentry_set.all()
1991 for queue_entry in hosts_queue:
1992 summary_text.append("Host: %s Status: %s" %
1993 (queue_entry.host.hostname,
1994 queue_entry.status))
1995
1996 summary_text = "\n".join(summary_text)
1997 status_counts = models.Job.objects.get_status_counts(
1998 [self.job.id])[self.job.id]
1999 status = ', '.join('%d %s' % (count, status) for status, count
2000 in status_counts.iteritems())
2001
2002 subject = 'Autotest: Job ID: %s "%s" %s' % (
2003 self.job.id, self.job.name, status)
2004 body = "Job ID: %s\nJob Name: %s\nStatus: %s\n%s\nSummary:\n%s" % (
2005 self.job.id, self.job.name, status, self._view_job_url(),
2006 summary_text)
2007 send_email(self.job.email_list, subject, body)
mbligh36768f02008-02-22 18:28:33 +00002008
2009
jadmanski0afbb632008-06-06 21:10:57 +00002010 def run(self,assigned_host=None):
2011 if self.meta_host:
2012 assert assigned_host
2013 # ensure results dir exists for the queue log
2014 self.job.create_results_dir()
2015 self.set_host(assigned_host)
mbligh36768f02008-02-22 18:28:33 +00002016
jadmanski0afbb632008-06-06 21:10:57 +00002017 print "%s/%s scheduled on %s, status=%s" % (self.job.name,
2018 self.meta_host, self.host.hostname, self.status)
mbligh36768f02008-02-22 18:28:33 +00002019
jadmanski0afbb632008-06-06 21:10:57 +00002020 return self.job.run(queue_entry=self)
mblighe2586682008-02-29 22:45:46 +00002021
jadmanski0afbb632008-06-06 21:10:57 +00002022 def requeue(self):
2023 self.set_status('Queued')
mblighe2586682008-02-29 22:45:46 +00002024
jadmanski0afbb632008-06-06 21:10:57 +00002025 if self.meta_host:
2026 self.set_host(None)
mbligh36768f02008-02-22 18:28:33 +00002027
2028
jadmanski0afbb632008-06-06 21:10:57 +00002029 def handle_host_failure(self):
2030 """\
2031 Called when this queue entry's host has failed verification and
2032 repair.
2033 """
2034 assert not self.meta_host
2035 self.set_status('Failed')
showard2bab8f42008-11-12 18:15:22 +00002036 self.job.stop_if_necessary()
mblighe2586682008-02-29 22:45:46 +00002037
2038
showard2bab8f42008-11-12 18:15:22 +00002039 def clear_results_dir(self, dont_delete_files=False):
2040 if not self.execution_subdir:
2041 return
2042 results_dir = self.results_dir()
jadmanski0afbb632008-06-06 21:10:57 +00002043 if not os.path.exists(results_dir):
2044 return
2045 if dont_delete_files:
2046 temp_dir = tempfile.mkdtemp(suffix='.clear_results')
showard2bab8f42008-11-12 18:15:22 +00002047 print 'Moving results from %s to %s' % (results_dir, temp_dir)
jadmanski0afbb632008-06-06 21:10:57 +00002048 for filename in os.listdir(results_dir):
2049 path = os.path.join(results_dir, filename)
2050 if dont_delete_files:
showard2bab8f42008-11-12 18:15:22 +00002051 shutil.move(path, os.path.join(temp_dir, filename))
jadmanski0afbb632008-06-06 21:10:57 +00002052 else:
2053 remove_file_or_dir(path)
showard2bab8f42008-11-12 18:15:22 +00002054 remove_file_or_dir(results_dir)
mbligh36768f02008-02-22 18:28:33 +00002055
2056
jadmanskif7fa2cc2008-10-01 14:13:23 +00002057 @property
2058 def aborted_by(self):
2059 self._load_abort_info()
2060 return self._aborted_by
2061
2062
2063 @property
2064 def aborted_on(self):
2065 self._load_abort_info()
2066 return self._aborted_on
2067
2068
2069 def _load_abort_info(self):
2070 """ Fetch info about who aborted the job. """
2071 if hasattr(self, "_aborted_by"):
2072 return
2073 rows = _db.execute("""
2074 SELECT users.login, aborted_host_queue_entries.aborted_on
2075 FROM aborted_host_queue_entries
2076 INNER JOIN users
2077 ON users.id = aborted_host_queue_entries.aborted_by_id
2078 WHERE aborted_host_queue_entries.queue_entry_id = %s
2079 """, (self.id,))
2080 if rows:
2081 self._aborted_by, self._aborted_on = rows[0]
2082 else:
2083 self._aborted_by = self._aborted_on = None
2084
2085
showardb2e2c322008-10-14 17:33:55 +00002086 def on_pending(self):
2087 """
2088 Called when an entry in a synchronous job has passed verify. If the
2089 job is ready to run, returns an agent to run the job. Returns None
2090 otherwise.
2091 """
2092 self.set_status('Pending')
showardcfd66a32008-10-15 20:31:48 +00002093 self.get_host().set_status('Pending')
showardb2e2c322008-10-14 17:33:55 +00002094 if self.job.is_ready():
2095 return self.job.run(self)
showard2bab8f42008-11-12 18:15:22 +00002096 self.job.stop_if_necessary()
showardb2e2c322008-10-14 17:33:55 +00002097 return None
2098
2099
showard1be97432008-10-17 15:30:45 +00002100 def abort(self, agents_to_abort=[]):
2101 abort_task = AbortTask(self, agents_to_abort)
2102 tasks = [abort_task]
2103
2104 host = self.get_host()
showard9d9ffd52008-11-09 23:14:35 +00002105 if self.active and host:
showard45ae8192008-11-05 19:32:53 +00002106 cleanup_task = CleanupTask(host=host)
showard1be97432008-10-17 15:30:45 +00002107 verify_task = VerifyTask(host=host)
2108 # just to make sure this host does not get taken away
showard45ae8192008-11-05 19:32:53 +00002109 host.set_status('Cleaning')
2110 tasks += [cleanup_task, verify_task]
showard1be97432008-10-17 15:30:45 +00002111
2112 self.set_status('Aborting')
2113 return Agent(tasks=tasks, queue_entry_ids=[self.id])
2114
2115
mbligh36768f02008-02-22 18:28:33 +00002116class Job(DBObject):
jadmanski0afbb632008-06-06 21:10:57 +00002117 def __init__(self, id=None, row=None):
2118 assert id or row
2119 super(Job, self).__init__(id=id, row=row)
mbligh36768f02008-02-22 18:28:33 +00002120
jadmanski0afbb632008-06-06 21:10:57 +00002121 self.job_dir = os.path.join(RESULTS_DIR, "%s-%s" % (self.id,
2122 self.owner))
mblighe2586682008-02-29 22:45:46 +00002123
2124
jadmanski0afbb632008-06-06 21:10:57 +00002125 @classmethod
2126 def _get_table(cls):
2127 return 'jobs'
mbligh36768f02008-02-22 18:28:33 +00002128
2129
jadmanski0afbb632008-06-06 21:10:57 +00002130 @classmethod
2131 def _fields(cls):
2132 return ['id', 'owner', 'name', 'priority', 'control_file',
showard2bab8f42008-11-12 18:15:22 +00002133 'control_type', 'created_on', 'synch_count', 'timeout',
showard21baa452008-10-21 00:08:39 +00002134 'run_verify', 'email_list', 'reboot_before', 'reboot_after']
showard04c82c52008-05-29 19:38:12 +00002135
2136
jadmanski0afbb632008-06-06 21:10:57 +00002137 def is_server_job(self):
2138 return self.control_type != 2
mbligh36768f02008-02-22 18:28:33 +00002139
2140
jadmanski0afbb632008-06-06 21:10:57 +00002141 def get_host_queue_entries(self):
2142 rows = _db.execute("""
2143 SELECT * FROM host_queue_entries
2144 WHERE job_id= %s
2145 """, (self.id,))
2146 entries = [HostQueueEntry(row=i) for i in rows]
mbligh36768f02008-02-22 18:28:33 +00002147
jadmanski0afbb632008-06-06 21:10:57 +00002148 assert len(entries)>0
mbligh36768f02008-02-22 18:28:33 +00002149
jadmanski0afbb632008-06-06 21:10:57 +00002150 return entries
mbligh36768f02008-02-22 18:28:33 +00002151
2152
jadmanski0afbb632008-06-06 21:10:57 +00002153 def set_status(self, status, update_queues=False):
2154 self.update_field('status',status)
2155
2156 if update_queues:
2157 for queue_entry in self.get_host_queue_entries():
2158 queue_entry.set_status(status)
mbligh36768f02008-02-22 18:28:33 +00002159
2160
jadmanski0afbb632008-06-06 21:10:57 +00002161 def is_ready(self):
showard2bab8f42008-11-12 18:15:22 +00002162 pending_entries = models.HostQueueEntry.objects.filter(job=self.id,
2163 status='Pending')
2164 return (pending_entries.count() >= self.synch_count)
mbligh36768f02008-02-22 18:28:33 +00002165
2166
jadmanski0afbb632008-06-06 21:10:57 +00002167 def results_dir(self):
2168 return self.job_dir
mbligh36768f02008-02-22 18:28:33 +00002169
jadmanski0afbb632008-06-06 21:10:57 +00002170 def num_machines(self, clause = None):
2171 sql = "job_id=%s" % self.id
2172 if clause:
2173 sql += " AND (%s)" % clause
2174 return self.count(sql, table='host_queue_entries')
mbligh36768f02008-02-22 18:28:33 +00002175
2176
jadmanski0afbb632008-06-06 21:10:57 +00002177 def num_queued(self):
2178 return self.num_machines('not complete')
mbligh36768f02008-02-22 18:28:33 +00002179
2180
jadmanski0afbb632008-06-06 21:10:57 +00002181 def num_active(self):
2182 return self.num_machines('active')
mbligh36768f02008-02-22 18:28:33 +00002183
2184
jadmanski0afbb632008-06-06 21:10:57 +00002185 def num_complete(self):
2186 return self.num_machines('complete')
mbligh36768f02008-02-22 18:28:33 +00002187
2188
jadmanski0afbb632008-06-06 21:10:57 +00002189 def is_finished(self):
showardc85c21b2008-11-24 22:17:37 +00002190 return self.num_complete() == self.num_machines()
mbligh36768f02008-02-22 18:28:33 +00002191
mbligh36768f02008-02-22 18:28:33 +00002192
showard2bab8f42008-11-12 18:15:22 +00002193 def _stop_all_entries(self, entries_to_abort):
2194 """
2195 queue_entries: sequence of models.HostQueueEntry objects
2196 """
2197 for child_entry in entries_to_abort:
2198 assert not child_entry.complete
2199 if child_entry.status == models.HostQueueEntry.Status.PENDING:
2200 child_entry.host.status = models.Host.Status.READY
2201 child_entry.host.save()
2202 child_entry.status = models.HostQueueEntry.Status.STOPPED
2203 child_entry.save()
2204
2205
2206 def stop_if_necessary(self):
2207 not_yet_run = models.HostQueueEntry.objects.filter(
2208 job=self.id, status__in=(models.HostQueueEntry.Status.QUEUED,
2209 models.HostQueueEntry.Status.VERIFYING,
2210 models.HostQueueEntry.Status.PENDING))
2211 if not_yet_run.count() < self.synch_count:
2212 self._stop_all_entries(not_yet_run)
mblighe2586682008-02-29 22:45:46 +00002213
2214
jadmanski0afbb632008-06-06 21:10:57 +00002215 def write_to_machines_file(self, queue_entry):
2216 hostname = queue_entry.get_host().hostname
2217 print "writing %s to job %s machines file" % (hostname, self.id)
2218 file_path = os.path.join(self.job_dir, '.machines')
2219 mf = open(file_path, 'a')
showard2bab8f42008-11-12 18:15:22 +00002220 mf.write(hostname + '\n')
jadmanski0afbb632008-06-06 21:10:57 +00002221 mf.close()
mbligh36768f02008-02-22 18:28:33 +00002222
2223
jadmanski0afbb632008-06-06 21:10:57 +00002224 def create_results_dir(self, queue_entry=None):
showard2bab8f42008-11-12 18:15:22 +00002225 ensure_directory_exists(self.job_dir)
mbligh36768f02008-02-22 18:28:33 +00002226
jadmanski0afbb632008-06-06 21:10:57 +00002227 if queue_entry:
showarde05654d2008-10-28 20:38:40 +00002228 results_dir = queue_entry.results_dir()
showarde788ea62008-11-17 21:02:47 +00002229 if os.path.exists(results_dir):
2230 warning = 'QE results dir ' + results_dir + ' already exists'
2231 print warning
2232 email_manager.enqueue_notify_email(warning, warning)
showard2bab8f42008-11-12 18:15:22 +00002233 ensure_directory_exists(results_dir)
showarde05654d2008-10-28 20:38:40 +00002234 return results_dir
jadmanski0afbb632008-06-06 21:10:57 +00002235 return self.job_dir
mbligh36768f02008-02-22 18:28:33 +00002236
2237
showard2bab8f42008-11-12 18:15:22 +00002238 def _next_group_name(self):
2239 query = models.HostQueueEntry.objects.filter(
2240 job=self.id).values('execution_subdir').distinct()
2241 subdirs = (entry['execution_subdir'] for entry in query)
2242 groups = (re.match(r'group(\d+)', subdir) for subdir in subdirs)
2243 ids = [int(match.group(1)) for match in groups if match]
2244 if ids:
2245 next_id = max(ids) + 1
2246 else:
2247 next_id = 0
2248 return "group%d" % next_id
2249
2250
showardb2e2c322008-10-14 17:33:55 +00002251 def _write_control_file(self):
2252 'Writes control file out to disk, returns a filename'
2253 control_fd, control_filename = tempfile.mkstemp(suffix='.control_file')
2254 control_file = os.fdopen(control_fd, 'w')
jadmanski0afbb632008-06-06 21:10:57 +00002255 if self.control_file:
showardb2e2c322008-10-14 17:33:55 +00002256 control_file.write(self.control_file)
2257 control_file.close()
2258 return control_filename
mbligh36768f02008-02-22 18:28:33 +00002259
showardb2e2c322008-10-14 17:33:55 +00002260
showard2bab8f42008-11-12 18:15:22 +00002261 def get_group_entries(self, queue_entry_from_group):
2262 execution_subdir = queue_entry_from_group.execution_subdir
showarde788ea62008-11-17 21:02:47 +00002263 return list(HostQueueEntry.fetch(
2264 where='job_id=%s AND execution_subdir=%s',
2265 params=(self.id, execution_subdir)))
showard2bab8f42008-11-12 18:15:22 +00002266
2267
2268 def get_job_tag(self, queue_entries):
2269 assert len(queue_entries) > 0
2270 execution_subdir = queue_entries[0].execution_subdir
2271 assert execution_subdir
2272 return "%s-%s/%s" % (self.id, self.owner, execution_subdir)
showardb2e2c322008-10-14 17:33:55 +00002273
2274
2275 def _get_autoserv_params(self, queue_entries):
2276 results_dir = self.create_results_dir(queue_entries[0])
2277 control_filename = self._write_control_file()
jadmanski0afbb632008-06-06 21:10:57 +00002278 hostnames = ','.join([entry.get_host().hostname
2279 for entry in queue_entries])
showard2bab8f42008-11-12 18:15:22 +00002280 job_tag = self.get_job_tag(queue_entries)
mbligh36768f02008-02-22 18:28:33 +00002281
showardb2e2c322008-10-14 17:33:55 +00002282 params = [_autoserv_path, '-P', job_tag, '-p', '-n',
showard21baa452008-10-21 00:08:39 +00002283 '-r', os.path.abspath(results_dir), '-u', self.owner,
2284 '-l', self.name, '-m', hostnames, control_filename]
mbligh36768f02008-02-22 18:28:33 +00002285
jadmanski0afbb632008-06-06 21:10:57 +00002286 if not self.is_server_job():
2287 params.append('-c')
mbligh36768f02008-02-22 18:28:33 +00002288
showardb2e2c322008-10-14 17:33:55 +00002289 return params
mblighe2586682008-02-29 22:45:46 +00002290
mbligh36768f02008-02-22 18:28:33 +00002291
showard2bab8f42008-11-12 18:15:22 +00002292 def _get_pre_job_tasks(self, queue_entry):
showard21baa452008-10-21 00:08:39 +00002293 do_reboot = False
showard0fc38302008-10-23 00:44:07 +00002294 if self.reboot_before == models.RebootBefore.ALWAYS:
showard21baa452008-10-21 00:08:39 +00002295 do_reboot = True
showard0fc38302008-10-23 00:44:07 +00002296 elif self.reboot_before == models.RebootBefore.IF_DIRTY:
showard21baa452008-10-21 00:08:39 +00002297 do_reboot = queue_entry.get_host().dirty
2298
2299 tasks = []
2300 if do_reboot:
showard45ae8192008-11-05 19:32:53 +00002301 tasks.append(CleanupTask(queue_entry=queue_entry))
showard2bab8f42008-11-12 18:15:22 +00002302 tasks.append(VerifyTask(queue_entry=queue_entry))
showard21baa452008-10-21 00:08:39 +00002303 return tasks
2304
2305
showard2bab8f42008-11-12 18:15:22 +00002306 def _assign_new_group(self, queue_entries):
2307 if len(queue_entries) == 1:
2308 group_name = queue_entries[0].get_host().hostname
2309 else:
2310 group_name = self._next_group_name()
2311 print 'Running synchronous job %d hosts %s as %s' % (
2312 self.id, [entry.host.hostname for entry in queue_entries],
2313 group_name)
2314
2315 for queue_entry in queue_entries:
2316 queue_entry.set_execution_subdir(group_name)
2317
2318
2319 def _choose_group_to_run(self, include_queue_entry):
2320 chosen_entries = [include_queue_entry]
2321
2322 num_entries_needed = self.synch_count - 1
2323 if num_entries_needed > 0:
2324 pending_entries = HostQueueEntry.fetch(
2325 where='job_id = %s AND status = "Pending" AND id != %s',
2326 params=(self.id, include_queue_entry.id))
2327 chosen_entries += list(pending_entries)[:num_entries_needed]
2328
2329 self._assign_new_group(chosen_entries)
2330 return chosen_entries
2331
2332
2333 def run(self, queue_entry):
showardb2e2c322008-10-14 17:33:55 +00002334 if not self.is_ready():
showard9976ce92008-10-15 20:28:13 +00002335 if self.run_verify:
showarde58e3f82008-11-20 19:04:59 +00002336 queue_entry.set_status(models.HostQueueEntry.Status.VERIFYING)
showard2bab8f42008-11-12 18:15:22 +00002337 return Agent(self._get_pre_job_tasks(queue_entry),
showard21baa452008-10-21 00:08:39 +00002338 [queue_entry.id])
showard9976ce92008-10-15 20:28:13 +00002339 else:
2340 return queue_entry.on_pending()
mbligh36768f02008-02-22 18:28:33 +00002341
showard2bab8f42008-11-12 18:15:22 +00002342 queue_entries = self._choose_group_to_run(queue_entry)
2343 return self._finish_run(queue_entries)
showardb2e2c322008-10-14 17:33:55 +00002344
2345
2346 def _finish_run(self, queue_entries, initial_tasks=[]):
showardb2ccdda2008-10-28 20:39:05 +00002347 for queue_entry in queue_entries:
2348 queue_entry.set_status('Starting')
showardb2e2c322008-10-14 17:33:55 +00002349 params = self._get_autoserv_params(queue_entries)
2350 queue_task = QueueTask(job=self, queue_entries=queue_entries,
2351 cmd=params)
2352 tasks = initial_tasks + [queue_task]
2353 entry_ids = [entry.id for entry in queue_entries]
2354
2355 return Agent(tasks, entry_ids, num_processes=len(queue_entries))
2356
2357
mbligh36768f02008-02-22 18:28:33 +00002358if __name__ == '__main__':
jadmanski0afbb632008-06-06 21:10:57 +00002359 main()