blob: 21c15b068a60f7b2f5f2aa4aa28f4cd4035d1943 [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
13from autotest_lib.client.common_lib import host_protections, utils
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]
mbligh36768f02008-02-22 18:28:33 +000045
46
47def main():
jadmanski0afbb632008-06-06 21:10:57 +000048 usage = 'usage: %prog [options] results_dir'
mbligh36768f02008-02-22 18:28:33 +000049
jadmanski0afbb632008-06-06 21:10:57 +000050 parser = optparse.OptionParser(usage)
51 parser.add_option('--recover-hosts', help='Try to recover dead hosts',
52 action='store_true')
53 parser.add_option('--logfile', help='Set a log file that all stdout ' +
54 'should be redirected to. Stderr will go to this ' +
55 'file + ".err"')
56 parser.add_option('--test', help='Indicate that scheduler is under ' +
57 'test and should use dummy autoserv and no parsing',
58 action='store_true')
59 (options, args) = parser.parse_args()
60 if len(args) != 1:
61 parser.print_usage()
62 return
mbligh36768f02008-02-22 18:28:33 +000063
jadmanski0afbb632008-06-06 21:10:57 +000064 global RESULTS_DIR
65 RESULTS_DIR = args[0]
mbligh36768f02008-02-22 18:28:33 +000066
jadmanski0afbb632008-06-06 21:10:57 +000067 # read in notify_email from global_config
68 c = global_config.global_config
69 global _notify_email
70 val = c.get_config_value(_global_config_section, "notify_email")
71 if val != "":
72 _notify_email = val
mbligh36768f02008-02-22 18:28:33 +000073
showard3bb499f2008-07-03 19:42:20 +000074 tick_pause = c.get_config_value(
75 _global_config_section, 'tick_pause_sec', type=int)
76
jadmanski0afbb632008-06-06 21:10:57 +000077 if options.test:
78 global _autoserv_path
79 _autoserv_path = 'autoserv_dummy'
80 global _testing_mode
81 _testing_mode = True
mbligh36768f02008-02-22 18:28:33 +000082
showard542e8402008-09-19 20:16:18 +000083 # read in base url
84 global _base_url
showardb1e51872008-10-07 11:08:18 +000085 val = c.get_config_value(CONFIG_SECTION, "base_url")
showard542e8402008-09-19 20:16:18 +000086 if val:
87 _base_url = val
88 else:
89 _base_url = "http://your_autotest_server/afe/"
90
jadmanski0afbb632008-06-06 21:10:57 +000091 init(options.logfile)
92 dispatcher = Dispatcher()
93 dispatcher.do_initial_recovery(recover_hosts=options.recover_hosts)
94
95 try:
96 while not _shutdown:
97 dispatcher.tick()
showard3bb499f2008-07-03 19:42:20 +000098 time.sleep(tick_pause)
jadmanski0afbb632008-06-06 21:10:57 +000099 except:
100 log_stacktrace("Uncaught exception; terminating monitor_db")
101
102 email_manager.send_queued_emails()
103 _db.disconnect()
mbligh36768f02008-02-22 18:28:33 +0000104
105
106def handle_sigint(signum, frame):
jadmanski0afbb632008-06-06 21:10:57 +0000107 global _shutdown
108 _shutdown = True
109 print "Shutdown request received."
mbligh36768f02008-02-22 18:28:33 +0000110
111
112def init(logfile):
jadmanski0afbb632008-06-06 21:10:57 +0000113 if logfile:
114 enable_logging(logfile)
115 print "%s> dispatcher starting" % time.strftime("%X %x")
116 print "My PID is %d" % os.getpid()
mbligh36768f02008-02-22 18:28:33 +0000117
showardb1e51872008-10-07 11:08:18 +0000118 if _testing_mode:
119 global_config.global_config.override_config_value(
120 CONFIG_SECTION, 'database', 'stresstest_autotest_web')
121
jadmanski0afbb632008-06-06 21:10:57 +0000122 os.environ['PATH'] = AUTOTEST_SERVER_DIR + ':' + os.environ['PATH']
123 global _db
showardb1e51872008-10-07 11:08:18 +0000124 _db = database_connection.DatabaseConnection(CONFIG_SECTION)
jadmanski0afbb632008-06-06 21:10:57 +0000125 _db.connect()
mbligh36768f02008-02-22 18:28:33 +0000126
jadmanski0afbb632008-06-06 21:10:57 +0000127 print "Setting signal handler"
128 signal.signal(signal.SIGINT, handle_sigint)
129
130 print "Connected! Running..."
mbligh36768f02008-02-22 18:28:33 +0000131
132
133def enable_logging(logfile):
jadmanski0afbb632008-06-06 21:10:57 +0000134 out_file = logfile
135 err_file = "%s.err" % logfile
136 print "Enabling logging to %s (%s)" % (out_file, err_file)
137 out_fd = open(out_file, "a", buffering=0)
138 err_fd = open(err_file, "a", buffering=0)
mbligh36768f02008-02-22 18:28:33 +0000139
jadmanski0afbb632008-06-06 21:10:57 +0000140 os.dup2(out_fd.fileno(), sys.stdout.fileno())
141 os.dup2(err_fd.fileno(), sys.stderr.fileno())
mbligh36768f02008-02-22 18:28:33 +0000142
jadmanski0afbb632008-06-06 21:10:57 +0000143 sys.stdout = out_fd
144 sys.stderr = err_fd
mbligh36768f02008-02-22 18:28:33 +0000145
146
mblighd5c95802008-03-05 00:33:46 +0000147def queue_entries_to_abort():
jadmanski0afbb632008-06-06 21:10:57 +0000148 rows = _db.execute("""
149 SELECT * FROM host_queue_entries WHERE status='Abort';
150 """)
151 qe = [HostQueueEntry(row=i) for i in rows]
152 return qe
mbligh36768f02008-02-22 18:28:33 +0000153
mblighe2586682008-02-29 22:45:46 +0000154def remove_file_or_dir(path):
jadmanski0afbb632008-06-06 21:10:57 +0000155 if stat.S_ISDIR(os.stat(path).st_mode):
156 # directory
157 shutil.rmtree(path)
158 else:
159 # file
160 os.remove(path)
mblighe2586682008-02-29 22:45:46 +0000161
162
mblighdbdac6c2008-03-05 15:49:58 +0000163def generate_parse_command(results_dir, flags=""):
jadmanski0afbb632008-06-06 21:10:57 +0000164 parse = os.path.abspath(os.path.join(AUTOTEST_TKO_DIR, 'parse'))
165 output = os.path.abspath(os.path.join(results_dir, '.parse.log'))
166 cmd = "%s %s -r -o %s > %s 2>&1 &"
167 return cmd % (parse, flags, results_dir, output)
mblighdbdac6c2008-03-05 15:49:58 +0000168
169
showard970a6db2008-09-03 20:02:39 +0000170_parse_command_queue = []
mbligh36768f02008-02-22 18:28:33 +0000171def parse_results(results_dir, flags=""):
jadmanski0afbb632008-06-06 21:10:57 +0000172 if _testing_mode:
173 return
showard970a6db2008-09-03 20:02:39 +0000174 _parse_command_queue.append(generate_parse_command(results_dir, flags))
mbligh36768f02008-02-22 18:28:33 +0000175
176
mblighbb421852008-03-11 22:36:16 +0000177
178
mbligh36768f02008-02-22 18:28:33 +0000179def log_stacktrace(reason):
jadmanski0afbb632008-06-06 21:10:57 +0000180 (type, value, tb) = sys.exc_info()
181 str = "EXCEPTION: %s\n" % reason
182 str += ''.join(traceback.format_exception(type, value, tb))
mbligh36768f02008-02-22 18:28:33 +0000183
jadmanski0afbb632008-06-06 21:10:57 +0000184 sys.stderr.write("\n%s\n" % str)
185 email_manager.enqueue_notify_email("monitor_db exception", str)
mbligh36768f02008-02-22 18:28:33 +0000186
mblighbb421852008-03-11 22:36:16 +0000187
188def get_proc_poll_fn(pid):
jadmanski0afbb632008-06-06 21:10:57 +0000189 proc_path = os.path.join('/proc', str(pid))
190 def poll_fn():
191 if os.path.exists(proc_path):
192 return None
193 return 0 # we can't get a real exit code
194 return poll_fn
mblighbb421852008-03-11 22:36:16 +0000195
196
showard542e8402008-09-19 20:16:18 +0000197def send_email(from_addr, to_string, subject, body):
198 """Mails out emails to the addresses listed in to_string.
199
200 to_string is split into a list which can be delimited by any of:
201 ';', ',', ':' or any whitespace
202 """
203
204 # Create list from string removing empty strings from the list.
205 to_list = [x for x in re.split('\s|,|;|:', to_string) if x]
showard7d182aa2008-09-22 16:17:24 +0000206 if not to_list:
207 return
208
showard542e8402008-09-19 20:16:18 +0000209 msg = "From: %s\nTo: %s\nSubject: %s\n\n%s" % (
210 from_addr, ', '.join(to_list), subject, body)
showard7d182aa2008-09-22 16:17:24 +0000211 try:
212 mailer = smtplib.SMTP('localhost')
213 try:
214 mailer.sendmail(from_addr, to_list, msg)
215 finally:
216 mailer.quit()
217 except Exception, e:
218 print "Sending email failed. Reason: %s" % repr(e)
showard542e8402008-09-19 20:16:18 +0000219
220
mblighbb421852008-03-11 22:36:16 +0000221def kill_autoserv(pid, poll_fn=None):
jadmanski0afbb632008-06-06 21:10:57 +0000222 print 'killing', pid
223 if poll_fn is None:
224 poll_fn = get_proc_poll_fn(pid)
225 if poll_fn() == None:
226 os.kill(pid, signal.SIGCONT)
227 os.kill(pid, signal.SIGTERM)
mbligh36768f02008-02-22 18:28:33 +0000228
229
showard7cf9a9b2008-05-15 21:15:52 +0000230class EmailNotificationManager(object):
jadmanski0afbb632008-06-06 21:10:57 +0000231 def __init__(self):
232 self._emails = []
showard7cf9a9b2008-05-15 21:15:52 +0000233
jadmanski0afbb632008-06-06 21:10:57 +0000234 def enqueue_notify_email(self, subject, message):
235 if not _notify_email:
236 return
showard7cf9a9b2008-05-15 21:15:52 +0000237
jadmanski0afbb632008-06-06 21:10:57 +0000238 body = 'Subject: ' + subject + '\n'
239 body += "%s / %s / %s\n%s" % (socket.gethostname(),
240 os.getpid(),
241 time.strftime("%X %x"), message)
242 self._emails.append(body)
showard7cf9a9b2008-05-15 21:15:52 +0000243
244
jadmanski0afbb632008-06-06 21:10:57 +0000245 def send_queued_emails(self):
246 if not self._emails:
247 return
248 subject = 'Scheduler notifications from ' + socket.gethostname()
249 separator = '\n' + '-' * 40 + '\n'
250 body = separator.join(self._emails)
showard7cf9a9b2008-05-15 21:15:52 +0000251
showard542e8402008-09-19 20:16:18 +0000252 send_email(_email_from, _notify_email, subject, body)
jadmanski0afbb632008-06-06 21:10:57 +0000253 self._emails = []
showard7cf9a9b2008-05-15 21:15:52 +0000254
255email_manager = EmailNotificationManager()
256
257
showard63a34772008-08-18 19:32:50 +0000258class HostScheduler(object):
259 def _get_ready_hosts(self):
260 # avoid any host with a currently active queue entry against it
261 hosts = Host.fetch(
262 joins='LEFT JOIN host_queue_entries AS active_hqe '
263 'ON (hosts.id = active_hqe.host_id AND '
showardb1e51872008-10-07 11:08:18 +0000264 'active_hqe.active)',
showard63a34772008-08-18 19:32:50 +0000265 where="active_hqe.host_id IS NULL "
showardb1e51872008-10-07 11:08:18 +0000266 "AND NOT hosts.locked "
showard63a34772008-08-18 19:32:50 +0000267 "AND (hosts.status IS NULL OR hosts.status = 'Ready')")
268 return dict((host.id, host) for host in hosts)
269
270
271 @staticmethod
272 def _get_sql_id_list(id_list):
273 return ','.join(str(item_id) for item_id in id_list)
274
275
276 @classmethod
showard989f25d2008-10-01 11:38:11 +0000277 def _get_many2many_dict(cls, query, id_list, flip=False):
mbligh849a0f62008-08-28 20:12:19 +0000278 if not id_list:
279 return {}
showard63a34772008-08-18 19:32:50 +0000280 query %= cls._get_sql_id_list(id_list)
281 rows = _db.execute(query)
showard989f25d2008-10-01 11:38:11 +0000282 return cls._process_many2many_dict(rows, flip)
283
284
285 @staticmethod
286 def _process_many2many_dict(rows, flip=False):
showard63a34772008-08-18 19:32:50 +0000287 result = {}
288 for row in rows:
289 left_id, right_id = long(row[0]), long(row[1])
showard989f25d2008-10-01 11:38:11 +0000290 if flip:
291 left_id, right_id = right_id, left_id
showard63a34772008-08-18 19:32:50 +0000292 result.setdefault(left_id, set()).add(right_id)
293 return result
294
295
296 @classmethod
297 def _get_job_acl_groups(cls, job_ids):
298 query = """
299 SELECT jobs.id, acl_groups_users.acl_group_id
300 FROM jobs
301 INNER JOIN users ON users.login = jobs.owner
302 INNER JOIN acl_groups_users ON acl_groups_users.user_id = users.id
303 WHERE jobs.id IN (%s)
304 """
305 return cls._get_many2many_dict(query, job_ids)
306
307
308 @classmethod
309 def _get_job_ineligible_hosts(cls, job_ids):
310 query = """
311 SELECT job_id, host_id
312 FROM ineligible_host_queues
313 WHERE job_id IN (%s)
314 """
315 return cls._get_many2many_dict(query, job_ids)
316
317
318 @classmethod
showard989f25d2008-10-01 11:38:11 +0000319 def _get_job_dependencies(cls, job_ids):
320 query = """
321 SELECT job_id, label_id
322 FROM jobs_dependency_labels
323 WHERE job_id IN (%s)
324 """
325 return cls._get_many2many_dict(query, job_ids)
326
327
328 @classmethod
showard63a34772008-08-18 19:32:50 +0000329 def _get_host_acls(cls, host_ids):
330 query = """
331 SELECT host_id, acl_group_id
332 FROM acl_groups_hosts
333 WHERE host_id IN (%s)
334 """
335 return cls._get_many2many_dict(query, host_ids)
336
337
338 @classmethod
339 def _get_label_hosts(cls, host_ids):
340 query = """
341 SELECT label_id, host_id
342 FROM hosts_labels
343 WHERE host_id IN (%s)
showard989f25d2008-10-01 11:38:11 +0000344 """ % cls._get_sql_id_list(host_ids)
345 rows = _db.execute(query)
346 labels_to_hosts = cls._process_many2many_dict(rows)
347 hosts_to_labels = cls._process_many2many_dict(rows, flip=True)
348 return labels_to_hosts, hosts_to_labels
349
350
351 @classmethod
352 def _get_labels(cls):
353 return dict((label.id, label) for label in Label.fetch())
showard63a34772008-08-18 19:32:50 +0000354
355
356 def refresh(self, pending_queue_entries):
357 self._hosts_available = self._get_ready_hosts()
358
359 relevant_jobs = [queue_entry.job_id
360 for queue_entry in pending_queue_entries]
361 self._job_acls = self._get_job_acl_groups(relevant_jobs)
362 self._ineligible_hosts = self._get_job_ineligible_hosts(relevant_jobs)
showard989f25d2008-10-01 11:38:11 +0000363 self._job_dependencies = self._get_job_dependencies(relevant_jobs)
showard63a34772008-08-18 19:32:50 +0000364
365 host_ids = self._hosts_available.keys()
366 self._host_acls = self._get_host_acls(host_ids)
showard989f25d2008-10-01 11:38:11 +0000367 self._label_hosts, self._host_labels = self._get_label_hosts(host_ids)
368
369 self._labels = self._get_labels()
showard63a34772008-08-18 19:32:50 +0000370
371
372 def _is_acl_accessible(self, host_id, queue_entry):
373 job_acls = self._job_acls.get(queue_entry.job_id, set())
374 host_acls = self._host_acls.get(host_id, set())
375 return len(host_acls.intersection(job_acls)) > 0
376
377
showard989f25d2008-10-01 11:38:11 +0000378 def _check_job_dependencies(self, job_dependencies, host_labels):
379 missing = job_dependencies - host_labels
380 return len(job_dependencies - host_labels) == 0
381
382
383 def _check_only_if_needed_labels(self, job_dependencies, host_labels,
384 queue_entry):
385 for label_id in host_labels:
386 label = self._labels[label_id]
387 if not label.only_if_needed:
388 # we don't care about non-only_if_needed labels
389 continue
390 if queue_entry.meta_host == label_id:
391 # if the label was requested in a metahost it's OK
392 continue
393 if label_id not in job_dependencies:
394 return False
395 return True
396
397
398 def _is_host_eligible_for_job(self, host_id, queue_entry):
399 job_dependencies = self._job_dependencies.get(queue_entry.job_id, set())
400 host_labels = self._host_labels.get(host_id, set())
mblighc993bee2008-10-03 03:42:34 +0000401
402 acl = self._is_acl_accessible(host_id, queue_entry)
403 deps = self._check_job_dependencies(job_dependencies, host_labels)
404 only_if = self._check_only_if_needed_labels(job_dependencies,
405 host_labels, queue_entry)
406 return acl and deps and only_if
showard989f25d2008-10-01 11:38:11 +0000407
408
showard63a34772008-08-18 19:32:50 +0000409 def _schedule_non_metahost(self, queue_entry):
showard989f25d2008-10-01 11:38:11 +0000410 if not self._is_host_eligible_for_job(queue_entry.host_id, queue_entry):
showard63a34772008-08-18 19:32:50 +0000411 return None
412 return self._hosts_available.pop(queue_entry.host_id, None)
413
414
415 def _is_host_usable(self, host_id):
416 if host_id not in self._hosts_available:
417 # host was already used during this scheduling cycle
418 return False
419 if self._hosts_available[host_id].invalid:
420 # Invalid hosts cannot be used for metahosts. They're included in
421 # the original query because they can be used by non-metahosts.
422 return False
423 return True
424
425
426 def _schedule_metahost(self, queue_entry):
427 label_id = queue_entry.meta_host
428 hosts_in_label = self._label_hosts.get(label_id, set())
429 ineligible_host_ids = self._ineligible_hosts.get(queue_entry.job_id,
430 set())
431
432 # must iterate over a copy so we can mutate the original while iterating
433 for host_id in list(hosts_in_label):
434 if not self._is_host_usable(host_id):
435 hosts_in_label.remove(host_id)
436 continue
437 if host_id in ineligible_host_ids:
438 continue
showard989f25d2008-10-01 11:38:11 +0000439 if not self._is_host_eligible_for_job(host_id, queue_entry):
showard63a34772008-08-18 19:32:50 +0000440 continue
441
442 hosts_in_label.remove(host_id)
443 return self._hosts_available.pop(host_id)
444 return None
445
446
447 def find_eligible_host(self, queue_entry):
448 if not queue_entry.meta_host:
449 return self._schedule_non_metahost(queue_entry)
450 return self._schedule_metahost(queue_entry)
451
452
mbligh36768f02008-02-22 18:28:33 +0000453class Dispatcher:
jadmanski0afbb632008-06-06 21:10:57 +0000454 autoserv_procs_cache = None
showard4c5374f2008-09-04 17:02:56 +0000455 max_running_processes = global_config.global_config.get_config_value(
jadmanski0afbb632008-06-06 21:10:57 +0000456 _global_config_section, 'max_running_jobs', type=int)
showard4c5374f2008-09-04 17:02:56 +0000457 max_processes_started_per_cycle = (
jadmanski0afbb632008-06-06 21:10:57 +0000458 global_config.global_config.get_config_value(
459 _global_config_section, 'max_jobs_started_per_cycle', type=int))
showard3bb499f2008-07-03 19:42:20 +0000460 clean_interval = (
461 global_config.global_config.get_config_value(
462 _global_config_section, 'clean_interval_minutes', type=int))
showard970a6db2008-09-03 20:02:39 +0000463 max_parse_processes = (
464 global_config.global_config.get_config_value(
465 _global_config_section, 'max_parse_processes', type=int))
mbligh90a549d2008-03-25 23:52:34 +0000466
jadmanski0afbb632008-06-06 21:10:57 +0000467 def __init__(self):
468 self._agents = []
showard3bb499f2008-07-03 19:42:20 +0000469 self._last_clean_time = time.time()
showard63a34772008-08-18 19:32:50 +0000470 self._host_scheduler = HostScheduler()
mbligh36768f02008-02-22 18:28:33 +0000471
mbligh36768f02008-02-22 18:28:33 +0000472
jadmanski0afbb632008-06-06 21:10:57 +0000473 def do_initial_recovery(self, recover_hosts=True):
474 # always recover processes
475 self._recover_processes()
mblighbb421852008-03-11 22:36:16 +0000476
jadmanski0afbb632008-06-06 21:10:57 +0000477 if recover_hosts:
478 self._recover_hosts()
mbligh36768f02008-02-22 18:28:33 +0000479
480
jadmanski0afbb632008-06-06 21:10:57 +0000481 def tick(self):
482 Dispatcher.autoserv_procs_cache = None
showard3bb499f2008-07-03 19:42:20 +0000483 if self._last_clean_time + self.clean_interval * 60 < time.time():
484 self._abort_timed_out_jobs()
485 self._clear_inactive_blocks()
486 self._last_clean_time = time.time()
jadmanski0afbb632008-06-06 21:10:57 +0000487 self._find_aborting()
488 self._schedule_new_jobs()
489 self._handle_agents()
showard970a6db2008-09-03 20:02:39 +0000490 self._run_final_parses()
jadmanski0afbb632008-06-06 21:10:57 +0000491 email_manager.send_queued_emails()
mbligh36768f02008-02-22 18:28:33 +0000492
493
showard970a6db2008-09-03 20:02:39 +0000494 def _run_final_parses(self):
495 process_count = 0
496 try:
497 for line in utils.system_output('ps -e').splitlines():
498 if 'parse.py' in line:
499 process_count += 1
500 except Exception:
501 # We'll try again in a bit. This is a work-around for one time
502 # when the scheduler crashed due to a "Interrupted system call"
503 return
504
505 if process_count:
506 print "%d parses currently running" % process_count
507
508 while (process_count < self.max_parse_processes and
509 _parse_command_queue):
510 cmd = _parse_command_queue.pop(0)
511 print "Starting another final parse with cmd %s" % cmd
512 os.system(cmd)
513 process_count += 1
514
515 if _parse_command_queue:
516 print ("%d cmds still in final parse queue" %
517 len(_parse_command_queue))
518
519
jadmanski0afbb632008-06-06 21:10:57 +0000520 def add_agent(self, agent):
521 self._agents.append(agent)
522 agent.dispatcher = self
mblighd5c95802008-03-05 00:33:46 +0000523
jadmanski0afbb632008-06-06 21:10:57 +0000524 # Find agent corresponding to the specified queue_entry
525 def get_agents(self, queue_entry):
526 res_agents = []
527 for agent in self._agents:
528 if queue_entry.id in agent.queue_entry_ids:
529 res_agents.append(agent)
530 return res_agents
mbligh36768f02008-02-22 18:28:33 +0000531
532
jadmanski0afbb632008-06-06 21:10:57 +0000533 def remove_agent(self, agent):
534 self._agents.remove(agent)
showardec113162008-05-08 00:52:49 +0000535
536
showard4c5374f2008-09-04 17:02:56 +0000537 def num_running_processes(self):
538 return sum(agent.num_processes for agent in self._agents
539 if agent.is_running())
mblighbb421852008-03-11 22:36:16 +0000540
541
jadmanski0afbb632008-06-06 21:10:57 +0000542 @classmethod
543 def find_autoservs(cls, orphans_only=False):
544 """\
545 Returns a dict mapping pids to command lines for root autoserv
546 processes. If orphans_only=True, return only processes that
547 have been orphaned (i.e. parent pid = 1).
548 """
549 if cls.autoserv_procs_cache is not None:
550 return cls.autoserv_procs_cache
551
552 proc = subprocess.Popen(
553 ['/bin/ps', 'x', '-o', 'pid,pgid,ppid,comm,args'],
554 stdout=subprocess.PIPE)
555 # split each line into the four columns output by ps
556 procs = [line.split(None, 4) for line in
557 proc.communicate()[0].splitlines()]
558 autoserv_procs = {}
559 for proc in procs:
560 # check ppid == 1 for orphans
561 if orphans_only and proc[2] != 1:
562 continue
563 # only root autoserv processes have pgid == pid
564 if (proc[3] == 'autoserv' and # comm
565 proc[1] == proc[0]): # pgid == pid
566 # map pid to args
567 autoserv_procs[int(proc[0])] = proc[4]
568 cls.autoserv_procs_cache = autoserv_procs
569 return autoserv_procs
mblighbb421852008-03-11 22:36:16 +0000570
571
jadmanski0afbb632008-06-06 21:10:57 +0000572 def recover_queue_entry(self, queue_entry, run_monitor):
573 job = queue_entry.job
574 if job.is_synchronous():
575 all_queue_entries = job.get_host_queue_entries()
576 else:
577 all_queue_entries = [queue_entry]
578 all_queue_entry_ids = [queue_entry.id for queue_entry
579 in all_queue_entries]
580 queue_task = RecoveryQueueTask(
581 job=queue_entry.job,
582 queue_entries=all_queue_entries,
583 run_monitor=run_monitor)
584 self.add_agent(Agent(tasks=[queue_task],
585 queue_entry_ids=all_queue_entry_ids))
mblighbb421852008-03-11 22:36:16 +0000586
587
jadmanski0afbb632008-06-06 21:10:57 +0000588 def _recover_processes(self):
589 orphans = self.find_autoservs(orphans_only=True)
mblighbb421852008-03-11 22:36:16 +0000590
jadmanski0afbb632008-06-06 21:10:57 +0000591 # first, recover running queue entries
592 rows = _db.execute("""SELECT * FROM host_queue_entries
593 WHERE status = 'Running'""")
594 queue_entries = [HostQueueEntry(row=i) for i in rows]
595 requeue_entries = []
596 recovered_entry_ids = set()
597 for queue_entry in queue_entries:
598 run_monitor = PidfileRunMonitor(
599 queue_entry.results_dir())
showard21baa452008-10-21 00:08:39 +0000600 if not run_monitor.has_pid():
jadmanski0afbb632008-06-06 21:10:57 +0000601 # autoserv apparently never got run, so requeue
602 requeue_entries.append(queue_entry)
603 continue
604 if queue_entry.id in recovered_entry_ids:
605 # synchronous job we've already recovered
606 continue
showard21baa452008-10-21 00:08:39 +0000607 pid = run_monitor.get_pid()
jadmanski0afbb632008-06-06 21:10:57 +0000608 print 'Recovering queue entry %d (pid %d)' % (
609 queue_entry.id, pid)
610 job = queue_entry.job
611 if job.is_synchronous():
612 for entry in job.get_host_queue_entries():
613 assert entry.active
614 recovered_entry_ids.add(entry.id)
615 self.recover_queue_entry(queue_entry,
616 run_monitor)
617 orphans.pop(pid, None)
mblighd5c95802008-03-05 00:33:46 +0000618
jadmanski0afbb632008-06-06 21:10:57 +0000619 # and requeue other active queue entries
620 rows = _db.execute("""SELECT * FROM host_queue_entries
621 WHERE active AND NOT complete
622 AND status != 'Running'
623 AND status != 'Pending'
624 AND status != 'Abort'
625 AND status != 'Aborting'""")
626 queue_entries = [HostQueueEntry(row=i) for i in rows]
627 for queue_entry in queue_entries + requeue_entries:
628 print 'Requeuing running QE %d' % queue_entry.id
629 queue_entry.clear_results_dir(dont_delete_files=True)
630 queue_entry.requeue()
mbligh90a549d2008-03-25 23:52:34 +0000631
632
jadmanski0afbb632008-06-06 21:10:57 +0000633 # now kill any remaining autoserv processes
634 for pid in orphans.keys():
635 print 'Killing orphan %d (%s)' % (pid, orphans[pid])
636 kill_autoserv(pid)
637
638 # recover aborting tasks
639 rebooting_host_ids = set()
640 rows = _db.execute("""SELECT * FROM host_queue_entries
641 WHERE status='Abort' or status='Aborting'""")
642 queue_entries = [HostQueueEntry(row=i) for i in rows]
643 for queue_entry in queue_entries:
644 print 'Recovering aborting QE %d' % queue_entry.id
showard1be97432008-10-17 15:30:45 +0000645 agent = queue_entry.abort()
646 self.add_agent(agent)
647 if queue_entry.get_host():
648 rebooting_host_ids.add(queue_entry.get_host().id)
jadmanski0afbb632008-06-06 21:10:57 +0000649
650 # reverify hosts that were in the middle of verify, repair or
651 # reboot
652 self._reverify_hosts_where("""(status = 'Repairing' OR
653 status = 'Verifying' OR
654 status = 'Rebooting')""",
655 exclude_ids=rebooting_host_ids)
656
657 # finally, recover "Running" hosts with no active queue entries,
658 # although this should never happen
659 message = ('Recovering running host %s - this probably '
660 'indicates a scheduler bug')
661 self._reverify_hosts_where("""status = 'Running' AND
662 id NOT IN (SELECT host_id
663 FROM host_queue_entries
664 WHERE active)""",
665 print_message=message)
mblighbb421852008-03-11 22:36:16 +0000666
667
jadmanski0afbb632008-06-06 21:10:57 +0000668 def _reverify_hosts_where(self, where,
669 print_message='Reverifying host %s',
670 exclude_ids=set()):
671 rows = _db.execute('SELECT * FROM hosts WHERE locked = 0 AND '
672 'invalid = 0 AND ' + where)
673 hosts = [Host(row=i) for i in rows]
674 for host in hosts:
675 if host.id in exclude_ids:
676 continue
677 if print_message is not None:
678 print print_message % host.hostname
679 verify_task = VerifyTask(host = host)
680 self.add_agent(Agent(tasks = [verify_task]))
mbligh36768f02008-02-22 18:28:33 +0000681
682
jadmanski0afbb632008-06-06 21:10:57 +0000683 def _recover_hosts(self):
684 # recover "Repair Failed" hosts
685 message = 'Reverifying dead host %s'
686 self._reverify_hosts_where("status = 'Repair Failed'",
687 print_message=message)
mbligh62ba2ed2008-04-30 17:09:25 +0000688
689
showard3bb499f2008-07-03 19:42:20 +0000690 def _abort_timed_out_jobs(self):
691 """
692 Aborts all jobs that have timed out and not completed
693 """
694 update = """
695 UPDATE host_queue_entries INNER JOIN jobs
696 ON host_queue_entries.job_id = jobs.id"""
mbligh7e26d622008-07-29 21:04:42 +0000697 timed_out = ' AND jobs.created_on + INTERVAL jobs.timeout HOUR < NOW()'
showard3bb499f2008-07-03 19:42:20 +0000698
699 _db.execute(update + """
700 SET host_queue_entries.status = 'Abort'
showardb1e51872008-10-07 11:08:18 +0000701 WHERE host_queue_entries.active""" + timed_out)
showard3bb499f2008-07-03 19:42:20 +0000702
703 _db.execute(update + """
704 SET host_queue_entries.status = 'Aborted',
showardb1e51872008-10-07 11:08:18 +0000705 host_queue_entries.active = 0,
706 host_queue_entries.complete = 1
707 WHERE NOT host_queue_entries.active
708 AND NOT host_queue_entries.complete""" + timed_out)
showard3bb499f2008-07-03 19:42:20 +0000709
710
jadmanski0afbb632008-06-06 21:10:57 +0000711 def _clear_inactive_blocks(self):
712 """
713 Clear out blocks for all completed jobs.
714 """
715 # this would be simpler using NOT IN (subquery), but MySQL
716 # treats all IN subqueries as dependent, so this optimizes much
717 # better
718 _db.execute("""
719 DELETE ihq FROM ineligible_host_queues ihq
showard4eaaf522008-06-06 22:28:07 +0000720 LEFT JOIN (SELECT DISTINCT job_id FROM host_queue_entries
jadmanski0afbb632008-06-06 21:10:57 +0000721 WHERE NOT complete) hqe
722 USING (job_id) WHERE hqe.job_id IS NULL""")
showard04c82c52008-05-29 19:38:12 +0000723
724
showardb95b1bd2008-08-15 18:11:04 +0000725 def _get_pending_queue_entries(self):
showard63a34772008-08-18 19:32:50 +0000726 # prioritize by job priority, then non-metahost over metahost, then FIFO
727 return list(HostQueueEntry.fetch(
728 where='NOT complete AND NOT active',
729 order_by='priority DESC, meta_host, id'))
mbligh36768f02008-02-22 18:28:33 +0000730
731
jadmanski0afbb632008-06-06 21:10:57 +0000732 def _schedule_new_jobs(self):
733 print "finding work"
734
showard63a34772008-08-18 19:32:50 +0000735 queue_entries = self._get_pending_queue_entries()
736 if not queue_entries:
showardb95b1bd2008-08-15 18:11:04 +0000737 return
showardb95b1bd2008-08-15 18:11:04 +0000738
showard63a34772008-08-18 19:32:50 +0000739 self._host_scheduler.refresh(queue_entries)
showardb95b1bd2008-08-15 18:11:04 +0000740
showard63a34772008-08-18 19:32:50 +0000741 for queue_entry in queue_entries:
742 assigned_host = self._host_scheduler.find_eligible_host(queue_entry)
showardb95b1bd2008-08-15 18:11:04 +0000743 if not assigned_host:
jadmanski0afbb632008-06-06 21:10:57 +0000744 continue
showardb95b1bd2008-08-15 18:11:04 +0000745 self._run_queue_entry(queue_entry, assigned_host)
746
747
748 def _run_queue_entry(self, queue_entry, host):
749 agent = queue_entry.run(assigned_host=host)
showard9976ce92008-10-15 20:28:13 +0000750 # in some cases (synchronous jobs with run_verify=False), agent may be None
751 if agent:
752 self.add_agent(agent)
mblighd5c95802008-03-05 00:33:46 +0000753
754
jadmanski0afbb632008-06-06 21:10:57 +0000755 def _find_aborting(self):
756 num_aborted = 0
757 # Find jobs that are aborting
758 for entry in queue_entries_to_abort():
759 agents_to_abort = self.get_agents(entry)
showard1be97432008-10-17 15:30:45 +0000760 for agent in agents_to_abort:
761 self.remove_agent(agent)
762
763 agent = entry.abort(agents_to_abort)
764 self.add_agent(agent)
jadmanski0afbb632008-06-06 21:10:57 +0000765 num_aborted += 1
766 if num_aborted >= 50:
767 break
768
769
showard4c5374f2008-09-04 17:02:56 +0000770 def _can_start_agent(self, agent, num_running_processes,
771 num_started_this_cycle, have_reached_limit):
772 # always allow zero-process agents to run
773 if agent.num_processes == 0:
774 return True
775 # don't allow any nonzero-process agents to run after we've reached a
776 # limit (this avoids starvation of many-process agents)
777 if have_reached_limit:
778 return False
779 # total process throttling
780 if (num_running_processes + agent.num_processes >
781 self.max_running_processes):
782 return False
783 # if a single agent exceeds the per-cycle throttling, still allow it to
784 # run when it's the first agent in the cycle
785 if num_started_this_cycle == 0:
786 return True
787 # per-cycle throttling
788 if (num_started_this_cycle + agent.num_processes >
789 self.max_processes_started_per_cycle):
790 return False
791 return True
792
793
jadmanski0afbb632008-06-06 21:10:57 +0000794 def _handle_agents(self):
showard4c5374f2008-09-04 17:02:56 +0000795 num_running_processes = self.num_running_processes()
jadmanski0afbb632008-06-06 21:10:57 +0000796 num_started_this_cycle = 0
showard4c5374f2008-09-04 17:02:56 +0000797 have_reached_limit = False
798 # iterate over copy, so we can remove agents during iteration
799 for agent in list(self._agents):
800 if agent.is_done():
jadmanski0afbb632008-06-06 21:10:57 +0000801 print "agent finished"
showard4c5374f2008-09-04 17:02:56 +0000802 self._agents.remove(agent)
803 num_running_processes -= agent.num_processes
804 continue
805 if not agent.is_running():
806 if not self._can_start_agent(agent, num_running_processes,
807 num_started_this_cycle,
808 have_reached_limit):
809 have_reached_limit = True
810 continue
811 num_running_processes += agent.num_processes
812 num_started_this_cycle += agent.num_processes
813 agent.tick()
814 print num_running_processes, 'running processes'
mbligh36768f02008-02-22 18:28:33 +0000815
816
817class RunMonitor(object):
jadmanski0afbb632008-06-06 21:10:57 +0000818 def __init__(self, cmd, nice_level = None, log_file = None):
819 self.nice_level = nice_level
820 self.log_file = log_file
821 self.cmd = cmd
mbligh36768f02008-02-22 18:28:33 +0000822
jadmanski0afbb632008-06-06 21:10:57 +0000823 def run(self):
824 if self.nice_level:
825 nice_cmd = ['nice','-n', str(self.nice_level)]
826 nice_cmd.extend(self.cmd)
827 self.cmd = nice_cmd
mbligh36768f02008-02-22 18:28:33 +0000828
jadmanski0afbb632008-06-06 21:10:57 +0000829 out_file = None
830 if self.log_file:
831 try:
832 os.makedirs(os.path.dirname(self.log_file))
833 except OSError, exc:
834 if exc.errno != errno.EEXIST:
835 log_stacktrace(
836 'Unexpected error creating logfile '
837 'directory for %s' % self.log_file)
838 try:
839 out_file = open(self.log_file, 'a')
840 out_file.write("\n%s\n" % ('*'*80))
841 out_file.write("%s> %s\n" %
842 (time.strftime("%X %x"),
843 self.cmd))
844 out_file.write("%s\n" % ('*'*80))
845 except (OSError, IOError):
846 log_stacktrace('Error opening log file %s' %
847 self.log_file)
mblighcadb3532008-04-15 17:46:26 +0000848
jadmanski0afbb632008-06-06 21:10:57 +0000849 if not out_file:
850 out_file = open('/dev/null', 'w')
mblighcadb3532008-04-15 17:46:26 +0000851
jadmanski0afbb632008-06-06 21:10:57 +0000852 in_devnull = open('/dev/null', 'r')
853 print "cmd = %s" % self.cmd
854 print "path = %s" % os.getcwd()
mbligh36768f02008-02-22 18:28:33 +0000855
jadmanski0afbb632008-06-06 21:10:57 +0000856 self.proc = subprocess.Popen(self.cmd, stdout=out_file,
857 stderr=subprocess.STDOUT,
858 stdin=in_devnull)
859 out_file.close()
860 in_devnull.close()
mbligh36768f02008-02-22 18:28:33 +0000861
862
jadmanski0afbb632008-06-06 21:10:57 +0000863 def get_pid(self):
864 return self.proc.pid
mblighbb421852008-03-11 22:36:16 +0000865
866
jadmanski0afbb632008-06-06 21:10:57 +0000867 def kill(self):
868 kill_autoserv(self.get_pid(), self.exit_code)
mblighbb421852008-03-11 22:36:16 +0000869
mbligh36768f02008-02-22 18:28:33 +0000870
jadmanski0afbb632008-06-06 21:10:57 +0000871 def exit_code(self):
872 return self.proc.poll()
mbligh36768f02008-02-22 18:28:33 +0000873
874
mblighbb421852008-03-11 22:36:16 +0000875class PidfileException(Exception):
jadmanski0afbb632008-06-06 21:10:57 +0000876 """\
877 Raised when there's some unexpected behavior with the pid file.
878 """
mblighbb421852008-03-11 22:36:16 +0000879
880
881class PidfileRunMonitor(RunMonitor):
showard21baa452008-10-21 00:08:39 +0000882 class PidfileState(object):
883 pid = None
884 exit_status = None
885 num_tests_failed = None
886
887 def reset(self):
888 self.pid = self.exit_status = self.all_tests_passed = None
889
890
jadmanski0afbb632008-06-06 21:10:57 +0000891 def __init__(self, results_dir, cmd=None, nice_level=None,
892 log_file=None):
893 self.results_dir = os.path.abspath(results_dir)
894 self.pid_file = os.path.join(results_dir, AUTOSERV_PID_FILE)
895 self.lost_process = False
896 self.start_time = time.time()
showard21baa452008-10-21 00:08:39 +0000897 self._state = self.PidfileState()
showardb376bc52008-06-13 20:48:45 +0000898 super(PidfileRunMonitor, self).__init__(cmd, nice_level, log_file)
mblighbb421852008-03-11 22:36:16 +0000899
900
showard21baa452008-10-21 00:08:39 +0000901 def has_pid(self):
902 self._get_pidfile_info()
903 return self._state.pid is not None
904
905
jadmanski0afbb632008-06-06 21:10:57 +0000906 def get_pid(self):
showard21baa452008-10-21 00:08:39 +0000907 self._get_pidfile_info()
908 assert self._state.pid is not None
909 return self._state.pid
mblighbb421852008-03-11 22:36:16 +0000910
911
jadmanski0afbb632008-06-06 21:10:57 +0000912 def _check_command_line(self, command_line, spacer=' ',
913 print_error=False):
914 results_dir_arg = spacer.join(('', '-r', self.results_dir, ''))
915 match = results_dir_arg in command_line
916 if print_error and not match:
917 print '%s not found in %s' % (repr(results_dir_arg),
918 repr(command_line))
919 return match
mbligh90a549d2008-03-25 23:52:34 +0000920
921
showard21baa452008-10-21 00:08:39 +0000922 def _check_proc_fs(self):
923 cmdline_path = os.path.join('/proc', str(self._state.pid), 'cmdline')
jadmanski0afbb632008-06-06 21:10:57 +0000924 try:
925 cmdline_file = open(cmdline_path, 'r')
926 cmdline = cmdline_file.read().strip()
927 cmdline_file.close()
928 except IOError:
929 return False
930 # /proc/.../cmdline has \x00 separating args
931 return self._check_command_line(cmdline, spacer='\x00',
932 print_error=True)
mblighbb421852008-03-11 22:36:16 +0000933
934
showard21baa452008-10-21 00:08:39 +0000935 def _read_pidfile(self):
936 self._state.reset()
jadmanski0afbb632008-06-06 21:10:57 +0000937 if not os.path.exists(self.pid_file):
showard21baa452008-10-21 00:08:39 +0000938 return
jadmanski0afbb632008-06-06 21:10:57 +0000939 file_obj = open(self.pid_file, 'r')
940 lines = file_obj.readlines()
941 file_obj.close()
showard21baa452008-10-21 00:08:39 +0000942 if not 1 <= len(lines) <= 3:
943 raise PidfileException('Corrupt pid file (%d lines) at %s:\n%s' %
944 (len(lines), self.pid_file, lines))
jadmanski0afbb632008-06-06 21:10:57 +0000945 try:
showard21baa452008-10-21 00:08:39 +0000946 self._state.pid = int(lines[0])
947 if len(lines) > 1:
948 self._state.exit_status = int(lines[1])
949 if len(lines) == 3:
950 self._state.num_tests_failed = int(lines[2])
951 else:
952 # maintain backwards-compatibility with two-line pidfiles
953 self._state.num_tests_failed = 0
jadmanski0afbb632008-06-06 21:10:57 +0000954 except ValueError, exc:
955 raise PidfileException('Corrupt pid file: ' +
956 str(exc.args))
mblighbb421852008-03-11 22:36:16 +0000957
mblighbb421852008-03-11 22:36:16 +0000958
jadmanski0afbb632008-06-06 21:10:57 +0000959 def _find_autoserv_proc(self):
960 autoserv_procs = Dispatcher.find_autoservs()
961 for pid, args in autoserv_procs.iteritems():
962 if self._check_command_line(args):
963 return pid, args
964 return None, None
mbligh90a549d2008-03-25 23:52:34 +0000965
966
showard21baa452008-10-21 00:08:39 +0000967 def _handle_pidfile_error(self, error, message=''):
968 message = error + '\nPid: %s\nPidfile: %s\n%s' % (self._state.pid,
969 self.pid_file,
970 message)
971 print message
972 email_manager.enqueue_notify_email(error, message)
973 if self._state.pid is not None:
974 pid = self._state.pid
975 else:
976 pid = 0
977 self.on_lost_process(pid)
978
979
980 def _get_pidfile_info_helper(self):
jadmanski0afbb632008-06-06 21:10:57 +0000981 if self.lost_process:
showard21baa452008-10-21 00:08:39 +0000982 return
mblighbb421852008-03-11 22:36:16 +0000983
showard21baa452008-10-21 00:08:39 +0000984 self._read_pidfile()
mblighbb421852008-03-11 22:36:16 +0000985
showard21baa452008-10-21 00:08:39 +0000986 if self._state.pid is None:
987 self._handle_no_pid()
988 return
mbligh90a549d2008-03-25 23:52:34 +0000989
showard21baa452008-10-21 00:08:39 +0000990 if self._state.exit_status is None:
jadmanski0afbb632008-06-06 21:10:57 +0000991 # double check whether or not autoserv is running
showard21baa452008-10-21 00:08:39 +0000992 proc_running = self._check_proc_fs()
jadmanski0afbb632008-06-06 21:10:57 +0000993 if proc_running:
showard21baa452008-10-21 00:08:39 +0000994 return
mbligh90a549d2008-03-25 23:52:34 +0000995
jadmanski0afbb632008-06-06 21:10:57 +0000996 # pid but no process - maybe process *just* exited
showard21baa452008-10-21 00:08:39 +0000997 self._read_pidfile()
998 if self._state.exit_status is None:
jadmanski0afbb632008-06-06 21:10:57 +0000999 # autoserv exited without writing an exit code
1000 # to the pidfile
showard21baa452008-10-21 00:08:39 +00001001 self._handle_pidfile_error(
1002 'autoserv died without writing exit code')
mblighbb421852008-03-11 22:36:16 +00001003
showard21baa452008-10-21 00:08:39 +00001004
1005 def _get_pidfile_info(self):
1006 """\
1007 After completion, self._state will contain:
1008 pid=None, exit_status=None if autoserv has not yet run
1009 pid!=None, exit_status=None if autoserv is running
1010 pid!=None, exit_status!=None if autoserv has completed
1011 """
1012 try:
1013 self._get_pidfile_info_helper()
1014 except PidfileException, exc:
1015 self._handle_pidfile_error('Pidfile error', traceback.format_exc())
mblighbb421852008-03-11 22:36:16 +00001016
1017
jadmanski0afbb632008-06-06 21:10:57 +00001018 def _handle_no_pid(self):
1019 """\
1020 Called when no pidfile is found or no pid is in the pidfile.
1021 """
1022 # is autoserv running?
1023 pid, args = self._find_autoserv_proc()
1024 if pid is None:
1025 # no autoserv process running
1026 message = 'No pid found at ' + self.pid_file
1027 else:
1028 message = ("Process %d (%s) hasn't written pidfile %s" %
1029 (pid, args, self.pid_file))
mbligh90a549d2008-03-25 23:52:34 +00001030
jadmanski0afbb632008-06-06 21:10:57 +00001031 print message
1032 if time.time() - self.start_time > PIDFILE_TIMEOUT:
1033 email_manager.enqueue_notify_email(
1034 'Process has failed to write pidfile', message)
1035 if pid is not None:
1036 kill_autoserv(pid)
1037 else:
1038 pid = 0
1039 self.on_lost_process(pid)
showard21baa452008-10-21 00:08:39 +00001040 return
mbligh90a549d2008-03-25 23:52:34 +00001041
1042
jadmanski0afbb632008-06-06 21:10:57 +00001043 def on_lost_process(self, pid):
1044 """\
1045 Called when autoserv has exited without writing an exit status,
1046 or we've timed out waiting for autoserv to write a pid to the
1047 pidfile. In either case, we just return failure and the caller
1048 should signal some kind of warning.
mbligh90a549d2008-03-25 23:52:34 +00001049
jadmanski0afbb632008-06-06 21:10:57 +00001050 pid is unimportant here, as it shouldn't be used by anyone.
1051 """
1052 self.lost_process = True
showard21baa452008-10-21 00:08:39 +00001053 self._state.pid = pid
1054 self._state.exit_status = 1
1055 self._state.num_tests_failed = 0
mbligh90a549d2008-03-25 23:52:34 +00001056
1057
jadmanski0afbb632008-06-06 21:10:57 +00001058 def exit_code(self):
showard21baa452008-10-21 00:08:39 +00001059 self._get_pidfile_info()
1060 return self._state.exit_status
1061
1062
1063 def num_tests_failed(self):
1064 self._get_pidfile_info()
1065 assert self._state.num_tests_failed is not None
1066 return self._state.num_tests_failed
mblighbb421852008-03-11 22:36:16 +00001067
1068
mbligh36768f02008-02-22 18:28:33 +00001069class Agent(object):
showard4c5374f2008-09-04 17:02:56 +00001070 def __init__(self, tasks, queue_entry_ids=[], num_processes=1):
jadmanski0afbb632008-06-06 21:10:57 +00001071 self.active_task = None
1072 self.queue = Queue.Queue(0)
1073 self.dispatcher = None
1074 self.queue_entry_ids = queue_entry_ids
showard4c5374f2008-09-04 17:02:56 +00001075 self.num_processes = num_processes
jadmanski0afbb632008-06-06 21:10:57 +00001076
1077 for task in tasks:
1078 self.add_task(task)
mbligh36768f02008-02-22 18:28:33 +00001079
1080
jadmanski0afbb632008-06-06 21:10:57 +00001081 def add_task(self, task):
1082 self.queue.put_nowait(task)
1083 task.agent = self
mbligh36768f02008-02-22 18:28:33 +00001084
1085
jadmanski0afbb632008-06-06 21:10:57 +00001086 def tick(self):
showard21baa452008-10-21 00:08:39 +00001087 while not self.is_done():
1088 if self.active_task and not self.active_task.is_done():
1089 self.active_task.poll()
1090 if not self.active_task.is_done():
1091 return
1092 self._next_task()
mbligh36768f02008-02-22 18:28:33 +00001093
1094
jadmanski0afbb632008-06-06 21:10:57 +00001095 def _next_task(self):
1096 print "agent picking task"
1097 if self.active_task:
1098 assert self.active_task.is_done()
mbligh36768f02008-02-22 18:28:33 +00001099
jadmanski0afbb632008-06-06 21:10:57 +00001100 if not self.active_task.success:
1101 self.on_task_failure()
mblighe2586682008-02-29 22:45:46 +00001102
jadmanski0afbb632008-06-06 21:10:57 +00001103 self.active_task = None
1104 if not self.is_done():
1105 self.active_task = self.queue.get_nowait()
1106 if self.active_task:
1107 self.active_task.start()
mbligh36768f02008-02-22 18:28:33 +00001108
1109
jadmanski0afbb632008-06-06 21:10:57 +00001110 def on_task_failure(self):
1111 self.queue = Queue.Queue(0)
1112 for task in self.active_task.failure_tasks:
1113 self.add_task(task)
mbligh16c722d2008-03-05 00:58:44 +00001114
mblighe2586682008-02-29 22:45:46 +00001115
showard4c5374f2008-09-04 17:02:56 +00001116 def is_running(self):
jadmanski0afbb632008-06-06 21:10:57 +00001117 return self.active_task is not None
showardec113162008-05-08 00:52:49 +00001118
1119
jadmanski0afbb632008-06-06 21:10:57 +00001120 def is_done(self):
1121 return self.active_task == None and self.queue.empty()
mbligh36768f02008-02-22 18:28:33 +00001122
1123
jadmanski0afbb632008-06-06 21:10:57 +00001124 def start(self):
1125 assert self.dispatcher
mbligh36768f02008-02-22 18:28:33 +00001126
jadmanski0afbb632008-06-06 21:10:57 +00001127 self._next_task()
mbligh36768f02008-02-22 18:28:33 +00001128
jadmanski0afbb632008-06-06 21:10:57 +00001129
mbligh36768f02008-02-22 18:28:33 +00001130class AgentTask(object):
jadmanski0afbb632008-06-06 21:10:57 +00001131 def __init__(self, cmd, failure_tasks = []):
1132 self.done = False
1133 self.failure_tasks = failure_tasks
1134 self.started = False
1135 self.cmd = cmd
1136 self.task = None
1137 self.agent = None
1138 self.monitor = None
1139 self.success = None
mbligh36768f02008-02-22 18:28:33 +00001140
1141
jadmanski0afbb632008-06-06 21:10:57 +00001142 def poll(self):
1143 print "poll"
1144 if self.monitor:
1145 self.tick(self.monitor.exit_code())
1146 else:
1147 self.finished(False)
mbligh36768f02008-02-22 18:28:33 +00001148
1149
jadmanski0afbb632008-06-06 21:10:57 +00001150 def tick(self, exit_code):
1151 if exit_code==None:
1152 return
1153# print "exit_code was %d" % exit_code
1154 if exit_code == 0:
1155 success = True
1156 else:
1157 success = False
mbligh36768f02008-02-22 18:28:33 +00001158
jadmanski0afbb632008-06-06 21:10:57 +00001159 self.finished(success)
mbligh36768f02008-02-22 18:28:33 +00001160
1161
jadmanski0afbb632008-06-06 21:10:57 +00001162 def is_done(self):
1163 return self.done
mbligh36768f02008-02-22 18:28:33 +00001164
1165
jadmanski0afbb632008-06-06 21:10:57 +00001166 def finished(self, success):
1167 self.done = True
1168 self.success = success
1169 self.epilog()
mbligh36768f02008-02-22 18:28:33 +00001170
1171
jadmanski0afbb632008-06-06 21:10:57 +00001172 def prolog(self):
1173 pass
mblighd64e5702008-04-04 21:39:28 +00001174
1175
jadmanski0afbb632008-06-06 21:10:57 +00001176 def create_temp_resultsdir(self, suffix=''):
1177 self.temp_results_dir = tempfile.mkdtemp(suffix=suffix)
mblighd64e5702008-04-04 21:39:28 +00001178
mbligh36768f02008-02-22 18:28:33 +00001179
jadmanski0afbb632008-06-06 21:10:57 +00001180 def cleanup(self):
1181 if (hasattr(self, 'temp_results_dir') and
1182 os.path.exists(self.temp_results_dir)):
1183 shutil.rmtree(self.temp_results_dir)
mbligh36768f02008-02-22 18:28:33 +00001184
1185
jadmanski0afbb632008-06-06 21:10:57 +00001186 def epilog(self):
1187 self.cleanup()
mbligh36768f02008-02-22 18:28:33 +00001188
1189
jadmanski0afbb632008-06-06 21:10:57 +00001190 def start(self):
1191 assert self.agent
1192
1193 if not self.started:
1194 self.prolog()
1195 self.run()
1196
1197 self.started = True
1198
1199
1200 def abort(self):
1201 if self.monitor:
1202 self.monitor.kill()
1203 self.done = True
1204 self.cleanup()
1205
1206
1207 def run(self):
1208 if self.cmd:
1209 print "agent starting monitor"
1210 log_file = None
1211 if hasattr(self, 'host'):
1212 log_file = os.path.join(RESULTS_DIR, 'hosts',
1213 self.host.hostname)
1214 self.monitor = RunMonitor(
1215 self.cmd, nice_level = AUTOSERV_NICE_LEVEL,
1216 log_file = log_file)
1217 self.monitor.run()
mbligh36768f02008-02-22 18:28:33 +00001218
1219
1220class RepairTask(AgentTask):
jadmanski0afbb632008-06-06 21:10:57 +00001221 def __init__(self, host, fail_queue_entry=None):
1222 """\
1223 fail_queue_entry: queue entry to mark failed if this repair
1224 fails.
1225 """
jadmanskifb7cfb12008-07-09 14:13:21 +00001226 protection = host_protections.Protection.get_string(host.protection)
jadmanski542537f2008-07-24 14:14:56 +00001227 # normalize the protection name
1228 protection = host_protections.Protection.get_attr_name(protection)
jadmanski0afbb632008-06-06 21:10:57 +00001229 self.create_temp_resultsdir('.repair')
1230 cmd = [_autoserv_path , '-R', '-m', host.hostname,
jadmanskifb7cfb12008-07-09 14:13:21 +00001231 '-r', self.temp_results_dir, '--host-protection', protection]
jadmanski0afbb632008-06-06 21:10:57 +00001232 self.host = host
1233 self.fail_queue_entry = fail_queue_entry
1234 super(RepairTask, self).__init__(cmd)
mblighe2586682008-02-29 22:45:46 +00001235
mbligh36768f02008-02-22 18:28:33 +00001236
jadmanski0afbb632008-06-06 21:10:57 +00001237 def prolog(self):
1238 print "repair_task starting"
1239 self.host.set_status('Repairing')
mbligh36768f02008-02-22 18:28:33 +00001240
1241
jadmanski0afbb632008-06-06 21:10:57 +00001242 def epilog(self):
1243 super(RepairTask, self).epilog()
1244 if self.success:
1245 self.host.set_status('Ready')
1246 else:
1247 self.host.set_status('Repair Failed')
1248 if self.fail_queue_entry:
1249 self.fail_queue_entry.handle_host_failure()
mbligh36768f02008-02-22 18:28:33 +00001250
1251
1252class VerifyTask(AgentTask):
showard9976ce92008-10-15 20:28:13 +00001253 def __init__(self, queue_entry=None, host=None):
jadmanski0afbb632008-06-06 21:10:57 +00001254 assert bool(queue_entry) != bool(host)
mbligh36768f02008-02-22 18:28:33 +00001255
jadmanski0afbb632008-06-06 21:10:57 +00001256 self.host = host or queue_entry.host
1257 self.queue_entry = queue_entry
mbligh36768f02008-02-22 18:28:33 +00001258
jadmanski0afbb632008-06-06 21:10:57 +00001259 self.create_temp_resultsdir('.verify')
showard3d9899a2008-07-31 02:11:58 +00001260
showard9976ce92008-10-15 20:28:13 +00001261 cmd = [_autoserv_path,'-v','-m',self.host.hostname, '-r', self.temp_results_dir]
mbligh36768f02008-02-22 18:28:33 +00001262
jadmanski0afbb632008-06-06 21:10:57 +00001263 fail_queue_entry = None
1264 if queue_entry and not queue_entry.meta_host:
1265 fail_queue_entry = queue_entry
1266 failure_tasks = [RepairTask(self.host, fail_queue_entry)]
mblighe2586682008-02-29 22:45:46 +00001267
jadmanski0afbb632008-06-06 21:10:57 +00001268 super(VerifyTask, self).__init__(cmd,
1269 failure_tasks=failure_tasks)
mblighe2586682008-02-29 22:45:46 +00001270
1271
jadmanski0afbb632008-06-06 21:10:57 +00001272 def prolog(self):
1273 print "starting verify on %s" % (self.host.hostname)
1274 if self.queue_entry:
1275 self.queue_entry.set_status('Verifying')
1276 self.queue_entry.clear_results_dir(
1277 self.queue_entry.verify_results_dir())
1278 self.host.set_status('Verifying')
mbligh36768f02008-02-22 18:28:33 +00001279
1280
jadmanski0afbb632008-06-06 21:10:57 +00001281 def cleanup(self):
1282 if not os.path.exists(self.temp_results_dir):
1283 return
1284 if self.queue_entry and (self.success or
1285 not self.queue_entry.meta_host):
1286 self.move_results()
1287 super(VerifyTask, self).cleanup()
mblighd64e5702008-04-04 21:39:28 +00001288
1289
jadmanski0afbb632008-06-06 21:10:57 +00001290 def epilog(self):
1291 super(VerifyTask, self).epilog()
mbligh36768f02008-02-22 18:28:33 +00001292
jadmanski0afbb632008-06-06 21:10:57 +00001293 if self.success:
1294 self.host.set_status('Ready')
1295 elif self.queue_entry:
1296 self.queue_entry.requeue()
mbligh36768f02008-02-22 18:28:33 +00001297
1298
jadmanski0afbb632008-06-06 21:10:57 +00001299 def move_results(self):
1300 assert self.queue_entry is not None
1301 target_dir = self.queue_entry.verify_results_dir()
1302 if not os.path.exists(target_dir):
1303 os.makedirs(target_dir)
1304 files = os.listdir(self.temp_results_dir)
1305 for filename in files:
1306 if filename == AUTOSERV_PID_FILE:
1307 continue
1308 self.force_move(os.path.join(self.temp_results_dir,
1309 filename),
1310 os.path.join(target_dir, filename))
mbligh36768f02008-02-22 18:28:33 +00001311
1312
jadmanski0afbb632008-06-06 21:10:57 +00001313 @staticmethod
1314 def force_move(source, dest):
1315 """\
1316 Replacement for shutil.move() that will delete the destination
1317 if it exists, even if it's a directory.
1318 """
1319 if os.path.exists(dest):
1320 print ('Warning: removing existing destination file ' +
1321 dest)
1322 remove_file_or_dir(dest)
1323 shutil.move(source, dest)
mblighe2586682008-02-29 22:45:46 +00001324
1325
mblighdffd6372008-02-29 22:47:33 +00001326class VerifySynchronousTask(VerifyTask):
jadmanski0afbb632008-06-06 21:10:57 +00001327 def epilog(self):
1328 super(VerifySynchronousTask, self).epilog()
1329 if self.success:
1330 if self.queue_entry.job.num_complete() > 0:
1331 # some other entry failed verify, and we've
1332 # already been marked as stopped
1333 return
mblighdffd6372008-02-29 22:47:33 +00001334
showardb2e2c322008-10-14 17:33:55 +00001335 agent = self.queue_entry.on_pending()
1336 if agent:
jadmanski0afbb632008-06-06 21:10:57 +00001337 self.agent.dispatcher.add_agent(agent)
mblighe2586682008-02-29 22:45:46 +00001338
showardb2e2c322008-10-14 17:33:55 +00001339
mbligh36768f02008-02-22 18:28:33 +00001340class QueueTask(AgentTask):
jadmanski0afbb632008-06-06 21:10:57 +00001341 def __init__(self, job, queue_entries, cmd):
1342 super(QueueTask, self).__init__(cmd)
1343 self.job = job
1344 self.queue_entries = queue_entries
mbligh36768f02008-02-22 18:28:33 +00001345
1346
jadmanski0afbb632008-06-06 21:10:57 +00001347 @staticmethod
showardd8e548a2008-09-09 03:04:57 +00001348 def _write_keyval(keyval_dir, field, value, keyval_filename='keyval'):
1349 key_path = os.path.join(keyval_dir, keyval_filename)
jadmanski0afbb632008-06-06 21:10:57 +00001350 keyval_file = open(key_path, 'a')
showardd8e548a2008-09-09 03:04:57 +00001351 print >> keyval_file, '%s=%s' % (field, str(value))
jadmanski0afbb632008-06-06 21:10:57 +00001352 keyval_file.close()
mbligh36768f02008-02-22 18:28:33 +00001353
1354
showardd8e548a2008-09-09 03:04:57 +00001355 def _host_keyval_dir(self):
1356 return os.path.join(self.results_dir(), 'host_keyvals')
1357
1358
1359 def _write_host_keyval(self, host):
1360 labels = ','.join(host.labels())
1361 self._write_keyval(self._host_keyval_dir(), 'labels', labels,
1362 keyval_filename=host.hostname)
1363
1364 def _create_host_keyval_dir(self):
1365 directory = self._host_keyval_dir()
1366 if not os.path.exists(directory):
1367 os.makedirs(directory)
1368
1369
jadmanski0afbb632008-06-06 21:10:57 +00001370 def results_dir(self):
1371 return self.queue_entries[0].results_dir()
mblighbb421852008-03-11 22:36:16 +00001372
1373
jadmanski0afbb632008-06-06 21:10:57 +00001374 def run(self):
1375 """\
1376 Override AgentTask.run() so we can use a PidfileRunMonitor.
1377 """
1378 self.monitor = PidfileRunMonitor(self.results_dir(),
1379 cmd=self.cmd,
1380 nice_level=AUTOSERV_NICE_LEVEL)
1381 self.monitor.run()
mblighbb421852008-03-11 22:36:16 +00001382
1383
jadmanski0afbb632008-06-06 21:10:57 +00001384 def prolog(self):
1385 # write some job timestamps into the job keyval file
1386 queued = time.mktime(self.job.created_on.timetuple())
1387 started = time.time()
showardd8e548a2008-09-09 03:04:57 +00001388 self._write_keyval(self.results_dir(), "job_queued", int(queued))
1389 self._write_keyval(self.results_dir(), "job_started", int(started))
1390 self._create_host_keyval_dir()
jadmanski0afbb632008-06-06 21:10:57 +00001391 for queue_entry in self.queue_entries:
showardd8e548a2008-09-09 03:04:57 +00001392 self._write_host_keyval(queue_entry.host)
jadmanski0afbb632008-06-06 21:10:57 +00001393 print "starting queue_task on %s/%s" % (queue_entry.host.hostname, queue_entry.id)
1394 queue_entry.set_status('Running')
1395 queue_entry.host.set_status('Running')
showard21baa452008-10-21 00:08:39 +00001396 queue_entry.host.update_field('dirty', 1)
jadmanski0afbb632008-06-06 21:10:57 +00001397 if (not self.job.is_synchronous() and
1398 self.job.num_machines() > 1):
1399 assert len(self.queue_entries) == 1
1400 self.job.write_to_machines_file(self.queue_entries[0])
mbligh36768f02008-02-22 18:28:33 +00001401
1402
jadmanski0afbb632008-06-06 21:10:57 +00001403 def _finish_task(self):
1404 # write out the finished time into the results keyval
1405 finished = time.time()
jadmanskif7fa2cc2008-10-01 14:13:23 +00001406 self._write_keyval(self.results_dir(), "job_finished", int(finished))
jadmanskic2ac77f2008-05-16 21:44:04 +00001407
jadmanski0afbb632008-06-06 21:10:57 +00001408 # parse the results of the job
1409 if self.job.is_synchronous() or self.job.num_machines() == 1:
1410 parse_results(self.job.results_dir())
1411 else:
1412 for queue_entry in self.queue_entries:
jadmanskif7fa2cc2008-10-01 14:13:23 +00001413 parse_results(queue_entry.results_dir(), flags="-l 2")
1414
1415
1416 def _log_abort(self):
1417 # build up sets of all the aborted_by and aborted_on values
1418 aborted_by, aborted_on = set(), set()
1419 for queue_entry in self.queue_entries:
1420 if queue_entry.aborted_by:
1421 aborted_by.add(queue_entry.aborted_by)
1422 t = int(time.mktime(queue_entry.aborted_on.timetuple()))
1423 aborted_on.add(t)
1424
1425 # extract some actual, unique aborted by value and write it out
1426 assert len(aborted_by) <= 1
1427 if len(aborted_by) == 1:
1428 results_dir = self.results_dir()
1429 self._write_keyval(results_dir, "aborted_by", aborted_by.pop())
1430 self._write_keyval(results_dir, "aborted_on", max(aborted_on))
jadmanskic2ac77f2008-05-16 21:44:04 +00001431
1432
jadmanski0afbb632008-06-06 21:10:57 +00001433 def abort(self):
1434 super(QueueTask, self).abort()
jadmanskif7fa2cc2008-10-01 14:13:23 +00001435 self._log_abort()
jadmanski0afbb632008-06-06 21:10:57 +00001436 self._finish_task()
jadmanskic2ac77f2008-05-16 21:44:04 +00001437
1438
showard21baa452008-10-21 00:08:39 +00001439 def _reboot_hosts(self):
1440 reboot_after = self.job.reboot_after
1441 do_reboot = False
1442 if reboot_after == models.Job.RebootAfter.ALWAYS:
1443 do_reboot = True
1444 elif reboot_after == models.Job.RebootAfter.IF_ALL_TESTS_PASSED:
1445 num_tests_failed = self.monitor.num_tests_failed()
1446 do_reboot = (self.success and num_tests_failed == 0)
1447
1448 if do_reboot:
1449 for queue_entry in self.queue_entries:
1450 reboot_task = RebootTask(queue_entry.get_host())
1451 self.agent.dispatcher.add_agent(Agent([reboot_task]))
1452
1453
jadmanski0afbb632008-06-06 21:10:57 +00001454 def epilog(self):
1455 super(QueueTask, self).epilog()
1456 if self.success:
1457 status = 'Completed'
1458 else:
1459 status = 'Failed'
mbligh36768f02008-02-22 18:28:33 +00001460
jadmanski0afbb632008-06-06 21:10:57 +00001461 for queue_entry in self.queue_entries:
1462 queue_entry.set_status(status)
1463 queue_entry.host.set_status('Ready')
mbligh36768f02008-02-22 18:28:33 +00001464
jadmanski0afbb632008-06-06 21:10:57 +00001465 self._finish_task()
showard21baa452008-10-21 00:08:39 +00001466 self._reboot_hosts()
mblighbb421852008-03-11 22:36:16 +00001467
jadmanski0afbb632008-06-06 21:10:57 +00001468 print "queue_task finished with %s/%s" % (status, self.success)
mbligh36768f02008-02-22 18:28:33 +00001469
1470
mblighbb421852008-03-11 22:36:16 +00001471class RecoveryQueueTask(QueueTask):
jadmanski0afbb632008-06-06 21:10:57 +00001472 def __init__(self, job, queue_entries, run_monitor):
1473 super(RecoveryQueueTask, self).__init__(job,
1474 queue_entries, cmd=None)
1475 self.run_monitor = run_monitor
mblighbb421852008-03-11 22:36:16 +00001476
1477
jadmanski0afbb632008-06-06 21:10:57 +00001478 def run(self):
1479 self.monitor = self.run_monitor
mblighbb421852008-03-11 22:36:16 +00001480
1481
jadmanski0afbb632008-06-06 21:10:57 +00001482 def prolog(self):
1483 # recovering an existing process - don't do prolog
1484 pass
mblighbb421852008-03-11 22:36:16 +00001485
1486
mbligh36768f02008-02-22 18:28:33 +00001487class RebootTask(AgentTask):
jadmanski0afbb632008-06-06 21:10:57 +00001488 def __init__(self, host):
1489 global _autoserv_path
1490
1491 # Current implementation of autoserv requires control file
1492 # to be passed on reboot action request. TODO: remove when no
1493 # longer appropriate.
1494 self.create_temp_resultsdir('.reboot')
1495 self.cmd = [_autoserv_path, '-b', '-m', host.hostname,
1496 '-r', self.temp_results_dir, '/dev/null']
1497 self.host = host
1498 super(RebootTask, self).__init__(self.cmd,
1499 failure_tasks=[RepairTask(host)])
mbligh16c722d2008-03-05 00:58:44 +00001500
mblighd5c95802008-03-05 00:33:46 +00001501
jadmanski0afbb632008-06-06 21:10:57 +00001502 def prolog(self):
1503 print "starting reboot task for host: %s" % self.host.hostname
1504 self.host.set_status("Rebooting")
mblighd5c95802008-03-05 00:33:46 +00001505
mblighd5c95802008-03-05 00:33:46 +00001506
showard21baa452008-10-21 00:08:39 +00001507 def epilog(self):
1508 super(RebootTask, self).epilog()
1509 self.host.set_status('Ready')
1510 if self.success:
1511 self.host.update_field('dirty', 0)
1512
1513
mblighd5c95802008-03-05 00:33:46 +00001514class AbortTask(AgentTask):
jadmanski0afbb632008-06-06 21:10:57 +00001515 def __init__(self, queue_entry, agents_to_abort):
1516 self.queue_entry = queue_entry
1517 self.agents_to_abort = agents_to_abort
jadmanski0afbb632008-06-06 21:10:57 +00001518 super(AbortTask, self).__init__('')
mbligh36768f02008-02-22 18:28:33 +00001519
1520
jadmanski0afbb632008-06-06 21:10:57 +00001521 def prolog(self):
1522 print "starting abort on host %s, job %s" % (
1523 self.queue_entry.host_id, self.queue_entry.job_id)
mbligh36768f02008-02-22 18:28:33 +00001524
mblighd64e5702008-04-04 21:39:28 +00001525
jadmanski0afbb632008-06-06 21:10:57 +00001526 def epilog(self):
1527 super(AbortTask, self).epilog()
1528 self.queue_entry.set_status('Aborted')
1529 self.success = True
1530
1531
1532 def run(self):
1533 for agent in self.agents_to_abort:
1534 if (agent.active_task):
1535 agent.active_task.abort()
mbligh36768f02008-02-22 18:28:33 +00001536
1537
1538class DBObject(object):
jadmanski0afbb632008-06-06 21:10:57 +00001539 def __init__(self, id=None, row=None, new_record=False):
1540 assert (bool(id) != bool(row))
mbligh36768f02008-02-22 18:28:33 +00001541
jadmanski0afbb632008-06-06 21:10:57 +00001542 self.__table = self._get_table()
1543 fields = self._fields()
mbligh36768f02008-02-22 18:28:33 +00001544
jadmanski0afbb632008-06-06 21:10:57 +00001545 self.__new_record = new_record
mbligh36768f02008-02-22 18:28:33 +00001546
jadmanski0afbb632008-06-06 21:10:57 +00001547 if row is None:
1548 sql = 'SELECT * FROM %s WHERE ID=%%s' % self.__table
1549 rows = _db.execute(sql, (id,))
1550 if len(rows) == 0:
1551 raise "row not found (table=%s, id=%s)" % \
1552 (self.__table, id)
1553 row = rows[0]
mbligh36768f02008-02-22 18:28:33 +00001554
jadmanski0afbb632008-06-06 21:10:57 +00001555 assert len(row) == self.num_cols(), (
1556 "table = %s, row = %s/%d, fields = %s/%d" % (
1557 self.__table, row, len(row), fields, self.num_cols()))
mbligh36768f02008-02-22 18:28:33 +00001558
jadmanski0afbb632008-06-06 21:10:57 +00001559 self.__valid_fields = {}
1560 for i,value in enumerate(row):
1561 self.__dict__[fields[i]] = value
1562 self.__valid_fields[fields[i]] = True
mbligh36768f02008-02-22 18:28:33 +00001563
jadmanski0afbb632008-06-06 21:10:57 +00001564 del self.__valid_fields['id']
mbligh36768f02008-02-22 18:28:33 +00001565
mblighe2586682008-02-29 22:45:46 +00001566
jadmanski0afbb632008-06-06 21:10:57 +00001567 @classmethod
1568 def _get_table(cls):
1569 raise NotImplementedError('Subclasses must override this')
mblighe2586682008-02-29 22:45:46 +00001570
1571
jadmanski0afbb632008-06-06 21:10:57 +00001572 @classmethod
1573 def _fields(cls):
1574 raise NotImplementedError('Subclasses must override this')
showard04c82c52008-05-29 19:38:12 +00001575
1576
jadmanski0afbb632008-06-06 21:10:57 +00001577 @classmethod
1578 def num_cols(cls):
1579 return len(cls._fields())
showard04c82c52008-05-29 19:38:12 +00001580
1581
jadmanski0afbb632008-06-06 21:10:57 +00001582 def count(self, where, table = None):
1583 if not table:
1584 table = self.__table
mbligh36768f02008-02-22 18:28:33 +00001585
jadmanski0afbb632008-06-06 21:10:57 +00001586 rows = _db.execute("""
1587 SELECT count(*) FROM %s
1588 WHERE %s
1589 """ % (table, where))
mbligh6f8bab42008-02-29 22:45:14 +00001590
jadmanski0afbb632008-06-06 21:10:57 +00001591 assert len(rows) == 1
1592
1593 return int(rows[0][0])
mbligh36768f02008-02-22 18:28:33 +00001594
1595
mblighf8c624d2008-07-03 16:58:45 +00001596 def update_field(self, field, value, condition=''):
jadmanski0afbb632008-06-06 21:10:57 +00001597 assert self.__valid_fields[field]
mbligh36768f02008-02-22 18:28:33 +00001598
jadmanski0afbb632008-06-06 21:10:57 +00001599 if self.__dict__[field] == value:
1600 return
mbligh36768f02008-02-22 18:28:33 +00001601
mblighf8c624d2008-07-03 16:58:45 +00001602 query = "UPDATE %s SET %s = %%s WHERE id = %%s" % (self.__table, field)
1603 if condition:
1604 query += ' AND (%s)' % condition
jadmanski0afbb632008-06-06 21:10:57 +00001605 _db.execute(query, (value, self.id))
1606
1607 self.__dict__[field] = value
mbligh36768f02008-02-22 18:28:33 +00001608
1609
jadmanski0afbb632008-06-06 21:10:57 +00001610 def save(self):
1611 if self.__new_record:
1612 keys = self._fields()[1:] # avoid id
1613 columns = ','.join([str(key) for key in keys])
1614 values = ['"%s"' % self.__dict__[key] for key in keys]
1615 values = ','.join(values)
1616 query = """INSERT INTO %s (%s) VALUES (%s)""" % \
1617 (self.__table, columns, values)
1618 _db.execute(query)
mbligh36768f02008-02-22 18:28:33 +00001619
1620
jadmanski0afbb632008-06-06 21:10:57 +00001621 def delete(self):
1622 query = 'DELETE FROM %s WHERE id=%%s' % self.__table
1623 _db.execute(query, (self.id,))
mblighe2586682008-02-29 22:45:46 +00001624
1625
showard63a34772008-08-18 19:32:50 +00001626 @staticmethod
1627 def _prefix_with(string, prefix):
1628 if string:
1629 string = prefix + string
1630 return string
1631
1632
jadmanski0afbb632008-06-06 21:10:57 +00001633 @classmethod
showard989f25d2008-10-01 11:38:11 +00001634 def fetch(cls, where='', params=(), joins='', order_by=''):
showard63a34772008-08-18 19:32:50 +00001635 order_by = cls._prefix_with(order_by, 'ORDER BY ')
1636 where = cls._prefix_with(where, 'WHERE ')
1637 query = ('SELECT %(table)s.* FROM %(table)s %(joins)s '
1638 '%(where)s %(order_by)s' % {'table' : cls._get_table(),
1639 'joins' : joins,
1640 'where' : where,
1641 'order_by' : order_by})
1642 rows = _db.execute(query, params)
jadmanski0afbb632008-06-06 21:10:57 +00001643 for row in rows:
1644 yield cls(row=row)
mblighe2586682008-02-29 22:45:46 +00001645
mbligh36768f02008-02-22 18:28:33 +00001646
1647class IneligibleHostQueue(DBObject):
jadmanski0afbb632008-06-06 21:10:57 +00001648 def __init__(self, id=None, row=None, new_record=None):
1649 super(IneligibleHostQueue, self).__init__(id=id, row=row,
1650 new_record=new_record)
mblighe2586682008-02-29 22:45:46 +00001651
1652
jadmanski0afbb632008-06-06 21:10:57 +00001653 @classmethod
1654 def _get_table(cls):
1655 return 'ineligible_host_queues'
mbligh36768f02008-02-22 18:28:33 +00001656
1657
jadmanski0afbb632008-06-06 21:10:57 +00001658 @classmethod
1659 def _fields(cls):
1660 return ['id', 'job_id', 'host_id']
showard04c82c52008-05-29 19:38:12 +00001661
1662
showard989f25d2008-10-01 11:38:11 +00001663class Label(DBObject):
1664 @classmethod
1665 def _get_table(cls):
1666 return 'labels'
1667
1668
1669 @classmethod
1670 def _fields(cls):
1671 return ['id', 'name', 'kernel_config', 'platform', 'invalid',
1672 'only_if_needed']
1673
1674
mbligh36768f02008-02-22 18:28:33 +00001675class Host(DBObject):
jadmanski0afbb632008-06-06 21:10:57 +00001676 def __init__(self, id=None, row=None):
1677 super(Host, self).__init__(id=id, row=row)
mblighe2586682008-02-29 22:45:46 +00001678
1679
jadmanski0afbb632008-06-06 21:10:57 +00001680 @classmethod
1681 def _get_table(cls):
1682 return 'hosts'
mbligh36768f02008-02-22 18:28:33 +00001683
1684
jadmanski0afbb632008-06-06 21:10:57 +00001685 @classmethod
1686 def _fields(cls):
1687 return ['id', 'hostname', 'locked', 'synch_id','status',
showard21baa452008-10-21 00:08:39 +00001688 'invalid', 'protection', 'locked_by_id', 'lock_time', 'dirty']
showard04c82c52008-05-29 19:38:12 +00001689
1690
jadmanski0afbb632008-06-06 21:10:57 +00001691 def current_task(self):
1692 rows = _db.execute("""
1693 SELECT * FROM host_queue_entries WHERE host_id=%s AND NOT complete AND active
1694 """, (self.id,))
1695
1696 if len(rows) == 0:
1697 return None
1698 else:
1699 assert len(rows) == 1
1700 results = rows[0];
mblighf8c624d2008-07-03 16:58:45 +00001701# print "current = %s" % results
jadmanski0afbb632008-06-06 21:10:57 +00001702 return HostQueueEntry(row=results)
mbligh36768f02008-02-22 18:28:33 +00001703
1704
jadmanski0afbb632008-06-06 21:10:57 +00001705 def yield_work(self):
1706 print "%s yielding work" % self.hostname
1707 if self.current_task():
1708 self.current_task().requeue()
1709
1710 def set_status(self,status):
1711 print '%s -> %s' % (self.hostname, status)
1712 self.update_field('status',status)
mbligh36768f02008-02-22 18:28:33 +00001713
1714
showardd8e548a2008-09-09 03:04:57 +00001715 def labels(self):
1716 """
1717 Fetch a list of names of all non-platform labels associated with this
1718 host.
1719 """
1720 rows = _db.execute("""
1721 SELECT labels.name
1722 FROM labels
1723 INNER JOIN hosts_labels ON labels.id = hosts_labels.label_id
1724 WHERE NOT labels.platform AND hosts_labels.host_id = %s
1725 ORDER BY labels.name
1726 """, (self.id,))
1727 return [row[0] for row in rows]
1728
1729
mbligh36768f02008-02-22 18:28:33 +00001730class HostQueueEntry(DBObject):
jadmanski0afbb632008-06-06 21:10:57 +00001731 def __init__(self, id=None, row=None):
1732 assert id or row
1733 super(HostQueueEntry, self).__init__(id=id, row=row)
1734 self.job = Job(self.job_id)
mbligh36768f02008-02-22 18:28:33 +00001735
jadmanski0afbb632008-06-06 21:10:57 +00001736 if self.host_id:
1737 self.host = Host(self.host_id)
1738 else:
1739 self.host = None
mbligh36768f02008-02-22 18:28:33 +00001740
jadmanski0afbb632008-06-06 21:10:57 +00001741 self.queue_log_path = os.path.join(self.job.results_dir(),
1742 'queue.log.' + str(self.id))
mbligh36768f02008-02-22 18:28:33 +00001743
1744
jadmanski0afbb632008-06-06 21:10:57 +00001745 @classmethod
1746 def _get_table(cls):
1747 return 'host_queue_entries'
mblighe2586682008-02-29 22:45:46 +00001748
1749
jadmanski0afbb632008-06-06 21:10:57 +00001750 @classmethod
1751 def _fields(cls):
1752 return ['id', 'job_id', 'host_id', 'priority', 'status',
showardb8471e32008-07-03 19:51:08 +00001753 'meta_host', 'active', 'complete', 'deleted']
showard04c82c52008-05-29 19:38:12 +00001754
1755
jadmanski0afbb632008-06-06 21:10:57 +00001756 def set_host(self, host):
1757 if host:
1758 self.queue_log_record('Assigning host ' + host.hostname)
1759 self.update_field('host_id', host.id)
1760 self.update_field('active', True)
1761 self.block_host(host.id)
1762 else:
1763 self.queue_log_record('Releasing host')
1764 self.unblock_host(self.host.id)
1765 self.update_field('host_id', None)
mbligh36768f02008-02-22 18:28:33 +00001766
jadmanski0afbb632008-06-06 21:10:57 +00001767 self.host = host
mbligh36768f02008-02-22 18:28:33 +00001768
1769
jadmanski0afbb632008-06-06 21:10:57 +00001770 def get_host(self):
1771 return self.host
mbligh36768f02008-02-22 18:28:33 +00001772
1773
jadmanski0afbb632008-06-06 21:10:57 +00001774 def queue_log_record(self, log_line):
1775 now = str(datetime.datetime.now())
1776 queue_log = open(self.queue_log_path, 'a', 0)
1777 queue_log.write(now + ' ' + log_line + '\n')
1778 queue_log.close()
mbligh36768f02008-02-22 18:28:33 +00001779
1780
jadmanski0afbb632008-06-06 21:10:57 +00001781 def block_host(self, host_id):
1782 print "creating block %s/%s" % (self.job.id, host_id)
1783 row = [0, self.job.id, host_id]
1784 block = IneligibleHostQueue(row=row, new_record=True)
1785 block.save()
mblighe2586682008-02-29 22:45:46 +00001786
1787
jadmanski0afbb632008-06-06 21:10:57 +00001788 def unblock_host(self, host_id):
1789 print "removing block %s/%s" % (self.job.id, host_id)
1790 blocks = IneligibleHostQueue.fetch(
1791 'job_id=%d and host_id=%d' % (self.job.id, host_id))
1792 for block in blocks:
1793 block.delete()
mblighe2586682008-02-29 22:45:46 +00001794
1795
jadmanski0afbb632008-06-06 21:10:57 +00001796 def results_dir(self):
1797 if self.job.is_synchronous() or self.job.num_machines() == 1:
1798 return self.job.job_dir
1799 else:
1800 assert self.host
1801 return os.path.join(self.job.job_dir,
1802 self.host.hostname)
mbligh36768f02008-02-22 18:28:33 +00001803
mblighe2586682008-02-29 22:45:46 +00001804
jadmanski0afbb632008-06-06 21:10:57 +00001805 def verify_results_dir(self):
1806 if self.job.is_synchronous() or self.job.num_machines() > 1:
1807 assert self.host
1808 return os.path.join(self.job.job_dir,
1809 self.host.hostname)
1810 else:
1811 return self.job.job_dir
mbligh36768f02008-02-22 18:28:33 +00001812
1813
jadmanski0afbb632008-06-06 21:10:57 +00001814 def set_status(self, status):
mblighf8c624d2008-07-03 16:58:45 +00001815 abort_statuses = ['Abort', 'Aborting', 'Aborted']
1816 if status not in abort_statuses:
1817 condition = ' AND '.join(['status <> "%s"' % x
1818 for x in abort_statuses])
1819 else:
1820 condition = ''
1821 self.update_field('status', status, condition=condition)
1822
jadmanski0afbb632008-06-06 21:10:57 +00001823 if self.host:
1824 hostname = self.host.hostname
1825 else:
1826 hostname = 'no host'
1827 print "%s/%d status -> %s" % (hostname, self.id, self.status)
mblighf8c624d2008-07-03 16:58:45 +00001828
jadmanski0afbb632008-06-06 21:10:57 +00001829 if status in ['Queued']:
1830 self.update_field('complete', False)
1831 self.update_field('active', False)
mbligh36768f02008-02-22 18:28:33 +00001832
jadmanski0afbb632008-06-06 21:10:57 +00001833 if status in ['Pending', 'Running', 'Verifying', 'Starting',
1834 'Abort', 'Aborting']:
1835 self.update_field('complete', False)
1836 self.update_field('active', True)
mbligh36768f02008-02-22 18:28:33 +00001837
jadmanski0afbb632008-06-06 21:10:57 +00001838 if status in ['Failed', 'Completed', 'Stopped', 'Aborted']:
1839 self.update_field('complete', True)
1840 self.update_field('active', False)
showard542e8402008-09-19 20:16:18 +00001841 self._email_on_job_complete()
1842
1843
1844 def _email_on_job_complete(self):
1845 url = "%s#tab_id=view_job&object_id=%s" % (_base_url, self.job.id)
1846
1847 if self.job.is_finished():
1848 subject = "Autotest: Job ID: %s \"%s\" Completed" % (
1849 self.job.id, self.job.name)
1850 body = "Job ID: %s\nJob Name: %s\n%s\n" % (
1851 self.job.id, self.job.name, url)
1852 send_email(_email_from, self.job.email_list, subject, body)
mbligh36768f02008-02-22 18:28:33 +00001853
1854
jadmanski0afbb632008-06-06 21:10:57 +00001855 def run(self,assigned_host=None):
1856 if self.meta_host:
1857 assert assigned_host
1858 # ensure results dir exists for the queue log
1859 self.job.create_results_dir()
1860 self.set_host(assigned_host)
mbligh36768f02008-02-22 18:28:33 +00001861
jadmanski0afbb632008-06-06 21:10:57 +00001862 print "%s/%s scheduled on %s, status=%s" % (self.job.name,
1863 self.meta_host, self.host.hostname, self.status)
mbligh36768f02008-02-22 18:28:33 +00001864
jadmanski0afbb632008-06-06 21:10:57 +00001865 return self.job.run(queue_entry=self)
mblighe2586682008-02-29 22:45:46 +00001866
jadmanski0afbb632008-06-06 21:10:57 +00001867 def requeue(self):
1868 self.set_status('Queued')
mblighe2586682008-02-29 22:45:46 +00001869
jadmanski0afbb632008-06-06 21:10:57 +00001870 if self.meta_host:
1871 self.set_host(None)
mbligh36768f02008-02-22 18:28:33 +00001872
1873
jadmanski0afbb632008-06-06 21:10:57 +00001874 def handle_host_failure(self):
1875 """\
1876 Called when this queue entry's host has failed verification and
1877 repair.
1878 """
1879 assert not self.meta_host
1880 self.set_status('Failed')
1881 if self.job.is_synchronous():
1882 self.job.stop_all_entries()
mblighe2586682008-02-29 22:45:46 +00001883
1884
jadmanski0afbb632008-06-06 21:10:57 +00001885 def clear_results_dir(self, results_dir=None, dont_delete_files=False):
1886 results_dir = results_dir or self.results_dir()
1887 if not os.path.exists(results_dir):
1888 return
1889 if dont_delete_files:
1890 temp_dir = tempfile.mkdtemp(suffix='.clear_results')
1891 print 'Moving results from %s to %s' % (results_dir,
1892 temp_dir)
1893 for filename in os.listdir(results_dir):
1894 path = os.path.join(results_dir, filename)
1895 if dont_delete_files:
1896 shutil.move(path,
1897 os.path.join(temp_dir, filename))
1898 else:
1899 remove_file_or_dir(path)
mbligh36768f02008-02-22 18:28:33 +00001900
1901
jadmanskif7fa2cc2008-10-01 14:13:23 +00001902 @property
1903 def aborted_by(self):
1904 self._load_abort_info()
1905 return self._aborted_by
1906
1907
1908 @property
1909 def aborted_on(self):
1910 self._load_abort_info()
1911 return self._aborted_on
1912
1913
1914 def _load_abort_info(self):
1915 """ Fetch info about who aborted the job. """
1916 if hasattr(self, "_aborted_by"):
1917 return
1918 rows = _db.execute("""
1919 SELECT users.login, aborted_host_queue_entries.aborted_on
1920 FROM aborted_host_queue_entries
1921 INNER JOIN users
1922 ON users.id = aborted_host_queue_entries.aborted_by_id
1923 WHERE aborted_host_queue_entries.queue_entry_id = %s
1924 """, (self.id,))
1925 if rows:
1926 self._aborted_by, self._aborted_on = rows[0]
1927 else:
1928 self._aborted_by = self._aborted_on = None
1929
1930
showardb2e2c322008-10-14 17:33:55 +00001931 def on_pending(self):
1932 """
1933 Called when an entry in a synchronous job has passed verify. If the
1934 job is ready to run, returns an agent to run the job. Returns None
1935 otherwise.
1936 """
1937 self.set_status('Pending')
showardcfd66a32008-10-15 20:31:48 +00001938 self.get_host().set_status('Pending')
showardb2e2c322008-10-14 17:33:55 +00001939 if self.job.is_ready():
1940 return self.job.run(self)
1941 return None
1942
1943
showard1be97432008-10-17 15:30:45 +00001944 def abort(self, agents_to_abort=[]):
1945 abort_task = AbortTask(self, agents_to_abort)
1946 tasks = [abort_task]
1947
1948 host = self.get_host()
1949 if host:
1950 reboot_task = RebootTask(host)
1951 verify_task = VerifyTask(host=host)
1952 # just to make sure this host does not get taken away
1953 host.set_status('Rebooting')
1954 tasks += [reboot_task, verify_task]
1955
1956 self.set_status('Aborting')
1957 return Agent(tasks=tasks, queue_entry_ids=[self.id])
1958
1959
mbligh36768f02008-02-22 18:28:33 +00001960class Job(DBObject):
jadmanski0afbb632008-06-06 21:10:57 +00001961 def __init__(self, id=None, row=None):
1962 assert id or row
1963 super(Job, self).__init__(id=id, row=row)
mbligh36768f02008-02-22 18:28:33 +00001964
jadmanski0afbb632008-06-06 21:10:57 +00001965 self.job_dir = os.path.join(RESULTS_DIR, "%s-%s" % (self.id,
1966 self.owner))
mblighe2586682008-02-29 22:45:46 +00001967
1968
jadmanski0afbb632008-06-06 21:10:57 +00001969 @classmethod
1970 def _get_table(cls):
1971 return 'jobs'
mbligh36768f02008-02-22 18:28:33 +00001972
1973
jadmanski0afbb632008-06-06 21:10:57 +00001974 @classmethod
1975 def _fields(cls):
1976 return ['id', 'owner', 'name', 'priority', 'control_file',
1977 'control_type', 'created_on', 'synch_type',
showard542e8402008-09-19 20:16:18 +00001978 'synch_count', 'synchronizing', 'timeout',
showard21baa452008-10-21 00:08:39 +00001979 'run_verify', 'email_list', 'reboot_before', 'reboot_after']
showard04c82c52008-05-29 19:38:12 +00001980
1981
jadmanski0afbb632008-06-06 21:10:57 +00001982 def is_server_job(self):
1983 return self.control_type != 2
mbligh36768f02008-02-22 18:28:33 +00001984
1985
jadmanski0afbb632008-06-06 21:10:57 +00001986 def get_host_queue_entries(self):
1987 rows = _db.execute("""
1988 SELECT * FROM host_queue_entries
1989 WHERE job_id= %s
1990 """, (self.id,))
1991 entries = [HostQueueEntry(row=i) for i in rows]
mbligh36768f02008-02-22 18:28:33 +00001992
jadmanski0afbb632008-06-06 21:10:57 +00001993 assert len(entries)>0
mbligh36768f02008-02-22 18:28:33 +00001994
jadmanski0afbb632008-06-06 21:10:57 +00001995 return entries
mbligh36768f02008-02-22 18:28:33 +00001996
1997
jadmanski0afbb632008-06-06 21:10:57 +00001998 def set_status(self, status, update_queues=False):
1999 self.update_field('status',status)
2000
2001 if update_queues:
2002 for queue_entry in self.get_host_queue_entries():
2003 queue_entry.set_status(status)
mbligh36768f02008-02-22 18:28:33 +00002004
2005
jadmanski0afbb632008-06-06 21:10:57 +00002006 def is_synchronous(self):
2007 return self.synch_type == 2
mbligh36768f02008-02-22 18:28:33 +00002008
2009
jadmanski0afbb632008-06-06 21:10:57 +00002010 def is_ready(self):
2011 if not self.is_synchronous():
2012 return True
2013 sql = "job_id=%s AND status='Pending'" % self.id
2014 count = self.count(sql, table='host_queue_entries')
showardb2e2c322008-10-14 17:33:55 +00002015 return (count == self.num_machines())
mbligh36768f02008-02-22 18:28:33 +00002016
2017
jadmanski0afbb632008-06-06 21:10:57 +00002018 def results_dir(self):
2019 return self.job_dir
mbligh36768f02008-02-22 18:28:33 +00002020
jadmanski0afbb632008-06-06 21:10:57 +00002021 def num_machines(self, clause = None):
2022 sql = "job_id=%s" % self.id
2023 if clause:
2024 sql += " AND (%s)" % clause
2025 return self.count(sql, table='host_queue_entries')
mbligh36768f02008-02-22 18:28:33 +00002026
2027
jadmanski0afbb632008-06-06 21:10:57 +00002028 def num_queued(self):
2029 return self.num_machines('not complete')
mbligh36768f02008-02-22 18:28:33 +00002030
2031
jadmanski0afbb632008-06-06 21:10:57 +00002032 def num_active(self):
2033 return self.num_machines('active')
mbligh36768f02008-02-22 18:28:33 +00002034
2035
jadmanski0afbb632008-06-06 21:10:57 +00002036 def num_complete(self):
2037 return self.num_machines('complete')
mbligh36768f02008-02-22 18:28:33 +00002038
2039
jadmanski0afbb632008-06-06 21:10:57 +00002040 def is_finished(self):
2041 left = self.num_queued()
2042 print "%s: %s machines left" % (self.name, left)
2043 return left==0
mbligh36768f02008-02-22 18:28:33 +00002044
mbligh36768f02008-02-22 18:28:33 +00002045
jadmanski0afbb632008-06-06 21:10:57 +00002046 def stop_all_entries(self):
2047 for child_entry in self.get_host_queue_entries():
2048 if not child_entry.complete:
2049 child_entry.set_status('Stopped')
mblighe2586682008-02-29 22:45:46 +00002050
2051
jadmanski0afbb632008-06-06 21:10:57 +00002052 def write_to_machines_file(self, queue_entry):
2053 hostname = queue_entry.get_host().hostname
2054 print "writing %s to job %s machines file" % (hostname, self.id)
2055 file_path = os.path.join(self.job_dir, '.machines')
2056 mf = open(file_path, 'a')
2057 mf.write("%s\n" % queue_entry.get_host().hostname)
2058 mf.close()
mbligh36768f02008-02-22 18:28:33 +00002059
2060
jadmanski0afbb632008-06-06 21:10:57 +00002061 def create_results_dir(self, queue_entry=None):
2062 print "create: active: %s complete %s" % (self.num_active(),
2063 self.num_complete())
mbligh36768f02008-02-22 18:28:33 +00002064
jadmanski0afbb632008-06-06 21:10:57 +00002065 if not os.path.exists(self.job_dir):
2066 os.makedirs(self.job_dir)
mbligh36768f02008-02-22 18:28:33 +00002067
jadmanski0afbb632008-06-06 21:10:57 +00002068 if queue_entry:
2069 return queue_entry.results_dir()
2070 return self.job_dir
mbligh36768f02008-02-22 18:28:33 +00002071
2072
showardb2e2c322008-10-14 17:33:55 +00002073 def _write_control_file(self):
2074 'Writes control file out to disk, returns a filename'
2075 control_fd, control_filename = tempfile.mkstemp(suffix='.control_file')
2076 control_file = os.fdopen(control_fd, 'w')
jadmanski0afbb632008-06-06 21:10:57 +00002077 if self.control_file:
showardb2e2c322008-10-14 17:33:55 +00002078 control_file.write(self.control_file)
2079 control_file.close()
2080 return control_filename
mbligh36768f02008-02-22 18:28:33 +00002081
showardb2e2c322008-10-14 17:33:55 +00002082
2083 def _get_job_tag(self, queue_entries):
2084 base_job_tag = "%s-%s" % (self.id, self.owner)
2085 if self.is_synchronous() or self.num_machines() == 1:
2086 return base_job_tag
jadmanski0afbb632008-06-06 21:10:57 +00002087 else:
showardb2e2c322008-10-14 17:33:55 +00002088 return base_job_tag + '/' + queue_entries[0].get_host().hostname
2089
2090
2091 def _get_autoserv_params(self, queue_entries):
2092 results_dir = self.create_results_dir(queue_entries[0])
2093 control_filename = self._write_control_file()
jadmanski0afbb632008-06-06 21:10:57 +00002094 hostnames = ','.join([entry.get_host().hostname
2095 for entry in queue_entries])
showardb2e2c322008-10-14 17:33:55 +00002096 job_tag = self._get_job_tag(queue_entries)
mbligh36768f02008-02-22 18:28:33 +00002097
showardb2e2c322008-10-14 17:33:55 +00002098 params = [_autoserv_path, '-P', job_tag, '-p', '-n',
showard21baa452008-10-21 00:08:39 +00002099 '-r', os.path.abspath(results_dir), '-u', self.owner,
2100 '-l', self.name, '-m', hostnames, control_filename]
mbligh36768f02008-02-22 18:28:33 +00002101
jadmanski0afbb632008-06-06 21:10:57 +00002102 if not self.is_server_job():
2103 params.append('-c')
mbligh36768f02008-02-22 18:28:33 +00002104
showardb2e2c322008-10-14 17:33:55 +00002105 return params
mblighe2586682008-02-29 22:45:46 +00002106
mbligh36768f02008-02-22 18:28:33 +00002107
showard21baa452008-10-21 00:08:39 +00002108 def _get_pre_job_tasks(self, queue_entry, verify_task_class=VerifyTask):
2109 do_reboot = False
2110 if self.reboot_before == models.Job.RebootBefore.ALWAYS:
2111 do_reboot = True
2112 elif self.reboot_before == models.Job.RebootBefore.IF_DIRTY:
2113 do_reboot = queue_entry.get_host().dirty
2114
2115 tasks = []
2116 if do_reboot:
2117 tasks.append(RebootTask(queue_entry.get_host()))
2118 tasks.append(verify_task_class(queue_entry=queue_entry))
2119 return tasks
2120
2121
showardb2e2c322008-10-14 17:33:55 +00002122 def _run_synchronous(self, queue_entry):
2123 if not self.is_ready():
showard9976ce92008-10-15 20:28:13 +00002124 if self.run_verify:
showard21baa452008-10-21 00:08:39 +00002125 return Agent(self._get_pre_job_tasks(queue_entry,
2126 VerifySynchronousTask),
2127 [queue_entry.id])
showard9976ce92008-10-15 20:28:13 +00002128 else:
2129 return queue_entry.on_pending()
mbligh36768f02008-02-22 18:28:33 +00002130
showardb2e2c322008-10-14 17:33:55 +00002131 queue_entry.set_status('Starting')
jadmanski0afbb632008-06-06 21:10:57 +00002132
showardb2e2c322008-10-14 17:33:55 +00002133 return self._finish_run(self.get_host_queue_entries())
2134
2135
2136 def _run_asynchronous(self, queue_entry):
showard9976ce92008-10-15 20:28:13 +00002137 initial_tasks = []
2138 if self.run_verify:
showard21baa452008-10-21 00:08:39 +00002139 initial_tasks = self._get_pre_job_tasks(queue_entry)
showardb2e2c322008-10-14 17:33:55 +00002140 return self._finish_run([queue_entry], initial_tasks)
2141
2142
2143 def _finish_run(self, queue_entries, initial_tasks=[]):
2144 params = self._get_autoserv_params(queue_entries)
2145 queue_task = QueueTask(job=self, queue_entries=queue_entries,
2146 cmd=params)
2147 tasks = initial_tasks + [queue_task]
2148 entry_ids = [entry.id for entry in queue_entries]
2149
2150 return Agent(tasks, entry_ids, num_processes=len(queue_entries))
2151
2152
2153 def run(self, queue_entry):
2154 if self.is_synchronous():
2155 return self._run_synchronous(queue_entry)
2156 return self._run_asynchronous(queue_entry)
mbligh36768f02008-02-22 18:28:33 +00002157
2158
2159if __name__ == '__main__':
jadmanski0afbb632008-06-06 21:10:57 +00002160 main()