blob: 16b9255e2e607c8c37d1fe18964ec9f3c10d18eb [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',
showard3dd6b882008-10-27 19:21:39 +0000729 order_by='priority DESC, meta_host, job_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()
showard3dd6b882008-10-27 19:21:39 +0000942 if not lines:
943 return
944 if len(lines) > 3:
showard21baa452008-10-21 00:08:39 +0000945 raise PidfileException('Corrupt pid file (%d lines) at %s:\n%s' %
946 (len(lines), self.pid_file, lines))
jadmanski0afbb632008-06-06 21:10:57 +0000947 try:
showard21baa452008-10-21 00:08:39 +0000948 self._state.pid = int(lines[0])
949 if len(lines) > 1:
950 self._state.exit_status = int(lines[1])
951 if len(lines) == 3:
952 self._state.num_tests_failed = int(lines[2])
953 else:
954 # maintain backwards-compatibility with two-line pidfiles
955 self._state.num_tests_failed = 0
jadmanski0afbb632008-06-06 21:10:57 +0000956 except ValueError, exc:
showard3dd6b882008-10-27 19:21:39 +0000957 raise PidfileException('Corrupt pid file: ' + str(exc.args))
mblighbb421852008-03-11 22:36:16 +0000958
mblighbb421852008-03-11 22:36:16 +0000959
jadmanski0afbb632008-06-06 21:10:57 +0000960 def _find_autoserv_proc(self):
961 autoserv_procs = Dispatcher.find_autoservs()
962 for pid, args in autoserv_procs.iteritems():
963 if self._check_command_line(args):
964 return pid, args
965 return None, None
mbligh90a549d2008-03-25 23:52:34 +0000966
967
showard21baa452008-10-21 00:08:39 +0000968 def _handle_pidfile_error(self, error, message=''):
969 message = error + '\nPid: %s\nPidfile: %s\n%s' % (self._state.pid,
970 self.pid_file,
971 message)
972 print message
973 email_manager.enqueue_notify_email(error, message)
974 if self._state.pid is not None:
975 pid = self._state.pid
976 else:
977 pid = 0
978 self.on_lost_process(pid)
979
980
981 def _get_pidfile_info_helper(self):
jadmanski0afbb632008-06-06 21:10:57 +0000982 if self.lost_process:
showard21baa452008-10-21 00:08:39 +0000983 return
mblighbb421852008-03-11 22:36:16 +0000984
showard21baa452008-10-21 00:08:39 +0000985 self._read_pidfile()
mblighbb421852008-03-11 22:36:16 +0000986
showard21baa452008-10-21 00:08:39 +0000987 if self._state.pid is None:
988 self._handle_no_pid()
989 return
mbligh90a549d2008-03-25 23:52:34 +0000990
showard21baa452008-10-21 00:08:39 +0000991 if self._state.exit_status is None:
jadmanski0afbb632008-06-06 21:10:57 +0000992 # double check whether or not autoserv is running
showard21baa452008-10-21 00:08:39 +0000993 proc_running = self._check_proc_fs()
jadmanski0afbb632008-06-06 21:10:57 +0000994 if proc_running:
showard21baa452008-10-21 00:08:39 +0000995 return
mbligh90a549d2008-03-25 23:52:34 +0000996
jadmanski0afbb632008-06-06 21:10:57 +0000997 # pid but no process - maybe process *just* exited
showard21baa452008-10-21 00:08:39 +0000998 self._read_pidfile()
999 if self._state.exit_status is None:
jadmanski0afbb632008-06-06 21:10:57 +00001000 # autoserv exited without writing an exit code
1001 # to the pidfile
showard21baa452008-10-21 00:08:39 +00001002 self._handle_pidfile_error(
1003 'autoserv died without writing exit code')
mblighbb421852008-03-11 22:36:16 +00001004
showard21baa452008-10-21 00:08:39 +00001005
1006 def _get_pidfile_info(self):
1007 """\
1008 After completion, self._state will contain:
1009 pid=None, exit_status=None if autoserv has not yet run
1010 pid!=None, exit_status=None if autoserv is running
1011 pid!=None, exit_status!=None if autoserv has completed
1012 """
1013 try:
1014 self._get_pidfile_info_helper()
1015 except PidfileException, exc:
1016 self._handle_pidfile_error('Pidfile error', traceback.format_exc())
mblighbb421852008-03-11 22:36:16 +00001017
1018
jadmanski0afbb632008-06-06 21:10:57 +00001019 def _handle_no_pid(self):
1020 """\
1021 Called when no pidfile is found or no pid is in the pidfile.
1022 """
1023 # is autoserv running?
1024 pid, args = self._find_autoserv_proc()
1025 if pid is None:
1026 # no autoserv process running
1027 message = 'No pid found at ' + self.pid_file
1028 else:
1029 message = ("Process %d (%s) hasn't written pidfile %s" %
1030 (pid, args, self.pid_file))
mbligh90a549d2008-03-25 23:52:34 +00001031
jadmanski0afbb632008-06-06 21:10:57 +00001032 print message
1033 if time.time() - self.start_time > PIDFILE_TIMEOUT:
1034 email_manager.enqueue_notify_email(
1035 'Process has failed to write pidfile', message)
1036 if pid is not None:
1037 kill_autoserv(pid)
1038 else:
1039 pid = 0
1040 self.on_lost_process(pid)
showard21baa452008-10-21 00:08:39 +00001041 return
mbligh90a549d2008-03-25 23:52:34 +00001042
1043
jadmanski0afbb632008-06-06 21:10:57 +00001044 def on_lost_process(self, pid):
1045 """\
1046 Called when autoserv has exited without writing an exit status,
1047 or we've timed out waiting for autoserv to write a pid to the
1048 pidfile. In either case, we just return failure and the caller
1049 should signal some kind of warning.
mbligh90a549d2008-03-25 23:52:34 +00001050
jadmanski0afbb632008-06-06 21:10:57 +00001051 pid is unimportant here, as it shouldn't be used by anyone.
1052 """
1053 self.lost_process = True
showard21baa452008-10-21 00:08:39 +00001054 self._state.pid = pid
1055 self._state.exit_status = 1
1056 self._state.num_tests_failed = 0
mbligh90a549d2008-03-25 23:52:34 +00001057
1058
jadmanski0afbb632008-06-06 21:10:57 +00001059 def exit_code(self):
showard21baa452008-10-21 00:08:39 +00001060 self._get_pidfile_info()
1061 return self._state.exit_status
1062
1063
1064 def num_tests_failed(self):
1065 self._get_pidfile_info()
1066 assert self._state.num_tests_failed is not None
1067 return self._state.num_tests_failed
mblighbb421852008-03-11 22:36:16 +00001068
1069
mbligh36768f02008-02-22 18:28:33 +00001070class Agent(object):
showard4c5374f2008-09-04 17:02:56 +00001071 def __init__(self, tasks, queue_entry_ids=[], num_processes=1):
jadmanski0afbb632008-06-06 21:10:57 +00001072 self.active_task = None
1073 self.queue = Queue.Queue(0)
1074 self.dispatcher = None
1075 self.queue_entry_ids = queue_entry_ids
showard4c5374f2008-09-04 17:02:56 +00001076 self.num_processes = num_processes
jadmanski0afbb632008-06-06 21:10:57 +00001077
1078 for task in tasks:
1079 self.add_task(task)
mbligh36768f02008-02-22 18:28:33 +00001080
1081
jadmanski0afbb632008-06-06 21:10:57 +00001082 def add_task(self, task):
1083 self.queue.put_nowait(task)
1084 task.agent = self
mbligh36768f02008-02-22 18:28:33 +00001085
1086
jadmanski0afbb632008-06-06 21:10:57 +00001087 def tick(self):
showard21baa452008-10-21 00:08:39 +00001088 while not self.is_done():
1089 if self.active_task and not self.active_task.is_done():
1090 self.active_task.poll()
1091 if not self.active_task.is_done():
1092 return
1093 self._next_task()
mbligh36768f02008-02-22 18:28:33 +00001094
1095
jadmanski0afbb632008-06-06 21:10:57 +00001096 def _next_task(self):
1097 print "agent picking task"
1098 if self.active_task:
1099 assert self.active_task.is_done()
mbligh36768f02008-02-22 18:28:33 +00001100
jadmanski0afbb632008-06-06 21:10:57 +00001101 if not self.active_task.success:
1102 self.on_task_failure()
mblighe2586682008-02-29 22:45:46 +00001103
jadmanski0afbb632008-06-06 21:10:57 +00001104 self.active_task = None
1105 if not self.is_done():
1106 self.active_task = self.queue.get_nowait()
1107 if self.active_task:
1108 self.active_task.start()
mbligh36768f02008-02-22 18:28:33 +00001109
1110
jadmanski0afbb632008-06-06 21:10:57 +00001111 def on_task_failure(self):
1112 self.queue = Queue.Queue(0)
1113 for task in self.active_task.failure_tasks:
1114 self.add_task(task)
mbligh16c722d2008-03-05 00:58:44 +00001115
mblighe2586682008-02-29 22:45:46 +00001116
showard4c5374f2008-09-04 17:02:56 +00001117 def is_running(self):
jadmanski0afbb632008-06-06 21:10:57 +00001118 return self.active_task is not None
showardec113162008-05-08 00:52:49 +00001119
1120
jadmanski0afbb632008-06-06 21:10:57 +00001121 def is_done(self):
1122 return self.active_task == None and self.queue.empty()
mbligh36768f02008-02-22 18:28:33 +00001123
1124
jadmanski0afbb632008-06-06 21:10:57 +00001125 def start(self):
1126 assert self.dispatcher
mbligh36768f02008-02-22 18:28:33 +00001127
jadmanski0afbb632008-06-06 21:10:57 +00001128 self._next_task()
mbligh36768f02008-02-22 18:28:33 +00001129
jadmanski0afbb632008-06-06 21:10:57 +00001130
mbligh36768f02008-02-22 18:28:33 +00001131class AgentTask(object):
jadmanski0afbb632008-06-06 21:10:57 +00001132 def __init__(self, cmd, failure_tasks = []):
1133 self.done = False
1134 self.failure_tasks = failure_tasks
1135 self.started = False
1136 self.cmd = cmd
1137 self.task = None
1138 self.agent = None
1139 self.monitor = None
1140 self.success = None
mbligh36768f02008-02-22 18:28:33 +00001141
1142
jadmanski0afbb632008-06-06 21:10:57 +00001143 def poll(self):
1144 print "poll"
1145 if self.monitor:
1146 self.tick(self.monitor.exit_code())
1147 else:
1148 self.finished(False)
mbligh36768f02008-02-22 18:28:33 +00001149
1150
jadmanski0afbb632008-06-06 21:10:57 +00001151 def tick(self, exit_code):
1152 if exit_code==None:
1153 return
1154# print "exit_code was %d" % exit_code
1155 if exit_code == 0:
1156 success = True
1157 else:
1158 success = False
mbligh36768f02008-02-22 18:28:33 +00001159
jadmanski0afbb632008-06-06 21:10:57 +00001160 self.finished(success)
mbligh36768f02008-02-22 18:28:33 +00001161
1162
jadmanski0afbb632008-06-06 21:10:57 +00001163 def is_done(self):
1164 return self.done
mbligh36768f02008-02-22 18:28:33 +00001165
1166
jadmanski0afbb632008-06-06 21:10:57 +00001167 def finished(self, success):
1168 self.done = True
1169 self.success = success
1170 self.epilog()
mbligh36768f02008-02-22 18:28:33 +00001171
1172
jadmanski0afbb632008-06-06 21:10:57 +00001173 def prolog(self):
1174 pass
mblighd64e5702008-04-04 21:39:28 +00001175
1176
jadmanski0afbb632008-06-06 21:10:57 +00001177 def create_temp_resultsdir(self, suffix=''):
1178 self.temp_results_dir = tempfile.mkdtemp(suffix=suffix)
mblighd64e5702008-04-04 21:39:28 +00001179
mbligh36768f02008-02-22 18:28:33 +00001180
jadmanski0afbb632008-06-06 21:10:57 +00001181 def cleanup(self):
1182 if (hasattr(self, 'temp_results_dir') and
1183 os.path.exists(self.temp_results_dir)):
1184 shutil.rmtree(self.temp_results_dir)
mbligh36768f02008-02-22 18:28:33 +00001185
1186
jadmanski0afbb632008-06-06 21:10:57 +00001187 def epilog(self):
1188 self.cleanup()
mbligh36768f02008-02-22 18:28:33 +00001189
1190
jadmanski0afbb632008-06-06 21:10:57 +00001191 def start(self):
1192 assert self.agent
1193
1194 if not self.started:
1195 self.prolog()
1196 self.run()
1197
1198 self.started = True
1199
1200
1201 def abort(self):
1202 if self.monitor:
1203 self.monitor.kill()
1204 self.done = True
1205 self.cleanup()
1206
1207
1208 def run(self):
1209 if self.cmd:
1210 print "agent starting monitor"
1211 log_file = None
1212 if hasattr(self, 'host'):
1213 log_file = os.path.join(RESULTS_DIR, 'hosts',
1214 self.host.hostname)
1215 self.monitor = RunMonitor(
1216 self.cmd, nice_level = AUTOSERV_NICE_LEVEL,
1217 log_file = log_file)
1218 self.monitor.run()
mbligh36768f02008-02-22 18:28:33 +00001219
1220
1221class RepairTask(AgentTask):
jadmanski0afbb632008-06-06 21:10:57 +00001222 def __init__(self, host, fail_queue_entry=None):
1223 """\
1224 fail_queue_entry: queue entry to mark failed if this repair
1225 fails.
1226 """
jadmanskifb7cfb12008-07-09 14:13:21 +00001227 protection = host_protections.Protection.get_string(host.protection)
jadmanski542537f2008-07-24 14:14:56 +00001228 # normalize the protection name
1229 protection = host_protections.Protection.get_attr_name(protection)
jadmanski0afbb632008-06-06 21:10:57 +00001230 self.create_temp_resultsdir('.repair')
1231 cmd = [_autoserv_path , '-R', '-m', host.hostname,
jadmanskifb7cfb12008-07-09 14:13:21 +00001232 '-r', self.temp_results_dir, '--host-protection', protection]
jadmanski0afbb632008-06-06 21:10:57 +00001233 self.host = host
1234 self.fail_queue_entry = fail_queue_entry
1235 super(RepairTask, self).__init__(cmd)
mblighe2586682008-02-29 22:45:46 +00001236
mbligh36768f02008-02-22 18:28:33 +00001237
jadmanski0afbb632008-06-06 21:10:57 +00001238 def prolog(self):
1239 print "repair_task starting"
1240 self.host.set_status('Repairing')
mbligh36768f02008-02-22 18:28:33 +00001241
1242
jadmanski0afbb632008-06-06 21:10:57 +00001243 def epilog(self):
1244 super(RepairTask, self).epilog()
1245 if self.success:
1246 self.host.set_status('Ready')
1247 else:
1248 self.host.set_status('Repair Failed')
1249 if self.fail_queue_entry:
1250 self.fail_queue_entry.handle_host_failure()
mbligh36768f02008-02-22 18:28:33 +00001251
1252
1253class VerifyTask(AgentTask):
showard9976ce92008-10-15 20:28:13 +00001254 def __init__(self, queue_entry=None, host=None):
jadmanski0afbb632008-06-06 21:10:57 +00001255 assert bool(queue_entry) != bool(host)
mbligh36768f02008-02-22 18:28:33 +00001256
jadmanski0afbb632008-06-06 21:10:57 +00001257 self.host = host or queue_entry.host
1258 self.queue_entry = queue_entry
mbligh36768f02008-02-22 18:28:33 +00001259
jadmanski0afbb632008-06-06 21:10:57 +00001260 self.create_temp_resultsdir('.verify')
showard3d9899a2008-07-31 02:11:58 +00001261
showard9976ce92008-10-15 20:28:13 +00001262 cmd = [_autoserv_path,'-v','-m',self.host.hostname, '-r', self.temp_results_dir]
mbligh36768f02008-02-22 18:28:33 +00001263
jadmanski0afbb632008-06-06 21:10:57 +00001264 fail_queue_entry = None
1265 if queue_entry and not queue_entry.meta_host:
1266 fail_queue_entry = queue_entry
1267 failure_tasks = [RepairTask(self.host, fail_queue_entry)]
mblighe2586682008-02-29 22:45:46 +00001268
jadmanski0afbb632008-06-06 21:10:57 +00001269 super(VerifyTask, self).__init__(cmd,
1270 failure_tasks=failure_tasks)
mblighe2586682008-02-29 22:45:46 +00001271
1272
jadmanski0afbb632008-06-06 21:10:57 +00001273 def prolog(self):
1274 print "starting verify on %s" % (self.host.hostname)
1275 if self.queue_entry:
1276 self.queue_entry.set_status('Verifying')
1277 self.queue_entry.clear_results_dir(
1278 self.queue_entry.verify_results_dir())
1279 self.host.set_status('Verifying')
mbligh36768f02008-02-22 18:28:33 +00001280
1281
jadmanski0afbb632008-06-06 21:10:57 +00001282 def cleanup(self):
1283 if not os.path.exists(self.temp_results_dir):
1284 return
1285 if self.queue_entry and (self.success or
1286 not self.queue_entry.meta_host):
1287 self.move_results()
1288 super(VerifyTask, self).cleanup()
mblighd64e5702008-04-04 21:39:28 +00001289
1290
jadmanski0afbb632008-06-06 21:10:57 +00001291 def epilog(self):
1292 super(VerifyTask, self).epilog()
mbligh36768f02008-02-22 18:28:33 +00001293
jadmanski0afbb632008-06-06 21:10:57 +00001294 if self.success:
1295 self.host.set_status('Ready')
1296 elif self.queue_entry:
1297 self.queue_entry.requeue()
mbligh36768f02008-02-22 18:28:33 +00001298
1299
jadmanski0afbb632008-06-06 21:10:57 +00001300 def move_results(self):
1301 assert self.queue_entry is not None
1302 target_dir = self.queue_entry.verify_results_dir()
1303 if not os.path.exists(target_dir):
1304 os.makedirs(target_dir)
1305 files = os.listdir(self.temp_results_dir)
1306 for filename in files:
1307 if filename == AUTOSERV_PID_FILE:
1308 continue
1309 self.force_move(os.path.join(self.temp_results_dir,
1310 filename),
1311 os.path.join(target_dir, filename))
mbligh36768f02008-02-22 18:28:33 +00001312
1313
jadmanski0afbb632008-06-06 21:10:57 +00001314 @staticmethod
1315 def force_move(source, dest):
1316 """\
1317 Replacement for shutil.move() that will delete the destination
1318 if it exists, even if it's a directory.
1319 """
1320 if os.path.exists(dest):
1321 print ('Warning: removing existing destination file ' +
1322 dest)
1323 remove_file_or_dir(dest)
1324 shutil.move(source, dest)
mblighe2586682008-02-29 22:45:46 +00001325
1326
mblighdffd6372008-02-29 22:47:33 +00001327class VerifySynchronousTask(VerifyTask):
jadmanski0afbb632008-06-06 21:10:57 +00001328 def epilog(self):
1329 super(VerifySynchronousTask, self).epilog()
1330 if self.success:
1331 if self.queue_entry.job.num_complete() > 0:
1332 # some other entry failed verify, and we've
1333 # already been marked as stopped
1334 return
mblighdffd6372008-02-29 22:47:33 +00001335
showardb2e2c322008-10-14 17:33:55 +00001336 agent = self.queue_entry.on_pending()
1337 if agent:
jadmanski0afbb632008-06-06 21:10:57 +00001338 self.agent.dispatcher.add_agent(agent)
mblighe2586682008-02-29 22:45:46 +00001339
showardb2e2c322008-10-14 17:33:55 +00001340
mbligh36768f02008-02-22 18:28:33 +00001341class QueueTask(AgentTask):
jadmanski0afbb632008-06-06 21:10:57 +00001342 def __init__(self, job, queue_entries, cmd):
1343 super(QueueTask, self).__init__(cmd)
1344 self.job = job
1345 self.queue_entries = queue_entries
mbligh36768f02008-02-22 18:28:33 +00001346
1347
jadmanski0afbb632008-06-06 21:10:57 +00001348 @staticmethod
showardd8e548a2008-09-09 03:04:57 +00001349 def _write_keyval(keyval_dir, field, value, keyval_filename='keyval'):
1350 key_path = os.path.join(keyval_dir, keyval_filename)
jadmanski0afbb632008-06-06 21:10:57 +00001351 keyval_file = open(key_path, 'a')
showardd8e548a2008-09-09 03:04:57 +00001352 print >> keyval_file, '%s=%s' % (field, str(value))
jadmanski0afbb632008-06-06 21:10:57 +00001353 keyval_file.close()
mbligh36768f02008-02-22 18:28:33 +00001354
1355
showardd8e548a2008-09-09 03:04:57 +00001356 def _host_keyval_dir(self):
1357 return os.path.join(self.results_dir(), 'host_keyvals')
1358
1359
1360 def _write_host_keyval(self, host):
1361 labels = ','.join(host.labels())
1362 self._write_keyval(self._host_keyval_dir(), 'labels', labels,
1363 keyval_filename=host.hostname)
1364
1365 def _create_host_keyval_dir(self):
1366 directory = self._host_keyval_dir()
1367 if not os.path.exists(directory):
1368 os.makedirs(directory)
1369
1370
jadmanski0afbb632008-06-06 21:10:57 +00001371 def results_dir(self):
1372 return self.queue_entries[0].results_dir()
mblighbb421852008-03-11 22:36:16 +00001373
1374
jadmanski0afbb632008-06-06 21:10:57 +00001375 def run(self):
1376 """\
1377 Override AgentTask.run() so we can use a PidfileRunMonitor.
1378 """
1379 self.monitor = PidfileRunMonitor(self.results_dir(),
1380 cmd=self.cmd,
1381 nice_level=AUTOSERV_NICE_LEVEL)
1382 self.monitor.run()
mblighbb421852008-03-11 22:36:16 +00001383
1384
jadmanski0afbb632008-06-06 21:10:57 +00001385 def prolog(self):
1386 # write some job timestamps into the job keyval file
1387 queued = time.mktime(self.job.created_on.timetuple())
1388 started = time.time()
showardd8e548a2008-09-09 03:04:57 +00001389 self._write_keyval(self.results_dir(), "job_queued", int(queued))
1390 self._write_keyval(self.results_dir(), "job_started", int(started))
1391 self._create_host_keyval_dir()
jadmanski0afbb632008-06-06 21:10:57 +00001392 for queue_entry in self.queue_entries:
showardd8e548a2008-09-09 03:04:57 +00001393 self._write_host_keyval(queue_entry.host)
jadmanski0afbb632008-06-06 21:10:57 +00001394 print "starting queue_task on %s/%s" % (queue_entry.host.hostname, queue_entry.id)
1395 queue_entry.set_status('Running')
1396 queue_entry.host.set_status('Running')
showard21baa452008-10-21 00:08:39 +00001397 queue_entry.host.update_field('dirty', 1)
jadmanski0afbb632008-06-06 21:10:57 +00001398 if (not self.job.is_synchronous() and
1399 self.job.num_machines() > 1):
1400 assert len(self.queue_entries) == 1
1401 self.job.write_to_machines_file(self.queue_entries[0])
mbligh36768f02008-02-22 18:28:33 +00001402
1403
jadmanski0afbb632008-06-06 21:10:57 +00001404 def _finish_task(self):
1405 # write out the finished time into the results keyval
1406 finished = time.time()
jadmanskif7fa2cc2008-10-01 14:13:23 +00001407 self._write_keyval(self.results_dir(), "job_finished", int(finished))
jadmanskic2ac77f2008-05-16 21:44:04 +00001408
jadmanski0afbb632008-06-06 21:10:57 +00001409 # parse the results of the job
1410 if self.job.is_synchronous() or self.job.num_machines() == 1:
1411 parse_results(self.job.results_dir())
1412 else:
1413 for queue_entry in self.queue_entries:
jadmanskif7fa2cc2008-10-01 14:13:23 +00001414 parse_results(queue_entry.results_dir(), flags="-l 2")
1415
1416
1417 def _log_abort(self):
1418 # build up sets of all the aborted_by and aborted_on values
1419 aborted_by, aborted_on = set(), set()
1420 for queue_entry in self.queue_entries:
1421 if queue_entry.aborted_by:
1422 aborted_by.add(queue_entry.aborted_by)
1423 t = int(time.mktime(queue_entry.aborted_on.timetuple()))
1424 aborted_on.add(t)
1425
1426 # extract some actual, unique aborted by value and write it out
1427 assert len(aborted_by) <= 1
1428 if len(aborted_by) == 1:
1429 results_dir = self.results_dir()
1430 self._write_keyval(results_dir, "aborted_by", aborted_by.pop())
1431 self._write_keyval(results_dir, "aborted_on", max(aborted_on))
jadmanskic2ac77f2008-05-16 21:44:04 +00001432
1433
jadmanski0afbb632008-06-06 21:10:57 +00001434 def abort(self):
1435 super(QueueTask, self).abort()
jadmanskif7fa2cc2008-10-01 14:13:23 +00001436 self._log_abort()
jadmanski0afbb632008-06-06 21:10:57 +00001437 self._finish_task()
jadmanskic2ac77f2008-05-16 21:44:04 +00001438
1439
showard21baa452008-10-21 00:08:39 +00001440 def _reboot_hosts(self):
1441 reboot_after = self.job.reboot_after
1442 do_reboot = False
showard0fc38302008-10-23 00:44:07 +00001443 if reboot_after == models.RebootAfter.ALWAYS:
showard21baa452008-10-21 00:08:39 +00001444 do_reboot = True
showard0fc38302008-10-23 00:44:07 +00001445 elif reboot_after == models.RebootAfter.IF_ALL_TESTS_PASSED:
showard21baa452008-10-21 00:08:39 +00001446 num_tests_failed = self.monitor.num_tests_failed()
1447 do_reboot = (self.success and num_tests_failed == 0)
1448
1449 if do_reboot:
1450 for queue_entry in self.queue_entries:
1451 reboot_task = RebootTask(queue_entry.get_host())
1452 self.agent.dispatcher.add_agent(Agent([reboot_task]))
1453
1454
jadmanski0afbb632008-06-06 21:10:57 +00001455 def epilog(self):
1456 super(QueueTask, self).epilog()
1457 if self.success:
1458 status = 'Completed'
1459 else:
1460 status = 'Failed'
mbligh36768f02008-02-22 18:28:33 +00001461
jadmanski0afbb632008-06-06 21:10:57 +00001462 for queue_entry in self.queue_entries:
1463 queue_entry.set_status(status)
1464 queue_entry.host.set_status('Ready')
mbligh36768f02008-02-22 18:28:33 +00001465
jadmanski0afbb632008-06-06 21:10:57 +00001466 self._finish_task()
showard21baa452008-10-21 00:08:39 +00001467 self._reboot_hosts()
mblighbb421852008-03-11 22:36:16 +00001468
jadmanski0afbb632008-06-06 21:10:57 +00001469 print "queue_task finished with %s/%s" % (status, self.success)
mbligh36768f02008-02-22 18:28:33 +00001470
1471
mblighbb421852008-03-11 22:36:16 +00001472class RecoveryQueueTask(QueueTask):
jadmanski0afbb632008-06-06 21:10:57 +00001473 def __init__(self, job, queue_entries, run_monitor):
1474 super(RecoveryQueueTask, self).__init__(job,
1475 queue_entries, cmd=None)
1476 self.run_monitor = run_monitor
mblighbb421852008-03-11 22:36:16 +00001477
1478
jadmanski0afbb632008-06-06 21:10:57 +00001479 def run(self):
1480 self.monitor = self.run_monitor
mblighbb421852008-03-11 22:36:16 +00001481
1482
jadmanski0afbb632008-06-06 21:10:57 +00001483 def prolog(self):
1484 # recovering an existing process - don't do prolog
1485 pass
mblighbb421852008-03-11 22:36:16 +00001486
1487
mbligh36768f02008-02-22 18:28:33 +00001488class RebootTask(AgentTask):
jadmanski0afbb632008-06-06 21:10:57 +00001489 def __init__(self, host):
1490 global _autoserv_path
1491
1492 # Current implementation of autoserv requires control file
1493 # to be passed on reboot action request. TODO: remove when no
1494 # longer appropriate.
1495 self.create_temp_resultsdir('.reboot')
1496 self.cmd = [_autoserv_path, '-b', '-m', host.hostname,
1497 '-r', self.temp_results_dir, '/dev/null']
1498 self.host = host
1499 super(RebootTask, self).__init__(self.cmd,
1500 failure_tasks=[RepairTask(host)])
mbligh16c722d2008-03-05 00:58:44 +00001501
mblighd5c95802008-03-05 00:33:46 +00001502
jadmanski0afbb632008-06-06 21:10:57 +00001503 def prolog(self):
1504 print "starting reboot task for host: %s" % self.host.hostname
1505 self.host.set_status("Rebooting")
mblighd5c95802008-03-05 00:33:46 +00001506
mblighd5c95802008-03-05 00:33:46 +00001507
showard21baa452008-10-21 00:08:39 +00001508 def epilog(self):
1509 super(RebootTask, self).epilog()
1510 self.host.set_status('Ready')
1511 if self.success:
1512 self.host.update_field('dirty', 0)
1513
1514
mblighd5c95802008-03-05 00:33:46 +00001515class AbortTask(AgentTask):
jadmanski0afbb632008-06-06 21:10:57 +00001516 def __init__(self, queue_entry, agents_to_abort):
1517 self.queue_entry = queue_entry
1518 self.agents_to_abort = agents_to_abort
jadmanski0afbb632008-06-06 21:10:57 +00001519 super(AbortTask, self).__init__('')
mbligh36768f02008-02-22 18:28:33 +00001520
1521
jadmanski0afbb632008-06-06 21:10:57 +00001522 def prolog(self):
1523 print "starting abort on host %s, job %s" % (
1524 self.queue_entry.host_id, self.queue_entry.job_id)
mbligh36768f02008-02-22 18:28:33 +00001525
mblighd64e5702008-04-04 21:39:28 +00001526
jadmanski0afbb632008-06-06 21:10:57 +00001527 def epilog(self):
1528 super(AbortTask, self).epilog()
1529 self.queue_entry.set_status('Aborted')
1530 self.success = True
1531
1532
1533 def run(self):
1534 for agent in self.agents_to_abort:
1535 if (agent.active_task):
1536 agent.active_task.abort()
mbligh36768f02008-02-22 18:28:33 +00001537
1538
1539class DBObject(object):
jadmanski0afbb632008-06-06 21:10:57 +00001540 def __init__(self, id=None, row=None, new_record=False):
1541 assert (bool(id) != bool(row))
mbligh36768f02008-02-22 18:28:33 +00001542
jadmanski0afbb632008-06-06 21:10:57 +00001543 self.__table = self._get_table()
1544 fields = self._fields()
mbligh36768f02008-02-22 18:28:33 +00001545
jadmanski0afbb632008-06-06 21:10:57 +00001546 self.__new_record = new_record
mbligh36768f02008-02-22 18:28:33 +00001547
jadmanski0afbb632008-06-06 21:10:57 +00001548 if row is None:
1549 sql = 'SELECT * FROM %s WHERE ID=%%s' % self.__table
1550 rows = _db.execute(sql, (id,))
1551 if len(rows) == 0:
1552 raise "row not found (table=%s, id=%s)" % \
1553 (self.__table, id)
1554 row = rows[0]
mbligh36768f02008-02-22 18:28:33 +00001555
jadmanski0afbb632008-06-06 21:10:57 +00001556 assert len(row) == self.num_cols(), (
1557 "table = %s, row = %s/%d, fields = %s/%d" % (
1558 self.__table, row, len(row), fields, self.num_cols()))
mbligh36768f02008-02-22 18:28:33 +00001559
jadmanski0afbb632008-06-06 21:10:57 +00001560 self.__valid_fields = {}
1561 for i,value in enumerate(row):
1562 self.__dict__[fields[i]] = value
1563 self.__valid_fields[fields[i]] = True
mbligh36768f02008-02-22 18:28:33 +00001564
jadmanski0afbb632008-06-06 21:10:57 +00001565 del self.__valid_fields['id']
mbligh36768f02008-02-22 18:28:33 +00001566
mblighe2586682008-02-29 22:45:46 +00001567
jadmanski0afbb632008-06-06 21:10:57 +00001568 @classmethod
1569 def _get_table(cls):
1570 raise NotImplementedError('Subclasses must override this')
mblighe2586682008-02-29 22:45:46 +00001571
1572
jadmanski0afbb632008-06-06 21:10:57 +00001573 @classmethod
1574 def _fields(cls):
1575 raise NotImplementedError('Subclasses must override this')
showard04c82c52008-05-29 19:38:12 +00001576
1577
jadmanski0afbb632008-06-06 21:10:57 +00001578 @classmethod
1579 def num_cols(cls):
1580 return len(cls._fields())
showard04c82c52008-05-29 19:38:12 +00001581
1582
jadmanski0afbb632008-06-06 21:10:57 +00001583 def count(self, where, table = None):
1584 if not table:
1585 table = self.__table
mbligh36768f02008-02-22 18:28:33 +00001586
jadmanski0afbb632008-06-06 21:10:57 +00001587 rows = _db.execute("""
1588 SELECT count(*) FROM %s
1589 WHERE %s
1590 """ % (table, where))
mbligh6f8bab42008-02-29 22:45:14 +00001591
jadmanski0afbb632008-06-06 21:10:57 +00001592 assert len(rows) == 1
1593
1594 return int(rows[0][0])
mbligh36768f02008-02-22 18:28:33 +00001595
1596
mblighf8c624d2008-07-03 16:58:45 +00001597 def update_field(self, field, value, condition=''):
jadmanski0afbb632008-06-06 21:10:57 +00001598 assert self.__valid_fields[field]
mbligh36768f02008-02-22 18:28:33 +00001599
jadmanski0afbb632008-06-06 21:10:57 +00001600 if self.__dict__[field] == value:
1601 return
mbligh36768f02008-02-22 18:28:33 +00001602
mblighf8c624d2008-07-03 16:58:45 +00001603 query = "UPDATE %s SET %s = %%s WHERE id = %%s" % (self.__table, field)
1604 if condition:
1605 query += ' AND (%s)' % condition
jadmanski0afbb632008-06-06 21:10:57 +00001606 _db.execute(query, (value, self.id))
1607
1608 self.__dict__[field] = value
mbligh36768f02008-02-22 18:28:33 +00001609
1610
jadmanski0afbb632008-06-06 21:10:57 +00001611 def save(self):
1612 if self.__new_record:
1613 keys = self._fields()[1:] # avoid id
1614 columns = ','.join([str(key) for key in keys])
1615 values = ['"%s"' % self.__dict__[key] for key in keys]
1616 values = ','.join(values)
1617 query = """INSERT INTO %s (%s) VALUES (%s)""" % \
1618 (self.__table, columns, values)
1619 _db.execute(query)
mbligh36768f02008-02-22 18:28:33 +00001620
1621
jadmanski0afbb632008-06-06 21:10:57 +00001622 def delete(self):
1623 query = 'DELETE FROM %s WHERE id=%%s' % self.__table
1624 _db.execute(query, (self.id,))
mblighe2586682008-02-29 22:45:46 +00001625
1626
showard63a34772008-08-18 19:32:50 +00001627 @staticmethod
1628 def _prefix_with(string, prefix):
1629 if string:
1630 string = prefix + string
1631 return string
1632
1633
jadmanski0afbb632008-06-06 21:10:57 +00001634 @classmethod
showard989f25d2008-10-01 11:38:11 +00001635 def fetch(cls, where='', params=(), joins='', order_by=''):
showard63a34772008-08-18 19:32:50 +00001636 order_by = cls._prefix_with(order_by, 'ORDER BY ')
1637 where = cls._prefix_with(where, 'WHERE ')
1638 query = ('SELECT %(table)s.* FROM %(table)s %(joins)s '
1639 '%(where)s %(order_by)s' % {'table' : cls._get_table(),
1640 'joins' : joins,
1641 'where' : where,
1642 'order_by' : order_by})
1643 rows = _db.execute(query, params)
jadmanski0afbb632008-06-06 21:10:57 +00001644 for row in rows:
1645 yield cls(row=row)
mblighe2586682008-02-29 22:45:46 +00001646
mbligh36768f02008-02-22 18:28:33 +00001647
1648class IneligibleHostQueue(DBObject):
jadmanski0afbb632008-06-06 21:10:57 +00001649 def __init__(self, id=None, row=None, new_record=None):
1650 super(IneligibleHostQueue, self).__init__(id=id, row=row,
1651 new_record=new_record)
mblighe2586682008-02-29 22:45:46 +00001652
1653
jadmanski0afbb632008-06-06 21:10:57 +00001654 @classmethod
1655 def _get_table(cls):
1656 return 'ineligible_host_queues'
mbligh36768f02008-02-22 18:28:33 +00001657
1658
jadmanski0afbb632008-06-06 21:10:57 +00001659 @classmethod
1660 def _fields(cls):
1661 return ['id', 'job_id', 'host_id']
showard04c82c52008-05-29 19:38:12 +00001662
1663
showard989f25d2008-10-01 11:38:11 +00001664class Label(DBObject):
1665 @classmethod
1666 def _get_table(cls):
1667 return 'labels'
1668
1669
1670 @classmethod
1671 def _fields(cls):
1672 return ['id', 'name', 'kernel_config', 'platform', 'invalid',
1673 'only_if_needed']
1674
1675
mbligh36768f02008-02-22 18:28:33 +00001676class Host(DBObject):
jadmanski0afbb632008-06-06 21:10:57 +00001677 def __init__(self, id=None, row=None):
1678 super(Host, self).__init__(id=id, row=row)
mblighe2586682008-02-29 22:45:46 +00001679
1680
jadmanski0afbb632008-06-06 21:10:57 +00001681 @classmethod
1682 def _get_table(cls):
1683 return 'hosts'
mbligh36768f02008-02-22 18:28:33 +00001684
1685
jadmanski0afbb632008-06-06 21:10:57 +00001686 @classmethod
1687 def _fields(cls):
1688 return ['id', 'hostname', 'locked', 'synch_id','status',
showard21baa452008-10-21 00:08:39 +00001689 'invalid', 'protection', 'locked_by_id', 'lock_time', 'dirty']
showard04c82c52008-05-29 19:38:12 +00001690
1691
jadmanski0afbb632008-06-06 21:10:57 +00001692 def current_task(self):
1693 rows = _db.execute("""
1694 SELECT * FROM host_queue_entries WHERE host_id=%s AND NOT complete AND active
1695 """, (self.id,))
1696
1697 if len(rows) == 0:
1698 return None
1699 else:
1700 assert len(rows) == 1
1701 results = rows[0];
mblighf8c624d2008-07-03 16:58:45 +00001702# print "current = %s" % results
jadmanski0afbb632008-06-06 21:10:57 +00001703 return HostQueueEntry(row=results)
mbligh36768f02008-02-22 18:28:33 +00001704
1705
jadmanski0afbb632008-06-06 21:10:57 +00001706 def yield_work(self):
1707 print "%s yielding work" % self.hostname
1708 if self.current_task():
1709 self.current_task().requeue()
1710
1711 def set_status(self,status):
1712 print '%s -> %s' % (self.hostname, status)
1713 self.update_field('status',status)
mbligh36768f02008-02-22 18:28:33 +00001714
1715
showardd8e548a2008-09-09 03:04:57 +00001716 def labels(self):
1717 """
1718 Fetch a list of names of all non-platform labels associated with this
1719 host.
1720 """
1721 rows = _db.execute("""
1722 SELECT labels.name
1723 FROM labels
1724 INNER JOIN hosts_labels ON labels.id = hosts_labels.label_id
1725 WHERE NOT labels.platform AND hosts_labels.host_id = %s
1726 ORDER BY labels.name
1727 """, (self.id,))
1728 return [row[0] for row in rows]
1729
1730
mbligh36768f02008-02-22 18:28:33 +00001731class HostQueueEntry(DBObject):
jadmanski0afbb632008-06-06 21:10:57 +00001732 def __init__(self, id=None, row=None):
1733 assert id or row
1734 super(HostQueueEntry, self).__init__(id=id, row=row)
1735 self.job = Job(self.job_id)
mbligh36768f02008-02-22 18:28:33 +00001736
jadmanski0afbb632008-06-06 21:10:57 +00001737 if self.host_id:
1738 self.host = Host(self.host_id)
1739 else:
1740 self.host = None
mbligh36768f02008-02-22 18:28:33 +00001741
jadmanski0afbb632008-06-06 21:10:57 +00001742 self.queue_log_path = os.path.join(self.job.results_dir(),
1743 'queue.log.' + str(self.id))
mbligh36768f02008-02-22 18:28:33 +00001744
1745
jadmanski0afbb632008-06-06 21:10:57 +00001746 @classmethod
1747 def _get_table(cls):
1748 return 'host_queue_entries'
mblighe2586682008-02-29 22:45:46 +00001749
1750
jadmanski0afbb632008-06-06 21:10:57 +00001751 @classmethod
1752 def _fields(cls):
1753 return ['id', 'job_id', 'host_id', 'priority', 'status',
showardb8471e32008-07-03 19:51:08 +00001754 'meta_host', 'active', 'complete', 'deleted']
showard04c82c52008-05-29 19:38:12 +00001755
1756
jadmanski0afbb632008-06-06 21:10:57 +00001757 def set_host(self, host):
1758 if host:
1759 self.queue_log_record('Assigning host ' + host.hostname)
1760 self.update_field('host_id', host.id)
1761 self.update_field('active', True)
1762 self.block_host(host.id)
1763 else:
1764 self.queue_log_record('Releasing host')
1765 self.unblock_host(self.host.id)
1766 self.update_field('host_id', None)
mbligh36768f02008-02-22 18:28:33 +00001767
jadmanski0afbb632008-06-06 21:10:57 +00001768 self.host = host
mbligh36768f02008-02-22 18:28:33 +00001769
1770
jadmanski0afbb632008-06-06 21:10:57 +00001771 def get_host(self):
1772 return self.host
mbligh36768f02008-02-22 18:28:33 +00001773
1774
jadmanski0afbb632008-06-06 21:10:57 +00001775 def queue_log_record(self, log_line):
1776 now = str(datetime.datetime.now())
1777 queue_log = open(self.queue_log_path, 'a', 0)
1778 queue_log.write(now + ' ' + log_line + '\n')
1779 queue_log.close()
mbligh36768f02008-02-22 18:28:33 +00001780
1781
jadmanski0afbb632008-06-06 21:10:57 +00001782 def block_host(self, host_id):
1783 print "creating block %s/%s" % (self.job.id, host_id)
1784 row = [0, self.job.id, host_id]
1785 block = IneligibleHostQueue(row=row, new_record=True)
1786 block.save()
mblighe2586682008-02-29 22:45:46 +00001787
1788
jadmanski0afbb632008-06-06 21:10:57 +00001789 def unblock_host(self, host_id):
1790 print "removing block %s/%s" % (self.job.id, host_id)
1791 blocks = IneligibleHostQueue.fetch(
1792 'job_id=%d and host_id=%d' % (self.job.id, host_id))
1793 for block in blocks:
1794 block.delete()
mblighe2586682008-02-29 22:45:46 +00001795
1796
jadmanski0afbb632008-06-06 21:10:57 +00001797 def results_dir(self):
1798 if self.job.is_synchronous() or self.job.num_machines() == 1:
1799 return self.job.job_dir
1800 else:
1801 assert self.host
1802 return os.path.join(self.job.job_dir,
1803 self.host.hostname)
mbligh36768f02008-02-22 18:28:33 +00001804
mblighe2586682008-02-29 22:45:46 +00001805
jadmanski0afbb632008-06-06 21:10:57 +00001806 def verify_results_dir(self):
1807 if self.job.is_synchronous() or self.job.num_machines() > 1:
1808 assert self.host
1809 return os.path.join(self.job.job_dir,
1810 self.host.hostname)
1811 else:
1812 return self.job.job_dir
mbligh36768f02008-02-22 18:28:33 +00001813
1814
jadmanski0afbb632008-06-06 21:10:57 +00001815 def set_status(self, status):
mblighf8c624d2008-07-03 16:58:45 +00001816 abort_statuses = ['Abort', 'Aborting', 'Aborted']
1817 if status not in abort_statuses:
1818 condition = ' AND '.join(['status <> "%s"' % x
1819 for x in abort_statuses])
1820 else:
1821 condition = ''
1822 self.update_field('status', status, condition=condition)
1823
jadmanski0afbb632008-06-06 21:10:57 +00001824 if self.host:
1825 hostname = self.host.hostname
1826 else:
1827 hostname = 'no host'
1828 print "%s/%d status -> %s" % (hostname, self.id, self.status)
mblighf8c624d2008-07-03 16:58:45 +00001829
jadmanski0afbb632008-06-06 21:10:57 +00001830 if status in ['Queued']:
1831 self.update_field('complete', False)
1832 self.update_field('active', False)
mbligh36768f02008-02-22 18:28:33 +00001833
jadmanski0afbb632008-06-06 21:10:57 +00001834 if status in ['Pending', 'Running', 'Verifying', 'Starting',
1835 'Abort', 'Aborting']:
1836 self.update_field('complete', False)
1837 self.update_field('active', True)
mbligh36768f02008-02-22 18:28:33 +00001838
jadmanski0afbb632008-06-06 21:10:57 +00001839 if status in ['Failed', 'Completed', 'Stopped', 'Aborted']:
1840 self.update_field('complete', True)
1841 self.update_field('active', False)
showard542e8402008-09-19 20:16:18 +00001842 self._email_on_job_complete()
1843
1844
1845 def _email_on_job_complete(self):
1846 url = "%s#tab_id=view_job&object_id=%s" % (_base_url, self.job.id)
1847
1848 if self.job.is_finished():
1849 subject = "Autotest: Job ID: %s \"%s\" Completed" % (
1850 self.job.id, self.job.name)
1851 body = "Job ID: %s\nJob Name: %s\n%s\n" % (
1852 self.job.id, self.job.name, url)
1853 send_email(_email_from, self.job.email_list, subject, body)
mbligh36768f02008-02-22 18:28:33 +00001854
1855
jadmanski0afbb632008-06-06 21:10:57 +00001856 def run(self,assigned_host=None):
1857 if self.meta_host:
1858 assert assigned_host
1859 # ensure results dir exists for the queue log
1860 self.job.create_results_dir()
1861 self.set_host(assigned_host)
mbligh36768f02008-02-22 18:28:33 +00001862
jadmanski0afbb632008-06-06 21:10:57 +00001863 print "%s/%s scheduled on %s, status=%s" % (self.job.name,
1864 self.meta_host, self.host.hostname, self.status)
mbligh36768f02008-02-22 18:28:33 +00001865
jadmanski0afbb632008-06-06 21:10:57 +00001866 return self.job.run(queue_entry=self)
mblighe2586682008-02-29 22:45:46 +00001867
jadmanski0afbb632008-06-06 21:10:57 +00001868 def requeue(self):
1869 self.set_status('Queued')
mblighe2586682008-02-29 22:45:46 +00001870
jadmanski0afbb632008-06-06 21:10:57 +00001871 if self.meta_host:
1872 self.set_host(None)
mbligh36768f02008-02-22 18:28:33 +00001873
1874
jadmanski0afbb632008-06-06 21:10:57 +00001875 def handle_host_failure(self):
1876 """\
1877 Called when this queue entry's host has failed verification and
1878 repair.
1879 """
1880 assert not self.meta_host
1881 self.set_status('Failed')
1882 if self.job.is_synchronous():
1883 self.job.stop_all_entries()
mblighe2586682008-02-29 22:45:46 +00001884
1885
jadmanski0afbb632008-06-06 21:10:57 +00001886 def clear_results_dir(self, results_dir=None, dont_delete_files=False):
1887 results_dir = results_dir or self.results_dir()
1888 if not os.path.exists(results_dir):
1889 return
1890 if dont_delete_files:
1891 temp_dir = tempfile.mkdtemp(suffix='.clear_results')
1892 print 'Moving results from %s to %s' % (results_dir,
1893 temp_dir)
1894 for filename in os.listdir(results_dir):
1895 path = os.path.join(results_dir, filename)
1896 if dont_delete_files:
1897 shutil.move(path,
1898 os.path.join(temp_dir, filename))
1899 else:
1900 remove_file_or_dir(path)
mbligh36768f02008-02-22 18:28:33 +00001901
1902
jadmanskif7fa2cc2008-10-01 14:13:23 +00001903 @property
1904 def aborted_by(self):
1905 self._load_abort_info()
1906 return self._aborted_by
1907
1908
1909 @property
1910 def aborted_on(self):
1911 self._load_abort_info()
1912 return self._aborted_on
1913
1914
1915 def _load_abort_info(self):
1916 """ Fetch info about who aborted the job. """
1917 if hasattr(self, "_aborted_by"):
1918 return
1919 rows = _db.execute("""
1920 SELECT users.login, aborted_host_queue_entries.aborted_on
1921 FROM aborted_host_queue_entries
1922 INNER JOIN users
1923 ON users.id = aborted_host_queue_entries.aborted_by_id
1924 WHERE aborted_host_queue_entries.queue_entry_id = %s
1925 """, (self.id,))
1926 if rows:
1927 self._aborted_by, self._aborted_on = rows[0]
1928 else:
1929 self._aborted_by = self._aborted_on = None
1930
1931
showardb2e2c322008-10-14 17:33:55 +00001932 def on_pending(self):
1933 """
1934 Called when an entry in a synchronous job has passed verify. If the
1935 job is ready to run, returns an agent to run the job. Returns None
1936 otherwise.
1937 """
1938 self.set_status('Pending')
showardcfd66a32008-10-15 20:31:48 +00001939 self.get_host().set_status('Pending')
showardb2e2c322008-10-14 17:33:55 +00001940 if self.job.is_ready():
1941 return self.job.run(self)
1942 return None
1943
1944
showard1be97432008-10-17 15:30:45 +00001945 def abort(self, agents_to_abort=[]):
1946 abort_task = AbortTask(self, agents_to_abort)
1947 tasks = [abort_task]
1948
1949 host = self.get_host()
1950 if host:
1951 reboot_task = RebootTask(host)
1952 verify_task = VerifyTask(host=host)
1953 # just to make sure this host does not get taken away
1954 host.set_status('Rebooting')
1955 tasks += [reboot_task, verify_task]
1956
1957 self.set_status('Aborting')
1958 return Agent(tasks=tasks, queue_entry_ids=[self.id])
1959
1960
mbligh36768f02008-02-22 18:28:33 +00001961class Job(DBObject):
jadmanski0afbb632008-06-06 21:10:57 +00001962 def __init__(self, id=None, row=None):
1963 assert id or row
1964 super(Job, self).__init__(id=id, row=row)
mbligh36768f02008-02-22 18:28:33 +00001965
jadmanski0afbb632008-06-06 21:10:57 +00001966 self.job_dir = os.path.join(RESULTS_DIR, "%s-%s" % (self.id,
1967 self.owner))
mblighe2586682008-02-29 22:45:46 +00001968
1969
jadmanski0afbb632008-06-06 21:10:57 +00001970 @classmethod
1971 def _get_table(cls):
1972 return 'jobs'
mbligh36768f02008-02-22 18:28:33 +00001973
1974
jadmanski0afbb632008-06-06 21:10:57 +00001975 @classmethod
1976 def _fields(cls):
1977 return ['id', 'owner', 'name', 'priority', 'control_file',
1978 'control_type', 'created_on', 'synch_type',
showard542e8402008-09-19 20:16:18 +00001979 'synch_count', 'synchronizing', 'timeout',
showard21baa452008-10-21 00:08:39 +00001980 'run_verify', 'email_list', 'reboot_before', 'reboot_after']
showard04c82c52008-05-29 19:38:12 +00001981
1982
jadmanski0afbb632008-06-06 21:10:57 +00001983 def is_server_job(self):
1984 return self.control_type != 2
mbligh36768f02008-02-22 18:28:33 +00001985
1986
jadmanski0afbb632008-06-06 21:10:57 +00001987 def get_host_queue_entries(self):
1988 rows = _db.execute("""
1989 SELECT * FROM host_queue_entries
1990 WHERE job_id= %s
1991 """, (self.id,))
1992 entries = [HostQueueEntry(row=i) for i in rows]
mbligh36768f02008-02-22 18:28:33 +00001993
jadmanski0afbb632008-06-06 21:10:57 +00001994 assert len(entries)>0
mbligh36768f02008-02-22 18:28:33 +00001995
jadmanski0afbb632008-06-06 21:10:57 +00001996 return entries
mbligh36768f02008-02-22 18:28:33 +00001997
1998
jadmanski0afbb632008-06-06 21:10:57 +00001999 def set_status(self, status, update_queues=False):
2000 self.update_field('status',status)
2001
2002 if update_queues:
2003 for queue_entry in self.get_host_queue_entries():
2004 queue_entry.set_status(status)
mbligh36768f02008-02-22 18:28:33 +00002005
2006
jadmanski0afbb632008-06-06 21:10:57 +00002007 def is_synchronous(self):
2008 return self.synch_type == 2
mbligh36768f02008-02-22 18:28:33 +00002009
2010
jadmanski0afbb632008-06-06 21:10:57 +00002011 def is_ready(self):
2012 if not self.is_synchronous():
2013 return True
2014 sql = "job_id=%s AND status='Pending'" % self.id
2015 count = self.count(sql, table='host_queue_entries')
showardb2e2c322008-10-14 17:33:55 +00002016 return (count == self.num_machines())
mbligh36768f02008-02-22 18:28:33 +00002017
2018
jadmanski0afbb632008-06-06 21:10:57 +00002019 def results_dir(self):
2020 return self.job_dir
mbligh36768f02008-02-22 18:28:33 +00002021
jadmanski0afbb632008-06-06 21:10:57 +00002022 def num_machines(self, clause = None):
2023 sql = "job_id=%s" % self.id
2024 if clause:
2025 sql += " AND (%s)" % clause
2026 return self.count(sql, table='host_queue_entries')
mbligh36768f02008-02-22 18:28:33 +00002027
2028
jadmanski0afbb632008-06-06 21:10:57 +00002029 def num_queued(self):
2030 return self.num_machines('not complete')
mbligh36768f02008-02-22 18:28:33 +00002031
2032
jadmanski0afbb632008-06-06 21:10:57 +00002033 def num_active(self):
2034 return self.num_machines('active')
mbligh36768f02008-02-22 18:28:33 +00002035
2036
jadmanski0afbb632008-06-06 21:10:57 +00002037 def num_complete(self):
2038 return self.num_machines('complete')
mbligh36768f02008-02-22 18:28:33 +00002039
2040
jadmanski0afbb632008-06-06 21:10:57 +00002041 def is_finished(self):
2042 left = self.num_queued()
2043 print "%s: %s machines left" % (self.name, left)
2044 return left==0
mbligh36768f02008-02-22 18:28:33 +00002045
mbligh36768f02008-02-22 18:28:33 +00002046
jadmanski0afbb632008-06-06 21:10:57 +00002047 def stop_all_entries(self):
2048 for child_entry in self.get_host_queue_entries():
2049 if not child_entry.complete:
2050 child_entry.set_status('Stopped')
mblighe2586682008-02-29 22:45:46 +00002051
2052
jadmanski0afbb632008-06-06 21:10:57 +00002053 def write_to_machines_file(self, queue_entry):
2054 hostname = queue_entry.get_host().hostname
2055 print "writing %s to job %s machines file" % (hostname, self.id)
2056 file_path = os.path.join(self.job_dir, '.machines')
2057 mf = open(file_path, 'a')
2058 mf.write("%s\n" % queue_entry.get_host().hostname)
2059 mf.close()
mbligh36768f02008-02-22 18:28:33 +00002060
2061
jadmanski0afbb632008-06-06 21:10:57 +00002062 def create_results_dir(self, queue_entry=None):
2063 print "create: active: %s complete %s" % (self.num_active(),
2064 self.num_complete())
mbligh36768f02008-02-22 18:28:33 +00002065
jadmanski0afbb632008-06-06 21:10:57 +00002066 if not os.path.exists(self.job_dir):
2067 os.makedirs(self.job_dir)
mbligh36768f02008-02-22 18:28:33 +00002068
jadmanski0afbb632008-06-06 21:10:57 +00002069 if queue_entry:
showarde05654d2008-10-28 20:38:40 +00002070 results_dir = queue_entry.results_dir()
2071 if not os.path.exists(results_dir):
2072 os.makedirs(results_dir)
2073 return results_dir
jadmanski0afbb632008-06-06 21:10:57 +00002074 return self.job_dir
mbligh36768f02008-02-22 18:28:33 +00002075
2076
showardb2e2c322008-10-14 17:33:55 +00002077 def _write_control_file(self):
2078 'Writes control file out to disk, returns a filename'
2079 control_fd, control_filename = tempfile.mkstemp(suffix='.control_file')
2080 control_file = os.fdopen(control_fd, 'w')
jadmanski0afbb632008-06-06 21:10:57 +00002081 if self.control_file:
showardb2e2c322008-10-14 17:33:55 +00002082 control_file.write(self.control_file)
2083 control_file.close()
2084 return control_filename
mbligh36768f02008-02-22 18:28:33 +00002085
showardb2e2c322008-10-14 17:33:55 +00002086
2087 def _get_job_tag(self, queue_entries):
2088 base_job_tag = "%s-%s" % (self.id, self.owner)
2089 if self.is_synchronous() or self.num_machines() == 1:
2090 return base_job_tag
jadmanski0afbb632008-06-06 21:10:57 +00002091 else:
showardb2e2c322008-10-14 17:33:55 +00002092 return base_job_tag + '/' + queue_entries[0].get_host().hostname
2093
2094
2095 def _get_autoserv_params(self, queue_entries):
2096 results_dir = self.create_results_dir(queue_entries[0])
2097 control_filename = self._write_control_file()
jadmanski0afbb632008-06-06 21:10:57 +00002098 hostnames = ','.join([entry.get_host().hostname
2099 for entry in queue_entries])
showardb2e2c322008-10-14 17:33:55 +00002100 job_tag = self._get_job_tag(queue_entries)
mbligh36768f02008-02-22 18:28:33 +00002101
showardb2e2c322008-10-14 17:33:55 +00002102 params = [_autoserv_path, '-P', job_tag, '-p', '-n',
showard21baa452008-10-21 00:08:39 +00002103 '-r', os.path.abspath(results_dir), '-u', self.owner,
2104 '-l', self.name, '-m', hostnames, control_filename]
mbligh36768f02008-02-22 18:28:33 +00002105
jadmanski0afbb632008-06-06 21:10:57 +00002106 if not self.is_server_job():
2107 params.append('-c')
mbligh36768f02008-02-22 18:28:33 +00002108
showardb2e2c322008-10-14 17:33:55 +00002109 return params
mblighe2586682008-02-29 22:45:46 +00002110
mbligh36768f02008-02-22 18:28:33 +00002111
showard21baa452008-10-21 00:08:39 +00002112 def _get_pre_job_tasks(self, queue_entry, verify_task_class=VerifyTask):
2113 do_reboot = False
showard0fc38302008-10-23 00:44:07 +00002114 if self.reboot_before == models.RebootBefore.ALWAYS:
showard21baa452008-10-21 00:08:39 +00002115 do_reboot = True
showard0fc38302008-10-23 00:44:07 +00002116 elif self.reboot_before == models.RebootBefore.IF_DIRTY:
showard21baa452008-10-21 00:08:39 +00002117 do_reboot = queue_entry.get_host().dirty
2118
2119 tasks = []
2120 if do_reboot:
2121 tasks.append(RebootTask(queue_entry.get_host()))
2122 tasks.append(verify_task_class(queue_entry=queue_entry))
2123 return tasks
2124
2125
showardb2e2c322008-10-14 17:33:55 +00002126 def _run_synchronous(self, queue_entry):
2127 if not self.is_ready():
showard9976ce92008-10-15 20:28:13 +00002128 if self.run_verify:
showard21baa452008-10-21 00:08:39 +00002129 return Agent(self._get_pre_job_tasks(queue_entry,
2130 VerifySynchronousTask),
2131 [queue_entry.id])
showard9976ce92008-10-15 20:28:13 +00002132 else:
2133 return queue_entry.on_pending()
mbligh36768f02008-02-22 18:28:33 +00002134
showardb2e2c322008-10-14 17:33:55 +00002135 queue_entry.set_status('Starting')
jadmanski0afbb632008-06-06 21:10:57 +00002136
showardb2e2c322008-10-14 17:33:55 +00002137 return self._finish_run(self.get_host_queue_entries())
2138
2139
2140 def _run_asynchronous(self, queue_entry):
showard9976ce92008-10-15 20:28:13 +00002141 initial_tasks = []
2142 if self.run_verify:
showard21baa452008-10-21 00:08:39 +00002143 initial_tasks = self._get_pre_job_tasks(queue_entry)
showardb2e2c322008-10-14 17:33:55 +00002144 return self._finish_run([queue_entry], initial_tasks)
2145
2146
2147 def _finish_run(self, queue_entries, initial_tasks=[]):
2148 params = self._get_autoserv_params(queue_entries)
2149 queue_task = QueueTask(job=self, queue_entries=queue_entries,
2150 cmd=params)
2151 tasks = initial_tasks + [queue_task]
2152 entry_ids = [entry.id for entry in queue_entries]
2153
2154 return Agent(tasks, entry_ids, num_processes=len(queue_entries))
2155
2156
2157 def run(self, queue_entry):
2158 if self.is_synchronous():
2159 return self._run_synchronous(queue_entry)
2160 return self._run_asynchronous(queue_entry)
mbligh36768f02008-02-22 18:28:33 +00002161
2162
2163if __name__ == '__main__':
jadmanski0afbb632008-06-06 21:10:57 +00002164 main()