blob: 26a70d73f1ba42de5dd7d4c625dc7c8e752b3afd [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
showardfa8629c2008-11-04 16:51:23 +0000127 # ensure Django connection is in autocommit
128 setup_django_environment.enable_autocommit()
129
jadmanski0afbb632008-06-06 21:10:57 +0000130 print "Setting signal handler"
131 signal.signal(signal.SIGINT, handle_sigint)
132
133 print "Connected! Running..."
mbligh36768f02008-02-22 18:28:33 +0000134
135
136def enable_logging(logfile):
jadmanski0afbb632008-06-06 21:10:57 +0000137 out_file = logfile
138 err_file = "%s.err" % logfile
139 print "Enabling logging to %s (%s)" % (out_file, err_file)
140 out_fd = open(out_file, "a", buffering=0)
141 err_fd = open(err_file, "a", buffering=0)
mbligh36768f02008-02-22 18:28:33 +0000142
jadmanski0afbb632008-06-06 21:10:57 +0000143 os.dup2(out_fd.fileno(), sys.stdout.fileno())
144 os.dup2(err_fd.fileno(), sys.stderr.fileno())
mbligh36768f02008-02-22 18:28:33 +0000145
jadmanski0afbb632008-06-06 21:10:57 +0000146 sys.stdout = out_fd
147 sys.stderr = err_fd
mbligh36768f02008-02-22 18:28:33 +0000148
149
mblighd5c95802008-03-05 00:33:46 +0000150def queue_entries_to_abort():
jadmanski0afbb632008-06-06 21:10:57 +0000151 rows = _db.execute("""
152 SELECT * FROM host_queue_entries WHERE status='Abort';
153 """)
154 qe = [HostQueueEntry(row=i) for i in rows]
155 return qe
mbligh36768f02008-02-22 18:28:33 +0000156
mblighe2586682008-02-29 22:45:46 +0000157def remove_file_or_dir(path):
jadmanski0afbb632008-06-06 21:10:57 +0000158 if stat.S_ISDIR(os.stat(path).st_mode):
159 # directory
160 shutil.rmtree(path)
161 else:
162 # file
163 os.remove(path)
mblighe2586682008-02-29 22:45:46 +0000164
165
mbligh36768f02008-02-22 18:28:33 +0000166def log_stacktrace(reason):
jadmanski0afbb632008-06-06 21:10:57 +0000167 (type, value, tb) = sys.exc_info()
168 str = "EXCEPTION: %s\n" % reason
169 str += ''.join(traceback.format_exception(type, value, tb))
mbligh36768f02008-02-22 18:28:33 +0000170
jadmanski0afbb632008-06-06 21:10:57 +0000171 sys.stderr.write("\n%s\n" % str)
172 email_manager.enqueue_notify_email("monitor_db exception", str)
mbligh36768f02008-02-22 18:28:33 +0000173
mblighbb421852008-03-11 22:36:16 +0000174
175def get_proc_poll_fn(pid):
jadmanski0afbb632008-06-06 21:10:57 +0000176 proc_path = os.path.join('/proc', str(pid))
177 def poll_fn():
178 if os.path.exists(proc_path):
179 return None
180 return 0 # we can't get a real exit code
181 return poll_fn
mblighbb421852008-03-11 22:36:16 +0000182
183
showard542e8402008-09-19 20:16:18 +0000184def send_email(from_addr, to_string, subject, body):
185 """Mails out emails to the addresses listed in to_string.
186
187 to_string is split into a list which can be delimited by any of:
188 ';', ',', ':' or any whitespace
189 """
190
191 # Create list from string removing empty strings from the list.
192 to_list = [x for x in re.split('\s|,|;|:', to_string) if x]
showard7d182aa2008-09-22 16:17:24 +0000193 if not to_list:
194 return
195
showard542e8402008-09-19 20:16:18 +0000196 msg = "From: %s\nTo: %s\nSubject: %s\n\n%s" % (
197 from_addr, ', '.join(to_list), subject, body)
showard7d182aa2008-09-22 16:17:24 +0000198 try:
199 mailer = smtplib.SMTP('localhost')
200 try:
201 mailer.sendmail(from_addr, to_list, msg)
202 finally:
203 mailer.quit()
204 except Exception, e:
205 print "Sending email failed. Reason: %s" % repr(e)
showard542e8402008-09-19 20:16:18 +0000206
207
mblighbb421852008-03-11 22:36:16 +0000208def kill_autoserv(pid, poll_fn=None):
jadmanski0afbb632008-06-06 21:10:57 +0000209 print 'killing', pid
210 if poll_fn is None:
211 poll_fn = get_proc_poll_fn(pid)
212 if poll_fn() == None:
213 os.kill(pid, signal.SIGCONT)
214 os.kill(pid, signal.SIGTERM)
mbligh36768f02008-02-22 18:28:33 +0000215
216
showard7cf9a9b2008-05-15 21:15:52 +0000217class EmailNotificationManager(object):
jadmanski0afbb632008-06-06 21:10:57 +0000218 def __init__(self):
219 self._emails = []
showard7cf9a9b2008-05-15 21:15:52 +0000220
jadmanski0afbb632008-06-06 21:10:57 +0000221 def enqueue_notify_email(self, subject, message):
222 if not _notify_email:
223 return
showard7cf9a9b2008-05-15 21:15:52 +0000224
jadmanski0afbb632008-06-06 21:10:57 +0000225 body = 'Subject: ' + subject + '\n'
226 body += "%s / %s / %s\n%s" % (socket.gethostname(),
227 os.getpid(),
228 time.strftime("%X %x"), message)
229 self._emails.append(body)
showard7cf9a9b2008-05-15 21:15:52 +0000230
231
jadmanski0afbb632008-06-06 21:10:57 +0000232 def send_queued_emails(self):
233 if not self._emails:
234 return
235 subject = 'Scheduler notifications from ' + socket.gethostname()
236 separator = '\n' + '-' * 40 + '\n'
237 body = separator.join(self._emails)
showard7cf9a9b2008-05-15 21:15:52 +0000238
showard542e8402008-09-19 20:16:18 +0000239 send_email(_email_from, _notify_email, subject, body)
jadmanski0afbb632008-06-06 21:10:57 +0000240 self._emails = []
showard7cf9a9b2008-05-15 21:15:52 +0000241
242email_manager = EmailNotificationManager()
243
244
showard63a34772008-08-18 19:32:50 +0000245class HostScheduler(object):
246 def _get_ready_hosts(self):
247 # avoid any host with a currently active queue entry against it
248 hosts = Host.fetch(
249 joins='LEFT JOIN host_queue_entries AS active_hqe '
250 'ON (hosts.id = active_hqe.host_id AND '
showardb1e51872008-10-07 11:08:18 +0000251 'active_hqe.active)',
showard63a34772008-08-18 19:32:50 +0000252 where="active_hqe.host_id IS NULL "
showardb1e51872008-10-07 11:08:18 +0000253 "AND NOT hosts.locked "
showard63a34772008-08-18 19:32:50 +0000254 "AND (hosts.status IS NULL OR hosts.status = 'Ready')")
255 return dict((host.id, host) for host in hosts)
256
257
258 @staticmethod
259 def _get_sql_id_list(id_list):
260 return ','.join(str(item_id) for item_id in id_list)
261
262
263 @classmethod
showard989f25d2008-10-01 11:38:11 +0000264 def _get_many2many_dict(cls, query, id_list, flip=False):
mbligh849a0f62008-08-28 20:12:19 +0000265 if not id_list:
266 return {}
showard63a34772008-08-18 19:32:50 +0000267 query %= cls._get_sql_id_list(id_list)
268 rows = _db.execute(query)
showard989f25d2008-10-01 11:38:11 +0000269 return cls._process_many2many_dict(rows, flip)
270
271
272 @staticmethod
273 def _process_many2many_dict(rows, flip=False):
showard63a34772008-08-18 19:32:50 +0000274 result = {}
275 for row in rows:
276 left_id, right_id = long(row[0]), long(row[1])
showard989f25d2008-10-01 11:38:11 +0000277 if flip:
278 left_id, right_id = right_id, left_id
showard63a34772008-08-18 19:32:50 +0000279 result.setdefault(left_id, set()).add(right_id)
280 return result
281
282
283 @classmethod
284 def _get_job_acl_groups(cls, job_ids):
285 query = """
286 SELECT jobs.id, acl_groups_users.acl_group_id
287 FROM jobs
288 INNER JOIN users ON users.login = jobs.owner
289 INNER JOIN acl_groups_users ON acl_groups_users.user_id = users.id
290 WHERE jobs.id IN (%s)
291 """
292 return cls._get_many2many_dict(query, job_ids)
293
294
295 @classmethod
296 def _get_job_ineligible_hosts(cls, job_ids):
297 query = """
298 SELECT job_id, host_id
299 FROM ineligible_host_queues
300 WHERE job_id IN (%s)
301 """
302 return cls._get_many2many_dict(query, job_ids)
303
304
305 @classmethod
showard989f25d2008-10-01 11:38:11 +0000306 def _get_job_dependencies(cls, job_ids):
307 query = """
308 SELECT job_id, label_id
309 FROM jobs_dependency_labels
310 WHERE job_id IN (%s)
311 """
312 return cls._get_many2many_dict(query, job_ids)
313
314
315 @classmethod
showard63a34772008-08-18 19:32:50 +0000316 def _get_host_acls(cls, host_ids):
317 query = """
318 SELECT host_id, acl_group_id
319 FROM acl_groups_hosts
320 WHERE host_id IN (%s)
321 """
322 return cls._get_many2many_dict(query, host_ids)
323
324
325 @classmethod
326 def _get_label_hosts(cls, host_ids):
showardfa8629c2008-11-04 16:51:23 +0000327 if not host_ids:
328 return {}, {}
showard63a34772008-08-18 19:32:50 +0000329 query = """
330 SELECT label_id, host_id
331 FROM hosts_labels
332 WHERE host_id IN (%s)
showard989f25d2008-10-01 11:38:11 +0000333 """ % cls._get_sql_id_list(host_ids)
334 rows = _db.execute(query)
335 labels_to_hosts = cls._process_many2many_dict(rows)
336 hosts_to_labels = cls._process_many2many_dict(rows, flip=True)
337 return labels_to_hosts, hosts_to_labels
338
339
340 @classmethod
341 def _get_labels(cls):
342 return dict((label.id, label) for label in Label.fetch())
showard63a34772008-08-18 19:32:50 +0000343
344
345 def refresh(self, pending_queue_entries):
346 self._hosts_available = self._get_ready_hosts()
347
348 relevant_jobs = [queue_entry.job_id
349 for queue_entry in pending_queue_entries]
350 self._job_acls = self._get_job_acl_groups(relevant_jobs)
351 self._ineligible_hosts = self._get_job_ineligible_hosts(relevant_jobs)
showard989f25d2008-10-01 11:38:11 +0000352 self._job_dependencies = self._get_job_dependencies(relevant_jobs)
showard63a34772008-08-18 19:32:50 +0000353
354 host_ids = self._hosts_available.keys()
355 self._host_acls = self._get_host_acls(host_ids)
showard989f25d2008-10-01 11:38:11 +0000356 self._label_hosts, self._host_labels = self._get_label_hosts(host_ids)
357
358 self._labels = self._get_labels()
showard63a34772008-08-18 19:32:50 +0000359
360
361 def _is_acl_accessible(self, host_id, queue_entry):
362 job_acls = self._job_acls.get(queue_entry.job_id, set())
363 host_acls = self._host_acls.get(host_id, set())
364 return len(host_acls.intersection(job_acls)) > 0
365
366
showard989f25d2008-10-01 11:38:11 +0000367 def _check_job_dependencies(self, job_dependencies, host_labels):
368 missing = job_dependencies - host_labels
369 return len(job_dependencies - host_labels) == 0
370
371
372 def _check_only_if_needed_labels(self, job_dependencies, host_labels,
373 queue_entry):
374 for label_id in host_labels:
375 label = self._labels[label_id]
376 if not label.only_if_needed:
377 # we don't care about non-only_if_needed labels
378 continue
379 if queue_entry.meta_host == label_id:
380 # if the label was requested in a metahost it's OK
381 continue
382 if label_id not in job_dependencies:
383 return False
384 return True
385
386
387 def _is_host_eligible_for_job(self, host_id, queue_entry):
388 job_dependencies = self._job_dependencies.get(queue_entry.job_id, set())
389 host_labels = self._host_labels.get(host_id, set())
mblighc993bee2008-10-03 03:42:34 +0000390
391 acl = self._is_acl_accessible(host_id, queue_entry)
392 deps = self._check_job_dependencies(job_dependencies, host_labels)
393 only_if = self._check_only_if_needed_labels(job_dependencies,
394 host_labels, queue_entry)
395 return acl and deps and only_if
showard989f25d2008-10-01 11:38:11 +0000396
397
showard63a34772008-08-18 19:32:50 +0000398 def _schedule_non_metahost(self, queue_entry):
showard989f25d2008-10-01 11:38:11 +0000399 if not self._is_host_eligible_for_job(queue_entry.host_id, queue_entry):
showard63a34772008-08-18 19:32:50 +0000400 return None
401 return self._hosts_available.pop(queue_entry.host_id, None)
402
403
404 def _is_host_usable(self, host_id):
405 if host_id not in self._hosts_available:
406 # host was already used during this scheduling cycle
407 return False
408 if self._hosts_available[host_id].invalid:
409 # Invalid hosts cannot be used for metahosts. They're included in
410 # the original query because they can be used by non-metahosts.
411 return False
412 return True
413
414
415 def _schedule_metahost(self, queue_entry):
416 label_id = queue_entry.meta_host
417 hosts_in_label = self._label_hosts.get(label_id, set())
418 ineligible_host_ids = self._ineligible_hosts.get(queue_entry.job_id,
419 set())
420
421 # must iterate over a copy so we can mutate the original while iterating
422 for host_id in list(hosts_in_label):
423 if not self._is_host_usable(host_id):
424 hosts_in_label.remove(host_id)
425 continue
426 if host_id in ineligible_host_ids:
427 continue
showard989f25d2008-10-01 11:38:11 +0000428 if not self._is_host_eligible_for_job(host_id, queue_entry):
showard63a34772008-08-18 19:32:50 +0000429 continue
430
431 hosts_in_label.remove(host_id)
432 return self._hosts_available.pop(host_id)
433 return None
434
435
436 def find_eligible_host(self, queue_entry):
437 if not queue_entry.meta_host:
438 return self._schedule_non_metahost(queue_entry)
439 return self._schedule_metahost(queue_entry)
440
441
mbligh36768f02008-02-22 18:28:33 +0000442class Dispatcher:
jadmanski0afbb632008-06-06 21:10:57 +0000443 autoserv_procs_cache = None
showard4c5374f2008-09-04 17:02:56 +0000444 max_running_processes = global_config.global_config.get_config_value(
jadmanski0afbb632008-06-06 21:10:57 +0000445 _global_config_section, 'max_running_jobs', type=int)
showard4c5374f2008-09-04 17:02:56 +0000446 max_processes_started_per_cycle = (
jadmanski0afbb632008-06-06 21:10:57 +0000447 global_config.global_config.get_config_value(
448 _global_config_section, 'max_jobs_started_per_cycle', type=int))
showard3bb499f2008-07-03 19:42:20 +0000449 clean_interval = (
450 global_config.global_config.get_config_value(
451 _global_config_section, 'clean_interval_minutes', type=int))
showard98863972008-10-29 21:14:56 +0000452 synch_job_start_timeout_minutes = (
453 global_config.global_config.get_config_value(
454 _global_config_section, 'synch_job_start_timeout_minutes',
455 type=int))
mbligh90a549d2008-03-25 23:52:34 +0000456
jadmanski0afbb632008-06-06 21:10:57 +0000457 def __init__(self):
458 self._agents = []
showard3bb499f2008-07-03 19:42:20 +0000459 self._last_clean_time = time.time()
showard63a34772008-08-18 19:32:50 +0000460 self._host_scheduler = HostScheduler()
mbligh36768f02008-02-22 18:28:33 +0000461
mbligh36768f02008-02-22 18:28:33 +0000462
jadmanski0afbb632008-06-06 21:10:57 +0000463 def do_initial_recovery(self, recover_hosts=True):
464 # always recover processes
465 self._recover_processes()
mblighbb421852008-03-11 22:36:16 +0000466
jadmanski0afbb632008-06-06 21:10:57 +0000467 if recover_hosts:
468 self._recover_hosts()
mbligh36768f02008-02-22 18:28:33 +0000469
470
jadmanski0afbb632008-06-06 21:10:57 +0000471 def tick(self):
472 Dispatcher.autoserv_procs_cache = None
showarda3ab0d52008-11-03 19:03:47 +0000473 self._run_cleanup_maybe()
jadmanski0afbb632008-06-06 21:10:57 +0000474 self._find_aborting()
475 self._schedule_new_jobs()
476 self._handle_agents()
jadmanski0afbb632008-06-06 21:10:57 +0000477 email_manager.send_queued_emails()
mbligh36768f02008-02-22 18:28:33 +0000478
showard97aed502008-11-04 02:01:24 +0000479
showarda3ab0d52008-11-03 19:03:47 +0000480 def _run_cleanup_maybe(self):
481 if self._last_clean_time + self.clean_interval * 60 < time.time():
482 print 'Running cleanup'
483 self._abort_timed_out_jobs()
484 self._abort_jobs_past_synch_start_timeout()
485 self._clear_inactive_blocks()
showardfa8629c2008-11-04 16:51:23 +0000486 self._check_for_db_inconsistencies()
showarda3ab0d52008-11-03 19:03:47 +0000487 self._last_clean_time = time.time()
488
mbligh36768f02008-02-22 18:28:33 +0000489
jadmanski0afbb632008-06-06 21:10:57 +0000490 def add_agent(self, agent):
491 self._agents.append(agent)
492 agent.dispatcher = self
mblighd5c95802008-03-05 00:33:46 +0000493
jadmanski0afbb632008-06-06 21:10:57 +0000494 # Find agent corresponding to the specified queue_entry
495 def get_agents(self, queue_entry):
496 res_agents = []
497 for agent in self._agents:
498 if queue_entry.id in agent.queue_entry_ids:
499 res_agents.append(agent)
500 return res_agents
mbligh36768f02008-02-22 18:28:33 +0000501
502
jadmanski0afbb632008-06-06 21:10:57 +0000503 def remove_agent(self, agent):
504 self._agents.remove(agent)
showardec113162008-05-08 00:52:49 +0000505
506
showard4c5374f2008-09-04 17:02:56 +0000507 def num_running_processes(self):
508 return sum(agent.num_processes for agent in self._agents
509 if agent.is_running())
mblighbb421852008-03-11 22:36:16 +0000510
511
jadmanski0afbb632008-06-06 21:10:57 +0000512 @classmethod
513 def find_autoservs(cls, orphans_only=False):
514 """\
515 Returns a dict mapping pids to command lines for root autoserv
516 processes. If orphans_only=True, return only processes that
517 have been orphaned (i.e. parent pid = 1).
518 """
519 if cls.autoserv_procs_cache is not None:
520 return cls.autoserv_procs_cache
521
522 proc = subprocess.Popen(
523 ['/bin/ps', 'x', '-o', 'pid,pgid,ppid,comm,args'],
524 stdout=subprocess.PIPE)
525 # split each line into the four columns output by ps
526 procs = [line.split(None, 4) for line in
527 proc.communicate()[0].splitlines()]
528 autoserv_procs = {}
529 for proc in procs:
530 # check ppid == 1 for orphans
531 if orphans_only and proc[2] != 1:
532 continue
533 # only root autoserv processes have pgid == pid
534 if (proc[3] == 'autoserv' and # comm
535 proc[1] == proc[0]): # pgid == pid
536 # map pid to args
537 autoserv_procs[int(proc[0])] = proc[4]
538 cls.autoserv_procs_cache = autoserv_procs
539 return autoserv_procs
mblighbb421852008-03-11 22:36:16 +0000540
541
jadmanski0afbb632008-06-06 21:10:57 +0000542 def recover_queue_entry(self, queue_entry, run_monitor):
543 job = queue_entry.job
544 if job.is_synchronous():
545 all_queue_entries = job.get_host_queue_entries()
546 else:
547 all_queue_entries = [queue_entry]
548 all_queue_entry_ids = [queue_entry.id for queue_entry
549 in all_queue_entries]
550 queue_task = RecoveryQueueTask(
551 job=queue_entry.job,
552 queue_entries=all_queue_entries,
553 run_monitor=run_monitor)
554 self.add_agent(Agent(tasks=[queue_task],
555 queue_entry_ids=all_queue_entry_ids))
mblighbb421852008-03-11 22:36:16 +0000556
557
jadmanski0afbb632008-06-06 21:10:57 +0000558 def _recover_processes(self):
559 orphans = self.find_autoservs(orphans_only=True)
mblighbb421852008-03-11 22:36:16 +0000560
jadmanski0afbb632008-06-06 21:10:57 +0000561 # first, recover running queue entries
562 rows = _db.execute("""SELECT * FROM host_queue_entries
563 WHERE status = 'Running'""")
564 queue_entries = [HostQueueEntry(row=i) for i in rows]
565 requeue_entries = []
566 recovered_entry_ids = set()
567 for queue_entry in queue_entries:
568 run_monitor = PidfileRunMonitor(
569 queue_entry.results_dir())
showard21baa452008-10-21 00:08:39 +0000570 if not run_monitor.has_pid():
jadmanski0afbb632008-06-06 21:10:57 +0000571 # autoserv apparently never got run, so requeue
572 requeue_entries.append(queue_entry)
573 continue
574 if queue_entry.id in recovered_entry_ids:
575 # synchronous job we've already recovered
576 continue
showard21baa452008-10-21 00:08:39 +0000577 pid = run_monitor.get_pid()
jadmanski0afbb632008-06-06 21:10:57 +0000578 print 'Recovering queue entry %d (pid %d)' % (
579 queue_entry.id, pid)
580 job = queue_entry.job
581 if job.is_synchronous():
582 for entry in job.get_host_queue_entries():
583 assert entry.active
584 recovered_entry_ids.add(entry.id)
585 self.recover_queue_entry(queue_entry,
586 run_monitor)
587 orphans.pop(pid, None)
mblighd5c95802008-03-05 00:33:46 +0000588
jadmanski0afbb632008-06-06 21:10:57 +0000589 # and requeue other active queue entries
590 rows = _db.execute("""SELECT * FROM host_queue_entries
591 WHERE active AND NOT complete
592 AND status != 'Running'
593 AND status != 'Pending'
594 AND status != 'Abort'
595 AND status != 'Aborting'""")
596 queue_entries = [HostQueueEntry(row=i) for i in rows]
597 for queue_entry in queue_entries + requeue_entries:
598 print 'Requeuing running QE %d' % queue_entry.id
599 queue_entry.clear_results_dir(dont_delete_files=True)
600 queue_entry.requeue()
mbligh90a549d2008-03-25 23:52:34 +0000601
602
jadmanski0afbb632008-06-06 21:10:57 +0000603 # now kill any remaining autoserv processes
604 for pid in orphans.keys():
605 print 'Killing orphan %d (%s)' % (pid, orphans[pid])
606 kill_autoserv(pid)
607
608 # recover aborting tasks
609 rebooting_host_ids = set()
610 rows = _db.execute("""SELECT * FROM host_queue_entries
611 WHERE status='Abort' or status='Aborting'""")
612 queue_entries = [HostQueueEntry(row=i) for i in rows]
613 for queue_entry in queue_entries:
614 print 'Recovering aborting QE %d' % queue_entry.id
showard1be97432008-10-17 15:30:45 +0000615 agent = queue_entry.abort()
616 self.add_agent(agent)
617 if queue_entry.get_host():
618 rebooting_host_ids.add(queue_entry.get_host().id)
jadmanski0afbb632008-06-06 21:10:57 +0000619
showard97aed502008-11-04 02:01:24 +0000620 self._recover_parsing_entries()
621
jadmanski0afbb632008-06-06 21:10:57 +0000622 # reverify hosts that were in the middle of verify, repair or
623 # reboot
624 self._reverify_hosts_where("""(status = 'Repairing' OR
625 status = 'Verifying' OR
626 status = 'Rebooting')""",
627 exclude_ids=rebooting_host_ids)
628
629 # finally, recover "Running" hosts with no active queue entries,
630 # although this should never happen
631 message = ('Recovering running host %s - this probably '
632 'indicates a scheduler bug')
633 self._reverify_hosts_where("""status = 'Running' AND
634 id NOT IN (SELECT host_id
635 FROM host_queue_entries
636 WHERE active)""",
637 print_message=message)
mblighbb421852008-03-11 22:36:16 +0000638
639
jadmanski0afbb632008-06-06 21:10:57 +0000640 def _reverify_hosts_where(self, where,
641 print_message='Reverifying host %s',
642 exclude_ids=set()):
643 rows = _db.execute('SELECT * FROM hosts WHERE locked = 0 AND '
644 'invalid = 0 AND ' + where)
645 hosts = [Host(row=i) for i in rows]
646 for host in hosts:
647 if host.id in exclude_ids:
648 continue
649 if print_message is not None:
650 print print_message % host.hostname
651 verify_task = VerifyTask(host = host)
652 self.add_agent(Agent(tasks = [verify_task]))
mbligh36768f02008-02-22 18:28:33 +0000653
654
showard97aed502008-11-04 02:01:24 +0000655 def _recover_parsing_entries(self):
656 # make sure there are no old parsers running
657 os.system('killall parse')
658
659 recovered_synch_jobs = set()
660 for entry in HostQueueEntry.fetch(where='status = "Parsing"'):
661 job = entry.job
662 if job.is_synchronous():
663 if job.id in recovered_synch_jobs:
664 continue
665 queue_entries = job.get_host_queue_entries()
666 recovered_synch_jobs.add(job.id)
667 else:
668 queue_entries = [entry]
669
670 reparse_task = FinalReparseTask(queue_entries)
671 self.add_agent(Agent([reparse_task]))
672
673
jadmanski0afbb632008-06-06 21:10:57 +0000674 def _recover_hosts(self):
675 # recover "Repair Failed" hosts
676 message = 'Reverifying dead host %s'
677 self._reverify_hosts_where("status = 'Repair Failed'",
678 print_message=message)
mbligh62ba2ed2008-04-30 17:09:25 +0000679
680
showard3bb499f2008-07-03 19:42:20 +0000681 def _abort_timed_out_jobs(self):
682 """
683 Aborts all jobs that have timed out and not completed
684 """
showarda3ab0d52008-11-03 19:03:47 +0000685 query = models.Job.objects.filter(hostqueueentry__complete=False).extra(
686 where=['created_on + INTERVAL timeout HOUR < NOW()'])
687 for job in query.distinct():
688 print 'Aborting job %d due to job timeout' % job.id
689 job.abort(None)
showard3bb499f2008-07-03 19:42:20 +0000690
691
showard98863972008-10-29 21:14:56 +0000692 def _abort_jobs_past_synch_start_timeout(self):
693 """
694 Abort synchronous jobs that are past the start timeout (from global
695 config) and are holding a machine that's in everyone.
696 """
697 timeout_delta = datetime.timedelta(
698 minutes=self.synch_job_start_timeout_minutes)
699 timeout_start = datetime.datetime.now() - timeout_delta
700 query = models.Job.objects.filter(
701 synch_type=models.Test.SynchType.SYNCHRONOUS,
702 created_on__lt=timeout_start,
703 hostqueueentry__status='Pending',
704 hostqueueentry__host__acl_group__name='Everyone')
705 for job in query.distinct():
706 print 'Aborting job %d due to start timeout' % job.id
707 job.abort(None)
708
709
jadmanski0afbb632008-06-06 21:10:57 +0000710 def _clear_inactive_blocks(self):
711 """
712 Clear out blocks for all completed jobs.
713 """
714 # this would be simpler using NOT IN (subquery), but MySQL
715 # treats all IN subqueries as dependent, so this optimizes much
716 # better
717 _db.execute("""
718 DELETE ihq FROM ineligible_host_queues ihq
showard4eaaf522008-06-06 22:28:07 +0000719 LEFT JOIN (SELECT DISTINCT job_id FROM host_queue_entries
jadmanski0afbb632008-06-06 21:10:57 +0000720 WHERE NOT complete) hqe
721 USING (job_id) WHERE hqe.job_id IS NULL""")
showard04c82c52008-05-29 19:38:12 +0000722
723
showardb95b1bd2008-08-15 18:11:04 +0000724 def _get_pending_queue_entries(self):
showard63a34772008-08-18 19:32:50 +0000725 # prioritize by job priority, then non-metahost over metahost, then FIFO
726 return list(HostQueueEntry.fetch(
727 where='NOT complete AND NOT active',
showard3dd6b882008-10-27 19:21:39 +0000728 order_by='priority DESC, meta_host, job_id'))
mbligh36768f02008-02-22 18:28:33 +0000729
730
jadmanski0afbb632008-06-06 21:10:57 +0000731 def _schedule_new_jobs(self):
732 print "finding work"
733
showard63a34772008-08-18 19:32:50 +0000734 queue_entries = self._get_pending_queue_entries()
735 if not queue_entries:
showardb95b1bd2008-08-15 18:11:04 +0000736 return
showardb95b1bd2008-08-15 18:11:04 +0000737
showard63a34772008-08-18 19:32:50 +0000738 self._host_scheduler.refresh(queue_entries)
showardb95b1bd2008-08-15 18:11:04 +0000739
showard63a34772008-08-18 19:32:50 +0000740 for queue_entry in queue_entries:
741 assigned_host = self._host_scheduler.find_eligible_host(queue_entry)
showardb95b1bd2008-08-15 18:11:04 +0000742 if not assigned_host:
jadmanski0afbb632008-06-06 21:10:57 +0000743 continue
showardb95b1bd2008-08-15 18:11:04 +0000744 self._run_queue_entry(queue_entry, assigned_host)
745
746
747 def _run_queue_entry(self, queue_entry, host):
748 agent = queue_entry.run(assigned_host=host)
showard9976ce92008-10-15 20:28:13 +0000749 # in some cases (synchronous jobs with run_verify=False), agent may be None
750 if agent:
751 self.add_agent(agent)
mblighd5c95802008-03-05 00:33:46 +0000752
753
jadmanski0afbb632008-06-06 21:10:57 +0000754 def _find_aborting(self):
755 num_aborted = 0
756 # Find jobs that are aborting
757 for entry in queue_entries_to_abort():
758 agents_to_abort = self.get_agents(entry)
showard1be97432008-10-17 15:30:45 +0000759 for agent in agents_to_abort:
760 self.remove_agent(agent)
761
762 agent = entry.abort(agents_to_abort)
763 self.add_agent(agent)
jadmanski0afbb632008-06-06 21:10:57 +0000764 num_aborted += 1
765 if num_aborted >= 50:
766 break
767
768
showard4c5374f2008-09-04 17:02:56 +0000769 def _can_start_agent(self, agent, num_running_processes,
770 num_started_this_cycle, have_reached_limit):
771 # always allow zero-process agents to run
772 if agent.num_processes == 0:
773 return True
774 # don't allow any nonzero-process agents to run after we've reached a
775 # limit (this avoids starvation of many-process agents)
776 if have_reached_limit:
777 return False
778 # total process throttling
779 if (num_running_processes + agent.num_processes >
780 self.max_running_processes):
781 return False
782 # if a single agent exceeds the per-cycle throttling, still allow it to
783 # run when it's the first agent in the cycle
784 if num_started_this_cycle == 0:
785 return True
786 # per-cycle throttling
787 if (num_started_this_cycle + agent.num_processes >
788 self.max_processes_started_per_cycle):
789 return False
790 return True
791
792
jadmanski0afbb632008-06-06 21:10:57 +0000793 def _handle_agents(self):
showard4c5374f2008-09-04 17:02:56 +0000794 num_running_processes = self.num_running_processes()
jadmanski0afbb632008-06-06 21:10:57 +0000795 num_started_this_cycle = 0
showard4c5374f2008-09-04 17:02:56 +0000796 have_reached_limit = False
797 # iterate over copy, so we can remove agents during iteration
798 for agent in list(self._agents):
799 if agent.is_done():
jadmanski0afbb632008-06-06 21:10:57 +0000800 print "agent finished"
showard4c5374f2008-09-04 17:02:56 +0000801 self._agents.remove(agent)
802 num_running_processes -= agent.num_processes
803 continue
804 if not agent.is_running():
805 if not self._can_start_agent(agent, num_running_processes,
806 num_started_this_cycle,
807 have_reached_limit):
808 have_reached_limit = True
809 continue
810 num_running_processes += agent.num_processes
811 num_started_this_cycle += agent.num_processes
812 agent.tick()
813 print num_running_processes, 'running processes'
mbligh36768f02008-02-22 18:28:33 +0000814
815
showardfa8629c2008-11-04 16:51:23 +0000816 def _check_for_db_inconsistencies(self):
817 query = models.HostQueueEntry.objects.filter(active=True, complete=True)
818 if query.count() != 0:
819 subject = ('%d queue entries found with active=complete=1'
820 % query.count())
821 message = '\n'.join(str(entry.get_object_dict())
822 for entry in query[:50])
823 if len(query) > 50:
824 message += '\n(truncated)\n'
825
826 print subject
827 email_manager.enqueue_notify_email(subject, message)
828
829
mbligh36768f02008-02-22 18:28:33 +0000830class RunMonitor(object):
jadmanski0afbb632008-06-06 21:10:57 +0000831 def __init__(self, cmd, nice_level = None, log_file = None):
832 self.nice_level = nice_level
833 self.log_file = log_file
834 self.cmd = cmd
mbligh36768f02008-02-22 18:28:33 +0000835
jadmanski0afbb632008-06-06 21:10:57 +0000836 def run(self):
837 if self.nice_level:
838 nice_cmd = ['nice','-n', str(self.nice_level)]
839 nice_cmd.extend(self.cmd)
840 self.cmd = nice_cmd
mbligh36768f02008-02-22 18:28:33 +0000841
jadmanski0afbb632008-06-06 21:10:57 +0000842 out_file = None
843 if self.log_file:
844 try:
845 os.makedirs(os.path.dirname(self.log_file))
846 except OSError, exc:
847 if exc.errno != errno.EEXIST:
848 log_stacktrace(
849 'Unexpected error creating logfile '
850 'directory for %s' % self.log_file)
851 try:
852 out_file = open(self.log_file, 'a')
853 out_file.write("\n%s\n" % ('*'*80))
854 out_file.write("%s> %s\n" %
855 (time.strftime("%X %x"),
856 self.cmd))
857 out_file.write("%s\n" % ('*'*80))
858 except (OSError, IOError):
859 log_stacktrace('Error opening log file %s' %
860 self.log_file)
mblighcadb3532008-04-15 17:46:26 +0000861
jadmanski0afbb632008-06-06 21:10:57 +0000862 if not out_file:
863 out_file = open('/dev/null', 'w')
mblighcadb3532008-04-15 17:46:26 +0000864
jadmanski0afbb632008-06-06 21:10:57 +0000865 in_devnull = open('/dev/null', 'r')
866 print "cmd = %s" % self.cmd
867 print "path = %s" % os.getcwd()
mbligh36768f02008-02-22 18:28:33 +0000868
jadmanski0afbb632008-06-06 21:10:57 +0000869 self.proc = subprocess.Popen(self.cmd, stdout=out_file,
870 stderr=subprocess.STDOUT,
871 stdin=in_devnull)
872 out_file.close()
873 in_devnull.close()
mbligh36768f02008-02-22 18:28:33 +0000874
875
jadmanski0afbb632008-06-06 21:10:57 +0000876 def get_pid(self):
877 return self.proc.pid
mblighbb421852008-03-11 22:36:16 +0000878
879
jadmanski0afbb632008-06-06 21:10:57 +0000880 def kill(self):
881 kill_autoserv(self.get_pid(), self.exit_code)
mblighbb421852008-03-11 22:36:16 +0000882
mbligh36768f02008-02-22 18:28:33 +0000883
jadmanski0afbb632008-06-06 21:10:57 +0000884 def exit_code(self):
885 return self.proc.poll()
mbligh36768f02008-02-22 18:28:33 +0000886
887
mblighbb421852008-03-11 22:36:16 +0000888class PidfileException(Exception):
jadmanski0afbb632008-06-06 21:10:57 +0000889 """\
890 Raised when there's some unexpected behavior with the pid file.
891 """
mblighbb421852008-03-11 22:36:16 +0000892
893
894class PidfileRunMonitor(RunMonitor):
showard21baa452008-10-21 00:08:39 +0000895 class PidfileState(object):
896 pid = None
897 exit_status = None
898 num_tests_failed = None
899
900 def reset(self):
901 self.pid = self.exit_status = self.all_tests_passed = None
902
903
jadmanski0afbb632008-06-06 21:10:57 +0000904 def __init__(self, results_dir, cmd=None, nice_level=None,
905 log_file=None):
906 self.results_dir = os.path.abspath(results_dir)
907 self.pid_file = os.path.join(results_dir, AUTOSERV_PID_FILE)
908 self.lost_process = False
909 self.start_time = time.time()
showard21baa452008-10-21 00:08:39 +0000910 self._state = self.PidfileState()
showardb376bc52008-06-13 20:48:45 +0000911 super(PidfileRunMonitor, self).__init__(cmd, nice_level, log_file)
mblighbb421852008-03-11 22:36:16 +0000912
913
showard21baa452008-10-21 00:08:39 +0000914 def has_pid(self):
915 self._get_pidfile_info()
916 return self._state.pid is not None
917
918
jadmanski0afbb632008-06-06 21:10:57 +0000919 def get_pid(self):
showard21baa452008-10-21 00:08:39 +0000920 self._get_pidfile_info()
921 assert self._state.pid is not None
922 return self._state.pid
mblighbb421852008-03-11 22:36:16 +0000923
924
jadmanski0afbb632008-06-06 21:10:57 +0000925 def _check_command_line(self, command_line, spacer=' ',
926 print_error=False):
927 results_dir_arg = spacer.join(('', '-r', self.results_dir, ''))
928 match = results_dir_arg in command_line
929 if print_error and not match:
930 print '%s not found in %s' % (repr(results_dir_arg),
931 repr(command_line))
932 return match
mbligh90a549d2008-03-25 23:52:34 +0000933
934
showard21baa452008-10-21 00:08:39 +0000935 def _check_proc_fs(self):
936 cmdline_path = os.path.join('/proc', str(self._state.pid), 'cmdline')
jadmanski0afbb632008-06-06 21:10:57 +0000937 try:
938 cmdline_file = open(cmdline_path, 'r')
939 cmdline = cmdline_file.read().strip()
940 cmdline_file.close()
941 except IOError:
942 return False
943 # /proc/.../cmdline has \x00 separating args
944 return self._check_command_line(cmdline, spacer='\x00',
945 print_error=True)
mblighbb421852008-03-11 22:36:16 +0000946
947
showard21baa452008-10-21 00:08:39 +0000948 def _read_pidfile(self):
949 self._state.reset()
jadmanski0afbb632008-06-06 21:10:57 +0000950 if not os.path.exists(self.pid_file):
showard21baa452008-10-21 00:08:39 +0000951 return
jadmanski0afbb632008-06-06 21:10:57 +0000952 file_obj = open(self.pid_file, 'r')
953 lines = file_obj.readlines()
954 file_obj.close()
showard3dd6b882008-10-27 19:21:39 +0000955 if not lines:
956 return
957 if len(lines) > 3:
showard21baa452008-10-21 00:08:39 +0000958 raise PidfileException('Corrupt pid file (%d lines) at %s:\n%s' %
959 (len(lines), self.pid_file, lines))
jadmanski0afbb632008-06-06 21:10:57 +0000960 try:
showard21baa452008-10-21 00:08:39 +0000961 self._state.pid = int(lines[0])
962 if len(lines) > 1:
963 self._state.exit_status = int(lines[1])
964 if len(lines) == 3:
965 self._state.num_tests_failed = int(lines[2])
966 else:
967 # maintain backwards-compatibility with two-line pidfiles
968 self._state.num_tests_failed = 0
jadmanski0afbb632008-06-06 21:10:57 +0000969 except ValueError, exc:
showard3dd6b882008-10-27 19:21:39 +0000970 raise PidfileException('Corrupt pid file: ' + str(exc.args))
mblighbb421852008-03-11 22:36:16 +0000971
mblighbb421852008-03-11 22:36:16 +0000972
jadmanski0afbb632008-06-06 21:10:57 +0000973 def _find_autoserv_proc(self):
974 autoserv_procs = Dispatcher.find_autoservs()
975 for pid, args in autoserv_procs.iteritems():
976 if self._check_command_line(args):
977 return pid, args
978 return None, None
mbligh90a549d2008-03-25 23:52:34 +0000979
980
showard21baa452008-10-21 00:08:39 +0000981 def _handle_pidfile_error(self, error, message=''):
982 message = error + '\nPid: %s\nPidfile: %s\n%s' % (self._state.pid,
983 self.pid_file,
984 message)
985 print message
986 email_manager.enqueue_notify_email(error, message)
987 if self._state.pid is not None:
988 pid = self._state.pid
989 else:
990 pid = 0
991 self.on_lost_process(pid)
992
993
994 def _get_pidfile_info_helper(self):
jadmanski0afbb632008-06-06 21:10:57 +0000995 if self.lost_process:
showard21baa452008-10-21 00:08:39 +0000996 return
mblighbb421852008-03-11 22:36:16 +0000997
showard21baa452008-10-21 00:08:39 +0000998 self._read_pidfile()
mblighbb421852008-03-11 22:36:16 +0000999
showard21baa452008-10-21 00:08:39 +00001000 if self._state.pid is None:
1001 self._handle_no_pid()
1002 return
mbligh90a549d2008-03-25 23:52:34 +00001003
showard21baa452008-10-21 00:08:39 +00001004 if self._state.exit_status is None:
jadmanski0afbb632008-06-06 21:10:57 +00001005 # double check whether or not autoserv is running
showard21baa452008-10-21 00:08:39 +00001006 proc_running = self._check_proc_fs()
jadmanski0afbb632008-06-06 21:10:57 +00001007 if proc_running:
showard21baa452008-10-21 00:08:39 +00001008 return
mbligh90a549d2008-03-25 23:52:34 +00001009
jadmanski0afbb632008-06-06 21:10:57 +00001010 # pid but no process - maybe process *just* exited
showard21baa452008-10-21 00:08:39 +00001011 self._read_pidfile()
1012 if self._state.exit_status is None:
jadmanski0afbb632008-06-06 21:10:57 +00001013 # autoserv exited without writing an exit code
1014 # to the pidfile
showard21baa452008-10-21 00:08:39 +00001015 self._handle_pidfile_error(
1016 'autoserv died without writing exit code')
mblighbb421852008-03-11 22:36:16 +00001017
showard21baa452008-10-21 00:08:39 +00001018
1019 def _get_pidfile_info(self):
1020 """\
1021 After completion, self._state will contain:
1022 pid=None, exit_status=None if autoserv has not yet run
1023 pid!=None, exit_status=None if autoserv is running
1024 pid!=None, exit_status!=None if autoserv has completed
1025 """
1026 try:
1027 self._get_pidfile_info_helper()
1028 except PidfileException, exc:
1029 self._handle_pidfile_error('Pidfile error', traceback.format_exc())
mblighbb421852008-03-11 22:36:16 +00001030
1031
jadmanski0afbb632008-06-06 21:10:57 +00001032 def _handle_no_pid(self):
1033 """\
1034 Called when no pidfile is found or no pid is in the pidfile.
1035 """
1036 # is autoserv running?
1037 pid, args = self._find_autoserv_proc()
1038 if pid is None:
1039 # no autoserv process running
1040 message = 'No pid found at ' + self.pid_file
1041 else:
1042 message = ("Process %d (%s) hasn't written pidfile %s" %
1043 (pid, args, self.pid_file))
mbligh90a549d2008-03-25 23:52:34 +00001044
jadmanski0afbb632008-06-06 21:10:57 +00001045 print message
1046 if time.time() - self.start_time > PIDFILE_TIMEOUT:
1047 email_manager.enqueue_notify_email(
1048 'Process has failed to write pidfile', message)
1049 if pid is not None:
1050 kill_autoserv(pid)
1051 else:
1052 pid = 0
1053 self.on_lost_process(pid)
showard21baa452008-10-21 00:08:39 +00001054 return
mbligh90a549d2008-03-25 23:52:34 +00001055
1056
jadmanski0afbb632008-06-06 21:10:57 +00001057 def on_lost_process(self, pid):
1058 """\
1059 Called when autoserv has exited without writing an exit status,
1060 or we've timed out waiting for autoserv to write a pid to the
1061 pidfile. In either case, we just return failure and the caller
1062 should signal some kind of warning.
mbligh90a549d2008-03-25 23:52:34 +00001063
jadmanski0afbb632008-06-06 21:10:57 +00001064 pid is unimportant here, as it shouldn't be used by anyone.
1065 """
1066 self.lost_process = True
showard21baa452008-10-21 00:08:39 +00001067 self._state.pid = pid
1068 self._state.exit_status = 1
1069 self._state.num_tests_failed = 0
mbligh90a549d2008-03-25 23:52:34 +00001070
1071
jadmanski0afbb632008-06-06 21:10:57 +00001072 def exit_code(self):
showard21baa452008-10-21 00:08:39 +00001073 self._get_pidfile_info()
1074 return self._state.exit_status
1075
1076
1077 def num_tests_failed(self):
1078 self._get_pidfile_info()
1079 assert self._state.num_tests_failed is not None
1080 return self._state.num_tests_failed
mblighbb421852008-03-11 22:36:16 +00001081
1082
mbligh36768f02008-02-22 18:28:33 +00001083class Agent(object):
showard4c5374f2008-09-04 17:02:56 +00001084 def __init__(self, tasks, queue_entry_ids=[], num_processes=1):
jadmanski0afbb632008-06-06 21:10:57 +00001085 self.active_task = None
1086 self.queue = Queue.Queue(0)
1087 self.dispatcher = None
1088 self.queue_entry_ids = queue_entry_ids
showard4c5374f2008-09-04 17:02:56 +00001089 self.num_processes = num_processes
jadmanski0afbb632008-06-06 21:10:57 +00001090
1091 for task in tasks:
1092 self.add_task(task)
mbligh36768f02008-02-22 18:28:33 +00001093
1094
jadmanski0afbb632008-06-06 21:10:57 +00001095 def add_task(self, task):
1096 self.queue.put_nowait(task)
1097 task.agent = self
mbligh36768f02008-02-22 18:28:33 +00001098
1099
jadmanski0afbb632008-06-06 21:10:57 +00001100 def tick(self):
showard21baa452008-10-21 00:08:39 +00001101 while not self.is_done():
1102 if self.active_task and not self.active_task.is_done():
1103 self.active_task.poll()
1104 if not self.active_task.is_done():
1105 return
1106 self._next_task()
mbligh36768f02008-02-22 18:28:33 +00001107
1108
jadmanski0afbb632008-06-06 21:10:57 +00001109 def _next_task(self):
1110 print "agent picking task"
1111 if self.active_task:
1112 assert self.active_task.is_done()
mbligh36768f02008-02-22 18:28:33 +00001113
jadmanski0afbb632008-06-06 21:10:57 +00001114 if not self.active_task.success:
1115 self.on_task_failure()
mblighe2586682008-02-29 22:45:46 +00001116
jadmanski0afbb632008-06-06 21:10:57 +00001117 self.active_task = None
1118 if not self.is_done():
1119 self.active_task = self.queue.get_nowait()
1120 if self.active_task:
1121 self.active_task.start()
mbligh36768f02008-02-22 18:28:33 +00001122
1123
jadmanski0afbb632008-06-06 21:10:57 +00001124 def on_task_failure(self):
1125 self.queue = Queue.Queue(0)
1126 for task in self.active_task.failure_tasks:
1127 self.add_task(task)
mbligh16c722d2008-03-05 00:58:44 +00001128
mblighe2586682008-02-29 22:45:46 +00001129
showard4c5374f2008-09-04 17:02:56 +00001130 def is_running(self):
jadmanski0afbb632008-06-06 21:10:57 +00001131 return self.active_task is not None
showardec113162008-05-08 00:52:49 +00001132
1133
jadmanski0afbb632008-06-06 21:10:57 +00001134 def is_done(self):
1135 return self.active_task == None and self.queue.empty()
mbligh36768f02008-02-22 18:28:33 +00001136
1137
jadmanski0afbb632008-06-06 21:10:57 +00001138 def start(self):
1139 assert self.dispatcher
mbligh36768f02008-02-22 18:28:33 +00001140
jadmanski0afbb632008-06-06 21:10:57 +00001141 self._next_task()
mbligh36768f02008-02-22 18:28:33 +00001142
jadmanski0afbb632008-06-06 21:10:57 +00001143
mbligh36768f02008-02-22 18:28:33 +00001144class AgentTask(object):
jadmanski0afbb632008-06-06 21:10:57 +00001145 def __init__(self, cmd, failure_tasks = []):
1146 self.done = False
1147 self.failure_tasks = failure_tasks
1148 self.started = False
1149 self.cmd = cmd
1150 self.task = None
1151 self.agent = None
1152 self.monitor = None
1153 self.success = None
mbligh36768f02008-02-22 18:28:33 +00001154
1155
jadmanski0afbb632008-06-06 21:10:57 +00001156 def poll(self):
1157 print "poll"
1158 if self.monitor:
1159 self.tick(self.monitor.exit_code())
1160 else:
1161 self.finished(False)
mbligh36768f02008-02-22 18:28:33 +00001162
1163
jadmanski0afbb632008-06-06 21:10:57 +00001164 def tick(self, exit_code):
1165 if exit_code==None:
1166 return
1167# print "exit_code was %d" % exit_code
1168 if exit_code == 0:
1169 success = True
1170 else:
1171 success = False
mbligh36768f02008-02-22 18:28:33 +00001172
jadmanski0afbb632008-06-06 21:10:57 +00001173 self.finished(success)
mbligh36768f02008-02-22 18:28:33 +00001174
1175
jadmanski0afbb632008-06-06 21:10:57 +00001176 def is_done(self):
1177 return self.done
mbligh36768f02008-02-22 18:28:33 +00001178
1179
jadmanski0afbb632008-06-06 21:10:57 +00001180 def finished(self, success):
1181 self.done = True
1182 self.success = success
1183 self.epilog()
mbligh36768f02008-02-22 18:28:33 +00001184
1185
jadmanski0afbb632008-06-06 21:10:57 +00001186 def prolog(self):
1187 pass
mblighd64e5702008-04-04 21:39:28 +00001188
1189
jadmanski0afbb632008-06-06 21:10:57 +00001190 def create_temp_resultsdir(self, suffix=''):
1191 self.temp_results_dir = tempfile.mkdtemp(suffix=suffix)
mblighd64e5702008-04-04 21:39:28 +00001192
mbligh36768f02008-02-22 18:28:33 +00001193
jadmanski0afbb632008-06-06 21:10:57 +00001194 def cleanup(self):
1195 if (hasattr(self, 'temp_results_dir') and
1196 os.path.exists(self.temp_results_dir)):
1197 shutil.rmtree(self.temp_results_dir)
mbligh36768f02008-02-22 18:28:33 +00001198
1199
jadmanski0afbb632008-06-06 21:10:57 +00001200 def epilog(self):
1201 self.cleanup()
mbligh36768f02008-02-22 18:28:33 +00001202
1203
jadmanski0afbb632008-06-06 21:10:57 +00001204 def start(self):
1205 assert self.agent
1206
1207 if not self.started:
1208 self.prolog()
1209 self.run()
1210
1211 self.started = True
1212
1213
1214 def abort(self):
1215 if self.monitor:
1216 self.monitor.kill()
1217 self.done = True
1218 self.cleanup()
1219
1220
1221 def run(self):
1222 if self.cmd:
1223 print "agent starting monitor"
1224 log_file = None
showard97aed502008-11-04 02:01:24 +00001225 if hasattr(self, 'log_file'):
1226 log_file = self.log_file
1227 elif hasattr(self, 'host'):
jadmanski0afbb632008-06-06 21:10:57 +00001228 log_file = os.path.join(RESULTS_DIR, 'hosts',
1229 self.host.hostname)
1230 self.monitor = RunMonitor(
showard97aed502008-11-04 02:01:24 +00001231 self.cmd, nice_level=AUTOSERV_NICE_LEVEL, log_file=log_file)
jadmanski0afbb632008-06-06 21:10:57 +00001232 self.monitor.run()
mbligh36768f02008-02-22 18:28:33 +00001233
1234
1235class RepairTask(AgentTask):
jadmanski0afbb632008-06-06 21:10:57 +00001236 def __init__(self, host, fail_queue_entry=None):
1237 """\
1238 fail_queue_entry: queue entry to mark failed if this repair
1239 fails.
1240 """
jadmanskifb7cfb12008-07-09 14:13:21 +00001241 protection = host_protections.Protection.get_string(host.protection)
jadmanski542537f2008-07-24 14:14:56 +00001242 # normalize the protection name
1243 protection = host_protections.Protection.get_attr_name(protection)
jadmanski0afbb632008-06-06 21:10:57 +00001244 self.create_temp_resultsdir('.repair')
1245 cmd = [_autoserv_path , '-R', '-m', host.hostname,
jadmanskifb7cfb12008-07-09 14:13:21 +00001246 '-r', self.temp_results_dir, '--host-protection', protection]
jadmanski0afbb632008-06-06 21:10:57 +00001247 self.host = host
1248 self.fail_queue_entry = fail_queue_entry
1249 super(RepairTask, self).__init__(cmd)
mblighe2586682008-02-29 22:45:46 +00001250
mbligh36768f02008-02-22 18:28:33 +00001251
jadmanski0afbb632008-06-06 21:10:57 +00001252 def prolog(self):
1253 print "repair_task starting"
1254 self.host.set_status('Repairing')
mbligh36768f02008-02-22 18:28:33 +00001255
1256
jadmanski0afbb632008-06-06 21:10:57 +00001257 def epilog(self):
1258 super(RepairTask, self).epilog()
1259 if self.success:
1260 self.host.set_status('Ready')
1261 else:
1262 self.host.set_status('Repair Failed')
1263 if self.fail_queue_entry:
1264 self.fail_queue_entry.handle_host_failure()
mbligh36768f02008-02-22 18:28:33 +00001265
1266
1267class VerifyTask(AgentTask):
showard9976ce92008-10-15 20:28:13 +00001268 def __init__(self, queue_entry=None, host=None):
jadmanski0afbb632008-06-06 21:10:57 +00001269 assert bool(queue_entry) != bool(host)
mbligh36768f02008-02-22 18:28:33 +00001270
jadmanski0afbb632008-06-06 21:10:57 +00001271 self.host = host or queue_entry.host
1272 self.queue_entry = queue_entry
mbligh36768f02008-02-22 18:28:33 +00001273
jadmanski0afbb632008-06-06 21:10:57 +00001274 self.create_temp_resultsdir('.verify')
showard3d9899a2008-07-31 02:11:58 +00001275
showard9976ce92008-10-15 20:28:13 +00001276 cmd = [_autoserv_path,'-v','-m',self.host.hostname, '-r', self.temp_results_dir]
mbligh36768f02008-02-22 18:28:33 +00001277
jadmanski0afbb632008-06-06 21:10:57 +00001278 fail_queue_entry = None
1279 if queue_entry and not queue_entry.meta_host:
1280 fail_queue_entry = queue_entry
1281 failure_tasks = [RepairTask(self.host, fail_queue_entry)]
mblighe2586682008-02-29 22:45:46 +00001282
jadmanski0afbb632008-06-06 21:10:57 +00001283 super(VerifyTask, self).__init__(cmd,
1284 failure_tasks=failure_tasks)
mblighe2586682008-02-29 22:45:46 +00001285
1286
jadmanski0afbb632008-06-06 21:10:57 +00001287 def prolog(self):
1288 print "starting verify on %s" % (self.host.hostname)
1289 if self.queue_entry:
1290 self.queue_entry.set_status('Verifying')
1291 self.queue_entry.clear_results_dir(
1292 self.queue_entry.verify_results_dir())
1293 self.host.set_status('Verifying')
mbligh36768f02008-02-22 18:28:33 +00001294
1295
jadmanski0afbb632008-06-06 21:10:57 +00001296 def cleanup(self):
1297 if not os.path.exists(self.temp_results_dir):
1298 return
1299 if self.queue_entry and (self.success or
1300 not self.queue_entry.meta_host):
1301 self.move_results()
1302 super(VerifyTask, self).cleanup()
mblighd64e5702008-04-04 21:39:28 +00001303
1304
jadmanski0afbb632008-06-06 21:10:57 +00001305 def epilog(self):
1306 super(VerifyTask, self).epilog()
mbligh36768f02008-02-22 18:28:33 +00001307
jadmanski0afbb632008-06-06 21:10:57 +00001308 if self.success:
1309 self.host.set_status('Ready')
1310 elif self.queue_entry:
1311 self.queue_entry.requeue()
mbligh36768f02008-02-22 18:28:33 +00001312
1313
jadmanski0afbb632008-06-06 21:10:57 +00001314 def move_results(self):
1315 assert self.queue_entry is not None
1316 target_dir = self.queue_entry.verify_results_dir()
1317 if not os.path.exists(target_dir):
1318 os.makedirs(target_dir)
1319 files = os.listdir(self.temp_results_dir)
1320 for filename in files:
1321 if filename == AUTOSERV_PID_FILE:
1322 continue
1323 self.force_move(os.path.join(self.temp_results_dir,
1324 filename),
1325 os.path.join(target_dir, filename))
mbligh36768f02008-02-22 18:28:33 +00001326
1327
jadmanski0afbb632008-06-06 21:10:57 +00001328 @staticmethod
1329 def force_move(source, dest):
1330 """\
1331 Replacement for shutil.move() that will delete the destination
1332 if it exists, even if it's a directory.
1333 """
1334 if os.path.exists(dest):
showardfa8629c2008-11-04 16:51:23 +00001335 warning = 'Warning: removing existing destination file ' + dest
1336 print warning
1337 email_manager.enqueue_notify_email(warning, warning)
jadmanski0afbb632008-06-06 21:10:57 +00001338 remove_file_or_dir(dest)
1339 shutil.move(source, dest)
mblighe2586682008-02-29 22:45:46 +00001340
1341
mblighdffd6372008-02-29 22:47:33 +00001342class VerifySynchronousTask(VerifyTask):
jadmanski0afbb632008-06-06 21:10:57 +00001343 def epilog(self):
1344 super(VerifySynchronousTask, self).epilog()
1345 if self.success:
1346 if self.queue_entry.job.num_complete() > 0:
1347 # some other entry failed verify, and we've
1348 # already been marked as stopped
1349 return
mblighdffd6372008-02-29 22:47:33 +00001350
showardb2e2c322008-10-14 17:33:55 +00001351 agent = self.queue_entry.on_pending()
1352 if agent:
jadmanski0afbb632008-06-06 21:10:57 +00001353 self.agent.dispatcher.add_agent(agent)
mblighe2586682008-02-29 22:45:46 +00001354
showardb2e2c322008-10-14 17:33:55 +00001355
mbligh36768f02008-02-22 18:28:33 +00001356class QueueTask(AgentTask):
jadmanski0afbb632008-06-06 21:10:57 +00001357 def __init__(self, job, queue_entries, cmd):
1358 super(QueueTask, self).__init__(cmd)
1359 self.job = job
1360 self.queue_entries = queue_entries
mbligh36768f02008-02-22 18:28:33 +00001361
1362
jadmanski0afbb632008-06-06 21:10:57 +00001363 @staticmethod
showardd8e548a2008-09-09 03:04:57 +00001364 def _write_keyval(keyval_dir, field, value, keyval_filename='keyval'):
1365 key_path = os.path.join(keyval_dir, keyval_filename)
jadmanski0afbb632008-06-06 21:10:57 +00001366 keyval_file = open(key_path, 'a')
showardd8e548a2008-09-09 03:04:57 +00001367 print >> keyval_file, '%s=%s' % (field, str(value))
jadmanski0afbb632008-06-06 21:10:57 +00001368 keyval_file.close()
mbligh36768f02008-02-22 18:28:33 +00001369
1370
showardd8e548a2008-09-09 03:04:57 +00001371 def _host_keyval_dir(self):
1372 return os.path.join(self.results_dir(), 'host_keyvals')
1373
1374
1375 def _write_host_keyval(self, host):
1376 labels = ','.join(host.labels())
1377 self._write_keyval(self._host_keyval_dir(), 'labels', labels,
1378 keyval_filename=host.hostname)
1379
1380 def _create_host_keyval_dir(self):
1381 directory = self._host_keyval_dir()
1382 if not os.path.exists(directory):
1383 os.makedirs(directory)
1384
1385
jadmanski0afbb632008-06-06 21:10:57 +00001386 def results_dir(self):
1387 return self.queue_entries[0].results_dir()
mblighbb421852008-03-11 22:36:16 +00001388
1389
jadmanski0afbb632008-06-06 21:10:57 +00001390 def run(self):
1391 """\
1392 Override AgentTask.run() so we can use a PidfileRunMonitor.
1393 """
1394 self.monitor = PidfileRunMonitor(self.results_dir(),
1395 cmd=self.cmd,
1396 nice_level=AUTOSERV_NICE_LEVEL)
1397 self.monitor.run()
mblighbb421852008-03-11 22:36:16 +00001398
1399
jadmanski0afbb632008-06-06 21:10:57 +00001400 def prolog(self):
1401 # write some job timestamps into the job keyval file
1402 queued = time.mktime(self.job.created_on.timetuple())
1403 started = time.time()
showardd8e548a2008-09-09 03:04:57 +00001404 self._write_keyval(self.results_dir(), "job_queued", int(queued))
1405 self._write_keyval(self.results_dir(), "job_started", int(started))
1406 self._create_host_keyval_dir()
jadmanski0afbb632008-06-06 21:10:57 +00001407 for queue_entry in self.queue_entries:
showardd8e548a2008-09-09 03:04:57 +00001408 self._write_host_keyval(queue_entry.host)
jadmanski0afbb632008-06-06 21:10:57 +00001409 print "starting queue_task on %s/%s" % (queue_entry.host.hostname, queue_entry.id)
1410 queue_entry.set_status('Running')
1411 queue_entry.host.set_status('Running')
showard21baa452008-10-21 00:08:39 +00001412 queue_entry.host.update_field('dirty', 1)
jadmanski0afbb632008-06-06 21:10:57 +00001413 if (not self.job.is_synchronous() and
1414 self.job.num_machines() > 1):
1415 assert len(self.queue_entries) == 1
1416 self.job.write_to_machines_file(self.queue_entries[0])
mbligh36768f02008-02-22 18:28:33 +00001417
1418
showard97aed502008-11-04 02:01:24 +00001419 def _finish_task(self, success):
jadmanski0afbb632008-06-06 21:10:57 +00001420 # write out the finished time into the results keyval
1421 finished = time.time()
jadmanskif7fa2cc2008-10-01 14:13:23 +00001422 self._write_keyval(self.results_dir(), "job_finished", int(finished))
jadmanskic2ac77f2008-05-16 21:44:04 +00001423
jadmanski0afbb632008-06-06 21:10:57 +00001424 # parse the results of the job
showard97aed502008-11-04 02:01:24 +00001425 reparse_task = FinalReparseTask(self.queue_entries)
1426 self.agent.dispatcher.add_agent(Agent([reparse_task]))
jadmanskif7fa2cc2008-10-01 14:13:23 +00001427
1428
1429 def _log_abort(self):
1430 # build up sets of all the aborted_by and aborted_on values
1431 aborted_by, aborted_on = set(), set()
1432 for queue_entry in self.queue_entries:
1433 if queue_entry.aborted_by:
1434 aborted_by.add(queue_entry.aborted_by)
1435 t = int(time.mktime(queue_entry.aborted_on.timetuple()))
1436 aborted_on.add(t)
1437
1438 # extract some actual, unique aborted by value and write it out
1439 assert len(aborted_by) <= 1
1440 if len(aborted_by) == 1:
1441 results_dir = self.results_dir()
1442 self._write_keyval(results_dir, "aborted_by", aborted_by.pop())
1443 self._write_keyval(results_dir, "aborted_on", max(aborted_on))
jadmanskic2ac77f2008-05-16 21:44:04 +00001444
1445
jadmanski0afbb632008-06-06 21:10:57 +00001446 def abort(self):
1447 super(QueueTask, self).abort()
jadmanskif7fa2cc2008-10-01 14:13:23 +00001448 self._log_abort()
showard97aed502008-11-04 02:01:24 +00001449 self._finish_task(False)
jadmanskic2ac77f2008-05-16 21:44:04 +00001450
1451
showard21baa452008-10-21 00:08:39 +00001452 def _reboot_hosts(self):
1453 reboot_after = self.job.reboot_after
1454 do_reboot = False
showard0fc38302008-10-23 00:44:07 +00001455 if reboot_after == models.RebootAfter.ALWAYS:
showard21baa452008-10-21 00:08:39 +00001456 do_reboot = True
showard0fc38302008-10-23 00:44:07 +00001457 elif reboot_after == models.RebootAfter.IF_ALL_TESTS_PASSED:
showard21baa452008-10-21 00:08:39 +00001458 num_tests_failed = self.monitor.num_tests_failed()
1459 do_reboot = (self.success and num_tests_failed == 0)
1460
1461 if do_reboot:
1462 for queue_entry in self.queue_entries:
showardfa8629c2008-11-04 16:51:23 +00001463 # don't pass the queue entry to the RebootTask. if the reboot
1464 # fails, the job doesn't care -- it's over.
1465 reboot_task = RebootTask(host=queue_entry.get_host())
showard21baa452008-10-21 00:08:39 +00001466 self.agent.dispatcher.add_agent(Agent([reboot_task]))
1467
1468
jadmanski0afbb632008-06-06 21:10:57 +00001469 def epilog(self):
1470 super(QueueTask, self).epilog()
jadmanski0afbb632008-06-06 21:10:57 +00001471 for queue_entry in self.queue_entries:
showard97aed502008-11-04 02:01:24 +00001472 # set status to PARSING here so queue entry is marked complete
1473 queue_entry.set_status(models.HostQueueEntry.Status.PARSING)
jadmanski0afbb632008-06-06 21:10:57 +00001474 queue_entry.host.set_status('Ready')
mbligh36768f02008-02-22 18:28:33 +00001475
showard97aed502008-11-04 02:01:24 +00001476 self._finish_task(self.success)
showard21baa452008-10-21 00:08:39 +00001477 self._reboot_hosts()
mblighbb421852008-03-11 22:36:16 +00001478
showard97aed502008-11-04 02:01:24 +00001479 print "queue_task finished with succes=%s" % self.success
mbligh36768f02008-02-22 18:28:33 +00001480
1481
mblighbb421852008-03-11 22:36:16 +00001482class RecoveryQueueTask(QueueTask):
jadmanski0afbb632008-06-06 21:10:57 +00001483 def __init__(self, job, queue_entries, run_monitor):
1484 super(RecoveryQueueTask, self).__init__(job,
1485 queue_entries, cmd=None)
1486 self.run_monitor = run_monitor
mblighbb421852008-03-11 22:36:16 +00001487
1488
jadmanski0afbb632008-06-06 21:10:57 +00001489 def run(self):
1490 self.monitor = self.run_monitor
mblighbb421852008-03-11 22:36:16 +00001491
1492
jadmanski0afbb632008-06-06 21:10:57 +00001493 def prolog(self):
1494 # recovering an existing process - don't do prolog
1495 pass
mblighbb421852008-03-11 22:36:16 +00001496
1497
mbligh36768f02008-02-22 18:28:33 +00001498class RebootTask(AgentTask):
showardfa8629c2008-11-04 16:51:23 +00001499 def __init__(self, host=None, queue_entry=None):
1500 assert bool(host) ^ bool(queue_entry)
1501 if queue_entry:
1502 host = queue_entry.get_host()
jadmanski0afbb632008-06-06 21:10:57 +00001503
1504 # Current implementation of autoserv requires control file
1505 # to be passed on reboot action request. TODO: remove when no
1506 # longer appropriate.
1507 self.create_temp_resultsdir('.reboot')
1508 self.cmd = [_autoserv_path, '-b', '-m', host.hostname,
1509 '-r', self.temp_results_dir, '/dev/null']
showardfa8629c2008-11-04 16:51:23 +00001510 self.queue_entry = queue_entry
jadmanski0afbb632008-06-06 21:10:57 +00001511 self.host = host
showardfa8629c2008-11-04 16:51:23 +00001512 repair_task = RepairTask(host, fail_queue_entry=queue_entry)
1513 super(RebootTask, self).__init__(self.cmd, failure_tasks=[repair_task])
mbligh16c722d2008-03-05 00:58:44 +00001514
mblighd5c95802008-03-05 00:33:46 +00001515
jadmanski0afbb632008-06-06 21:10:57 +00001516 def prolog(self):
1517 print "starting reboot task for host: %s" % self.host.hostname
1518 self.host.set_status("Rebooting")
mblighd5c95802008-03-05 00:33:46 +00001519
mblighd5c95802008-03-05 00:33:46 +00001520
showard21baa452008-10-21 00:08:39 +00001521 def epilog(self):
1522 super(RebootTask, self).epilog()
showard21baa452008-10-21 00:08:39 +00001523 if self.success:
showardfa8629c2008-11-04 16:51:23 +00001524 self.host.set_status('Ready')
showard21baa452008-10-21 00:08:39 +00001525 self.host.update_field('dirty', 0)
showardfa8629c2008-11-04 16:51:23 +00001526 elif self.queue_entry:
1527 self.queue_entry.requeue()
showard21baa452008-10-21 00:08:39 +00001528
1529
mblighd5c95802008-03-05 00:33:46 +00001530class AbortTask(AgentTask):
jadmanski0afbb632008-06-06 21:10:57 +00001531 def __init__(self, queue_entry, agents_to_abort):
1532 self.queue_entry = queue_entry
1533 self.agents_to_abort = agents_to_abort
jadmanski0afbb632008-06-06 21:10:57 +00001534 super(AbortTask, self).__init__('')
mbligh36768f02008-02-22 18:28:33 +00001535
1536
jadmanski0afbb632008-06-06 21:10:57 +00001537 def prolog(self):
1538 print "starting abort on host %s, job %s" % (
1539 self.queue_entry.host_id, self.queue_entry.job_id)
mbligh36768f02008-02-22 18:28:33 +00001540
mblighd64e5702008-04-04 21:39:28 +00001541
jadmanski0afbb632008-06-06 21:10:57 +00001542 def epilog(self):
1543 super(AbortTask, self).epilog()
1544 self.queue_entry.set_status('Aborted')
1545 self.success = True
1546
1547
1548 def run(self):
1549 for agent in self.agents_to_abort:
1550 if (agent.active_task):
1551 agent.active_task.abort()
mbligh36768f02008-02-22 18:28:33 +00001552
1553
showard97aed502008-11-04 02:01:24 +00001554class FinalReparseTask(AgentTask):
1555 MAX_PARSE_PROCESSES = (
1556 global_config.global_config.get_config_value(
1557 _global_config_section, 'max_parse_processes', type=int))
1558 _num_running_parses = 0
1559
1560 def __init__(self, queue_entries):
1561 self._queue_entries = queue_entries
1562 self._parse_started = False
1563
1564 assert len(queue_entries) > 0
1565 queue_entry = queue_entries[0]
1566 job = queue_entry.job
1567
1568 flags = []
1569 if job.is_synchronous():
1570 assert len(queue_entries) == job.num_machines()
1571 else:
1572 assert len(queue_entries) == 1
1573 if job.num_machines() > 1:
1574 flags = ['-l', '2']
1575
1576 if _testing_mode:
1577 self.cmd = 'true'
1578 return
1579
1580 self._results_dir = queue_entry.results_dir()
1581 self.log_file = os.path.abspath(os.path.join(self._results_dir,
1582 '.parse.log'))
1583 super(FinalReparseTask, self).__init__(
1584 cmd=self.generate_parse_command(flags=flags))
1585
1586
1587 @classmethod
1588 def _increment_running_parses(cls):
1589 cls._num_running_parses += 1
1590
1591
1592 @classmethod
1593 def _decrement_running_parses(cls):
1594 cls._num_running_parses -= 1
1595
1596
1597 @classmethod
1598 def _can_run_new_parse(cls):
1599 return cls._num_running_parses < cls.MAX_PARSE_PROCESSES
1600
1601
1602 def prolog(self):
1603 super(FinalReparseTask, self).prolog()
1604 for queue_entry in self._queue_entries:
1605 queue_entry.set_status(models.HostQueueEntry.Status.PARSING)
1606
1607
1608 def epilog(self):
1609 super(FinalReparseTask, self).epilog()
1610 final_status = self._determine_final_status()
1611 for queue_entry in self._queue_entries:
1612 queue_entry.set_status(final_status)
1613
1614
1615 def _determine_final_status(self):
1616 # use a PidfileRunMonitor to read the autoserv exit status
1617 monitor = PidfileRunMonitor(self._results_dir)
1618 if monitor.exit_code() == 0:
1619 return models.HostQueueEntry.Status.COMPLETED
1620 return models.HostQueueEntry.Status.FAILED
1621
1622
1623 def generate_parse_command(self, flags=[]):
1624 parse = os.path.abspath(os.path.join(AUTOTEST_TKO_DIR, 'parse'))
1625 return [parse] + flags + ['-r', '-o', self._results_dir]
1626
1627
1628 def poll(self):
1629 # override poll to keep trying to start until the parse count goes down
1630 # and we can, at which point we revert to default behavior
1631 if self._parse_started:
1632 super(FinalReparseTask, self).poll()
1633 else:
1634 self._try_starting_parse()
1635
1636
1637 def run(self):
1638 # override run() to not actually run unless we can
1639 self._try_starting_parse()
1640
1641
1642 def _try_starting_parse(self):
1643 if not self._can_run_new_parse():
1644 return
1645 # actually run the parse command
1646 super(FinalReparseTask, self).run()
1647 self._increment_running_parses()
1648 self._parse_started = True
1649
1650
1651 def finished(self, success):
1652 super(FinalReparseTask, self).finished(success)
1653 self._decrement_running_parses()
1654
1655
mbligh36768f02008-02-22 18:28:33 +00001656class DBObject(object):
jadmanski0afbb632008-06-06 21:10:57 +00001657 def __init__(self, id=None, row=None, new_record=False):
1658 assert (bool(id) != bool(row))
mbligh36768f02008-02-22 18:28:33 +00001659
jadmanski0afbb632008-06-06 21:10:57 +00001660 self.__table = self._get_table()
1661 fields = self._fields()
mbligh36768f02008-02-22 18:28:33 +00001662
jadmanski0afbb632008-06-06 21:10:57 +00001663 self.__new_record = new_record
mbligh36768f02008-02-22 18:28:33 +00001664
jadmanski0afbb632008-06-06 21:10:57 +00001665 if row is None:
1666 sql = 'SELECT * FROM %s WHERE ID=%%s' % self.__table
1667 rows = _db.execute(sql, (id,))
1668 if len(rows) == 0:
1669 raise "row not found (table=%s, id=%s)" % \
1670 (self.__table, id)
1671 row = rows[0]
mbligh36768f02008-02-22 18:28:33 +00001672
jadmanski0afbb632008-06-06 21:10:57 +00001673 assert len(row) == self.num_cols(), (
1674 "table = %s, row = %s/%d, fields = %s/%d" % (
1675 self.__table, row, len(row), fields, self.num_cols()))
mbligh36768f02008-02-22 18:28:33 +00001676
jadmanski0afbb632008-06-06 21:10:57 +00001677 self.__valid_fields = {}
1678 for i,value in enumerate(row):
1679 self.__dict__[fields[i]] = value
1680 self.__valid_fields[fields[i]] = True
mbligh36768f02008-02-22 18:28:33 +00001681
jadmanski0afbb632008-06-06 21:10:57 +00001682 del self.__valid_fields['id']
mbligh36768f02008-02-22 18:28:33 +00001683
mblighe2586682008-02-29 22:45:46 +00001684
jadmanski0afbb632008-06-06 21:10:57 +00001685 @classmethod
1686 def _get_table(cls):
1687 raise NotImplementedError('Subclasses must override this')
mblighe2586682008-02-29 22:45:46 +00001688
1689
jadmanski0afbb632008-06-06 21:10:57 +00001690 @classmethod
1691 def _fields(cls):
1692 raise NotImplementedError('Subclasses must override this')
showard04c82c52008-05-29 19:38:12 +00001693
1694
jadmanski0afbb632008-06-06 21:10:57 +00001695 @classmethod
1696 def num_cols(cls):
1697 return len(cls._fields())
showard04c82c52008-05-29 19:38:12 +00001698
1699
jadmanski0afbb632008-06-06 21:10:57 +00001700 def count(self, where, table = None):
1701 if not table:
1702 table = self.__table
mbligh36768f02008-02-22 18:28:33 +00001703
jadmanski0afbb632008-06-06 21:10:57 +00001704 rows = _db.execute("""
1705 SELECT count(*) FROM %s
1706 WHERE %s
1707 """ % (table, where))
mbligh6f8bab42008-02-29 22:45:14 +00001708
jadmanski0afbb632008-06-06 21:10:57 +00001709 assert len(rows) == 1
1710
1711 return int(rows[0][0])
mbligh36768f02008-02-22 18:28:33 +00001712
1713
mblighf8c624d2008-07-03 16:58:45 +00001714 def update_field(self, field, value, condition=''):
jadmanski0afbb632008-06-06 21:10:57 +00001715 assert self.__valid_fields[field]
mbligh36768f02008-02-22 18:28:33 +00001716
jadmanski0afbb632008-06-06 21:10:57 +00001717 if self.__dict__[field] == value:
1718 return
mbligh36768f02008-02-22 18:28:33 +00001719
mblighf8c624d2008-07-03 16:58:45 +00001720 query = "UPDATE %s SET %s = %%s WHERE id = %%s" % (self.__table, field)
1721 if condition:
1722 query += ' AND (%s)' % condition
jadmanski0afbb632008-06-06 21:10:57 +00001723 _db.execute(query, (value, self.id))
1724
1725 self.__dict__[field] = value
mbligh36768f02008-02-22 18:28:33 +00001726
1727
jadmanski0afbb632008-06-06 21:10:57 +00001728 def save(self):
1729 if self.__new_record:
1730 keys = self._fields()[1:] # avoid id
1731 columns = ','.join([str(key) for key in keys])
1732 values = ['"%s"' % self.__dict__[key] for key in keys]
1733 values = ','.join(values)
1734 query = """INSERT INTO %s (%s) VALUES (%s)""" % \
1735 (self.__table, columns, values)
1736 _db.execute(query)
mbligh36768f02008-02-22 18:28:33 +00001737
1738
jadmanski0afbb632008-06-06 21:10:57 +00001739 def delete(self):
1740 query = 'DELETE FROM %s WHERE id=%%s' % self.__table
1741 _db.execute(query, (self.id,))
mblighe2586682008-02-29 22:45:46 +00001742
1743
showard63a34772008-08-18 19:32:50 +00001744 @staticmethod
1745 def _prefix_with(string, prefix):
1746 if string:
1747 string = prefix + string
1748 return string
1749
1750
jadmanski0afbb632008-06-06 21:10:57 +00001751 @classmethod
showard989f25d2008-10-01 11:38:11 +00001752 def fetch(cls, where='', params=(), joins='', order_by=''):
showard63a34772008-08-18 19:32:50 +00001753 order_by = cls._prefix_with(order_by, 'ORDER BY ')
1754 where = cls._prefix_with(where, 'WHERE ')
1755 query = ('SELECT %(table)s.* FROM %(table)s %(joins)s '
1756 '%(where)s %(order_by)s' % {'table' : cls._get_table(),
1757 'joins' : joins,
1758 'where' : where,
1759 'order_by' : order_by})
1760 rows = _db.execute(query, params)
jadmanski0afbb632008-06-06 21:10:57 +00001761 for row in rows:
1762 yield cls(row=row)
mblighe2586682008-02-29 22:45:46 +00001763
mbligh36768f02008-02-22 18:28:33 +00001764
1765class IneligibleHostQueue(DBObject):
jadmanski0afbb632008-06-06 21:10:57 +00001766 def __init__(self, id=None, row=None, new_record=None):
1767 super(IneligibleHostQueue, self).__init__(id=id, row=row,
1768 new_record=new_record)
mblighe2586682008-02-29 22:45:46 +00001769
1770
jadmanski0afbb632008-06-06 21:10:57 +00001771 @classmethod
1772 def _get_table(cls):
1773 return 'ineligible_host_queues'
mbligh36768f02008-02-22 18:28:33 +00001774
1775
jadmanski0afbb632008-06-06 21:10:57 +00001776 @classmethod
1777 def _fields(cls):
1778 return ['id', 'job_id', 'host_id']
showard04c82c52008-05-29 19:38:12 +00001779
1780
showard989f25d2008-10-01 11:38:11 +00001781class Label(DBObject):
1782 @classmethod
1783 def _get_table(cls):
1784 return 'labels'
1785
1786
1787 @classmethod
1788 def _fields(cls):
1789 return ['id', 'name', 'kernel_config', 'platform', 'invalid',
1790 'only_if_needed']
1791
1792
mbligh36768f02008-02-22 18:28:33 +00001793class Host(DBObject):
jadmanski0afbb632008-06-06 21:10:57 +00001794 def __init__(self, id=None, row=None):
1795 super(Host, self).__init__(id=id, row=row)
mblighe2586682008-02-29 22:45:46 +00001796
1797
jadmanski0afbb632008-06-06 21:10:57 +00001798 @classmethod
1799 def _get_table(cls):
1800 return 'hosts'
mbligh36768f02008-02-22 18:28:33 +00001801
1802
jadmanski0afbb632008-06-06 21:10:57 +00001803 @classmethod
1804 def _fields(cls):
1805 return ['id', 'hostname', 'locked', 'synch_id','status',
showard21baa452008-10-21 00:08:39 +00001806 'invalid', 'protection', 'locked_by_id', 'lock_time', 'dirty']
showard04c82c52008-05-29 19:38:12 +00001807
1808
jadmanski0afbb632008-06-06 21:10:57 +00001809 def current_task(self):
1810 rows = _db.execute("""
1811 SELECT * FROM host_queue_entries WHERE host_id=%s AND NOT complete AND active
1812 """, (self.id,))
1813
1814 if len(rows) == 0:
1815 return None
1816 else:
1817 assert len(rows) == 1
1818 results = rows[0];
mblighf8c624d2008-07-03 16:58:45 +00001819# print "current = %s" % results
jadmanski0afbb632008-06-06 21:10:57 +00001820 return HostQueueEntry(row=results)
mbligh36768f02008-02-22 18:28:33 +00001821
1822
jadmanski0afbb632008-06-06 21:10:57 +00001823 def yield_work(self):
1824 print "%s yielding work" % self.hostname
1825 if self.current_task():
1826 self.current_task().requeue()
1827
1828 def set_status(self,status):
1829 print '%s -> %s' % (self.hostname, status)
1830 self.update_field('status',status)
mbligh36768f02008-02-22 18:28:33 +00001831
1832
showardd8e548a2008-09-09 03:04:57 +00001833 def labels(self):
1834 """
1835 Fetch a list of names of all non-platform labels associated with this
1836 host.
1837 """
1838 rows = _db.execute("""
1839 SELECT labels.name
1840 FROM labels
1841 INNER JOIN hosts_labels ON labels.id = hosts_labels.label_id
1842 WHERE NOT labels.platform AND hosts_labels.host_id = %s
1843 ORDER BY labels.name
1844 """, (self.id,))
1845 return [row[0] for row in rows]
1846
1847
mbligh36768f02008-02-22 18:28:33 +00001848class HostQueueEntry(DBObject):
jadmanski0afbb632008-06-06 21:10:57 +00001849 def __init__(self, id=None, row=None):
1850 assert id or row
1851 super(HostQueueEntry, self).__init__(id=id, row=row)
1852 self.job = Job(self.job_id)
mbligh36768f02008-02-22 18:28:33 +00001853
jadmanski0afbb632008-06-06 21:10:57 +00001854 if self.host_id:
1855 self.host = Host(self.host_id)
1856 else:
1857 self.host = None
mbligh36768f02008-02-22 18:28:33 +00001858
jadmanski0afbb632008-06-06 21:10:57 +00001859 self.queue_log_path = os.path.join(self.job.results_dir(),
1860 'queue.log.' + str(self.id))
mbligh36768f02008-02-22 18:28:33 +00001861
1862
jadmanski0afbb632008-06-06 21:10:57 +00001863 @classmethod
1864 def _get_table(cls):
1865 return 'host_queue_entries'
mblighe2586682008-02-29 22:45:46 +00001866
1867
jadmanski0afbb632008-06-06 21:10:57 +00001868 @classmethod
1869 def _fields(cls):
1870 return ['id', 'job_id', 'host_id', 'priority', 'status',
showardb8471e32008-07-03 19:51:08 +00001871 'meta_host', 'active', 'complete', 'deleted']
showard04c82c52008-05-29 19:38:12 +00001872
1873
jadmanski0afbb632008-06-06 21:10:57 +00001874 def set_host(self, host):
1875 if host:
1876 self.queue_log_record('Assigning host ' + host.hostname)
1877 self.update_field('host_id', host.id)
1878 self.update_field('active', True)
1879 self.block_host(host.id)
1880 else:
1881 self.queue_log_record('Releasing host')
1882 self.unblock_host(self.host.id)
1883 self.update_field('host_id', None)
mbligh36768f02008-02-22 18:28:33 +00001884
jadmanski0afbb632008-06-06 21:10:57 +00001885 self.host = host
mbligh36768f02008-02-22 18:28:33 +00001886
1887
jadmanski0afbb632008-06-06 21:10:57 +00001888 def get_host(self):
1889 return self.host
mbligh36768f02008-02-22 18:28:33 +00001890
1891
jadmanski0afbb632008-06-06 21:10:57 +00001892 def queue_log_record(self, log_line):
1893 now = str(datetime.datetime.now())
1894 queue_log = open(self.queue_log_path, 'a', 0)
1895 queue_log.write(now + ' ' + log_line + '\n')
1896 queue_log.close()
mbligh36768f02008-02-22 18:28:33 +00001897
1898
jadmanski0afbb632008-06-06 21:10:57 +00001899 def block_host(self, host_id):
1900 print "creating block %s/%s" % (self.job.id, host_id)
1901 row = [0, self.job.id, host_id]
1902 block = IneligibleHostQueue(row=row, new_record=True)
1903 block.save()
mblighe2586682008-02-29 22:45:46 +00001904
1905
jadmanski0afbb632008-06-06 21:10:57 +00001906 def unblock_host(self, host_id):
1907 print "removing block %s/%s" % (self.job.id, host_id)
1908 blocks = IneligibleHostQueue.fetch(
1909 'job_id=%d and host_id=%d' % (self.job.id, host_id))
1910 for block in blocks:
1911 block.delete()
mblighe2586682008-02-29 22:45:46 +00001912
1913
jadmanski0afbb632008-06-06 21:10:57 +00001914 def results_dir(self):
1915 if self.job.is_synchronous() or self.job.num_machines() == 1:
1916 return self.job.job_dir
1917 else:
1918 assert self.host
1919 return os.path.join(self.job.job_dir,
1920 self.host.hostname)
mbligh36768f02008-02-22 18:28:33 +00001921
mblighe2586682008-02-29 22:45:46 +00001922
jadmanski0afbb632008-06-06 21:10:57 +00001923 def verify_results_dir(self):
1924 if self.job.is_synchronous() or self.job.num_machines() > 1:
1925 assert self.host
1926 return os.path.join(self.job.job_dir,
1927 self.host.hostname)
1928 else:
1929 return self.job.job_dir
mbligh36768f02008-02-22 18:28:33 +00001930
1931
jadmanski0afbb632008-06-06 21:10:57 +00001932 def set_status(self, status):
mblighf8c624d2008-07-03 16:58:45 +00001933 abort_statuses = ['Abort', 'Aborting', 'Aborted']
1934 if status not in abort_statuses:
1935 condition = ' AND '.join(['status <> "%s"' % x
1936 for x in abort_statuses])
1937 else:
1938 condition = ''
1939 self.update_field('status', status, condition=condition)
1940
jadmanski0afbb632008-06-06 21:10:57 +00001941 if self.host:
1942 hostname = self.host.hostname
1943 else:
1944 hostname = 'no host'
1945 print "%s/%d status -> %s" % (hostname, self.id, self.status)
mblighf8c624d2008-07-03 16:58:45 +00001946
jadmanski0afbb632008-06-06 21:10:57 +00001947 if status in ['Queued']:
1948 self.update_field('complete', False)
1949 self.update_field('active', False)
mbligh36768f02008-02-22 18:28:33 +00001950
jadmanski0afbb632008-06-06 21:10:57 +00001951 if status in ['Pending', 'Running', 'Verifying', 'Starting',
1952 'Abort', 'Aborting']:
1953 self.update_field('complete', False)
1954 self.update_field('active', True)
mbligh36768f02008-02-22 18:28:33 +00001955
showard97aed502008-11-04 02:01:24 +00001956 if status in ['Failed', 'Completed', 'Stopped', 'Aborted', 'Parsing']:
jadmanski0afbb632008-06-06 21:10:57 +00001957 self.update_field('complete', True)
1958 self.update_field('active', False)
showard542e8402008-09-19 20:16:18 +00001959 self._email_on_job_complete()
1960
1961
1962 def _email_on_job_complete(self):
1963 url = "%s#tab_id=view_job&object_id=%s" % (_base_url, self.job.id)
1964
1965 if self.job.is_finished():
1966 subject = "Autotest: Job ID: %s \"%s\" Completed" % (
1967 self.job.id, self.job.name)
1968 body = "Job ID: %s\nJob Name: %s\n%s\n" % (
1969 self.job.id, self.job.name, url)
1970 send_email(_email_from, self.job.email_list, subject, body)
mbligh36768f02008-02-22 18:28:33 +00001971
1972
jadmanski0afbb632008-06-06 21:10:57 +00001973 def run(self,assigned_host=None):
1974 if self.meta_host:
1975 assert assigned_host
1976 # ensure results dir exists for the queue log
1977 self.job.create_results_dir()
1978 self.set_host(assigned_host)
mbligh36768f02008-02-22 18:28:33 +00001979
jadmanski0afbb632008-06-06 21:10:57 +00001980 print "%s/%s scheduled on %s, status=%s" % (self.job.name,
1981 self.meta_host, self.host.hostname, self.status)
mbligh36768f02008-02-22 18:28:33 +00001982
jadmanski0afbb632008-06-06 21:10:57 +00001983 return self.job.run(queue_entry=self)
mblighe2586682008-02-29 22:45:46 +00001984
jadmanski0afbb632008-06-06 21:10:57 +00001985 def requeue(self):
1986 self.set_status('Queued')
mblighe2586682008-02-29 22:45:46 +00001987
jadmanski0afbb632008-06-06 21:10:57 +00001988 if self.meta_host:
1989 self.set_host(None)
mbligh36768f02008-02-22 18:28:33 +00001990
1991
jadmanski0afbb632008-06-06 21:10:57 +00001992 def handle_host_failure(self):
1993 """\
1994 Called when this queue entry's host has failed verification and
1995 repair.
1996 """
1997 assert not self.meta_host
1998 self.set_status('Failed')
1999 if self.job.is_synchronous():
2000 self.job.stop_all_entries()
mblighe2586682008-02-29 22:45:46 +00002001
2002
jadmanski0afbb632008-06-06 21:10:57 +00002003 def clear_results_dir(self, results_dir=None, dont_delete_files=False):
2004 results_dir = results_dir or self.results_dir()
2005 if not os.path.exists(results_dir):
2006 return
2007 if dont_delete_files:
2008 temp_dir = tempfile.mkdtemp(suffix='.clear_results')
2009 print 'Moving results from %s to %s' % (results_dir,
2010 temp_dir)
2011 for filename in os.listdir(results_dir):
2012 path = os.path.join(results_dir, filename)
2013 if dont_delete_files:
2014 shutil.move(path,
2015 os.path.join(temp_dir, filename))
2016 else:
2017 remove_file_or_dir(path)
mbligh36768f02008-02-22 18:28:33 +00002018
2019
jadmanskif7fa2cc2008-10-01 14:13:23 +00002020 @property
2021 def aborted_by(self):
2022 self._load_abort_info()
2023 return self._aborted_by
2024
2025
2026 @property
2027 def aborted_on(self):
2028 self._load_abort_info()
2029 return self._aborted_on
2030
2031
2032 def _load_abort_info(self):
2033 """ Fetch info about who aborted the job. """
2034 if hasattr(self, "_aborted_by"):
2035 return
2036 rows = _db.execute("""
2037 SELECT users.login, aborted_host_queue_entries.aborted_on
2038 FROM aborted_host_queue_entries
2039 INNER JOIN users
2040 ON users.id = aborted_host_queue_entries.aborted_by_id
2041 WHERE aborted_host_queue_entries.queue_entry_id = %s
2042 """, (self.id,))
2043 if rows:
2044 self._aborted_by, self._aborted_on = rows[0]
2045 else:
2046 self._aborted_by = self._aborted_on = None
2047
2048
showardb2e2c322008-10-14 17:33:55 +00002049 def on_pending(self):
2050 """
2051 Called when an entry in a synchronous job has passed verify. If the
2052 job is ready to run, returns an agent to run the job. Returns None
2053 otherwise.
2054 """
2055 self.set_status('Pending')
showardcfd66a32008-10-15 20:31:48 +00002056 self.get_host().set_status('Pending')
showardb2e2c322008-10-14 17:33:55 +00002057 if self.job.is_ready():
2058 return self.job.run(self)
2059 return None
2060
2061
showard1be97432008-10-17 15:30:45 +00002062 def abort(self, agents_to_abort=[]):
2063 abort_task = AbortTask(self, agents_to_abort)
2064 tasks = [abort_task]
2065
2066 host = self.get_host()
2067 if host:
showardfa8629c2008-11-04 16:51:23 +00002068 reboot_task = RebootTask(host=host)
showard1be97432008-10-17 15:30:45 +00002069 verify_task = VerifyTask(host=host)
2070 # just to make sure this host does not get taken away
2071 host.set_status('Rebooting')
2072 tasks += [reboot_task, verify_task]
2073
2074 self.set_status('Aborting')
2075 return Agent(tasks=tasks, queue_entry_ids=[self.id])
2076
2077
mbligh36768f02008-02-22 18:28:33 +00002078class Job(DBObject):
jadmanski0afbb632008-06-06 21:10:57 +00002079 def __init__(self, id=None, row=None):
2080 assert id or row
2081 super(Job, self).__init__(id=id, row=row)
mbligh36768f02008-02-22 18:28:33 +00002082
jadmanski0afbb632008-06-06 21:10:57 +00002083 self.job_dir = os.path.join(RESULTS_DIR, "%s-%s" % (self.id,
2084 self.owner))
mblighe2586682008-02-29 22:45:46 +00002085
2086
jadmanski0afbb632008-06-06 21:10:57 +00002087 @classmethod
2088 def _get_table(cls):
2089 return 'jobs'
mbligh36768f02008-02-22 18:28:33 +00002090
2091
jadmanski0afbb632008-06-06 21:10:57 +00002092 @classmethod
2093 def _fields(cls):
2094 return ['id', 'owner', 'name', 'priority', 'control_file',
2095 'control_type', 'created_on', 'synch_type',
showard542e8402008-09-19 20:16:18 +00002096 'synch_count', 'synchronizing', 'timeout',
showard21baa452008-10-21 00:08:39 +00002097 'run_verify', 'email_list', 'reboot_before', 'reboot_after']
showard04c82c52008-05-29 19:38:12 +00002098
2099
jadmanski0afbb632008-06-06 21:10:57 +00002100 def is_server_job(self):
2101 return self.control_type != 2
mbligh36768f02008-02-22 18:28:33 +00002102
2103
jadmanski0afbb632008-06-06 21:10:57 +00002104 def get_host_queue_entries(self):
2105 rows = _db.execute("""
2106 SELECT * FROM host_queue_entries
2107 WHERE job_id= %s
2108 """, (self.id,))
2109 entries = [HostQueueEntry(row=i) for i in rows]
mbligh36768f02008-02-22 18:28:33 +00002110
jadmanski0afbb632008-06-06 21:10:57 +00002111 assert len(entries)>0
mbligh36768f02008-02-22 18:28:33 +00002112
jadmanski0afbb632008-06-06 21:10:57 +00002113 return entries
mbligh36768f02008-02-22 18:28:33 +00002114
2115
jadmanski0afbb632008-06-06 21:10:57 +00002116 def set_status(self, status, update_queues=False):
2117 self.update_field('status',status)
2118
2119 if update_queues:
2120 for queue_entry in self.get_host_queue_entries():
2121 queue_entry.set_status(status)
mbligh36768f02008-02-22 18:28:33 +00002122
2123
jadmanski0afbb632008-06-06 21:10:57 +00002124 def is_synchronous(self):
2125 return self.synch_type == 2
mbligh36768f02008-02-22 18:28:33 +00002126
2127
jadmanski0afbb632008-06-06 21:10:57 +00002128 def is_ready(self):
2129 if not self.is_synchronous():
2130 return True
2131 sql = "job_id=%s AND status='Pending'" % self.id
2132 count = self.count(sql, table='host_queue_entries')
showardb2e2c322008-10-14 17:33:55 +00002133 return (count == self.num_machines())
mbligh36768f02008-02-22 18:28:33 +00002134
2135
jadmanski0afbb632008-06-06 21:10:57 +00002136 def results_dir(self):
2137 return self.job_dir
mbligh36768f02008-02-22 18:28:33 +00002138
jadmanski0afbb632008-06-06 21:10:57 +00002139 def num_machines(self, clause = None):
2140 sql = "job_id=%s" % self.id
2141 if clause:
2142 sql += " AND (%s)" % clause
2143 return self.count(sql, table='host_queue_entries')
mbligh36768f02008-02-22 18:28:33 +00002144
2145
jadmanski0afbb632008-06-06 21:10:57 +00002146 def num_queued(self):
2147 return self.num_machines('not complete')
mbligh36768f02008-02-22 18:28:33 +00002148
2149
jadmanski0afbb632008-06-06 21:10:57 +00002150 def num_active(self):
2151 return self.num_machines('active')
mbligh36768f02008-02-22 18:28:33 +00002152
2153
jadmanski0afbb632008-06-06 21:10:57 +00002154 def num_complete(self):
2155 return self.num_machines('complete')
mbligh36768f02008-02-22 18:28:33 +00002156
2157
jadmanski0afbb632008-06-06 21:10:57 +00002158 def is_finished(self):
2159 left = self.num_queued()
2160 print "%s: %s machines left" % (self.name, left)
2161 return left==0
mbligh36768f02008-02-22 18:28:33 +00002162
mbligh36768f02008-02-22 18:28:33 +00002163
jadmanski0afbb632008-06-06 21:10:57 +00002164 def stop_all_entries(self):
2165 for child_entry in self.get_host_queue_entries():
2166 if not child_entry.complete:
2167 child_entry.set_status('Stopped')
mblighe2586682008-02-29 22:45:46 +00002168
2169
jadmanski0afbb632008-06-06 21:10:57 +00002170 def write_to_machines_file(self, queue_entry):
2171 hostname = queue_entry.get_host().hostname
2172 print "writing %s to job %s machines file" % (hostname, self.id)
2173 file_path = os.path.join(self.job_dir, '.machines')
2174 mf = open(file_path, 'a')
2175 mf.write("%s\n" % queue_entry.get_host().hostname)
2176 mf.close()
mbligh36768f02008-02-22 18:28:33 +00002177
2178
jadmanski0afbb632008-06-06 21:10:57 +00002179 def create_results_dir(self, queue_entry=None):
2180 print "create: active: %s complete %s" % (self.num_active(),
2181 self.num_complete())
mbligh36768f02008-02-22 18:28:33 +00002182
jadmanski0afbb632008-06-06 21:10:57 +00002183 if not os.path.exists(self.job_dir):
2184 os.makedirs(self.job_dir)
mbligh36768f02008-02-22 18:28:33 +00002185
jadmanski0afbb632008-06-06 21:10:57 +00002186 if queue_entry:
showarde05654d2008-10-28 20:38:40 +00002187 results_dir = queue_entry.results_dir()
2188 if not os.path.exists(results_dir):
2189 os.makedirs(results_dir)
2190 return results_dir
jadmanski0afbb632008-06-06 21:10:57 +00002191 return self.job_dir
mbligh36768f02008-02-22 18:28:33 +00002192
2193
showardb2e2c322008-10-14 17:33:55 +00002194 def _write_control_file(self):
2195 'Writes control file out to disk, returns a filename'
2196 control_fd, control_filename = tempfile.mkstemp(suffix='.control_file')
2197 control_file = os.fdopen(control_fd, 'w')
jadmanski0afbb632008-06-06 21:10:57 +00002198 if self.control_file:
showardb2e2c322008-10-14 17:33:55 +00002199 control_file.write(self.control_file)
2200 control_file.close()
2201 return control_filename
mbligh36768f02008-02-22 18:28:33 +00002202
showardb2e2c322008-10-14 17:33:55 +00002203
2204 def _get_job_tag(self, queue_entries):
2205 base_job_tag = "%s-%s" % (self.id, self.owner)
2206 if self.is_synchronous() or self.num_machines() == 1:
2207 return base_job_tag
jadmanski0afbb632008-06-06 21:10:57 +00002208 else:
showardb2e2c322008-10-14 17:33:55 +00002209 return base_job_tag + '/' + queue_entries[0].get_host().hostname
2210
2211
2212 def _get_autoserv_params(self, queue_entries):
2213 results_dir = self.create_results_dir(queue_entries[0])
2214 control_filename = self._write_control_file()
jadmanski0afbb632008-06-06 21:10:57 +00002215 hostnames = ','.join([entry.get_host().hostname
2216 for entry in queue_entries])
showardb2e2c322008-10-14 17:33:55 +00002217 job_tag = self._get_job_tag(queue_entries)
mbligh36768f02008-02-22 18:28:33 +00002218
showardb2e2c322008-10-14 17:33:55 +00002219 params = [_autoserv_path, '-P', job_tag, '-p', '-n',
showard21baa452008-10-21 00:08:39 +00002220 '-r', os.path.abspath(results_dir), '-u', self.owner,
2221 '-l', self.name, '-m', hostnames, control_filename]
mbligh36768f02008-02-22 18:28:33 +00002222
jadmanski0afbb632008-06-06 21:10:57 +00002223 if not self.is_server_job():
2224 params.append('-c')
mbligh36768f02008-02-22 18:28:33 +00002225
showardb2e2c322008-10-14 17:33:55 +00002226 return params
mblighe2586682008-02-29 22:45:46 +00002227
mbligh36768f02008-02-22 18:28:33 +00002228
showard21baa452008-10-21 00:08:39 +00002229 def _get_pre_job_tasks(self, queue_entry, verify_task_class=VerifyTask):
2230 do_reboot = False
showard0fc38302008-10-23 00:44:07 +00002231 if self.reboot_before == models.RebootBefore.ALWAYS:
showard21baa452008-10-21 00:08:39 +00002232 do_reboot = True
showard0fc38302008-10-23 00:44:07 +00002233 elif self.reboot_before == models.RebootBefore.IF_DIRTY:
showard21baa452008-10-21 00:08:39 +00002234 do_reboot = queue_entry.get_host().dirty
2235
2236 tasks = []
2237 if do_reboot:
showardfa8629c2008-11-04 16:51:23 +00002238 tasks.append(RebootTask(queue_entry=queue_entry))
showard21baa452008-10-21 00:08:39 +00002239 tasks.append(verify_task_class(queue_entry=queue_entry))
2240 return tasks
2241
2242
showardb2e2c322008-10-14 17:33:55 +00002243 def _run_synchronous(self, queue_entry):
2244 if not self.is_ready():
showard9976ce92008-10-15 20:28:13 +00002245 if self.run_verify:
showard21baa452008-10-21 00:08:39 +00002246 return Agent(self._get_pre_job_tasks(queue_entry,
2247 VerifySynchronousTask),
2248 [queue_entry.id])
showard9976ce92008-10-15 20:28:13 +00002249 else:
2250 return queue_entry.on_pending()
mbligh36768f02008-02-22 18:28:33 +00002251
showardb2e2c322008-10-14 17:33:55 +00002252 return self._finish_run(self.get_host_queue_entries())
2253
2254
2255 def _run_asynchronous(self, queue_entry):
showard9976ce92008-10-15 20:28:13 +00002256 initial_tasks = []
2257 if self.run_verify:
showard21baa452008-10-21 00:08:39 +00002258 initial_tasks = self._get_pre_job_tasks(queue_entry)
showardb2e2c322008-10-14 17:33:55 +00002259 return self._finish_run([queue_entry], initial_tasks)
2260
2261
2262 def _finish_run(self, queue_entries, initial_tasks=[]):
showardb2ccdda2008-10-28 20:39:05 +00002263 for queue_entry in queue_entries:
2264 queue_entry.set_status('Starting')
showardb2e2c322008-10-14 17:33:55 +00002265 params = self._get_autoserv_params(queue_entries)
2266 queue_task = QueueTask(job=self, queue_entries=queue_entries,
2267 cmd=params)
2268 tasks = initial_tasks + [queue_task]
2269 entry_ids = [entry.id for entry in queue_entries]
2270
2271 return Agent(tasks, entry_ids, num_processes=len(queue_entries))
2272
2273
2274 def run(self, queue_entry):
2275 if self.is_synchronous():
2276 return self._run_synchronous(queue_entry)
2277 return self._run_asynchronous(queue_entry)
mbligh36768f02008-02-22 18:28:33 +00002278
2279
2280if __name__ == '__main__':
jadmanski0afbb632008-06-06 21:10:57 +00002281 main()