blob: eb5d08f46010e148b70835eab14d7ca8acf1695f [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
showard170873e2009-01-07 00:22:26 +000010import itertools, logging
mbligh70feeee2008-06-11 16:20:49 +000011import common
showard21baa452008-10-21 00:08:39 +000012from autotest_lib.frontend import setup_django_environment
showard542e8402008-09-19 20:16:18 +000013from autotest_lib.client.common_lib import global_config
showard2bab8f42008-11-12 18:15:22 +000014from autotest_lib.client.common_lib import host_protections, utils, debug
showardb1e51872008-10-07 11:08:18 +000015from autotest_lib.database import database_connection
showard21baa452008-10-21 00:08:39 +000016from autotest_lib.frontend.afe import models
showard170873e2009-01-07 00:22:26 +000017from autotest_lib.scheduler import drone_manager, drones, email_manager
showardd1ee1dd2009-01-07 21:33:08 +000018from autotest_lib.scheduler import status_server, scheduler_config
mbligh70feeee2008-06-11 16:20:49 +000019
mblighb090f142008-02-27 21:33:46 +000020
mbligh36768f02008-02-22 18:28:33 +000021RESULTS_DIR = '.'
22AUTOSERV_NICE_LEVEL = 10
showard170873e2009-01-07 00:22:26 +000023DB_CONFIG_SECTION = 'AUTOTEST_WEB'
mbligh36768f02008-02-22 18:28:33 +000024
25AUTOTEST_PATH = os.path.join(os.path.dirname(__file__), '..')
26
27if os.environ.has_key('AUTOTEST_DIR'):
jadmanski0afbb632008-06-06 21:10:57 +000028 AUTOTEST_PATH = os.environ['AUTOTEST_DIR']
mbligh36768f02008-02-22 18:28:33 +000029AUTOTEST_SERVER_DIR = os.path.join(AUTOTEST_PATH, 'server')
30AUTOTEST_TKO_DIR = os.path.join(AUTOTEST_PATH, 'tko')
31
32if AUTOTEST_SERVER_DIR not in sys.path:
jadmanski0afbb632008-06-06 21:10:57 +000033 sys.path.insert(0, AUTOTEST_SERVER_DIR)
mbligh36768f02008-02-22 18:28:33 +000034
mbligh90a549d2008-03-25 23:52:34 +000035# how long to wait for autoserv to write a pidfile
36PIDFILE_TIMEOUT = 5 * 60 # 5 min
mblighbb421852008-03-11 22:36:16 +000037
mbligh6f8bab42008-02-29 22:45:14 +000038_db = None
mbligh36768f02008-02-22 18:28:33 +000039_shutdown = False
showard170873e2009-01-07 00:22:26 +000040_autoserv_path = os.path.join(drones.AUTOTEST_INSTALL_DIR, 'server', 'autoserv')
41_parser_path = os.path.join(drones.AUTOTEST_INSTALL_DIR, 'tko', 'parse')
mbligh4314a712008-02-29 22:44:30 +000042_testing_mode = False
showard542e8402008-09-19 20:16:18 +000043_base_url = None
showardc85c21b2008-11-24 22:17:37 +000044_notify_email_statuses = []
showard170873e2009-01-07 00:22:26 +000045_drone_manager = drone_manager.DroneManager()
mbligh36768f02008-02-22 18:28:33 +000046
47
48def main():
jadmanski0afbb632008-06-06 21:10:57 +000049 usage = 'usage: %prog [options] results_dir'
mbligh36768f02008-02-22 18:28:33 +000050
jadmanski0afbb632008-06-06 21:10:57 +000051 parser = optparse.OptionParser(usage)
52 parser.add_option('--recover-hosts', help='Try to recover dead hosts',
53 action='store_true')
54 parser.add_option('--logfile', help='Set a log file that all stdout ' +
55 'should be redirected to. Stderr will go to this ' +
56 'file + ".err"')
57 parser.add_option('--test', help='Indicate that scheduler is under ' +
58 'test and should use dummy autoserv and no parsing',
59 action='store_true')
60 (options, args) = parser.parse_args()
61 if len(args) != 1:
62 parser.print_usage()
63 return
mbligh36768f02008-02-22 18:28:33 +000064
jadmanski0afbb632008-06-06 21:10:57 +000065 global RESULTS_DIR
66 RESULTS_DIR = args[0]
mbligh36768f02008-02-22 18:28:33 +000067
jadmanski0afbb632008-06-06 21:10:57 +000068 c = global_config.global_config
showardd1ee1dd2009-01-07 21:33:08 +000069 notify_statuses_list = c.get_config_value(scheduler_config.CONFIG_SECTION,
70 "notify_email_statuses",
71 default='')
showardc85c21b2008-11-24 22:17:37 +000072 global _notify_email_statuses
showard170873e2009-01-07 00:22:26 +000073 _notify_email_statuses = [status for status in
74 re.split(r'[\s,;:]', notify_statuses_list.lower())
75 if status]
showardc85c21b2008-11-24 22:17:37 +000076
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
mbligh37eceaa2008-12-15 22:56:37 +000083 # AUTOTEST_WEB.base_url is still a supported config option as some people
84 # may wish to override the entire url.
showard542e8402008-09-19 20:16:18 +000085 global _base_url
showard170873e2009-01-07 00:22:26 +000086 config_base_url = c.get_config_value(DB_CONFIG_SECTION, 'base_url',
87 default='')
mbligh37eceaa2008-12-15 22:56:37 +000088 if config_base_url:
89 _base_url = config_base_url
showard542e8402008-09-19 20:16:18 +000090 else:
mbligh37eceaa2008-12-15 22:56:37 +000091 # For the common case of everything running on a single server you
92 # can just set the hostname in a single place in the config file.
93 server_name = c.get_config_value('SERVER', 'hostname')
94 if not server_name:
95 print 'Error: [SERVER] hostname missing from the config file.'
96 sys.exit(1)
97 _base_url = 'http://%s/afe/' % server_name
showard542e8402008-09-19 20:16:18 +000098
showardd1ee1dd2009-01-07 21:33:08 +000099 server = status_server.StatusServer()
100 server.start()
101
jadmanski0afbb632008-06-06 21:10:57 +0000102 init(options.logfile)
103 dispatcher = Dispatcher()
104 dispatcher.do_initial_recovery(recover_hosts=options.recover_hosts)
105
106 try:
107 while not _shutdown:
108 dispatcher.tick()
showardd1ee1dd2009-01-07 21:33:08 +0000109 time.sleep(scheduler_config.config.tick_pause_sec)
jadmanski0afbb632008-06-06 21:10:57 +0000110 except:
showard170873e2009-01-07 00:22:26 +0000111 email_manager.manager.log_stacktrace(
112 "Uncaught exception; terminating monitor_db")
jadmanski0afbb632008-06-06 21:10:57 +0000113
showard170873e2009-01-07 00:22:26 +0000114 email_manager.manager.send_queued_emails()
showard55b4b542009-01-08 23:30:30 +0000115 server.shutdown()
showard170873e2009-01-07 00:22:26 +0000116 _drone_manager.shutdown()
jadmanski0afbb632008-06-06 21:10:57 +0000117 _db.disconnect()
mbligh36768f02008-02-22 18:28:33 +0000118
119
120def handle_sigint(signum, frame):
jadmanski0afbb632008-06-06 21:10:57 +0000121 global _shutdown
122 _shutdown = True
123 print "Shutdown request received."
mbligh36768f02008-02-22 18:28:33 +0000124
125
126def init(logfile):
jadmanski0afbb632008-06-06 21:10:57 +0000127 if logfile:
128 enable_logging(logfile)
129 print "%s> dispatcher starting" % time.strftime("%X %x")
130 print "My PID is %d" % os.getpid()
mbligh36768f02008-02-22 18:28:33 +0000131
showardb1e51872008-10-07 11:08:18 +0000132 if _testing_mode:
133 global_config.global_config.override_config_value(
showard170873e2009-01-07 00:22:26 +0000134 DB_CONFIG_SECTION, 'database', 'stresstest_autotest_web')
showardb1e51872008-10-07 11:08:18 +0000135
jadmanski0afbb632008-06-06 21:10:57 +0000136 os.environ['PATH'] = AUTOTEST_SERVER_DIR + ':' + os.environ['PATH']
137 global _db
showard170873e2009-01-07 00:22:26 +0000138 _db = database_connection.DatabaseConnection(DB_CONFIG_SECTION)
jadmanski0afbb632008-06-06 21:10:57 +0000139 _db.connect()
mbligh36768f02008-02-22 18:28:33 +0000140
showardfa8629c2008-11-04 16:51:23 +0000141 # ensure Django connection is in autocommit
142 setup_django_environment.enable_autocommit()
143
showard2bab8f42008-11-12 18:15:22 +0000144 debug.configure('scheduler', format_string='%(message)s')
showard170873e2009-01-07 00:22:26 +0000145 debug.get_logger().setLevel(logging.WARNING)
showard2bab8f42008-11-12 18:15:22 +0000146
jadmanski0afbb632008-06-06 21:10:57 +0000147 print "Setting signal handler"
148 signal.signal(signal.SIGINT, handle_sigint)
149
showardd1ee1dd2009-01-07 21:33:08 +0000150 drones = global_config.global_config.get_config_value(
151 scheduler_config.CONFIG_SECTION, 'drones', default='localhost')
152 drone_list = [hostname.strip() for hostname in drones.split(',')]
showard170873e2009-01-07 00:22:26 +0000153 results_host = global_config.global_config.get_config_value(
showardd1ee1dd2009-01-07 21:33:08 +0000154 scheduler_config.CONFIG_SECTION, 'results_host', default='localhost')
showard170873e2009-01-07 00:22:26 +0000155 _drone_manager.initialize(RESULTS_DIR, drone_list, results_host)
156
jadmanski0afbb632008-06-06 21:10:57 +0000157 print "Connected! Running..."
mbligh36768f02008-02-22 18:28:33 +0000158
159
160def enable_logging(logfile):
jadmanski0afbb632008-06-06 21:10:57 +0000161 out_file = logfile
162 err_file = "%s.err" % logfile
163 print "Enabling logging to %s (%s)" % (out_file, err_file)
164 out_fd = open(out_file, "a", buffering=0)
165 err_fd = open(err_file, "a", buffering=0)
mbligh36768f02008-02-22 18:28:33 +0000166
jadmanski0afbb632008-06-06 21:10:57 +0000167 os.dup2(out_fd.fileno(), sys.stdout.fileno())
168 os.dup2(err_fd.fileno(), sys.stderr.fileno())
mbligh36768f02008-02-22 18:28:33 +0000169
jadmanski0afbb632008-06-06 21:10:57 +0000170 sys.stdout = out_fd
171 sys.stderr = err_fd
mbligh36768f02008-02-22 18:28:33 +0000172
173
mblighd5c95802008-03-05 00:33:46 +0000174def queue_entries_to_abort():
jadmanski0afbb632008-06-06 21:10:57 +0000175 rows = _db.execute("""
176 SELECT * FROM host_queue_entries WHERE status='Abort';
177 """)
showard2bab8f42008-11-12 18:15:22 +0000178
jadmanski0afbb632008-06-06 21:10:57 +0000179 qe = [HostQueueEntry(row=i) for i in rows]
180 return qe
mbligh36768f02008-02-22 18:28:33 +0000181
showard7cf9a9b2008-05-15 21:15:52 +0000182
showard63a34772008-08-18 19:32:50 +0000183class HostScheduler(object):
184 def _get_ready_hosts(self):
185 # avoid any host with a currently active queue entry against it
186 hosts = Host.fetch(
187 joins='LEFT JOIN host_queue_entries AS active_hqe '
188 'ON (hosts.id = active_hqe.host_id AND '
showardb1e51872008-10-07 11:08:18 +0000189 'active_hqe.active)',
showard63a34772008-08-18 19:32:50 +0000190 where="active_hqe.host_id IS NULL "
showardb1e51872008-10-07 11:08:18 +0000191 "AND NOT hosts.locked "
showard63a34772008-08-18 19:32:50 +0000192 "AND (hosts.status IS NULL OR hosts.status = 'Ready')")
193 return dict((host.id, host) for host in hosts)
194
195
196 @staticmethod
197 def _get_sql_id_list(id_list):
198 return ','.join(str(item_id) for item_id in id_list)
199
200
201 @classmethod
showard989f25d2008-10-01 11:38:11 +0000202 def _get_many2many_dict(cls, query, id_list, flip=False):
mbligh849a0f62008-08-28 20:12:19 +0000203 if not id_list:
204 return {}
showard63a34772008-08-18 19:32:50 +0000205 query %= cls._get_sql_id_list(id_list)
206 rows = _db.execute(query)
showard989f25d2008-10-01 11:38:11 +0000207 return cls._process_many2many_dict(rows, flip)
208
209
210 @staticmethod
211 def _process_many2many_dict(rows, flip=False):
showard63a34772008-08-18 19:32:50 +0000212 result = {}
213 for row in rows:
214 left_id, right_id = long(row[0]), long(row[1])
showard989f25d2008-10-01 11:38:11 +0000215 if flip:
216 left_id, right_id = right_id, left_id
showard63a34772008-08-18 19:32:50 +0000217 result.setdefault(left_id, set()).add(right_id)
218 return result
219
220
221 @classmethod
222 def _get_job_acl_groups(cls, job_ids):
223 query = """
224 SELECT jobs.id, acl_groups_users.acl_group_id
225 FROM jobs
226 INNER JOIN users ON users.login = jobs.owner
227 INNER JOIN acl_groups_users ON acl_groups_users.user_id = users.id
228 WHERE jobs.id IN (%s)
229 """
230 return cls._get_many2many_dict(query, job_ids)
231
232
233 @classmethod
234 def _get_job_ineligible_hosts(cls, job_ids):
235 query = """
236 SELECT job_id, host_id
237 FROM ineligible_host_queues
238 WHERE job_id IN (%s)
239 """
240 return cls._get_many2many_dict(query, job_ids)
241
242
243 @classmethod
showard989f25d2008-10-01 11:38:11 +0000244 def _get_job_dependencies(cls, job_ids):
245 query = """
246 SELECT job_id, label_id
247 FROM jobs_dependency_labels
248 WHERE job_id IN (%s)
249 """
250 return cls._get_many2many_dict(query, job_ids)
251
252
253 @classmethod
showard63a34772008-08-18 19:32:50 +0000254 def _get_host_acls(cls, host_ids):
255 query = """
256 SELECT host_id, acl_group_id
257 FROM acl_groups_hosts
258 WHERE host_id IN (%s)
259 """
260 return cls._get_many2many_dict(query, host_ids)
261
262
263 @classmethod
264 def _get_label_hosts(cls, host_ids):
showardfa8629c2008-11-04 16:51:23 +0000265 if not host_ids:
266 return {}, {}
showard63a34772008-08-18 19:32:50 +0000267 query = """
268 SELECT label_id, host_id
269 FROM hosts_labels
270 WHERE host_id IN (%s)
showard989f25d2008-10-01 11:38:11 +0000271 """ % cls._get_sql_id_list(host_ids)
272 rows = _db.execute(query)
273 labels_to_hosts = cls._process_many2many_dict(rows)
274 hosts_to_labels = cls._process_many2many_dict(rows, flip=True)
275 return labels_to_hosts, hosts_to_labels
276
277
278 @classmethod
279 def _get_labels(cls):
280 return dict((label.id, label) for label in Label.fetch())
showard63a34772008-08-18 19:32:50 +0000281
282
283 def refresh(self, pending_queue_entries):
284 self._hosts_available = self._get_ready_hosts()
285
286 relevant_jobs = [queue_entry.job_id
287 for queue_entry in pending_queue_entries]
288 self._job_acls = self._get_job_acl_groups(relevant_jobs)
289 self._ineligible_hosts = self._get_job_ineligible_hosts(relevant_jobs)
showard989f25d2008-10-01 11:38:11 +0000290 self._job_dependencies = self._get_job_dependencies(relevant_jobs)
showard63a34772008-08-18 19:32:50 +0000291
292 host_ids = self._hosts_available.keys()
293 self._host_acls = self._get_host_acls(host_ids)
showard989f25d2008-10-01 11:38:11 +0000294 self._label_hosts, self._host_labels = self._get_label_hosts(host_ids)
295
296 self._labels = self._get_labels()
showard63a34772008-08-18 19:32:50 +0000297
298
299 def _is_acl_accessible(self, host_id, queue_entry):
300 job_acls = self._job_acls.get(queue_entry.job_id, set())
301 host_acls = self._host_acls.get(host_id, set())
302 return len(host_acls.intersection(job_acls)) > 0
303
304
showard989f25d2008-10-01 11:38:11 +0000305 def _check_job_dependencies(self, job_dependencies, host_labels):
306 missing = job_dependencies - host_labels
307 return len(job_dependencies - host_labels) == 0
308
309
310 def _check_only_if_needed_labels(self, job_dependencies, host_labels,
311 queue_entry):
312 for label_id in host_labels:
313 label = self._labels[label_id]
314 if not label.only_if_needed:
315 # we don't care about non-only_if_needed labels
316 continue
317 if queue_entry.meta_host == label_id:
318 # if the label was requested in a metahost it's OK
319 continue
320 if label_id not in job_dependencies:
321 return False
322 return True
323
324
325 def _is_host_eligible_for_job(self, host_id, queue_entry):
326 job_dependencies = self._job_dependencies.get(queue_entry.job_id, set())
327 host_labels = self._host_labels.get(host_id, set())
mblighc993bee2008-10-03 03:42:34 +0000328
329 acl = self._is_acl_accessible(host_id, queue_entry)
330 deps = self._check_job_dependencies(job_dependencies, host_labels)
331 only_if = self._check_only_if_needed_labels(job_dependencies,
332 host_labels, queue_entry)
333 return acl and deps and only_if
showard989f25d2008-10-01 11:38:11 +0000334
335
showard63a34772008-08-18 19:32:50 +0000336 def _schedule_non_metahost(self, queue_entry):
showard989f25d2008-10-01 11:38:11 +0000337 if not self._is_host_eligible_for_job(queue_entry.host_id, queue_entry):
showard63a34772008-08-18 19:32:50 +0000338 return None
339 return self._hosts_available.pop(queue_entry.host_id, None)
340
341
342 def _is_host_usable(self, host_id):
343 if host_id not in self._hosts_available:
344 # host was already used during this scheduling cycle
345 return False
346 if self._hosts_available[host_id].invalid:
347 # Invalid hosts cannot be used for metahosts. They're included in
348 # the original query because they can be used by non-metahosts.
349 return False
350 return True
351
352
353 def _schedule_metahost(self, queue_entry):
354 label_id = queue_entry.meta_host
355 hosts_in_label = self._label_hosts.get(label_id, set())
356 ineligible_host_ids = self._ineligible_hosts.get(queue_entry.job_id,
357 set())
358
359 # must iterate over a copy so we can mutate the original while iterating
360 for host_id in list(hosts_in_label):
361 if not self._is_host_usable(host_id):
362 hosts_in_label.remove(host_id)
363 continue
364 if host_id in ineligible_host_ids:
365 continue
showard989f25d2008-10-01 11:38:11 +0000366 if not self._is_host_eligible_for_job(host_id, queue_entry):
showard63a34772008-08-18 19:32:50 +0000367 continue
368
369 hosts_in_label.remove(host_id)
370 return self._hosts_available.pop(host_id)
371 return None
372
373
374 def find_eligible_host(self, queue_entry):
375 if not queue_entry.meta_host:
376 return self._schedule_non_metahost(queue_entry)
377 return self._schedule_metahost(queue_entry)
378
379
showard170873e2009-01-07 00:22:26 +0000380class Dispatcher(object):
jadmanski0afbb632008-06-06 21:10:57 +0000381 def __init__(self):
382 self._agents = []
showard3bb499f2008-07-03 19:42:20 +0000383 self._last_clean_time = time.time()
showard63a34772008-08-18 19:32:50 +0000384 self._host_scheduler = HostScheduler()
showard170873e2009-01-07 00:22:26 +0000385 self._host_agents = {}
386 self._queue_entry_agents = {}
mbligh36768f02008-02-22 18:28:33 +0000387
mbligh36768f02008-02-22 18:28:33 +0000388
jadmanski0afbb632008-06-06 21:10:57 +0000389 def do_initial_recovery(self, recover_hosts=True):
390 # always recover processes
391 self._recover_processes()
mblighbb421852008-03-11 22:36:16 +0000392
jadmanski0afbb632008-06-06 21:10:57 +0000393 if recover_hosts:
394 self._recover_hosts()
mbligh36768f02008-02-22 18:28:33 +0000395
396
jadmanski0afbb632008-06-06 21:10:57 +0000397 def tick(self):
showard170873e2009-01-07 00:22:26 +0000398 _drone_manager.refresh()
showarda3ab0d52008-11-03 19:03:47 +0000399 self._run_cleanup_maybe()
jadmanski0afbb632008-06-06 21:10:57 +0000400 self._find_aborting()
401 self._schedule_new_jobs()
402 self._handle_agents()
showard170873e2009-01-07 00:22:26 +0000403 _drone_manager.execute_actions()
404 email_manager.manager.send_queued_emails()
mbligh36768f02008-02-22 18:28:33 +0000405
showard97aed502008-11-04 02:01:24 +0000406
showarda3ab0d52008-11-03 19:03:47 +0000407 def _run_cleanup_maybe(self):
showardd1ee1dd2009-01-07 21:33:08 +0000408 should_cleanup = (self._last_clean_time +
409 scheduler_config.config.clean_interval * 60 <
410 time.time())
411 if should_cleanup:
showarda3ab0d52008-11-03 19:03:47 +0000412 print 'Running cleanup'
413 self._abort_timed_out_jobs()
414 self._abort_jobs_past_synch_start_timeout()
415 self._clear_inactive_blocks()
showardfa8629c2008-11-04 16:51:23 +0000416 self._check_for_db_inconsistencies()
showarda3ab0d52008-11-03 19:03:47 +0000417 self._last_clean_time = time.time()
418
mbligh36768f02008-02-22 18:28:33 +0000419
showard170873e2009-01-07 00:22:26 +0000420 def _register_agent_for_ids(self, agent_dict, object_ids, agent):
421 for object_id in object_ids:
422 agent_dict.setdefault(object_id, set()).add(agent)
423
424
425 def _unregister_agent_for_ids(self, agent_dict, object_ids, agent):
426 for object_id in object_ids:
427 assert object_id in agent_dict
428 agent_dict[object_id].remove(agent)
429
430
jadmanski0afbb632008-06-06 21:10:57 +0000431 def add_agent(self, agent):
432 self._agents.append(agent)
433 agent.dispatcher = self
showard170873e2009-01-07 00:22:26 +0000434 self._register_agent_for_ids(self._host_agents, agent.host_ids, agent)
435 self._register_agent_for_ids(self._queue_entry_agents,
436 agent.queue_entry_ids, agent)
mblighd5c95802008-03-05 00:33:46 +0000437
showard170873e2009-01-07 00:22:26 +0000438
439 def get_agents_for_entry(self, queue_entry):
440 """
441 Find agents corresponding to the specified queue_entry.
442 """
443 return self._queue_entry_agents.get(queue_entry.id, set())
444
445
446 def host_has_agent(self, host):
447 """
448 Determine if there is currently an Agent present using this host.
449 """
450 return bool(self._host_agents.get(host.id, None))
mbligh36768f02008-02-22 18:28:33 +0000451
452
jadmanski0afbb632008-06-06 21:10:57 +0000453 def remove_agent(self, agent):
454 self._agents.remove(agent)
showard170873e2009-01-07 00:22:26 +0000455 self._unregister_agent_for_ids(self._host_agents, agent.host_ids,
456 agent)
457 self._unregister_agent_for_ids(self._queue_entry_agents,
458 agent.queue_entry_ids, agent)
showardec113162008-05-08 00:52:49 +0000459
460
showard4c5374f2008-09-04 17:02:56 +0000461 def num_running_processes(self):
462 return sum(agent.num_processes for agent in self._agents
463 if agent.is_running())
mblighbb421852008-03-11 22:36:16 +0000464
465
showard170873e2009-01-07 00:22:26 +0000466 def _extract_execution_tag(self, command_line):
467 match = re.match(r'.* -P (\S+) ', command_line)
468 if not match:
469 return None
470 return match.group(1)
mblighbb421852008-03-11 22:36:16 +0000471
472
showard2bab8f42008-11-12 18:15:22 +0000473 def _recover_queue_entries(self, queue_entries, run_monitor):
474 assert len(queue_entries) > 0
showard2bab8f42008-11-12 18:15:22 +0000475 queue_task = RecoveryQueueTask(job=queue_entries[0].job,
476 queue_entries=queue_entries,
477 run_monitor=run_monitor)
jadmanski0afbb632008-06-06 21:10:57 +0000478 self.add_agent(Agent(tasks=[queue_task],
showard170873e2009-01-07 00:22:26 +0000479 num_processes=len(queue_entries)))
mblighbb421852008-03-11 22:36:16 +0000480
481
jadmanski0afbb632008-06-06 21:10:57 +0000482 def _recover_processes(self):
showard170873e2009-01-07 00:22:26 +0000483 self._register_pidfiles()
484 _drone_manager.refresh()
485 self._recover_running_entries()
486 self._recover_aborting_entries()
487 self._requeue_other_active_entries()
488 self._recover_parsing_entries()
489 self._reverify_remaining_hosts()
490 # reinitialize drones after killing orphaned processes, since they can
491 # leave around files when they die
492 _drone_manager.execute_actions()
493 _drone_manager.reinitialize_drones()
mblighbb421852008-03-11 22:36:16 +0000494
showard170873e2009-01-07 00:22:26 +0000495
496 def _register_pidfiles(self):
497 # during recovery we may need to read pidfiles for both running and
498 # parsing entries
499 queue_entries = HostQueueEntry.fetch(
500 where="status IN ('Running', 'Parsing')")
jadmanski0afbb632008-06-06 21:10:57 +0000501 for queue_entry in queue_entries:
showard170873e2009-01-07 00:22:26 +0000502 pidfile_id = _drone_manager.get_pidfile_id_from(
503 queue_entry.execution_tag())
504 _drone_manager.register_pidfile(pidfile_id)
505
506
507 def _recover_running_entries(self):
508 orphans = _drone_manager.get_orphaned_autoserv_processes()
509
510 queue_entries = HostQueueEntry.fetch(where="status = 'Running'")
511 requeue_entries = []
512 for queue_entry in queue_entries:
513 if self.get_agents_for_entry(queue_entry):
jadmanski0afbb632008-06-06 21:10:57 +0000514 # synchronous job we've already recovered
515 continue
showard170873e2009-01-07 00:22:26 +0000516 execution_tag = queue_entry.execution_tag()
517 run_monitor = PidfileRunMonitor()
518 run_monitor.attach_to_existing_process(execution_tag)
519 if not run_monitor.has_process():
520 # autoserv apparently never got run, so let it get requeued
521 continue
showarde788ea62008-11-17 21:02:47 +0000522 queue_entries = queue_entry.job.get_group_entries(queue_entry)
showard170873e2009-01-07 00:22:26 +0000523 print 'Recovering %s (process %s)' % (
524 ', '.join(str(entry) for entry in queue_entries),
525 run_monitor.get_process())
showard2bab8f42008-11-12 18:15:22 +0000526 self._recover_queue_entries(queue_entries, run_monitor)
showard170873e2009-01-07 00:22:26 +0000527 orphans.pop(execution_tag, None)
mbligh90a549d2008-03-25 23:52:34 +0000528
jadmanski0afbb632008-06-06 21:10:57 +0000529 # now kill any remaining autoserv processes
showard170873e2009-01-07 00:22:26 +0000530 for process in orphans.itervalues():
531 print 'Killing orphan %s' % process
532 _drone_manager.kill_process(process)
jadmanski0afbb632008-06-06 21:10:57 +0000533
showard170873e2009-01-07 00:22:26 +0000534
535 def _recover_aborting_entries(self):
536 queue_entries = HostQueueEntry.fetch(
537 where='status IN ("Abort", "Aborting")')
jadmanski0afbb632008-06-06 21:10:57 +0000538 for queue_entry in queue_entries:
showard170873e2009-01-07 00:22:26 +0000539 print 'Recovering aborting QE %s' % queue_entry
540 agent = queue_entry.abort(self)
jadmanski0afbb632008-06-06 21:10:57 +0000541
showard97aed502008-11-04 02:01:24 +0000542
showard170873e2009-01-07 00:22:26 +0000543 def _requeue_other_active_entries(self):
544 queue_entries = HostQueueEntry.fetch(
545 where='active AND NOT complete AND status != "Pending"')
546 for queue_entry in queue_entries:
547 if self.get_agents_for_entry(queue_entry):
548 # entry has already been recovered
549 continue
550 print 'Requeuing active QE %s (status=%s)' % (queue_entry,
551 queue_entry.status)
552 if queue_entry.host:
553 tasks = queue_entry.host.reverify_tasks()
554 self.add_agent(Agent(tasks))
555 agent = queue_entry.requeue()
556
557
558 def _reverify_remaining_hosts(self):
showard45ae8192008-11-05 19:32:53 +0000559 # reverify hosts that were in the middle of verify, repair or cleanup
jadmanski0afbb632008-06-06 21:10:57 +0000560 self._reverify_hosts_where("""(status = 'Repairing' OR
561 status = 'Verifying' OR
showard170873e2009-01-07 00:22:26 +0000562 status = 'Cleaning')""")
jadmanski0afbb632008-06-06 21:10:57 +0000563
showard170873e2009-01-07 00:22:26 +0000564 # recover "Running" hosts with no active queue entries, although this
565 # should never happen
566 message = ('Recovering running host %s - this probably indicates a '
567 'scheduler bug')
jadmanski0afbb632008-06-06 21:10:57 +0000568 self._reverify_hosts_where("""status = 'Running' AND
569 id NOT IN (SELECT host_id
570 FROM host_queue_entries
571 WHERE active)""",
572 print_message=message)
mblighbb421852008-03-11 22:36:16 +0000573
574
jadmanski0afbb632008-06-06 21:10:57 +0000575 def _reverify_hosts_where(self, where,
showard170873e2009-01-07 00:22:26 +0000576 print_message='Reverifying host %s'):
577 full_where='locked = 0 AND invalid = 0 AND ' + where
578 for host in Host.fetch(where=full_where):
579 if self.host_has_agent(host):
580 # host has already been recovered in some way
jadmanski0afbb632008-06-06 21:10:57 +0000581 continue
showard170873e2009-01-07 00:22:26 +0000582 if print_message:
jadmanski0afbb632008-06-06 21:10:57 +0000583 print print_message % host.hostname
showard170873e2009-01-07 00:22:26 +0000584 tasks = host.reverify_tasks()
585 self.add_agent(Agent(tasks))
mbligh36768f02008-02-22 18:28:33 +0000586
587
showard97aed502008-11-04 02:01:24 +0000588 def _recover_parsing_entries(self):
showard2bab8f42008-11-12 18:15:22 +0000589 recovered_entry_ids = set()
showard97aed502008-11-04 02:01:24 +0000590 for entry in HostQueueEntry.fetch(where='status = "Parsing"'):
showard2bab8f42008-11-12 18:15:22 +0000591 if entry.id in recovered_entry_ids:
592 continue
593 queue_entries = entry.job.get_group_entries(entry)
showard170873e2009-01-07 00:22:26 +0000594 recovered_entry_ids = recovered_entry_ids.union(
595 entry.id for entry in queue_entries)
596 print 'Recovering parsing entries %s' % (
597 ', '.join(str(entry) for entry in queue_entries))
showard97aed502008-11-04 02:01:24 +0000598
599 reparse_task = FinalReparseTask(queue_entries)
showard170873e2009-01-07 00:22:26 +0000600 self.add_agent(Agent([reparse_task], num_processes=0))
showard97aed502008-11-04 02:01:24 +0000601
602
jadmanski0afbb632008-06-06 21:10:57 +0000603 def _recover_hosts(self):
604 # recover "Repair Failed" hosts
605 message = 'Reverifying dead host %s'
606 self._reverify_hosts_where("status = 'Repair Failed'",
607 print_message=message)
mbligh62ba2ed2008-04-30 17:09:25 +0000608
609
showard3bb499f2008-07-03 19:42:20 +0000610 def _abort_timed_out_jobs(self):
611 """
612 Aborts all jobs that have timed out and not completed
613 """
showarda3ab0d52008-11-03 19:03:47 +0000614 query = models.Job.objects.filter(hostqueueentry__complete=False).extra(
615 where=['created_on + INTERVAL timeout HOUR < NOW()'])
616 for job in query.distinct():
617 print 'Aborting job %d due to job timeout' % job.id
618 job.abort(None)
showard3bb499f2008-07-03 19:42:20 +0000619
620
showard98863972008-10-29 21:14:56 +0000621 def _abort_jobs_past_synch_start_timeout(self):
622 """
623 Abort synchronous jobs that are past the start timeout (from global
624 config) and are holding a machine that's in everyone.
625 """
626 timeout_delta = datetime.timedelta(
showardd1ee1dd2009-01-07 21:33:08 +0000627 minutes=scheduler_config.config.synch_job_start_timeout_minutes)
showard98863972008-10-29 21:14:56 +0000628 timeout_start = datetime.datetime.now() - timeout_delta
629 query = models.Job.objects.filter(
showard98863972008-10-29 21:14:56 +0000630 created_on__lt=timeout_start,
631 hostqueueentry__status='Pending',
632 hostqueueentry__host__acl_group__name='Everyone')
633 for job in query.distinct():
634 print 'Aborting job %d due to start timeout' % job.id
showardff059d72008-12-03 18:18:53 +0000635 entries_to_abort = job.hostqueueentry_set.exclude(
636 status=models.HostQueueEntry.Status.RUNNING)
637 for queue_entry in entries_to_abort:
638 queue_entry.abort(None)
showard98863972008-10-29 21:14:56 +0000639
640
jadmanski0afbb632008-06-06 21:10:57 +0000641 def _clear_inactive_blocks(self):
642 """
643 Clear out blocks for all completed jobs.
644 """
645 # this would be simpler using NOT IN (subquery), but MySQL
646 # treats all IN subqueries as dependent, so this optimizes much
647 # better
648 _db.execute("""
649 DELETE ihq FROM ineligible_host_queues ihq
showard4eaaf522008-06-06 22:28:07 +0000650 LEFT JOIN (SELECT DISTINCT job_id FROM host_queue_entries
jadmanski0afbb632008-06-06 21:10:57 +0000651 WHERE NOT complete) hqe
652 USING (job_id) WHERE hqe.job_id IS NULL""")
showard04c82c52008-05-29 19:38:12 +0000653
654
showardb95b1bd2008-08-15 18:11:04 +0000655 def _get_pending_queue_entries(self):
showard63a34772008-08-18 19:32:50 +0000656 # prioritize by job priority, then non-metahost over metahost, then FIFO
657 return list(HostQueueEntry.fetch(
showardac9ce222008-12-03 18:19:44 +0000658 where='NOT complete AND NOT active AND status="Queued"',
showard3dd6b882008-10-27 19:21:39 +0000659 order_by='priority DESC, meta_host, job_id'))
mbligh36768f02008-02-22 18:28:33 +0000660
661
jadmanski0afbb632008-06-06 21:10:57 +0000662 def _schedule_new_jobs(self):
showard63a34772008-08-18 19:32:50 +0000663 queue_entries = self._get_pending_queue_entries()
664 if not queue_entries:
showardb95b1bd2008-08-15 18:11:04 +0000665 return
showardb95b1bd2008-08-15 18:11:04 +0000666
showard63a34772008-08-18 19:32:50 +0000667 self._host_scheduler.refresh(queue_entries)
showardb95b1bd2008-08-15 18:11:04 +0000668
showard63a34772008-08-18 19:32:50 +0000669 for queue_entry in queue_entries:
670 assigned_host = self._host_scheduler.find_eligible_host(queue_entry)
showardb95b1bd2008-08-15 18:11:04 +0000671 if not assigned_host:
jadmanski0afbb632008-06-06 21:10:57 +0000672 continue
showardb95b1bd2008-08-15 18:11:04 +0000673 self._run_queue_entry(queue_entry, assigned_host)
674
675
676 def _run_queue_entry(self, queue_entry, host):
677 agent = queue_entry.run(assigned_host=host)
showard170873e2009-01-07 00:22:26 +0000678 # in some cases (synchronous jobs with run_verify=False), agent may be
679 # None
showard9976ce92008-10-15 20:28:13 +0000680 if agent:
681 self.add_agent(agent)
mblighd5c95802008-03-05 00:33:46 +0000682
683
jadmanski0afbb632008-06-06 21:10:57 +0000684 def _find_aborting(self):
jadmanski0afbb632008-06-06 21:10:57 +0000685 for entry in queue_entries_to_abort():
showard170873e2009-01-07 00:22:26 +0000686 agents_to_abort = list(self.get_agents_for_entry(entry))
showard1be97432008-10-17 15:30:45 +0000687 for agent in agents_to_abort:
688 self.remove_agent(agent)
689
showard170873e2009-01-07 00:22:26 +0000690 entry.abort(self, agents_to_abort)
jadmanski0afbb632008-06-06 21:10:57 +0000691
692
showard4c5374f2008-09-04 17:02:56 +0000693 def _can_start_agent(self, agent, num_running_processes,
694 num_started_this_cycle, have_reached_limit):
695 # always allow zero-process agents to run
696 if agent.num_processes == 0:
697 return True
698 # don't allow any nonzero-process agents to run after we've reached a
699 # limit (this avoids starvation of many-process agents)
700 if have_reached_limit:
701 return False
702 # total process throttling
703 if (num_running_processes + agent.num_processes >
showardd1ee1dd2009-01-07 21:33:08 +0000704 scheduler_config.config.max_running_processes):
showard4c5374f2008-09-04 17:02:56 +0000705 return False
706 # if a single agent exceeds the per-cycle throttling, still allow it to
707 # run when it's the first agent in the cycle
708 if num_started_this_cycle == 0:
709 return True
710 # per-cycle throttling
711 if (num_started_this_cycle + agent.num_processes >
showardd1ee1dd2009-01-07 21:33:08 +0000712 scheduler_config.config.max_processes_started_per_cycle):
showard4c5374f2008-09-04 17:02:56 +0000713 return False
714 return True
715
716
jadmanski0afbb632008-06-06 21:10:57 +0000717 def _handle_agents(self):
showard4c5374f2008-09-04 17:02:56 +0000718 num_running_processes = self.num_running_processes()
jadmanski0afbb632008-06-06 21:10:57 +0000719 num_started_this_cycle = 0
showard4c5374f2008-09-04 17:02:56 +0000720 have_reached_limit = False
721 # iterate over copy, so we can remove agents during iteration
722 for agent in list(self._agents):
723 if agent.is_done():
jadmanski0afbb632008-06-06 21:10:57 +0000724 print "agent finished"
showard170873e2009-01-07 00:22:26 +0000725 self.remove_agent(agent)
showard4c5374f2008-09-04 17:02:56 +0000726 continue
727 if not agent.is_running():
728 if not self._can_start_agent(agent, num_running_processes,
729 num_started_this_cycle,
730 have_reached_limit):
731 have_reached_limit = True
732 continue
733 num_running_processes += agent.num_processes
734 num_started_this_cycle += agent.num_processes
735 agent.tick()
736 print num_running_processes, 'running processes'
mbligh36768f02008-02-22 18:28:33 +0000737
738
showardfa8629c2008-11-04 16:51:23 +0000739 def _check_for_db_inconsistencies(self):
740 query = models.HostQueueEntry.objects.filter(active=True, complete=True)
741 if query.count() != 0:
742 subject = ('%d queue entries found with active=complete=1'
743 % query.count())
744 message = '\n'.join(str(entry.get_object_dict())
745 for entry in query[:50])
746 if len(query) > 50:
747 message += '\n(truncated)\n'
748
749 print subject
showard170873e2009-01-07 00:22:26 +0000750 email_manager.manager.enqueue_notify_email(subject, message)
showardfa8629c2008-11-04 16:51:23 +0000751
752
showard170873e2009-01-07 00:22:26 +0000753class PidfileRunMonitor(object):
754 """
755 Client must call either run() to start a new process or
756 attach_to_existing_process().
757 """
mbligh36768f02008-02-22 18:28:33 +0000758
showard170873e2009-01-07 00:22:26 +0000759 class _PidfileException(Exception):
760 """
761 Raised when there's some unexpected behavior with the pid file, but only
762 used internally (never allowed to escape this class).
763 """
mbligh36768f02008-02-22 18:28:33 +0000764
765
showard170873e2009-01-07 00:22:26 +0000766 def __init__(self):
767 self._lost_process = False
768 self._start_time = None
769 self.pidfile_id = None
770 self._state = drone_manager.PidfileContents()
showard2bab8f42008-11-12 18:15:22 +0000771
772
showard170873e2009-01-07 00:22:26 +0000773 def _add_nice_command(self, command, nice_level):
774 if not nice_level:
775 return command
776 return ['nice', '-n', str(nice_level)] + command
777
778
779 def _set_start_time(self):
780 self._start_time = time.time()
781
782
783 def run(self, command, working_directory, nice_level=None, log_file=None,
784 pidfile_name=None, paired_with_pidfile=None):
785 assert command is not None
786 if nice_level is not None:
787 command = ['nice', '-n', str(nice_level)] + command
788 self._set_start_time()
789 self.pidfile_id = _drone_manager.execute_command(
790 command, working_directory, log_file=log_file,
791 pidfile_name=pidfile_name, paired_with_pidfile=paired_with_pidfile)
792
793
794 def attach_to_existing_process(self, execution_tag):
795 self._set_start_time()
796 self.pidfile_id = _drone_manager.get_pidfile_id_from(execution_tag)
797 _drone_manager.register_pidfile(self.pidfile_id)
mblighbb421852008-03-11 22:36:16 +0000798
799
jadmanski0afbb632008-06-06 21:10:57 +0000800 def kill(self):
showard170873e2009-01-07 00:22:26 +0000801 if self.has_process():
802 _drone_manager.kill_process(self.get_process())
mblighbb421852008-03-11 22:36:16 +0000803
mbligh36768f02008-02-22 18:28:33 +0000804
showard170873e2009-01-07 00:22:26 +0000805 def has_process(self):
showard21baa452008-10-21 00:08:39 +0000806 self._get_pidfile_info()
showard170873e2009-01-07 00:22:26 +0000807 return self._state.process is not None
showard21baa452008-10-21 00:08:39 +0000808
809
showard170873e2009-01-07 00:22:26 +0000810 def get_process(self):
showard21baa452008-10-21 00:08:39 +0000811 self._get_pidfile_info()
showard170873e2009-01-07 00:22:26 +0000812 assert self.has_process()
813 return self._state.process
mblighbb421852008-03-11 22:36:16 +0000814
815
showard170873e2009-01-07 00:22:26 +0000816 def _read_pidfile(self, use_second_read=False):
817 assert self.pidfile_id is not None, (
818 'You must call run() or attach_to_existing_process()')
819 contents = _drone_manager.get_pidfile_contents(
820 self.pidfile_id, use_second_read=use_second_read)
821 if contents.is_invalid():
822 self._state = drone_manager.PidfileContents()
823 raise self._PidfileException(contents)
824 self._state = contents
mbligh90a549d2008-03-25 23:52:34 +0000825
826
showard21baa452008-10-21 00:08:39 +0000827 def _handle_pidfile_error(self, error, message=''):
showard170873e2009-01-07 00:22:26 +0000828 message = error + '\nProcess: %s\nPidfile: %s\n%s' % (
829 self._state.process, self.pidfile_id, message)
showard21baa452008-10-21 00:08:39 +0000830 print message
showard170873e2009-01-07 00:22:26 +0000831 email_manager.manager.enqueue_notify_email(error, message)
832 if self._state.process is not None:
833 process = self._state.process
showard21baa452008-10-21 00:08:39 +0000834 else:
showard170873e2009-01-07 00:22:26 +0000835 process = _drone_manager.get_dummy_process()
836 self.on_lost_process(process)
showard21baa452008-10-21 00:08:39 +0000837
838
839 def _get_pidfile_info_helper(self):
showard170873e2009-01-07 00:22:26 +0000840 if self._lost_process:
showard21baa452008-10-21 00:08:39 +0000841 return
mblighbb421852008-03-11 22:36:16 +0000842
showard21baa452008-10-21 00:08:39 +0000843 self._read_pidfile()
mblighbb421852008-03-11 22:36:16 +0000844
showard170873e2009-01-07 00:22:26 +0000845 if self._state.process is None:
846 self._handle_no_process()
showard21baa452008-10-21 00:08:39 +0000847 return
mbligh90a549d2008-03-25 23:52:34 +0000848
showard21baa452008-10-21 00:08:39 +0000849 if self._state.exit_status is None:
jadmanski0afbb632008-06-06 21:10:57 +0000850 # double check whether or not autoserv is running
showard170873e2009-01-07 00:22:26 +0000851 if _drone_manager.is_process_running(self._state.process):
showard21baa452008-10-21 00:08:39 +0000852 return
mbligh90a549d2008-03-25 23:52:34 +0000853
showard170873e2009-01-07 00:22:26 +0000854 # pid but no running process - maybe process *just* exited
855 self._read_pidfile(use_second_read=True)
showard21baa452008-10-21 00:08:39 +0000856 if self._state.exit_status is None:
jadmanski0afbb632008-06-06 21:10:57 +0000857 # autoserv exited without writing an exit code
858 # to the pidfile
showard21baa452008-10-21 00:08:39 +0000859 self._handle_pidfile_error(
860 'autoserv died without writing exit code')
mblighbb421852008-03-11 22:36:16 +0000861
showard21baa452008-10-21 00:08:39 +0000862
863 def _get_pidfile_info(self):
864 """\
865 After completion, self._state will contain:
866 pid=None, exit_status=None if autoserv has not yet run
867 pid!=None, exit_status=None if autoserv is running
868 pid!=None, exit_status!=None if autoserv has completed
869 """
870 try:
871 self._get_pidfile_info_helper()
showard170873e2009-01-07 00:22:26 +0000872 except self._PidfileException, exc:
showard21baa452008-10-21 00:08:39 +0000873 self._handle_pidfile_error('Pidfile error', traceback.format_exc())
mblighbb421852008-03-11 22:36:16 +0000874
875
showard170873e2009-01-07 00:22:26 +0000876 def _handle_no_process(self):
jadmanski0afbb632008-06-06 21:10:57 +0000877 """\
878 Called when no pidfile is found or no pid is in the pidfile.
879 """
showard170873e2009-01-07 00:22:26 +0000880 message = 'No pid found at %s' % self.pidfile_id
jadmanski0afbb632008-06-06 21:10:57 +0000881 print message
showard170873e2009-01-07 00:22:26 +0000882 if time.time() - self._start_time > PIDFILE_TIMEOUT:
883 email_manager.manager.enqueue_notify_email(
jadmanski0afbb632008-06-06 21:10:57 +0000884 'Process has failed to write pidfile', message)
showard170873e2009-01-07 00:22:26 +0000885 self.on_lost_process(_drone_manager.get_dummy_process())
mbligh90a549d2008-03-25 23:52:34 +0000886
887
showard170873e2009-01-07 00:22:26 +0000888 def on_lost_process(self, process):
jadmanski0afbb632008-06-06 21:10:57 +0000889 """\
890 Called when autoserv has exited without writing an exit status,
891 or we've timed out waiting for autoserv to write a pid to the
892 pidfile. In either case, we just return failure and the caller
893 should signal some kind of warning.
mbligh90a549d2008-03-25 23:52:34 +0000894
showard170873e2009-01-07 00:22:26 +0000895 process is unimportant here, as it shouldn't be used by anyone.
jadmanski0afbb632008-06-06 21:10:57 +0000896 """
897 self.lost_process = True
showard170873e2009-01-07 00:22:26 +0000898 self._state.process = process
showard21baa452008-10-21 00:08:39 +0000899 self._state.exit_status = 1
900 self._state.num_tests_failed = 0
mbligh90a549d2008-03-25 23:52:34 +0000901
902
jadmanski0afbb632008-06-06 21:10:57 +0000903 def exit_code(self):
showard21baa452008-10-21 00:08:39 +0000904 self._get_pidfile_info()
905 return self._state.exit_status
906
907
908 def num_tests_failed(self):
909 self._get_pidfile_info()
910 assert self._state.num_tests_failed is not None
911 return self._state.num_tests_failed
mblighbb421852008-03-11 22:36:16 +0000912
913
mbligh36768f02008-02-22 18:28:33 +0000914class Agent(object):
showard170873e2009-01-07 00:22:26 +0000915 def __init__(self, tasks, num_processes=1):
jadmanski0afbb632008-06-06 21:10:57 +0000916 self.active_task = None
917 self.queue = Queue.Queue(0)
918 self.dispatcher = None
showard4c5374f2008-09-04 17:02:56 +0000919 self.num_processes = num_processes
jadmanski0afbb632008-06-06 21:10:57 +0000920
showard170873e2009-01-07 00:22:26 +0000921 self.queue_entry_ids = self._union_ids(task.queue_entry_ids
922 for task in tasks)
923 self.host_ids = self._union_ids(task.host_ids for task in tasks)
924
jadmanski0afbb632008-06-06 21:10:57 +0000925 for task in tasks:
926 self.add_task(task)
mbligh36768f02008-02-22 18:28:33 +0000927
928
showard170873e2009-01-07 00:22:26 +0000929 def _union_ids(self, id_lists):
930 return set(itertools.chain(*id_lists))
931
932
jadmanski0afbb632008-06-06 21:10:57 +0000933 def add_task(self, task):
934 self.queue.put_nowait(task)
935 task.agent = self
mbligh36768f02008-02-22 18:28:33 +0000936
937
jadmanski0afbb632008-06-06 21:10:57 +0000938 def tick(self):
showard21baa452008-10-21 00:08:39 +0000939 while not self.is_done():
940 if self.active_task and not self.active_task.is_done():
941 self.active_task.poll()
942 if not self.active_task.is_done():
943 return
944 self._next_task()
mbligh36768f02008-02-22 18:28:33 +0000945
946
jadmanski0afbb632008-06-06 21:10:57 +0000947 def _next_task(self):
948 print "agent picking task"
949 if self.active_task:
950 assert self.active_task.is_done()
mbligh36768f02008-02-22 18:28:33 +0000951
jadmanski0afbb632008-06-06 21:10:57 +0000952 if not self.active_task.success:
953 self.on_task_failure()
mblighe2586682008-02-29 22:45:46 +0000954
jadmanski0afbb632008-06-06 21:10:57 +0000955 self.active_task = None
956 if not self.is_done():
957 self.active_task = self.queue.get_nowait()
958 if self.active_task:
959 self.active_task.start()
mbligh36768f02008-02-22 18:28:33 +0000960
961
jadmanski0afbb632008-06-06 21:10:57 +0000962 def on_task_failure(self):
963 self.queue = Queue.Queue(0)
964 for task in self.active_task.failure_tasks:
965 self.add_task(task)
mbligh16c722d2008-03-05 00:58:44 +0000966
mblighe2586682008-02-29 22:45:46 +0000967
showard4c5374f2008-09-04 17:02:56 +0000968 def is_running(self):
jadmanski0afbb632008-06-06 21:10:57 +0000969 return self.active_task is not None
showardec113162008-05-08 00:52:49 +0000970
971
jadmanski0afbb632008-06-06 21:10:57 +0000972 def is_done(self):
mblighd876f452008-12-03 15:09:17 +0000973 return self.active_task is None and self.queue.empty()
mbligh36768f02008-02-22 18:28:33 +0000974
975
jadmanski0afbb632008-06-06 21:10:57 +0000976 def start(self):
977 assert self.dispatcher
mbligh36768f02008-02-22 18:28:33 +0000978
jadmanski0afbb632008-06-06 21:10:57 +0000979 self._next_task()
mbligh36768f02008-02-22 18:28:33 +0000980
jadmanski0afbb632008-06-06 21:10:57 +0000981
mbligh36768f02008-02-22 18:28:33 +0000982class AgentTask(object):
showard170873e2009-01-07 00:22:26 +0000983 def __init__(self, cmd, working_directory=None, failure_tasks=[]):
jadmanski0afbb632008-06-06 21:10:57 +0000984 self.done = False
985 self.failure_tasks = failure_tasks
986 self.started = False
987 self.cmd = cmd
showard170873e2009-01-07 00:22:26 +0000988 self._working_directory = working_directory
jadmanski0afbb632008-06-06 21:10:57 +0000989 self.task = None
990 self.agent = None
991 self.monitor = None
992 self.success = None
showard170873e2009-01-07 00:22:26 +0000993 self.queue_entry_ids = []
994 self.host_ids = []
995 self.log_file = None
996
997
998 def _set_ids(self, host=None, queue_entries=None):
999 if queue_entries and queue_entries != [None]:
1000 self.host_ids = [entry.host.id for entry in queue_entries]
1001 self.queue_entry_ids = [entry.id for entry in queue_entries]
1002 else:
1003 assert host
1004 self.host_ids = [host.id]
mbligh36768f02008-02-22 18:28:33 +00001005
1006
jadmanski0afbb632008-06-06 21:10:57 +00001007 def poll(self):
jadmanski0afbb632008-06-06 21:10:57 +00001008 if self.monitor:
1009 self.tick(self.monitor.exit_code())
1010 else:
1011 self.finished(False)
mbligh36768f02008-02-22 18:28:33 +00001012
1013
jadmanski0afbb632008-06-06 21:10:57 +00001014 def tick(self, exit_code):
showard170873e2009-01-07 00:22:26 +00001015 if exit_code is None:
jadmanski0afbb632008-06-06 21:10:57 +00001016 return
jadmanski0afbb632008-06-06 21:10:57 +00001017 if exit_code == 0:
1018 success = True
1019 else:
1020 success = False
mbligh36768f02008-02-22 18:28:33 +00001021
jadmanski0afbb632008-06-06 21:10:57 +00001022 self.finished(success)
mbligh36768f02008-02-22 18:28:33 +00001023
1024
jadmanski0afbb632008-06-06 21:10:57 +00001025 def is_done(self):
1026 return self.done
mbligh36768f02008-02-22 18:28:33 +00001027
1028
jadmanski0afbb632008-06-06 21:10:57 +00001029 def finished(self, success):
1030 self.done = True
1031 self.success = success
1032 self.epilog()
mbligh36768f02008-02-22 18:28:33 +00001033
1034
jadmanski0afbb632008-06-06 21:10:57 +00001035 def prolog(self):
1036 pass
mblighd64e5702008-04-04 21:39:28 +00001037
1038
jadmanski0afbb632008-06-06 21:10:57 +00001039 def create_temp_resultsdir(self, suffix=''):
showard170873e2009-01-07 00:22:26 +00001040 self.temp_results_dir = _drone_manager.get_temporary_path('agent_task')
mblighd64e5702008-04-04 21:39:28 +00001041
mbligh36768f02008-02-22 18:28:33 +00001042
jadmanski0afbb632008-06-06 21:10:57 +00001043 def cleanup(self):
showard170873e2009-01-07 00:22:26 +00001044 if self.monitor and self.log_file:
1045 _drone_manager.copy_to_results_repository(
1046 self.monitor.get_process(), self.log_file)
mbligh36768f02008-02-22 18:28:33 +00001047
1048
jadmanski0afbb632008-06-06 21:10:57 +00001049 def epilog(self):
1050 self.cleanup()
mbligh36768f02008-02-22 18:28:33 +00001051
1052
jadmanski0afbb632008-06-06 21:10:57 +00001053 def start(self):
1054 assert self.agent
1055
1056 if not self.started:
1057 self.prolog()
1058 self.run()
1059
1060 self.started = True
1061
1062
1063 def abort(self):
1064 if self.monitor:
1065 self.monitor.kill()
1066 self.done = True
1067 self.cleanup()
1068
1069
showard170873e2009-01-07 00:22:26 +00001070 def set_host_log_file(self, base_name, host):
1071 filename = '%s.%s' % (time.time(), base_name)
1072 self.log_file = os.path.join('hosts', host.hostname, filename)
1073
1074
jadmanski0afbb632008-06-06 21:10:57 +00001075 def run(self):
1076 if self.cmd:
showard170873e2009-01-07 00:22:26 +00001077 self.monitor = PidfileRunMonitor()
1078 self.monitor.run(self.cmd, self._working_directory,
1079 nice_level=AUTOSERV_NICE_LEVEL,
1080 log_file=self.log_file)
mbligh36768f02008-02-22 18:28:33 +00001081
1082
1083class RepairTask(AgentTask):
showarde788ea62008-11-17 21:02:47 +00001084 def __init__(self, host, queue_entry=None):
jadmanski0afbb632008-06-06 21:10:57 +00001085 """\
showard170873e2009-01-07 00:22:26 +00001086 queue_entry: queue entry to mark failed if this repair fails.
jadmanski0afbb632008-06-06 21:10:57 +00001087 """
jadmanskifb7cfb12008-07-09 14:13:21 +00001088 protection = host_protections.Protection.get_string(host.protection)
jadmanski542537f2008-07-24 14:14:56 +00001089 # normalize the protection name
1090 protection = host_protections.Protection.get_attr_name(protection)
showard170873e2009-01-07 00:22:26 +00001091
jadmanski0afbb632008-06-06 21:10:57 +00001092 self.host = host
showarde788ea62008-11-17 21:02:47 +00001093 self.queue_entry = queue_entry
showard170873e2009-01-07 00:22:26 +00001094 self._set_ids(host=host, queue_entries=[queue_entry])
1095
1096 self.create_temp_resultsdir('.repair')
1097 cmd = [_autoserv_path , '-p', '-R', '-m', host.hostname,
1098 '-r', _drone_manager.absolute_path(self.temp_results_dir),
1099 '--host-protection', protection]
1100 super(RepairTask, self).__init__(cmd, self.temp_results_dir)
1101
1102 self._set_ids(host=host, queue_entries=[queue_entry])
1103 self.set_host_log_file('repair', self.host)
mblighe2586682008-02-29 22:45:46 +00001104
mbligh36768f02008-02-22 18:28:33 +00001105
jadmanski0afbb632008-06-06 21:10:57 +00001106 def prolog(self):
1107 print "repair_task starting"
1108 self.host.set_status('Repairing')
showarde788ea62008-11-17 21:02:47 +00001109 if self.queue_entry:
1110 self.queue_entry.requeue()
mbligh36768f02008-02-22 18:28:33 +00001111
1112
jadmanski0afbb632008-06-06 21:10:57 +00001113 def epilog(self):
1114 super(RepairTask, self).epilog()
1115 if self.success:
1116 self.host.set_status('Ready')
1117 else:
1118 self.host.set_status('Repair Failed')
showarde788ea62008-11-17 21:02:47 +00001119 if self.queue_entry and not self.queue_entry.meta_host:
1120 self.queue_entry.handle_host_failure()
mbligh36768f02008-02-22 18:28:33 +00001121
1122
showard8fe93b52008-11-18 17:53:22 +00001123class PreJobTask(AgentTask):
showard170873e2009-01-07 00:22:26 +00001124 def epilog(self):
1125 super(PreJobTask, self).epilog()
showard8fe93b52008-11-18 17:53:22 +00001126 should_copy_results = (self.queue_entry and not self.success
1127 and not self.queue_entry.meta_host)
1128 if should_copy_results:
1129 self.queue_entry.set_execution_subdir()
showard170873e2009-01-07 00:22:26 +00001130 destination = os.path.join(self.queue_entry.execution_tag(),
1131 os.path.basename(self.log_file))
1132 _drone_manager.copy_to_results_repository(
1133 self.monitor.get_process(), self.log_file,
1134 destination_path=destination)
showard8fe93b52008-11-18 17:53:22 +00001135
1136
1137class VerifyTask(PreJobTask):
showard9976ce92008-10-15 20:28:13 +00001138 def __init__(self, queue_entry=None, host=None):
jadmanski0afbb632008-06-06 21:10:57 +00001139 assert bool(queue_entry) != bool(host)
jadmanski0afbb632008-06-06 21:10:57 +00001140 self.host = host or queue_entry.host
1141 self.queue_entry = queue_entry
mbligh36768f02008-02-22 18:28:33 +00001142
jadmanski0afbb632008-06-06 21:10:57 +00001143 self.create_temp_resultsdir('.verify')
showard170873e2009-01-07 00:22:26 +00001144 cmd = [_autoserv_path, '-p', '-v', '-m', self.host.hostname, '-r',
1145 _drone_manager.absolute_path(self.temp_results_dir)]
showarde788ea62008-11-17 21:02:47 +00001146 failure_tasks = [RepairTask(self.host, queue_entry=queue_entry)]
showard170873e2009-01-07 00:22:26 +00001147 super(VerifyTask, self).__init__(cmd, self.temp_results_dir,
1148 failure_tasks=failure_tasks)
mblighe2586682008-02-29 22:45:46 +00001149
showard170873e2009-01-07 00:22:26 +00001150 self.set_host_log_file('verify', self.host)
1151 self._set_ids(host=host, queue_entries=[queue_entry])
mblighe2586682008-02-29 22:45:46 +00001152
1153
jadmanski0afbb632008-06-06 21:10:57 +00001154 def prolog(self):
showard8fe93b52008-11-18 17:53:22 +00001155 super(VerifyTask, self).prolog()
jadmanski0afbb632008-06-06 21:10:57 +00001156 print "starting verify on %s" % (self.host.hostname)
1157 if self.queue_entry:
1158 self.queue_entry.set_status('Verifying')
jadmanski0afbb632008-06-06 21:10:57 +00001159 self.host.set_status('Verifying')
mbligh36768f02008-02-22 18:28:33 +00001160
1161
jadmanski0afbb632008-06-06 21:10:57 +00001162 def epilog(self):
1163 super(VerifyTask, self).epilog()
mbligh36768f02008-02-22 18:28:33 +00001164
jadmanski0afbb632008-06-06 21:10:57 +00001165 if self.success:
1166 self.host.set_status('Ready')
showard2bab8f42008-11-12 18:15:22 +00001167 if self.queue_entry:
1168 agent = self.queue_entry.on_pending()
1169 if agent:
1170 self.agent.dispatcher.add_agent(agent)
mbligh36768f02008-02-22 18:28:33 +00001171
1172
mbligh36768f02008-02-22 18:28:33 +00001173class QueueTask(AgentTask):
jadmanski0afbb632008-06-06 21:10:57 +00001174 def __init__(self, job, queue_entries, cmd):
jadmanski0afbb632008-06-06 21:10:57 +00001175 self.job = job
1176 self.queue_entries = queue_entries
showard170873e2009-01-07 00:22:26 +00001177 super(QueueTask, self).__init__(cmd, self._execution_tag())
1178 self._set_ids(queue_entries=queue_entries)
mbligh36768f02008-02-22 18:28:33 +00001179
1180
showard170873e2009-01-07 00:22:26 +00001181 def _format_keyval(self, key, value):
1182 return '%s=%s' % (key, value)
mbligh36768f02008-02-22 18:28:33 +00001183
1184
showard170873e2009-01-07 00:22:26 +00001185 def _write_keyval(self, field, value):
1186 keyval_path = os.path.join(self._execution_tag(), 'keyval')
1187 assert self.monitor and self.monitor.has_process()
1188 paired_with_pidfile = self.monitor.pidfile_id
1189 _drone_manager.write_lines_to_file(
1190 keyval_path, [self._format_keyval(field, value)],
1191 paired_with_pidfile=paired_with_pidfile)
showardd8e548a2008-09-09 03:04:57 +00001192
1193
showard170873e2009-01-07 00:22:26 +00001194 def _write_host_keyvals(self, host):
1195 keyval_path = os.path.join(self._execution_tag(), 'host_keyvals',
1196 host.hostname)
1197 platform, all_labels = host.platform_and_labels()
1198 keyvals = dict(platform=platform, labels=','.join(all_labels))
1199 keyval_content = '\n'.join(self._format_keyval(key, value)
1200 for key, value in keyvals.iteritems())
1201 _drone_manager.attach_file_to_execution(self._execution_tag(),
1202 keyval_content,
1203 file_path=keyval_path)
showardd8e548a2008-09-09 03:04:57 +00001204
1205
showard170873e2009-01-07 00:22:26 +00001206 def _execution_tag(self):
1207 return self.queue_entries[0].execution_tag()
mblighbb421852008-03-11 22:36:16 +00001208
1209
jadmanski0afbb632008-06-06 21:10:57 +00001210 def prolog(self):
jadmanski0afbb632008-06-06 21:10:57 +00001211 for queue_entry in self.queue_entries:
showard170873e2009-01-07 00:22:26 +00001212 self._write_host_keyvals(queue_entry.host)
jadmanski0afbb632008-06-06 21:10:57 +00001213 queue_entry.set_status('Running')
1214 queue_entry.host.set_status('Running')
showard21baa452008-10-21 00:08:39 +00001215 queue_entry.host.update_field('dirty', 1)
showard2bab8f42008-11-12 18:15:22 +00001216 if self.job.synch_count == 1:
jadmanski0afbb632008-06-06 21:10:57 +00001217 assert len(self.queue_entries) == 1
1218 self.job.write_to_machines_file(self.queue_entries[0])
mbligh36768f02008-02-22 18:28:33 +00001219
1220
showard97aed502008-11-04 02:01:24 +00001221 def _finish_task(self, success):
showard170873e2009-01-07 00:22:26 +00001222 queued = time.mktime(self.job.created_on.timetuple())
jadmanski0afbb632008-06-06 21:10:57 +00001223 finished = time.time()
showard170873e2009-01-07 00:22:26 +00001224 self._write_keyval("job_queued", int(queued))
1225 self._write_keyval("job_finished", int(finished))
1226
1227 _drone_manager.copy_to_results_repository(self.monitor.get_process(),
1228 self._execution_tag() + '/')
jadmanskic2ac77f2008-05-16 21:44:04 +00001229
jadmanski0afbb632008-06-06 21:10:57 +00001230 # parse the results of the job
showard97aed502008-11-04 02:01:24 +00001231 reparse_task = FinalReparseTask(self.queue_entries)
showard170873e2009-01-07 00:22:26 +00001232 self.agent.dispatcher.add_agent(Agent([reparse_task], num_processes=0))
jadmanskif7fa2cc2008-10-01 14:13:23 +00001233
1234
showardcbd74612008-11-19 21:42:02 +00001235 def _write_status_comment(self, comment):
showard170873e2009-01-07 00:22:26 +00001236 _drone_manager.write_lines_to_file(
1237 os.path.join(self._execution_tag(), 'status.log'),
1238 ['INFO\t----\t----\t' + comment],
1239 paired_with_pidfile=self.monitor.pidfile_id)
showardcbd74612008-11-19 21:42:02 +00001240
1241
jadmanskif7fa2cc2008-10-01 14:13:23 +00001242 def _log_abort(self):
showard170873e2009-01-07 00:22:26 +00001243 if not self.monitor or not self.monitor.has_process():
1244 return
1245
jadmanskif7fa2cc2008-10-01 14:13:23 +00001246 # build up sets of all the aborted_by and aborted_on values
1247 aborted_by, aborted_on = set(), set()
1248 for queue_entry in self.queue_entries:
1249 if queue_entry.aborted_by:
1250 aborted_by.add(queue_entry.aborted_by)
1251 t = int(time.mktime(queue_entry.aborted_on.timetuple()))
1252 aborted_on.add(t)
1253
1254 # extract some actual, unique aborted by value and write it out
1255 assert len(aborted_by) <= 1
1256 if len(aborted_by) == 1:
showardcbd74612008-11-19 21:42:02 +00001257 aborted_by_value = aborted_by.pop()
1258 aborted_on_value = max(aborted_on)
1259 else:
1260 aborted_by_value = 'autotest_system'
1261 aborted_on_value = int(time.time())
showard170873e2009-01-07 00:22:26 +00001262
1263 self._write_keyval("aborted_by", aborted_by_value)
1264 self._write_keyval("aborted_on", aborted_on_value)
1265
showardcbd74612008-11-19 21:42:02 +00001266 aborted_on_string = str(datetime.datetime.fromtimestamp(
1267 aborted_on_value))
1268 self._write_status_comment('Job aborted by %s on %s' %
1269 (aborted_by_value, aborted_on_string))
jadmanskic2ac77f2008-05-16 21:44:04 +00001270
1271
jadmanski0afbb632008-06-06 21:10:57 +00001272 def abort(self):
1273 super(QueueTask, self).abort()
jadmanskif7fa2cc2008-10-01 14:13:23 +00001274 self._log_abort()
showard97aed502008-11-04 02:01:24 +00001275 self._finish_task(False)
jadmanskic2ac77f2008-05-16 21:44:04 +00001276
1277
showard21baa452008-10-21 00:08:39 +00001278 def _reboot_hosts(self):
1279 reboot_after = self.job.reboot_after
1280 do_reboot = False
showard0fc38302008-10-23 00:44:07 +00001281 if reboot_after == models.RebootAfter.ALWAYS:
showard21baa452008-10-21 00:08:39 +00001282 do_reboot = True
showard0fc38302008-10-23 00:44:07 +00001283 elif reboot_after == models.RebootAfter.IF_ALL_TESTS_PASSED:
showard21baa452008-10-21 00:08:39 +00001284 num_tests_failed = self.monitor.num_tests_failed()
1285 do_reboot = (self.success and num_tests_failed == 0)
1286
showard8ebca792008-11-04 21:54:22 +00001287 for queue_entry in self.queue_entries:
1288 if do_reboot:
showard45ae8192008-11-05 19:32:53 +00001289 # don't pass the queue entry to the CleanupTask. if the cleanup
showardfa8629c2008-11-04 16:51:23 +00001290 # fails, the job doesn't care -- it's over.
showard45ae8192008-11-05 19:32:53 +00001291 cleanup_task = CleanupTask(host=queue_entry.get_host())
1292 self.agent.dispatcher.add_agent(Agent([cleanup_task]))
showard8ebca792008-11-04 21:54:22 +00001293 else:
1294 queue_entry.host.set_status('Ready')
showard21baa452008-10-21 00:08:39 +00001295
1296
jadmanski0afbb632008-06-06 21:10:57 +00001297 def epilog(self):
1298 super(QueueTask, self).epilog()
showard97aed502008-11-04 02:01:24 +00001299 self._finish_task(self.success)
showard21baa452008-10-21 00:08:39 +00001300 self._reboot_hosts()
mblighbb421852008-03-11 22:36:16 +00001301
showard97aed502008-11-04 02:01:24 +00001302 print "queue_task finished with succes=%s" % self.success
mbligh36768f02008-02-22 18:28:33 +00001303
1304
mblighbb421852008-03-11 22:36:16 +00001305class RecoveryQueueTask(QueueTask):
jadmanski0afbb632008-06-06 21:10:57 +00001306 def __init__(self, job, queue_entries, run_monitor):
showard170873e2009-01-07 00:22:26 +00001307 super(RecoveryQueueTask, self).__init__(job, queue_entries, cmd=None)
jadmanski0afbb632008-06-06 21:10:57 +00001308 self.run_monitor = run_monitor
mblighbb421852008-03-11 22:36:16 +00001309
1310
jadmanski0afbb632008-06-06 21:10:57 +00001311 def run(self):
1312 self.monitor = self.run_monitor
mblighbb421852008-03-11 22:36:16 +00001313
1314
jadmanski0afbb632008-06-06 21:10:57 +00001315 def prolog(self):
1316 # recovering an existing process - don't do prolog
1317 pass
mblighbb421852008-03-11 22:36:16 +00001318
1319
showard8fe93b52008-11-18 17:53:22 +00001320class CleanupTask(PreJobTask):
showardfa8629c2008-11-04 16:51:23 +00001321 def __init__(self, host=None, queue_entry=None):
1322 assert bool(host) ^ bool(queue_entry)
1323 if queue_entry:
1324 host = queue_entry.get_host()
showardfa8629c2008-11-04 16:51:23 +00001325 self.queue_entry = queue_entry
jadmanski0afbb632008-06-06 21:10:57 +00001326 self.host = host
showard170873e2009-01-07 00:22:26 +00001327
1328 self.create_temp_resultsdir('.cleanup')
1329 self.cmd = [_autoserv_path, '-p', '--cleanup', '-m', host.hostname,
1330 '-r', _drone_manager.absolute_path(self.temp_results_dir)]
showarde788ea62008-11-17 21:02:47 +00001331 repair_task = RepairTask(host, queue_entry=queue_entry)
showard170873e2009-01-07 00:22:26 +00001332 super(CleanupTask, self).__init__(self.cmd, self.temp_results_dir,
1333 failure_tasks=[repair_task])
1334
1335 self._set_ids(host=host, queue_entries=[queue_entry])
1336 self.set_host_log_file('cleanup', self.host)
mbligh16c722d2008-03-05 00:58:44 +00001337
mblighd5c95802008-03-05 00:33:46 +00001338
jadmanski0afbb632008-06-06 21:10:57 +00001339 def prolog(self):
showard8fe93b52008-11-18 17:53:22 +00001340 super(CleanupTask, self).prolog()
showard45ae8192008-11-05 19:32:53 +00001341 print "starting cleanup task for host: %s" % self.host.hostname
1342 self.host.set_status("Cleaning")
mblighd5c95802008-03-05 00:33:46 +00001343
mblighd5c95802008-03-05 00:33:46 +00001344
showard21baa452008-10-21 00:08:39 +00001345 def epilog(self):
showard45ae8192008-11-05 19:32:53 +00001346 super(CleanupTask, self).epilog()
showard21baa452008-10-21 00:08:39 +00001347 if self.success:
showardfa8629c2008-11-04 16:51:23 +00001348 self.host.set_status('Ready')
showard21baa452008-10-21 00:08:39 +00001349 self.host.update_field('dirty', 0)
1350
1351
mblighd5c95802008-03-05 00:33:46 +00001352class AbortTask(AgentTask):
jadmanski0afbb632008-06-06 21:10:57 +00001353 def __init__(self, queue_entry, agents_to_abort):
jadmanski0afbb632008-06-06 21:10:57 +00001354 super(AbortTask, self).__init__('')
showard170873e2009-01-07 00:22:26 +00001355 self.queue_entry = queue_entry
1356 # don't use _set_ids, since we don't want to set the host_ids
1357 self.queue_entry_ids = [queue_entry.id]
1358 self.agents_to_abort = agents_to_abort
mbligh36768f02008-02-22 18:28:33 +00001359
1360
jadmanski0afbb632008-06-06 21:10:57 +00001361 def prolog(self):
1362 print "starting abort on host %s, job %s" % (
1363 self.queue_entry.host_id, self.queue_entry.job_id)
mbligh36768f02008-02-22 18:28:33 +00001364
mblighd64e5702008-04-04 21:39:28 +00001365
jadmanski0afbb632008-06-06 21:10:57 +00001366 def epilog(self):
1367 super(AbortTask, self).epilog()
1368 self.queue_entry.set_status('Aborted')
1369 self.success = True
1370
1371
1372 def run(self):
1373 for agent in self.agents_to_abort:
1374 if (agent.active_task):
1375 agent.active_task.abort()
mbligh36768f02008-02-22 18:28:33 +00001376
1377
showard97aed502008-11-04 02:01:24 +00001378class FinalReparseTask(AgentTask):
showard97aed502008-11-04 02:01:24 +00001379 _num_running_parses = 0
1380
1381 def __init__(self, queue_entries):
1382 self._queue_entries = queue_entries
showard170873e2009-01-07 00:22:26 +00001383 # don't use _set_ids, since we don't want to set the host_ids
1384 self.queue_entry_ids = [entry.id for entry in queue_entries]
showard97aed502008-11-04 02:01:24 +00001385 self._parse_started = False
1386
1387 assert len(queue_entries) > 0
1388 queue_entry = queue_entries[0]
showard97aed502008-11-04 02:01:24 +00001389
showard170873e2009-01-07 00:22:26 +00001390 self._execution_tag = queue_entry.execution_tag()
1391 self._results_dir = _drone_manager.absolute_path(self._execution_tag)
1392 self._autoserv_monitor = PidfileRunMonitor()
1393 self._autoserv_monitor.attach_to_existing_process(self._execution_tag)
1394 self._final_status = self._determine_final_status()
1395
showard97aed502008-11-04 02:01:24 +00001396 if _testing_mode:
1397 self.cmd = 'true'
showard170873e2009-01-07 00:22:26 +00001398 else:
1399 super(FinalReparseTask, self).__init__(
1400 cmd=self._generate_parse_command(),
1401 working_directory=self._execution_tag)
showard97aed502008-11-04 02:01:24 +00001402
showard170873e2009-01-07 00:22:26 +00001403 self.log_file = os.path.join(self._execution_tag, '.parse.log')
showard97aed502008-11-04 02:01:24 +00001404
1405
1406 @classmethod
1407 def _increment_running_parses(cls):
1408 cls._num_running_parses += 1
1409
1410
1411 @classmethod
1412 def _decrement_running_parses(cls):
1413 cls._num_running_parses -= 1
1414
1415
1416 @classmethod
1417 def _can_run_new_parse(cls):
showardd1ee1dd2009-01-07 21:33:08 +00001418 return (cls._num_running_parses <
1419 scheduler_config.config.max_parse_processes)
showard97aed502008-11-04 02:01:24 +00001420
1421
showard170873e2009-01-07 00:22:26 +00001422 def _determine_final_status(self):
1423 # we'll use a PidfileRunMonitor to read the autoserv exit status
1424 if self._autoserv_monitor.exit_code() == 0:
1425 return models.HostQueueEntry.Status.COMPLETED
1426 return models.HostQueueEntry.Status.FAILED
1427
1428
showard97aed502008-11-04 02:01:24 +00001429 def prolog(self):
1430 super(FinalReparseTask, self).prolog()
1431 for queue_entry in self._queue_entries:
1432 queue_entry.set_status(models.HostQueueEntry.Status.PARSING)
1433
1434
1435 def epilog(self):
1436 super(FinalReparseTask, self).epilog()
showard97aed502008-11-04 02:01:24 +00001437 for queue_entry in self._queue_entries:
showard170873e2009-01-07 00:22:26 +00001438 queue_entry.set_status(self._final_status)
showard97aed502008-11-04 02:01:24 +00001439
1440
showard2bab8f42008-11-12 18:15:22 +00001441 def _generate_parse_command(self):
showard170873e2009-01-07 00:22:26 +00001442 return [_parser_path, '--write-pidfile', '-l', '2', '-r', '-o',
1443 self._results_dir]
showard97aed502008-11-04 02:01:24 +00001444
1445
1446 def poll(self):
1447 # override poll to keep trying to start until the parse count goes down
1448 # and we can, at which point we revert to default behavior
1449 if self._parse_started:
1450 super(FinalReparseTask, self).poll()
1451 else:
1452 self._try_starting_parse()
1453
1454
1455 def run(self):
1456 # override run() to not actually run unless we can
1457 self._try_starting_parse()
1458
1459
1460 def _try_starting_parse(self):
1461 if not self._can_run_new_parse():
1462 return
showard170873e2009-01-07 00:22:26 +00001463
showard97aed502008-11-04 02:01:24 +00001464 # actually run the parse command
showard170873e2009-01-07 00:22:26 +00001465 self.monitor = PidfileRunMonitor()
1466 self.monitor.run(self.cmd, self._working_directory,
1467 log_file=self.log_file,
1468 pidfile_name='.parser_execute',
1469 paired_with_pidfile=self._autoserv_monitor.pidfile_id)
1470
showard97aed502008-11-04 02:01:24 +00001471 self._increment_running_parses()
1472 self._parse_started = True
1473
1474
1475 def finished(self, success):
1476 super(FinalReparseTask, self).finished(success)
1477 self._decrement_running_parses()
1478
1479
mbligh36768f02008-02-22 18:28:33 +00001480class DBObject(object):
jadmanski0afbb632008-06-06 21:10:57 +00001481 def __init__(self, id=None, row=None, new_record=False):
1482 assert (bool(id) != bool(row))
mbligh36768f02008-02-22 18:28:33 +00001483
jadmanski0afbb632008-06-06 21:10:57 +00001484 self.__table = self._get_table()
mbligh36768f02008-02-22 18:28:33 +00001485
jadmanski0afbb632008-06-06 21:10:57 +00001486 self.__new_record = new_record
mbligh36768f02008-02-22 18:28:33 +00001487
jadmanski0afbb632008-06-06 21:10:57 +00001488 if row is None:
1489 sql = 'SELECT * FROM %s WHERE ID=%%s' % self.__table
1490 rows = _db.execute(sql, (id,))
1491 if len(rows) == 0:
1492 raise "row not found (table=%s, id=%s)" % \
1493 (self.__table, id)
1494 row = rows[0]
mbligh36768f02008-02-22 18:28:33 +00001495
showard2bab8f42008-11-12 18:15:22 +00001496 self._update_fields_from_row(row)
1497
1498
1499 def _update_fields_from_row(self, row):
jadmanski0afbb632008-06-06 21:10:57 +00001500 assert len(row) == self.num_cols(), (
1501 "table = %s, row = %s/%d, fields = %s/%d" % (
showard2bab8f42008-11-12 18:15:22 +00001502 self.__table, row, len(row), self._fields(), self.num_cols()))
mbligh36768f02008-02-22 18:28:33 +00001503
showard2bab8f42008-11-12 18:15:22 +00001504 self._valid_fields = set()
1505 for field, value in zip(self._fields(), row):
1506 setattr(self, field, value)
1507 self._valid_fields.add(field)
mbligh36768f02008-02-22 18:28:33 +00001508
showard2bab8f42008-11-12 18:15:22 +00001509 self._valid_fields.remove('id')
mbligh36768f02008-02-22 18:28:33 +00001510
mblighe2586682008-02-29 22:45:46 +00001511
jadmanski0afbb632008-06-06 21:10:57 +00001512 @classmethod
1513 def _get_table(cls):
1514 raise NotImplementedError('Subclasses must override this')
mblighe2586682008-02-29 22:45:46 +00001515
1516
jadmanski0afbb632008-06-06 21:10:57 +00001517 @classmethod
1518 def _fields(cls):
1519 raise NotImplementedError('Subclasses must override this')
showard04c82c52008-05-29 19:38:12 +00001520
1521
jadmanski0afbb632008-06-06 21:10:57 +00001522 @classmethod
1523 def num_cols(cls):
1524 return len(cls._fields())
showard04c82c52008-05-29 19:38:12 +00001525
1526
jadmanski0afbb632008-06-06 21:10:57 +00001527 def count(self, where, table = None):
1528 if not table:
1529 table = self.__table
mbligh36768f02008-02-22 18:28:33 +00001530
jadmanski0afbb632008-06-06 21:10:57 +00001531 rows = _db.execute("""
1532 SELECT count(*) FROM %s
1533 WHERE %s
1534 """ % (table, where))
mbligh6f8bab42008-02-29 22:45:14 +00001535
jadmanski0afbb632008-06-06 21:10:57 +00001536 assert len(rows) == 1
1537
1538 return int(rows[0][0])
mbligh36768f02008-02-22 18:28:33 +00001539
1540
mblighf8c624d2008-07-03 16:58:45 +00001541 def update_field(self, field, value, condition=''):
showard2bab8f42008-11-12 18:15:22 +00001542 assert field in self._valid_fields
mbligh36768f02008-02-22 18:28:33 +00001543
showard2bab8f42008-11-12 18:15:22 +00001544 if getattr(self, field) == value:
jadmanski0afbb632008-06-06 21:10:57 +00001545 return
mbligh36768f02008-02-22 18:28:33 +00001546
mblighf8c624d2008-07-03 16:58:45 +00001547 query = "UPDATE %s SET %s = %%s WHERE id = %%s" % (self.__table, field)
1548 if condition:
1549 query += ' AND (%s)' % condition
jadmanski0afbb632008-06-06 21:10:57 +00001550 _db.execute(query, (value, self.id))
1551
showard2bab8f42008-11-12 18:15:22 +00001552 setattr(self, field, value)
mbligh36768f02008-02-22 18:28:33 +00001553
1554
jadmanski0afbb632008-06-06 21:10:57 +00001555 def save(self):
1556 if self.__new_record:
1557 keys = self._fields()[1:] # avoid id
1558 columns = ','.join([str(key) for key in keys])
1559 values = ['"%s"' % self.__dict__[key] for key in keys]
1560 values = ','.join(values)
1561 query = """INSERT INTO %s (%s) VALUES (%s)""" % \
1562 (self.__table, columns, values)
1563 _db.execute(query)
mbligh36768f02008-02-22 18:28:33 +00001564
1565
jadmanski0afbb632008-06-06 21:10:57 +00001566 def delete(self):
1567 query = 'DELETE FROM %s WHERE id=%%s' % self.__table
1568 _db.execute(query, (self.id,))
mblighe2586682008-02-29 22:45:46 +00001569
1570
showard63a34772008-08-18 19:32:50 +00001571 @staticmethod
1572 def _prefix_with(string, prefix):
1573 if string:
1574 string = prefix + string
1575 return string
1576
1577
jadmanski0afbb632008-06-06 21:10:57 +00001578 @classmethod
showard989f25d2008-10-01 11:38:11 +00001579 def fetch(cls, where='', params=(), joins='', order_by=''):
showard63a34772008-08-18 19:32:50 +00001580 order_by = cls._prefix_with(order_by, 'ORDER BY ')
1581 where = cls._prefix_with(where, 'WHERE ')
1582 query = ('SELECT %(table)s.* FROM %(table)s %(joins)s '
1583 '%(where)s %(order_by)s' % {'table' : cls._get_table(),
1584 'joins' : joins,
1585 'where' : where,
1586 'order_by' : order_by})
1587 rows = _db.execute(query, params)
jadmanski0afbb632008-06-06 21:10:57 +00001588 for row in rows:
1589 yield cls(row=row)
mblighe2586682008-02-29 22:45:46 +00001590
mbligh36768f02008-02-22 18:28:33 +00001591
1592class IneligibleHostQueue(DBObject):
jadmanski0afbb632008-06-06 21:10:57 +00001593 def __init__(self, id=None, row=None, new_record=None):
1594 super(IneligibleHostQueue, self).__init__(id=id, row=row,
1595 new_record=new_record)
mblighe2586682008-02-29 22:45:46 +00001596
1597
jadmanski0afbb632008-06-06 21:10:57 +00001598 @classmethod
1599 def _get_table(cls):
1600 return 'ineligible_host_queues'
mbligh36768f02008-02-22 18:28:33 +00001601
1602
jadmanski0afbb632008-06-06 21:10:57 +00001603 @classmethod
1604 def _fields(cls):
1605 return ['id', 'job_id', 'host_id']
showard04c82c52008-05-29 19:38:12 +00001606
1607
showard989f25d2008-10-01 11:38:11 +00001608class Label(DBObject):
1609 @classmethod
1610 def _get_table(cls):
1611 return 'labels'
1612
1613
1614 @classmethod
1615 def _fields(cls):
1616 return ['id', 'name', 'kernel_config', 'platform', 'invalid',
1617 'only_if_needed']
1618
1619
mbligh36768f02008-02-22 18:28:33 +00001620class Host(DBObject):
jadmanski0afbb632008-06-06 21:10:57 +00001621 def __init__(self, id=None, row=None):
1622 super(Host, self).__init__(id=id, row=row)
mblighe2586682008-02-29 22:45:46 +00001623
1624
jadmanski0afbb632008-06-06 21:10:57 +00001625 @classmethod
1626 def _get_table(cls):
1627 return 'hosts'
mbligh36768f02008-02-22 18:28:33 +00001628
1629
jadmanski0afbb632008-06-06 21:10:57 +00001630 @classmethod
1631 def _fields(cls):
1632 return ['id', 'hostname', 'locked', 'synch_id','status',
showard21baa452008-10-21 00:08:39 +00001633 'invalid', 'protection', 'locked_by_id', 'lock_time', 'dirty']
showard04c82c52008-05-29 19:38:12 +00001634
1635
jadmanski0afbb632008-06-06 21:10:57 +00001636 def current_task(self):
1637 rows = _db.execute("""
1638 SELECT * FROM host_queue_entries WHERE host_id=%s AND NOT complete AND active
1639 """, (self.id,))
1640
1641 if len(rows) == 0:
1642 return None
1643 else:
1644 assert len(rows) == 1
1645 results = rows[0];
mblighf8c624d2008-07-03 16:58:45 +00001646# print "current = %s" % results
jadmanski0afbb632008-06-06 21:10:57 +00001647 return HostQueueEntry(row=results)
mbligh36768f02008-02-22 18:28:33 +00001648
1649
jadmanski0afbb632008-06-06 21:10:57 +00001650 def yield_work(self):
1651 print "%s yielding work" % self.hostname
1652 if self.current_task():
1653 self.current_task().requeue()
1654
1655 def set_status(self,status):
1656 print '%s -> %s' % (self.hostname, status)
1657 self.update_field('status',status)
mbligh36768f02008-02-22 18:28:33 +00001658
1659
showard170873e2009-01-07 00:22:26 +00001660 def platform_and_labels(self):
showardd8e548a2008-09-09 03:04:57 +00001661 """
showard170873e2009-01-07 00:22:26 +00001662 Returns a tuple (platform_name, list_of_all_label_names).
showardd8e548a2008-09-09 03:04:57 +00001663 """
1664 rows = _db.execute("""
showard170873e2009-01-07 00:22:26 +00001665 SELECT labels.name, labels.platform
showardd8e548a2008-09-09 03:04:57 +00001666 FROM labels
1667 INNER JOIN hosts_labels ON labels.id = hosts_labels.label_id
showard170873e2009-01-07 00:22:26 +00001668 WHERE hosts_labels.host_id = %s
showardd8e548a2008-09-09 03:04:57 +00001669 ORDER BY labels.name
1670 """, (self.id,))
showard170873e2009-01-07 00:22:26 +00001671 platform = None
1672 all_labels = []
1673 for label_name, is_platform in rows:
1674 if is_platform:
1675 platform = label_name
1676 all_labels.append(label_name)
1677 return platform, all_labels
1678
1679
1680 def reverify_tasks(self):
1681 cleanup_task = CleanupTask(host=self)
1682 verify_task = VerifyTask(host=self)
1683 # just to make sure this host does not get taken away
1684 self.set_status('Cleaning')
1685 return [cleanup_task, verify_task]
showardd8e548a2008-09-09 03:04:57 +00001686
1687
mbligh36768f02008-02-22 18:28:33 +00001688class HostQueueEntry(DBObject):
jadmanski0afbb632008-06-06 21:10:57 +00001689 def __init__(self, id=None, row=None):
1690 assert id or row
1691 super(HostQueueEntry, self).__init__(id=id, row=row)
1692 self.job = Job(self.job_id)
mbligh36768f02008-02-22 18:28:33 +00001693
jadmanski0afbb632008-06-06 21:10:57 +00001694 if self.host_id:
1695 self.host = Host(self.host_id)
1696 else:
1697 self.host = None
mbligh36768f02008-02-22 18:28:33 +00001698
showard170873e2009-01-07 00:22:26 +00001699 self.queue_log_path = os.path.join(self.job.tag(),
jadmanski0afbb632008-06-06 21:10:57 +00001700 'queue.log.' + str(self.id))
mbligh36768f02008-02-22 18:28:33 +00001701
1702
jadmanski0afbb632008-06-06 21:10:57 +00001703 @classmethod
1704 def _get_table(cls):
1705 return 'host_queue_entries'
mblighe2586682008-02-29 22:45:46 +00001706
1707
jadmanski0afbb632008-06-06 21:10:57 +00001708 @classmethod
1709 def _fields(cls):
showard2bab8f42008-11-12 18:15:22 +00001710 return ['id', 'job_id', 'host_id', 'priority', 'status', 'meta_host',
1711 'active', 'complete', 'deleted', 'execution_subdir']
showard04c82c52008-05-29 19:38:12 +00001712
1713
showardc85c21b2008-11-24 22:17:37 +00001714 def _view_job_url(self):
1715 return "%s#tab_id=view_job&object_id=%s" % (_base_url, self.job.id)
1716
1717
jadmanski0afbb632008-06-06 21:10:57 +00001718 def set_host(self, host):
1719 if host:
1720 self.queue_log_record('Assigning host ' + host.hostname)
1721 self.update_field('host_id', host.id)
1722 self.update_field('active', True)
1723 self.block_host(host.id)
1724 else:
1725 self.queue_log_record('Releasing host')
1726 self.unblock_host(self.host.id)
1727 self.update_field('host_id', None)
mbligh36768f02008-02-22 18:28:33 +00001728
jadmanski0afbb632008-06-06 21:10:57 +00001729 self.host = host
mbligh36768f02008-02-22 18:28:33 +00001730
1731
jadmanski0afbb632008-06-06 21:10:57 +00001732 def get_host(self):
1733 return self.host
mbligh36768f02008-02-22 18:28:33 +00001734
1735
jadmanski0afbb632008-06-06 21:10:57 +00001736 def queue_log_record(self, log_line):
1737 now = str(datetime.datetime.now())
showard170873e2009-01-07 00:22:26 +00001738 _drone_manager.write_lines_to_file(self.queue_log_path,
1739 [now + ' ' + log_line])
mbligh36768f02008-02-22 18:28:33 +00001740
1741
jadmanski0afbb632008-06-06 21:10:57 +00001742 def block_host(self, host_id):
1743 print "creating block %s/%s" % (self.job.id, host_id)
1744 row = [0, self.job.id, host_id]
1745 block = IneligibleHostQueue(row=row, new_record=True)
1746 block.save()
mblighe2586682008-02-29 22:45:46 +00001747
1748
jadmanski0afbb632008-06-06 21:10:57 +00001749 def unblock_host(self, host_id):
1750 print "removing block %s/%s" % (self.job.id, host_id)
1751 blocks = IneligibleHostQueue.fetch(
1752 'job_id=%d and host_id=%d' % (self.job.id, host_id))
1753 for block in blocks:
1754 block.delete()
mblighe2586682008-02-29 22:45:46 +00001755
1756
showard2bab8f42008-11-12 18:15:22 +00001757 def set_execution_subdir(self, subdir=None):
1758 if subdir is None:
1759 assert self.get_host()
1760 subdir = self.get_host().hostname
1761 self.update_field('execution_subdir', subdir)
mbligh36768f02008-02-22 18:28:33 +00001762
1763
showard6355f6b2008-12-05 18:52:13 +00001764 def _get_hostname(self):
1765 if self.host:
1766 return self.host.hostname
1767 return 'no host'
1768
1769
showard170873e2009-01-07 00:22:26 +00001770 def __str__(self):
1771 return "%s/%d (%d)" % (self._get_hostname(), self.job.id, self.id)
1772
1773
jadmanski0afbb632008-06-06 21:10:57 +00001774 def set_status(self, status):
mblighf8c624d2008-07-03 16:58:45 +00001775 abort_statuses = ['Abort', 'Aborting', 'Aborted']
1776 if status not in abort_statuses:
1777 condition = ' AND '.join(['status <> "%s"' % x
1778 for x in abort_statuses])
1779 else:
1780 condition = ''
1781 self.update_field('status', status, condition=condition)
1782
showard170873e2009-01-07 00:22:26 +00001783 print "%s -> %s" % (self, self.status)
mblighf8c624d2008-07-03 16:58:45 +00001784
showardc85c21b2008-11-24 22:17:37 +00001785 if status in ['Queued', 'Parsing']:
jadmanski0afbb632008-06-06 21:10:57 +00001786 self.update_field('complete', False)
1787 self.update_field('active', False)
mbligh36768f02008-02-22 18:28:33 +00001788
jadmanski0afbb632008-06-06 21:10:57 +00001789 if status in ['Pending', 'Running', 'Verifying', 'Starting',
showarde58e3f82008-11-20 19:04:59 +00001790 'Aborting']:
jadmanski0afbb632008-06-06 21:10:57 +00001791 self.update_field('complete', False)
1792 self.update_field('active', True)
mbligh36768f02008-02-22 18:28:33 +00001793
showardc85c21b2008-11-24 22:17:37 +00001794 if status in ['Failed', 'Completed', 'Stopped', 'Aborted']:
jadmanski0afbb632008-06-06 21:10:57 +00001795 self.update_field('complete', True)
1796 self.update_field('active', False)
showardc85c21b2008-11-24 22:17:37 +00001797
1798 should_email_status = (status.lower() in _notify_email_statuses or
1799 'all' in _notify_email_statuses)
1800 if should_email_status:
1801 self._email_on_status(status)
1802
1803 self._email_on_job_complete()
1804
1805
1806 def _email_on_status(self, status):
showard6355f6b2008-12-05 18:52:13 +00001807 hostname = self._get_hostname()
showardc85c21b2008-11-24 22:17:37 +00001808
1809 subject = 'Autotest: Job ID: %s "%s" Host: %s %s' % (
1810 self.job.id, self.job.name, hostname, status)
1811 body = "Job ID: %s\nJob Name: %s\nHost: %s\nStatus: %s\n%s\n" % (
1812 self.job.id, self.job.name, hostname, status,
1813 self._view_job_url())
showard170873e2009-01-07 00:22:26 +00001814 email_manager.manager.send_email(self.job.email_list, subject, body)
showard542e8402008-09-19 20:16:18 +00001815
1816
1817 def _email_on_job_complete(self):
showardc85c21b2008-11-24 22:17:37 +00001818 if not self.job.is_finished():
1819 return
showard542e8402008-09-19 20:16:18 +00001820
showardc85c21b2008-11-24 22:17:37 +00001821 summary_text = []
showard6355f6b2008-12-05 18:52:13 +00001822 hosts_queue = HostQueueEntry.fetch('job_id = %s' % self.job.id)
showardc85c21b2008-11-24 22:17:37 +00001823 for queue_entry in hosts_queue:
1824 summary_text.append("Host: %s Status: %s" %
showard6355f6b2008-12-05 18:52:13 +00001825 (queue_entry._get_hostname(),
showardc85c21b2008-11-24 22:17:37 +00001826 queue_entry.status))
1827
1828 summary_text = "\n".join(summary_text)
1829 status_counts = models.Job.objects.get_status_counts(
1830 [self.job.id])[self.job.id]
1831 status = ', '.join('%d %s' % (count, status) for status, count
1832 in status_counts.iteritems())
1833
1834 subject = 'Autotest: Job ID: %s "%s" %s' % (
1835 self.job.id, self.job.name, status)
1836 body = "Job ID: %s\nJob Name: %s\nStatus: %s\n%s\nSummary:\n%s" % (
1837 self.job.id, self.job.name, status, self._view_job_url(),
1838 summary_text)
showard170873e2009-01-07 00:22:26 +00001839 email_manager.manager.send_email(self.job.email_list, subject, body)
mbligh36768f02008-02-22 18:28:33 +00001840
1841
jadmanski0afbb632008-06-06 21:10:57 +00001842 def run(self,assigned_host=None):
1843 if self.meta_host:
1844 assert assigned_host
1845 # ensure results dir exists for the queue log
jadmanski0afbb632008-06-06 21:10:57 +00001846 self.set_host(assigned_host)
mbligh36768f02008-02-22 18:28:33 +00001847
jadmanski0afbb632008-06-06 21:10:57 +00001848 print "%s/%s scheduled on %s, status=%s" % (self.job.name,
1849 self.meta_host, self.host.hostname, self.status)
mbligh36768f02008-02-22 18:28:33 +00001850
jadmanski0afbb632008-06-06 21:10:57 +00001851 return self.job.run(queue_entry=self)
mblighe2586682008-02-29 22:45:46 +00001852
jadmanski0afbb632008-06-06 21:10:57 +00001853 def requeue(self):
1854 self.set_status('Queued')
jadmanski0afbb632008-06-06 21:10:57 +00001855 if self.meta_host:
1856 self.set_host(None)
mbligh36768f02008-02-22 18:28:33 +00001857
1858
jadmanski0afbb632008-06-06 21:10:57 +00001859 def handle_host_failure(self):
1860 """\
1861 Called when this queue entry's host has failed verification and
1862 repair.
1863 """
1864 assert not self.meta_host
1865 self.set_status('Failed')
showard2bab8f42008-11-12 18:15:22 +00001866 self.job.stop_if_necessary()
mblighe2586682008-02-29 22:45:46 +00001867
1868
jadmanskif7fa2cc2008-10-01 14:13:23 +00001869 @property
1870 def aborted_by(self):
1871 self._load_abort_info()
1872 return self._aborted_by
1873
1874
1875 @property
1876 def aborted_on(self):
1877 self._load_abort_info()
1878 return self._aborted_on
1879
1880
1881 def _load_abort_info(self):
1882 """ Fetch info about who aborted the job. """
1883 if hasattr(self, "_aborted_by"):
1884 return
1885 rows = _db.execute("""
1886 SELECT users.login, aborted_host_queue_entries.aborted_on
1887 FROM aborted_host_queue_entries
1888 INNER JOIN users
1889 ON users.id = aborted_host_queue_entries.aborted_by_id
1890 WHERE aborted_host_queue_entries.queue_entry_id = %s
1891 """, (self.id,))
1892 if rows:
1893 self._aborted_by, self._aborted_on = rows[0]
1894 else:
1895 self._aborted_by = self._aborted_on = None
1896
1897
showardb2e2c322008-10-14 17:33:55 +00001898 def on_pending(self):
1899 """
1900 Called when an entry in a synchronous job has passed verify. If the
1901 job is ready to run, returns an agent to run the job. Returns None
1902 otherwise.
1903 """
1904 self.set_status('Pending')
showardcfd66a32008-10-15 20:31:48 +00001905 self.get_host().set_status('Pending')
showardb2e2c322008-10-14 17:33:55 +00001906 if self.job.is_ready():
1907 return self.job.run(self)
showard2bab8f42008-11-12 18:15:22 +00001908 self.job.stop_if_necessary()
showardb2e2c322008-10-14 17:33:55 +00001909 return None
1910
1911
showard170873e2009-01-07 00:22:26 +00001912 def abort(self, dispatcher, agents_to_abort=[]):
showard1be97432008-10-17 15:30:45 +00001913 host = self.get_host()
showard9d9ffd52008-11-09 23:14:35 +00001914 if self.active and host:
showard170873e2009-01-07 00:22:26 +00001915 dispatcher.add_agent(Agent(tasks=host.reverify_tasks()))
showard1be97432008-10-17 15:30:45 +00001916
showard170873e2009-01-07 00:22:26 +00001917 abort_task = AbortTask(self, agents_to_abort)
showard1be97432008-10-17 15:30:45 +00001918 self.set_status('Aborting')
showard170873e2009-01-07 00:22:26 +00001919 dispatcher.add_agent(Agent(tasks=[abort_task], num_processes=0))
1920
1921 def execution_tag(self):
1922 assert self.execution_subdir
1923 return "%s-%s/%s" % (self.job.id, self.job.owner, self.execution_subdir)
showard1be97432008-10-17 15:30:45 +00001924
1925
mbligh36768f02008-02-22 18:28:33 +00001926class Job(DBObject):
jadmanski0afbb632008-06-06 21:10:57 +00001927 def __init__(self, id=None, row=None):
1928 assert id or row
1929 super(Job, self).__init__(id=id, row=row)
mbligh36768f02008-02-22 18:28:33 +00001930
mblighe2586682008-02-29 22:45:46 +00001931
jadmanski0afbb632008-06-06 21:10:57 +00001932 @classmethod
1933 def _get_table(cls):
1934 return 'jobs'
mbligh36768f02008-02-22 18:28:33 +00001935
1936
jadmanski0afbb632008-06-06 21:10:57 +00001937 @classmethod
1938 def _fields(cls):
1939 return ['id', 'owner', 'name', 'priority', 'control_file',
showard2bab8f42008-11-12 18:15:22 +00001940 'control_type', 'created_on', 'synch_count', 'timeout',
showard21baa452008-10-21 00:08:39 +00001941 'run_verify', 'email_list', 'reboot_before', 'reboot_after']
showard04c82c52008-05-29 19:38:12 +00001942
1943
jadmanski0afbb632008-06-06 21:10:57 +00001944 def is_server_job(self):
1945 return self.control_type != 2
mbligh36768f02008-02-22 18:28:33 +00001946
1947
showard170873e2009-01-07 00:22:26 +00001948 def tag(self):
1949 return "%s-%s" % (self.id, self.owner)
1950
1951
jadmanski0afbb632008-06-06 21:10:57 +00001952 def get_host_queue_entries(self):
1953 rows = _db.execute("""
1954 SELECT * FROM host_queue_entries
1955 WHERE job_id= %s
1956 """, (self.id,))
1957 entries = [HostQueueEntry(row=i) for i in rows]
mbligh36768f02008-02-22 18:28:33 +00001958
jadmanski0afbb632008-06-06 21:10:57 +00001959 assert len(entries)>0
mbligh36768f02008-02-22 18:28:33 +00001960
jadmanski0afbb632008-06-06 21:10:57 +00001961 return entries
mbligh36768f02008-02-22 18:28:33 +00001962
1963
jadmanski0afbb632008-06-06 21:10:57 +00001964 def set_status(self, status, update_queues=False):
1965 self.update_field('status',status)
1966
1967 if update_queues:
1968 for queue_entry in self.get_host_queue_entries():
1969 queue_entry.set_status(status)
mbligh36768f02008-02-22 18:28:33 +00001970
1971
jadmanski0afbb632008-06-06 21:10:57 +00001972 def is_ready(self):
showard2bab8f42008-11-12 18:15:22 +00001973 pending_entries = models.HostQueueEntry.objects.filter(job=self.id,
1974 status='Pending')
1975 return (pending_entries.count() >= self.synch_count)
mbligh36768f02008-02-22 18:28:33 +00001976
1977
jadmanski0afbb632008-06-06 21:10:57 +00001978 def num_machines(self, clause = None):
1979 sql = "job_id=%s" % self.id
1980 if clause:
1981 sql += " AND (%s)" % clause
1982 return self.count(sql, table='host_queue_entries')
mbligh36768f02008-02-22 18:28:33 +00001983
1984
jadmanski0afbb632008-06-06 21:10:57 +00001985 def num_queued(self):
1986 return self.num_machines('not complete')
mbligh36768f02008-02-22 18:28:33 +00001987
1988
jadmanski0afbb632008-06-06 21:10:57 +00001989 def num_active(self):
1990 return self.num_machines('active')
mbligh36768f02008-02-22 18:28:33 +00001991
1992
jadmanski0afbb632008-06-06 21:10:57 +00001993 def num_complete(self):
1994 return self.num_machines('complete')
mbligh36768f02008-02-22 18:28:33 +00001995
1996
jadmanski0afbb632008-06-06 21:10:57 +00001997 def is_finished(self):
showardc85c21b2008-11-24 22:17:37 +00001998 return self.num_complete() == self.num_machines()
mbligh36768f02008-02-22 18:28:33 +00001999
mbligh36768f02008-02-22 18:28:33 +00002000
showard2bab8f42008-11-12 18:15:22 +00002001 def _stop_all_entries(self, entries_to_abort):
2002 """
2003 queue_entries: sequence of models.HostQueueEntry objects
2004 """
2005 for child_entry in entries_to_abort:
showard4f9e5372009-01-07 21:33:38 +00002006 assert not child_entry.complete, (
2007 '%s status=%s, active=%s, complete=%s' %
2008 (child_entry.id, child_entry.status, child_entry.active,
2009 child_entry.complete))
showard2bab8f42008-11-12 18:15:22 +00002010 if child_entry.status == models.HostQueueEntry.Status.PENDING:
2011 child_entry.host.status = models.Host.Status.READY
2012 child_entry.host.save()
2013 child_entry.status = models.HostQueueEntry.Status.STOPPED
2014 child_entry.save()
2015
2016
2017 def stop_if_necessary(self):
2018 not_yet_run = models.HostQueueEntry.objects.filter(
2019 job=self.id, status__in=(models.HostQueueEntry.Status.QUEUED,
2020 models.HostQueueEntry.Status.VERIFYING,
2021 models.HostQueueEntry.Status.PENDING))
2022 if not_yet_run.count() < self.synch_count:
2023 self._stop_all_entries(not_yet_run)
mblighe2586682008-02-29 22:45:46 +00002024
2025
jadmanski0afbb632008-06-06 21:10:57 +00002026 def write_to_machines_file(self, queue_entry):
2027 hostname = queue_entry.get_host().hostname
showard170873e2009-01-07 00:22:26 +00002028 file_path = os.path.join(self.tag(), '.machines')
2029 _drone_manager.write_lines_to_file(file_path, [hostname])
mbligh36768f02008-02-22 18:28:33 +00002030
2031
showard2bab8f42008-11-12 18:15:22 +00002032 def _next_group_name(self):
2033 query = models.HostQueueEntry.objects.filter(
2034 job=self.id).values('execution_subdir').distinct()
2035 subdirs = (entry['execution_subdir'] for entry in query)
2036 groups = (re.match(r'group(\d+)', subdir) for subdir in subdirs)
2037 ids = [int(match.group(1)) for match in groups if match]
2038 if ids:
2039 next_id = max(ids) + 1
2040 else:
2041 next_id = 0
2042 return "group%d" % next_id
2043
2044
showard170873e2009-01-07 00:22:26 +00002045 def _write_control_file(self, execution_tag):
2046 control_path = _drone_manager.attach_file_to_execution(
2047 execution_tag, self.control_file)
2048 return control_path
mbligh36768f02008-02-22 18:28:33 +00002049
showardb2e2c322008-10-14 17:33:55 +00002050
showard2bab8f42008-11-12 18:15:22 +00002051 def get_group_entries(self, queue_entry_from_group):
2052 execution_subdir = queue_entry_from_group.execution_subdir
showarde788ea62008-11-17 21:02:47 +00002053 return list(HostQueueEntry.fetch(
2054 where='job_id=%s AND execution_subdir=%s',
2055 params=(self.id, execution_subdir)))
showard2bab8f42008-11-12 18:15:22 +00002056
2057
showardb2e2c322008-10-14 17:33:55 +00002058 def _get_autoserv_params(self, queue_entries):
showard170873e2009-01-07 00:22:26 +00002059 assert queue_entries
2060 execution_tag = queue_entries[0].execution_tag()
2061 control_path = self._write_control_file(execution_tag)
jadmanski0afbb632008-06-06 21:10:57 +00002062 hostnames = ','.join([entry.get_host().hostname
2063 for entry in queue_entries])
mbligh36768f02008-02-22 18:28:33 +00002064
showard170873e2009-01-07 00:22:26 +00002065 params = [_autoserv_path, '-P', execution_tag, '-p', '-n',
2066 '-r', _drone_manager.absolute_path(execution_tag),
2067 '-u', self.owner, '-l', self.name, '-m', hostnames,
2068 _drone_manager.absolute_path(control_path)]
mbligh36768f02008-02-22 18:28:33 +00002069
jadmanski0afbb632008-06-06 21:10:57 +00002070 if not self.is_server_job():
2071 params.append('-c')
mbligh36768f02008-02-22 18:28:33 +00002072
showardb2e2c322008-10-14 17:33:55 +00002073 return params
mblighe2586682008-02-29 22:45:46 +00002074
mbligh36768f02008-02-22 18:28:33 +00002075
showard2bab8f42008-11-12 18:15:22 +00002076 def _get_pre_job_tasks(self, queue_entry):
showard21baa452008-10-21 00:08:39 +00002077 do_reboot = False
showard0fc38302008-10-23 00:44:07 +00002078 if self.reboot_before == models.RebootBefore.ALWAYS:
showard21baa452008-10-21 00:08:39 +00002079 do_reboot = True
showard0fc38302008-10-23 00:44:07 +00002080 elif self.reboot_before == models.RebootBefore.IF_DIRTY:
showard21baa452008-10-21 00:08:39 +00002081 do_reboot = queue_entry.get_host().dirty
2082
2083 tasks = []
2084 if do_reboot:
showard45ae8192008-11-05 19:32:53 +00002085 tasks.append(CleanupTask(queue_entry=queue_entry))
showard2bab8f42008-11-12 18:15:22 +00002086 tasks.append(VerifyTask(queue_entry=queue_entry))
showard21baa452008-10-21 00:08:39 +00002087 return tasks
2088
2089
showard2bab8f42008-11-12 18:15:22 +00002090 def _assign_new_group(self, queue_entries):
2091 if len(queue_entries) == 1:
2092 group_name = queue_entries[0].get_host().hostname
2093 else:
2094 group_name = self._next_group_name()
2095 print 'Running synchronous job %d hosts %s as %s' % (
2096 self.id, [entry.host.hostname for entry in queue_entries],
2097 group_name)
2098
2099 for queue_entry in queue_entries:
2100 queue_entry.set_execution_subdir(group_name)
2101
2102
2103 def _choose_group_to_run(self, include_queue_entry):
2104 chosen_entries = [include_queue_entry]
2105
2106 num_entries_needed = self.synch_count - 1
2107 if num_entries_needed > 0:
2108 pending_entries = HostQueueEntry.fetch(
2109 where='job_id = %s AND status = "Pending" AND id != %s',
2110 params=(self.id, include_queue_entry.id))
2111 chosen_entries += list(pending_entries)[:num_entries_needed]
2112
2113 self._assign_new_group(chosen_entries)
2114 return chosen_entries
2115
2116
2117 def run(self, queue_entry):
showardb2e2c322008-10-14 17:33:55 +00002118 if not self.is_ready():
showard9976ce92008-10-15 20:28:13 +00002119 if self.run_verify:
showarde58e3f82008-11-20 19:04:59 +00002120 queue_entry.set_status(models.HostQueueEntry.Status.VERIFYING)
showard170873e2009-01-07 00:22:26 +00002121 return Agent(self._get_pre_job_tasks(queue_entry))
showard9976ce92008-10-15 20:28:13 +00002122 else:
2123 return queue_entry.on_pending()
mbligh36768f02008-02-22 18:28:33 +00002124
showard2bab8f42008-11-12 18:15:22 +00002125 queue_entries = self._choose_group_to_run(queue_entry)
2126 return self._finish_run(queue_entries)
showardb2e2c322008-10-14 17:33:55 +00002127
2128
2129 def _finish_run(self, queue_entries, initial_tasks=[]):
showardb2ccdda2008-10-28 20:39:05 +00002130 for queue_entry in queue_entries:
2131 queue_entry.set_status('Starting')
showardb2e2c322008-10-14 17:33:55 +00002132 params = self._get_autoserv_params(queue_entries)
2133 queue_task = QueueTask(job=self, queue_entries=queue_entries,
2134 cmd=params)
2135 tasks = initial_tasks + [queue_task]
2136 entry_ids = [entry.id for entry in queue_entries]
2137
showard170873e2009-01-07 00:22:26 +00002138 return Agent(tasks, num_processes=len(queue_entries))
showardb2e2c322008-10-14 17:33:55 +00002139
2140
mbligh36768f02008-02-22 18:28:33 +00002141if __name__ == '__main__':
jadmanski0afbb632008-06-06 21:10:57 +00002142 main()