blob: 7e594a6b65d1a1b02d1f9ff95d947412cc9324ea [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
showardc5afc462009-01-13 00:09:39 +000099 server = status_server.StatusServer(_drone_manager)
showardd1ee1dd2009-01-07 21:33:08 +0000100 server.start()
101
jadmanski0afbb632008-06-06 21:10:57 +0000102 try:
showardc5afc462009-01-13 00:09:39 +0000103 init(options.logfile)
104 dispatcher = Dispatcher()
105 dispatcher.do_initial_recovery(recover_hosts=options.recover_hosts)
106
jadmanski0afbb632008-06-06 21:10:57 +0000107 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')
showard67831ae2009-01-16 03:07:38 +0000145 debug.get_logger().setLevel(logging.INFO)
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
showard324bf812009-01-20 23:23:38 +0000693 def _can_start_agent(self, agent, num_started_this_cycle,
694 have_reached_limit):
showard4c5374f2008-09-04 17:02:56 +0000695 # 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
showard324bf812009-01-20 23:23:38 +0000703 if agent.num_processes > _drone_manager.max_runnable_processes():
showard4c5374f2008-09-04 17:02:56 +0000704 return False
705 # if a single agent exceeds the per-cycle throttling, still allow it to
706 # run when it's the first agent in the cycle
707 if num_started_this_cycle == 0:
708 return True
709 # per-cycle throttling
710 if (num_started_this_cycle + agent.num_processes >
showardd1ee1dd2009-01-07 21:33:08 +0000711 scheduler_config.config.max_processes_started_per_cycle):
showard4c5374f2008-09-04 17:02:56 +0000712 return False
713 return True
714
715
jadmanski0afbb632008-06-06 21:10:57 +0000716 def _handle_agents(self):
jadmanski0afbb632008-06-06 21:10:57 +0000717 num_started_this_cycle = 0
showard4c5374f2008-09-04 17:02:56 +0000718 have_reached_limit = False
719 # iterate over copy, so we can remove agents during iteration
720 for agent in list(self._agents):
721 if agent.is_done():
jadmanski0afbb632008-06-06 21:10:57 +0000722 print "agent finished"
showard170873e2009-01-07 00:22:26 +0000723 self.remove_agent(agent)
showard4c5374f2008-09-04 17:02:56 +0000724 continue
725 if not agent.is_running():
showard324bf812009-01-20 23:23:38 +0000726 if not self._can_start_agent(agent, num_started_this_cycle,
showard4c5374f2008-09-04 17:02:56 +0000727 have_reached_limit):
728 have_reached_limit = True
729 continue
showard4c5374f2008-09-04 17:02:56 +0000730 num_started_this_cycle += agent.num_processes
731 agent.tick()
showard324bf812009-01-20 23:23:38 +0000732 print _drone_manager.total_running_processes(), 'running processes'
mbligh36768f02008-02-22 18:28:33 +0000733
734
showardfa8629c2008-11-04 16:51:23 +0000735 def _check_for_db_inconsistencies(self):
736 query = models.HostQueueEntry.objects.filter(active=True, complete=True)
737 if query.count() != 0:
738 subject = ('%d queue entries found with active=complete=1'
739 % query.count())
740 message = '\n'.join(str(entry.get_object_dict())
741 for entry in query[:50])
742 if len(query) > 50:
743 message += '\n(truncated)\n'
744
745 print subject
showard170873e2009-01-07 00:22:26 +0000746 email_manager.manager.enqueue_notify_email(subject, message)
showardfa8629c2008-11-04 16:51:23 +0000747
748
showard170873e2009-01-07 00:22:26 +0000749class PidfileRunMonitor(object):
750 """
751 Client must call either run() to start a new process or
752 attach_to_existing_process().
753 """
mbligh36768f02008-02-22 18:28:33 +0000754
showard170873e2009-01-07 00:22:26 +0000755 class _PidfileException(Exception):
756 """
757 Raised when there's some unexpected behavior with the pid file, but only
758 used internally (never allowed to escape this class).
759 """
mbligh36768f02008-02-22 18:28:33 +0000760
761
showard170873e2009-01-07 00:22:26 +0000762 def __init__(self):
763 self._lost_process = False
764 self._start_time = None
765 self.pidfile_id = None
766 self._state = drone_manager.PidfileContents()
showard2bab8f42008-11-12 18:15:22 +0000767
768
showard170873e2009-01-07 00:22:26 +0000769 def _add_nice_command(self, command, nice_level):
770 if not nice_level:
771 return command
772 return ['nice', '-n', str(nice_level)] + command
773
774
775 def _set_start_time(self):
776 self._start_time = time.time()
777
778
779 def run(self, command, working_directory, nice_level=None, log_file=None,
780 pidfile_name=None, paired_with_pidfile=None):
781 assert command is not None
782 if nice_level is not None:
783 command = ['nice', '-n', str(nice_level)] + command
784 self._set_start_time()
785 self.pidfile_id = _drone_manager.execute_command(
786 command, working_directory, log_file=log_file,
787 pidfile_name=pidfile_name, paired_with_pidfile=paired_with_pidfile)
788
789
790 def attach_to_existing_process(self, execution_tag):
791 self._set_start_time()
792 self.pidfile_id = _drone_manager.get_pidfile_id_from(execution_tag)
793 _drone_manager.register_pidfile(self.pidfile_id)
mblighbb421852008-03-11 22:36:16 +0000794
795
jadmanski0afbb632008-06-06 21:10:57 +0000796 def kill(self):
showard170873e2009-01-07 00:22:26 +0000797 if self.has_process():
798 _drone_manager.kill_process(self.get_process())
mblighbb421852008-03-11 22:36:16 +0000799
mbligh36768f02008-02-22 18:28:33 +0000800
showard170873e2009-01-07 00:22:26 +0000801 def has_process(self):
showard21baa452008-10-21 00:08:39 +0000802 self._get_pidfile_info()
showard170873e2009-01-07 00:22:26 +0000803 return self._state.process is not None
showard21baa452008-10-21 00:08:39 +0000804
805
showard170873e2009-01-07 00:22:26 +0000806 def get_process(self):
showard21baa452008-10-21 00:08:39 +0000807 self._get_pidfile_info()
showard170873e2009-01-07 00:22:26 +0000808 assert self.has_process()
809 return self._state.process
mblighbb421852008-03-11 22:36:16 +0000810
811
showard170873e2009-01-07 00:22:26 +0000812 def _read_pidfile(self, use_second_read=False):
813 assert self.pidfile_id is not None, (
814 'You must call run() or attach_to_existing_process()')
815 contents = _drone_manager.get_pidfile_contents(
816 self.pidfile_id, use_second_read=use_second_read)
817 if contents.is_invalid():
818 self._state = drone_manager.PidfileContents()
819 raise self._PidfileException(contents)
820 self._state = contents
mbligh90a549d2008-03-25 23:52:34 +0000821
822
showard21baa452008-10-21 00:08:39 +0000823 def _handle_pidfile_error(self, error, message=''):
showard170873e2009-01-07 00:22:26 +0000824 message = error + '\nProcess: %s\nPidfile: %s\n%s' % (
825 self._state.process, self.pidfile_id, message)
showard21baa452008-10-21 00:08:39 +0000826 print message
showard170873e2009-01-07 00:22:26 +0000827 email_manager.manager.enqueue_notify_email(error, message)
828 if self._state.process is not None:
829 process = self._state.process
showard21baa452008-10-21 00:08:39 +0000830 else:
showard170873e2009-01-07 00:22:26 +0000831 process = _drone_manager.get_dummy_process()
832 self.on_lost_process(process)
showard21baa452008-10-21 00:08:39 +0000833
834
835 def _get_pidfile_info_helper(self):
showard170873e2009-01-07 00:22:26 +0000836 if self._lost_process:
showard21baa452008-10-21 00:08:39 +0000837 return
mblighbb421852008-03-11 22:36:16 +0000838
showard21baa452008-10-21 00:08:39 +0000839 self._read_pidfile()
mblighbb421852008-03-11 22:36:16 +0000840
showard170873e2009-01-07 00:22:26 +0000841 if self._state.process is None:
842 self._handle_no_process()
showard21baa452008-10-21 00:08:39 +0000843 return
mbligh90a549d2008-03-25 23:52:34 +0000844
showard21baa452008-10-21 00:08:39 +0000845 if self._state.exit_status is None:
jadmanski0afbb632008-06-06 21:10:57 +0000846 # double check whether or not autoserv is running
showard170873e2009-01-07 00:22:26 +0000847 if _drone_manager.is_process_running(self._state.process):
showard21baa452008-10-21 00:08:39 +0000848 return
mbligh90a549d2008-03-25 23:52:34 +0000849
showard170873e2009-01-07 00:22:26 +0000850 # pid but no running process - maybe process *just* exited
851 self._read_pidfile(use_second_read=True)
showard21baa452008-10-21 00:08:39 +0000852 if self._state.exit_status is None:
jadmanski0afbb632008-06-06 21:10:57 +0000853 # autoserv exited without writing an exit code
854 # to the pidfile
showard21baa452008-10-21 00:08:39 +0000855 self._handle_pidfile_error(
856 'autoserv died without writing exit code')
mblighbb421852008-03-11 22:36:16 +0000857
showard21baa452008-10-21 00:08:39 +0000858
859 def _get_pidfile_info(self):
860 """\
861 After completion, self._state will contain:
862 pid=None, exit_status=None if autoserv has not yet run
863 pid!=None, exit_status=None if autoserv is running
864 pid!=None, exit_status!=None if autoserv has completed
865 """
866 try:
867 self._get_pidfile_info_helper()
showard170873e2009-01-07 00:22:26 +0000868 except self._PidfileException, exc:
showard21baa452008-10-21 00:08:39 +0000869 self._handle_pidfile_error('Pidfile error', traceback.format_exc())
mblighbb421852008-03-11 22:36:16 +0000870
871
showard170873e2009-01-07 00:22:26 +0000872 def _handle_no_process(self):
jadmanski0afbb632008-06-06 21:10:57 +0000873 """\
874 Called when no pidfile is found or no pid is in the pidfile.
875 """
showard170873e2009-01-07 00:22:26 +0000876 message = 'No pid found at %s' % self.pidfile_id
jadmanski0afbb632008-06-06 21:10:57 +0000877 print message
showard170873e2009-01-07 00:22:26 +0000878 if time.time() - self._start_time > PIDFILE_TIMEOUT:
879 email_manager.manager.enqueue_notify_email(
jadmanski0afbb632008-06-06 21:10:57 +0000880 'Process has failed to write pidfile', message)
showard170873e2009-01-07 00:22:26 +0000881 self.on_lost_process(_drone_manager.get_dummy_process())
mbligh90a549d2008-03-25 23:52:34 +0000882
883
showard170873e2009-01-07 00:22:26 +0000884 def on_lost_process(self, process):
jadmanski0afbb632008-06-06 21:10:57 +0000885 """\
886 Called when autoserv has exited without writing an exit status,
887 or we've timed out waiting for autoserv to write a pid to the
888 pidfile. In either case, we just return failure and the caller
889 should signal some kind of warning.
mbligh90a549d2008-03-25 23:52:34 +0000890
showard170873e2009-01-07 00:22:26 +0000891 process is unimportant here, as it shouldn't be used by anyone.
jadmanski0afbb632008-06-06 21:10:57 +0000892 """
893 self.lost_process = True
showard170873e2009-01-07 00:22:26 +0000894 self._state.process = process
showard21baa452008-10-21 00:08:39 +0000895 self._state.exit_status = 1
896 self._state.num_tests_failed = 0
mbligh90a549d2008-03-25 23:52:34 +0000897
898
jadmanski0afbb632008-06-06 21:10:57 +0000899 def exit_code(self):
showard21baa452008-10-21 00:08:39 +0000900 self._get_pidfile_info()
901 return self._state.exit_status
902
903
904 def num_tests_failed(self):
905 self._get_pidfile_info()
906 assert self._state.num_tests_failed is not None
907 return self._state.num_tests_failed
mblighbb421852008-03-11 22:36:16 +0000908
909
mbligh36768f02008-02-22 18:28:33 +0000910class Agent(object):
showard170873e2009-01-07 00:22:26 +0000911 def __init__(self, tasks, num_processes=1):
jadmanski0afbb632008-06-06 21:10:57 +0000912 self.active_task = None
913 self.queue = Queue.Queue(0)
914 self.dispatcher = None
showard4c5374f2008-09-04 17:02:56 +0000915 self.num_processes = num_processes
jadmanski0afbb632008-06-06 21:10:57 +0000916
showard170873e2009-01-07 00:22:26 +0000917 self.queue_entry_ids = self._union_ids(task.queue_entry_ids
918 for task in tasks)
919 self.host_ids = self._union_ids(task.host_ids for task in tasks)
920
jadmanski0afbb632008-06-06 21:10:57 +0000921 for task in tasks:
922 self.add_task(task)
mbligh36768f02008-02-22 18:28:33 +0000923
924
showard170873e2009-01-07 00:22:26 +0000925 def _union_ids(self, id_lists):
926 return set(itertools.chain(*id_lists))
927
928
jadmanski0afbb632008-06-06 21:10:57 +0000929 def add_task(self, task):
930 self.queue.put_nowait(task)
931 task.agent = self
mbligh36768f02008-02-22 18:28:33 +0000932
933
jadmanski0afbb632008-06-06 21:10:57 +0000934 def tick(self):
showard21baa452008-10-21 00:08:39 +0000935 while not self.is_done():
936 if self.active_task and not self.active_task.is_done():
937 self.active_task.poll()
938 if not self.active_task.is_done():
939 return
940 self._next_task()
mbligh36768f02008-02-22 18:28:33 +0000941
942
jadmanski0afbb632008-06-06 21:10:57 +0000943 def _next_task(self):
944 print "agent picking task"
945 if self.active_task:
946 assert self.active_task.is_done()
mbligh36768f02008-02-22 18:28:33 +0000947
jadmanski0afbb632008-06-06 21:10:57 +0000948 if not self.active_task.success:
949 self.on_task_failure()
mblighe2586682008-02-29 22:45:46 +0000950
jadmanski0afbb632008-06-06 21:10:57 +0000951 self.active_task = None
952 if not self.is_done():
953 self.active_task = self.queue.get_nowait()
954 if self.active_task:
955 self.active_task.start()
mbligh36768f02008-02-22 18:28:33 +0000956
957
jadmanski0afbb632008-06-06 21:10:57 +0000958 def on_task_failure(self):
959 self.queue = Queue.Queue(0)
960 for task in self.active_task.failure_tasks:
961 self.add_task(task)
mbligh16c722d2008-03-05 00:58:44 +0000962
mblighe2586682008-02-29 22:45:46 +0000963
showard4c5374f2008-09-04 17:02:56 +0000964 def is_running(self):
jadmanski0afbb632008-06-06 21:10:57 +0000965 return self.active_task is not None
showardec113162008-05-08 00:52:49 +0000966
967
jadmanski0afbb632008-06-06 21:10:57 +0000968 def is_done(self):
mblighd876f452008-12-03 15:09:17 +0000969 return self.active_task is None and self.queue.empty()
mbligh36768f02008-02-22 18:28:33 +0000970
971
jadmanski0afbb632008-06-06 21:10:57 +0000972 def start(self):
973 assert self.dispatcher
mbligh36768f02008-02-22 18:28:33 +0000974
jadmanski0afbb632008-06-06 21:10:57 +0000975 self._next_task()
mbligh36768f02008-02-22 18:28:33 +0000976
jadmanski0afbb632008-06-06 21:10:57 +0000977
mbligh36768f02008-02-22 18:28:33 +0000978class AgentTask(object):
showard170873e2009-01-07 00:22:26 +0000979 def __init__(self, cmd, working_directory=None, failure_tasks=[]):
jadmanski0afbb632008-06-06 21:10:57 +0000980 self.done = False
981 self.failure_tasks = failure_tasks
982 self.started = False
983 self.cmd = cmd
showard170873e2009-01-07 00:22:26 +0000984 self._working_directory = working_directory
jadmanski0afbb632008-06-06 21:10:57 +0000985 self.task = None
986 self.agent = None
987 self.monitor = None
988 self.success = None
showard170873e2009-01-07 00:22:26 +0000989 self.queue_entry_ids = []
990 self.host_ids = []
991 self.log_file = None
992
993
994 def _set_ids(self, host=None, queue_entries=None):
995 if queue_entries and queue_entries != [None]:
996 self.host_ids = [entry.host.id for entry in queue_entries]
997 self.queue_entry_ids = [entry.id for entry in queue_entries]
998 else:
999 assert host
1000 self.host_ids = [host.id]
mbligh36768f02008-02-22 18:28:33 +00001001
1002
jadmanski0afbb632008-06-06 21:10:57 +00001003 def poll(self):
jadmanski0afbb632008-06-06 21:10:57 +00001004 if self.monitor:
1005 self.tick(self.monitor.exit_code())
1006 else:
1007 self.finished(False)
mbligh36768f02008-02-22 18:28:33 +00001008
1009
jadmanski0afbb632008-06-06 21:10:57 +00001010 def tick(self, exit_code):
showard170873e2009-01-07 00:22:26 +00001011 if exit_code is None:
jadmanski0afbb632008-06-06 21:10:57 +00001012 return
jadmanski0afbb632008-06-06 21:10:57 +00001013 if exit_code == 0:
1014 success = True
1015 else:
1016 success = False
mbligh36768f02008-02-22 18:28:33 +00001017
jadmanski0afbb632008-06-06 21:10:57 +00001018 self.finished(success)
mbligh36768f02008-02-22 18:28:33 +00001019
1020
jadmanski0afbb632008-06-06 21:10:57 +00001021 def is_done(self):
1022 return self.done
mbligh36768f02008-02-22 18:28:33 +00001023
1024
jadmanski0afbb632008-06-06 21:10:57 +00001025 def finished(self, success):
1026 self.done = True
1027 self.success = success
1028 self.epilog()
mbligh36768f02008-02-22 18:28:33 +00001029
1030
jadmanski0afbb632008-06-06 21:10:57 +00001031 def prolog(self):
1032 pass
mblighd64e5702008-04-04 21:39:28 +00001033
1034
jadmanski0afbb632008-06-06 21:10:57 +00001035 def create_temp_resultsdir(self, suffix=''):
showard170873e2009-01-07 00:22:26 +00001036 self.temp_results_dir = _drone_manager.get_temporary_path('agent_task')
mblighd64e5702008-04-04 21:39:28 +00001037
mbligh36768f02008-02-22 18:28:33 +00001038
jadmanski0afbb632008-06-06 21:10:57 +00001039 def cleanup(self):
showard170873e2009-01-07 00:22:26 +00001040 if self.monitor and self.log_file:
1041 _drone_manager.copy_to_results_repository(
1042 self.monitor.get_process(), self.log_file)
mbligh36768f02008-02-22 18:28:33 +00001043
1044
jadmanski0afbb632008-06-06 21:10:57 +00001045 def epilog(self):
1046 self.cleanup()
mbligh36768f02008-02-22 18:28:33 +00001047
1048
jadmanski0afbb632008-06-06 21:10:57 +00001049 def start(self):
1050 assert self.agent
1051
1052 if not self.started:
1053 self.prolog()
1054 self.run()
1055
1056 self.started = True
1057
1058
1059 def abort(self):
1060 if self.monitor:
1061 self.monitor.kill()
1062 self.done = True
1063 self.cleanup()
1064
1065
showard170873e2009-01-07 00:22:26 +00001066 def set_host_log_file(self, base_name, host):
1067 filename = '%s.%s' % (time.time(), base_name)
1068 self.log_file = os.path.join('hosts', host.hostname, filename)
1069
1070
jadmanski0afbb632008-06-06 21:10:57 +00001071 def run(self):
1072 if self.cmd:
showard170873e2009-01-07 00:22:26 +00001073 self.monitor = PidfileRunMonitor()
1074 self.monitor.run(self.cmd, self._working_directory,
1075 nice_level=AUTOSERV_NICE_LEVEL,
1076 log_file=self.log_file)
mbligh36768f02008-02-22 18:28:33 +00001077
1078
1079class RepairTask(AgentTask):
showarde788ea62008-11-17 21:02:47 +00001080 def __init__(self, host, queue_entry=None):
jadmanski0afbb632008-06-06 21:10:57 +00001081 """\
showard170873e2009-01-07 00:22:26 +00001082 queue_entry: queue entry to mark failed if this repair fails.
jadmanski0afbb632008-06-06 21:10:57 +00001083 """
jadmanskifb7cfb12008-07-09 14:13:21 +00001084 protection = host_protections.Protection.get_string(host.protection)
jadmanski542537f2008-07-24 14:14:56 +00001085 # normalize the protection name
1086 protection = host_protections.Protection.get_attr_name(protection)
showard170873e2009-01-07 00:22:26 +00001087
jadmanski0afbb632008-06-06 21:10:57 +00001088 self.host = host
showarde788ea62008-11-17 21:02:47 +00001089 self.queue_entry = queue_entry
showard170873e2009-01-07 00:22:26 +00001090 self._set_ids(host=host, queue_entries=[queue_entry])
1091
1092 self.create_temp_resultsdir('.repair')
1093 cmd = [_autoserv_path , '-p', '-R', '-m', host.hostname,
1094 '-r', _drone_manager.absolute_path(self.temp_results_dir),
1095 '--host-protection', protection]
1096 super(RepairTask, self).__init__(cmd, self.temp_results_dir)
1097
1098 self._set_ids(host=host, queue_entries=[queue_entry])
1099 self.set_host_log_file('repair', self.host)
mblighe2586682008-02-29 22:45:46 +00001100
mbligh36768f02008-02-22 18:28:33 +00001101
jadmanski0afbb632008-06-06 21:10:57 +00001102 def prolog(self):
1103 print "repair_task starting"
1104 self.host.set_status('Repairing')
showarde788ea62008-11-17 21:02:47 +00001105 if self.queue_entry:
1106 self.queue_entry.requeue()
mbligh36768f02008-02-22 18:28:33 +00001107
1108
jadmanski0afbb632008-06-06 21:10:57 +00001109 def epilog(self):
1110 super(RepairTask, self).epilog()
1111 if self.success:
1112 self.host.set_status('Ready')
1113 else:
1114 self.host.set_status('Repair Failed')
showarde788ea62008-11-17 21:02:47 +00001115 if self.queue_entry and not self.queue_entry.meta_host:
1116 self.queue_entry.handle_host_failure()
mbligh36768f02008-02-22 18:28:33 +00001117
1118
showard8fe93b52008-11-18 17:53:22 +00001119class PreJobTask(AgentTask):
showard170873e2009-01-07 00:22:26 +00001120 def epilog(self):
1121 super(PreJobTask, self).epilog()
showard8fe93b52008-11-18 17:53:22 +00001122 should_copy_results = (self.queue_entry and not self.success
1123 and not self.queue_entry.meta_host)
1124 if should_copy_results:
1125 self.queue_entry.set_execution_subdir()
showard170873e2009-01-07 00:22:26 +00001126 destination = os.path.join(self.queue_entry.execution_tag(),
1127 os.path.basename(self.log_file))
1128 _drone_manager.copy_to_results_repository(
1129 self.monitor.get_process(), self.log_file,
1130 destination_path=destination)
showard8fe93b52008-11-18 17:53:22 +00001131
1132
1133class VerifyTask(PreJobTask):
showard9976ce92008-10-15 20:28:13 +00001134 def __init__(self, queue_entry=None, host=None):
jadmanski0afbb632008-06-06 21:10:57 +00001135 assert bool(queue_entry) != bool(host)
jadmanski0afbb632008-06-06 21:10:57 +00001136 self.host = host or queue_entry.host
1137 self.queue_entry = queue_entry
mbligh36768f02008-02-22 18:28:33 +00001138
jadmanski0afbb632008-06-06 21:10:57 +00001139 self.create_temp_resultsdir('.verify')
showard170873e2009-01-07 00:22:26 +00001140 cmd = [_autoserv_path, '-p', '-v', '-m', self.host.hostname, '-r',
1141 _drone_manager.absolute_path(self.temp_results_dir)]
showarde788ea62008-11-17 21:02:47 +00001142 failure_tasks = [RepairTask(self.host, queue_entry=queue_entry)]
showard170873e2009-01-07 00:22:26 +00001143 super(VerifyTask, self).__init__(cmd, self.temp_results_dir,
1144 failure_tasks=failure_tasks)
mblighe2586682008-02-29 22:45:46 +00001145
showard170873e2009-01-07 00:22:26 +00001146 self.set_host_log_file('verify', self.host)
1147 self._set_ids(host=host, queue_entries=[queue_entry])
mblighe2586682008-02-29 22:45:46 +00001148
1149
jadmanski0afbb632008-06-06 21:10:57 +00001150 def prolog(self):
showard8fe93b52008-11-18 17:53:22 +00001151 super(VerifyTask, self).prolog()
jadmanski0afbb632008-06-06 21:10:57 +00001152 print "starting verify on %s" % (self.host.hostname)
1153 if self.queue_entry:
1154 self.queue_entry.set_status('Verifying')
jadmanski0afbb632008-06-06 21:10:57 +00001155 self.host.set_status('Verifying')
mbligh36768f02008-02-22 18:28:33 +00001156
1157
jadmanski0afbb632008-06-06 21:10:57 +00001158 def epilog(self):
1159 super(VerifyTask, self).epilog()
mbligh36768f02008-02-22 18:28:33 +00001160
jadmanski0afbb632008-06-06 21:10:57 +00001161 if self.success:
1162 self.host.set_status('Ready')
showard2bab8f42008-11-12 18:15:22 +00001163 if self.queue_entry:
1164 agent = self.queue_entry.on_pending()
1165 if agent:
1166 self.agent.dispatcher.add_agent(agent)
mbligh36768f02008-02-22 18:28:33 +00001167
1168
mbligh36768f02008-02-22 18:28:33 +00001169class QueueTask(AgentTask):
jadmanski0afbb632008-06-06 21:10:57 +00001170 def __init__(self, job, queue_entries, cmd):
jadmanski0afbb632008-06-06 21:10:57 +00001171 self.job = job
1172 self.queue_entries = queue_entries
showard170873e2009-01-07 00:22:26 +00001173 super(QueueTask, self).__init__(cmd, self._execution_tag())
1174 self._set_ids(queue_entries=queue_entries)
mbligh36768f02008-02-22 18:28:33 +00001175
1176
showard170873e2009-01-07 00:22:26 +00001177 def _format_keyval(self, key, value):
1178 return '%s=%s' % (key, value)
mbligh36768f02008-02-22 18:28:33 +00001179
1180
showard170873e2009-01-07 00:22:26 +00001181 def _write_keyval(self, field, value):
1182 keyval_path = os.path.join(self._execution_tag(), 'keyval')
1183 assert self.monitor and self.monitor.has_process()
1184 paired_with_pidfile = self.monitor.pidfile_id
1185 _drone_manager.write_lines_to_file(
1186 keyval_path, [self._format_keyval(field, value)],
1187 paired_with_pidfile=paired_with_pidfile)
showardd8e548a2008-09-09 03:04:57 +00001188
1189
showard170873e2009-01-07 00:22:26 +00001190 def _write_host_keyvals(self, host):
1191 keyval_path = os.path.join(self._execution_tag(), 'host_keyvals',
1192 host.hostname)
1193 platform, all_labels = host.platform_and_labels()
1194 keyvals = dict(platform=platform, labels=','.join(all_labels))
1195 keyval_content = '\n'.join(self._format_keyval(key, value)
1196 for key, value in keyvals.iteritems())
1197 _drone_manager.attach_file_to_execution(self._execution_tag(),
1198 keyval_content,
1199 file_path=keyval_path)
showardd8e548a2008-09-09 03:04:57 +00001200
1201
showard170873e2009-01-07 00:22:26 +00001202 def _execution_tag(self):
1203 return self.queue_entries[0].execution_tag()
mblighbb421852008-03-11 22:36:16 +00001204
1205
jadmanski0afbb632008-06-06 21:10:57 +00001206 def prolog(self):
jadmanski0afbb632008-06-06 21:10:57 +00001207 for queue_entry in self.queue_entries:
showard170873e2009-01-07 00:22:26 +00001208 self._write_host_keyvals(queue_entry.host)
jadmanski0afbb632008-06-06 21:10:57 +00001209 queue_entry.set_status('Running')
1210 queue_entry.host.set_status('Running')
showard21baa452008-10-21 00:08:39 +00001211 queue_entry.host.update_field('dirty', 1)
showard2bab8f42008-11-12 18:15:22 +00001212 if self.job.synch_count == 1:
jadmanski0afbb632008-06-06 21:10:57 +00001213 assert len(self.queue_entries) == 1
1214 self.job.write_to_machines_file(self.queue_entries[0])
mbligh36768f02008-02-22 18:28:33 +00001215
1216
showard97aed502008-11-04 02:01:24 +00001217 def _finish_task(self, success):
showard170873e2009-01-07 00:22:26 +00001218 queued = time.mktime(self.job.created_on.timetuple())
jadmanski0afbb632008-06-06 21:10:57 +00001219 finished = time.time()
showard170873e2009-01-07 00:22:26 +00001220 self._write_keyval("job_queued", int(queued))
1221 self._write_keyval("job_finished", int(finished))
1222
1223 _drone_manager.copy_to_results_repository(self.monitor.get_process(),
1224 self._execution_tag() + '/')
jadmanskic2ac77f2008-05-16 21:44:04 +00001225
jadmanski0afbb632008-06-06 21:10:57 +00001226 # parse the results of the job
showard97aed502008-11-04 02:01:24 +00001227 reparse_task = FinalReparseTask(self.queue_entries)
showard170873e2009-01-07 00:22:26 +00001228 self.agent.dispatcher.add_agent(Agent([reparse_task], num_processes=0))
jadmanskif7fa2cc2008-10-01 14:13:23 +00001229
1230
showardcbd74612008-11-19 21:42:02 +00001231 def _write_status_comment(self, comment):
showard170873e2009-01-07 00:22:26 +00001232 _drone_manager.write_lines_to_file(
1233 os.path.join(self._execution_tag(), 'status.log'),
1234 ['INFO\t----\t----\t' + comment],
1235 paired_with_pidfile=self.monitor.pidfile_id)
showardcbd74612008-11-19 21:42:02 +00001236
1237
jadmanskif7fa2cc2008-10-01 14:13:23 +00001238 def _log_abort(self):
showard170873e2009-01-07 00:22:26 +00001239 if not self.monitor or not self.monitor.has_process():
1240 return
1241
jadmanskif7fa2cc2008-10-01 14:13:23 +00001242 # build up sets of all the aborted_by and aborted_on values
1243 aborted_by, aborted_on = set(), set()
1244 for queue_entry in self.queue_entries:
1245 if queue_entry.aborted_by:
1246 aborted_by.add(queue_entry.aborted_by)
1247 t = int(time.mktime(queue_entry.aborted_on.timetuple()))
1248 aborted_on.add(t)
1249
1250 # extract some actual, unique aborted by value and write it out
1251 assert len(aborted_by) <= 1
1252 if len(aborted_by) == 1:
showardcbd74612008-11-19 21:42:02 +00001253 aborted_by_value = aborted_by.pop()
1254 aborted_on_value = max(aborted_on)
1255 else:
1256 aborted_by_value = 'autotest_system'
1257 aborted_on_value = int(time.time())
showard170873e2009-01-07 00:22:26 +00001258
1259 self._write_keyval("aborted_by", aborted_by_value)
1260 self._write_keyval("aborted_on", aborted_on_value)
1261
showardcbd74612008-11-19 21:42:02 +00001262 aborted_on_string = str(datetime.datetime.fromtimestamp(
1263 aborted_on_value))
1264 self._write_status_comment('Job aborted by %s on %s' %
1265 (aborted_by_value, aborted_on_string))
jadmanskic2ac77f2008-05-16 21:44:04 +00001266
1267
jadmanski0afbb632008-06-06 21:10:57 +00001268 def abort(self):
1269 super(QueueTask, self).abort()
jadmanskif7fa2cc2008-10-01 14:13:23 +00001270 self._log_abort()
showard97aed502008-11-04 02:01:24 +00001271 self._finish_task(False)
jadmanskic2ac77f2008-05-16 21:44:04 +00001272
1273
showard21baa452008-10-21 00:08:39 +00001274 def _reboot_hosts(self):
1275 reboot_after = self.job.reboot_after
1276 do_reboot = False
showard0fc38302008-10-23 00:44:07 +00001277 if reboot_after == models.RebootAfter.ALWAYS:
showard21baa452008-10-21 00:08:39 +00001278 do_reboot = True
showard0fc38302008-10-23 00:44:07 +00001279 elif reboot_after == models.RebootAfter.IF_ALL_TESTS_PASSED:
showard21baa452008-10-21 00:08:39 +00001280 num_tests_failed = self.monitor.num_tests_failed()
1281 do_reboot = (self.success and num_tests_failed == 0)
1282
showard8ebca792008-11-04 21:54:22 +00001283 for queue_entry in self.queue_entries:
1284 if do_reboot:
showard45ae8192008-11-05 19:32:53 +00001285 # don't pass the queue entry to the CleanupTask. if the cleanup
showardfa8629c2008-11-04 16:51:23 +00001286 # fails, the job doesn't care -- it's over.
showard45ae8192008-11-05 19:32:53 +00001287 cleanup_task = CleanupTask(host=queue_entry.get_host())
1288 self.agent.dispatcher.add_agent(Agent([cleanup_task]))
showard8ebca792008-11-04 21:54:22 +00001289 else:
1290 queue_entry.host.set_status('Ready')
showard21baa452008-10-21 00:08:39 +00001291
1292
jadmanski0afbb632008-06-06 21:10:57 +00001293 def epilog(self):
1294 super(QueueTask, self).epilog()
showard97aed502008-11-04 02:01:24 +00001295 self._finish_task(self.success)
showard21baa452008-10-21 00:08:39 +00001296 self._reboot_hosts()
mblighbb421852008-03-11 22:36:16 +00001297
showard97aed502008-11-04 02:01:24 +00001298 print "queue_task finished with succes=%s" % self.success
mbligh36768f02008-02-22 18:28:33 +00001299
1300
mblighbb421852008-03-11 22:36:16 +00001301class RecoveryQueueTask(QueueTask):
jadmanski0afbb632008-06-06 21:10:57 +00001302 def __init__(self, job, queue_entries, run_monitor):
showard170873e2009-01-07 00:22:26 +00001303 super(RecoveryQueueTask, self).__init__(job, queue_entries, cmd=None)
jadmanski0afbb632008-06-06 21:10:57 +00001304 self.run_monitor = run_monitor
mblighbb421852008-03-11 22:36:16 +00001305
1306
jadmanski0afbb632008-06-06 21:10:57 +00001307 def run(self):
1308 self.monitor = self.run_monitor
mblighbb421852008-03-11 22:36:16 +00001309
1310
jadmanski0afbb632008-06-06 21:10:57 +00001311 def prolog(self):
1312 # recovering an existing process - don't do prolog
1313 pass
mblighbb421852008-03-11 22:36:16 +00001314
1315
showard8fe93b52008-11-18 17:53:22 +00001316class CleanupTask(PreJobTask):
showardfa8629c2008-11-04 16:51:23 +00001317 def __init__(self, host=None, queue_entry=None):
1318 assert bool(host) ^ bool(queue_entry)
1319 if queue_entry:
1320 host = queue_entry.get_host()
showardfa8629c2008-11-04 16:51:23 +00001321 self.queue_entry = queue_entry
jadmanski0afbb632008-06-06 21:10:57 +00001322 self.host = host
showard170873e2009-01-07 00:22:26 +00001323
1324 self.create_temp_resultsdir('.cleanup')
1325 self.cmd = [_autoserv_path, '-p', '--cleanup', '-m', host.hostname,
1326 '-r', _drone_manager.absolute_path(self.temp_results_dir)]
showarde788ea62008-11-17 21:02:47 +00001327 repair_task = RepairTask(host, queue_entry=queue_entry)
showard170873e2009-01-07 00:22:26 +00001328 super(CleanupTask, self).__init__(self.cmd, self.temp_results_dir,
1329 failure_tasks=[repair_task])
1330
1331 self._set_ids(host=host, queue_entries=[queue_entry])
1332 self.set_host_log_file('cleanup', self.host)
mbligh16c722d2008-03-05 00:58:44 +00001333
mblighd5c95802008-03-05 00:33:46 +00001334
jadmanski0afbb632008-06-06 21:10:57 +00001335 def prolog(self):
showard8fe93b52008-11-18 17:53:22 +00001336 super(CleanupTask, self).prolog()
showard45ae8192008-11-05 19:32:53 +00001337 print "starting cleanup task for host: %s" % self.host.hostname
1338 self.host.set_status("Cleaning")
mblighd5c95802008-03-05 00:33:46 +00001339
mblighd5c95802008-03-05 00:33:46 +00001340
showard21baa452008-10-21 00:08:39 +00001341 def epilog(self):
showard45ae8192008-11-05 19:32:53 +00001342 super(CleanupTask, self).epilog()
showard21baa452008-10-21 00:08:39 +00001343 if self.success:
showardfa8629c2008-11-04 16:51:23 +00001344 self.host.set_status('Ready')
showard21baa452008-10-21 00:08:39 +00001345 self.host.update_field('dirty', 0)
1346
1347
mblighd5c95802008-03-05 00:33:46 +00001348class AbortTask(AgentTask):
jadmanski0afbb632008-06-06 21:10:57 +00001349 def __init__(self, queue_entry, agents_to_abort):
jadmanski0afbb632008-06-06 21:10:57 +00001350 super(AbortTask, self).__init__('')
showard170873e2009-01-07 00:22:26 +00001351 self.queue_entry = queue_entry
1352 # don't use _set_ids, since we don't want to set the host_ids
1353 self.queue_entry_ids = [queue_entry.id]
1354 self.agents_to_abort = agents_to_abort
mbligh36768f02008-02-22 18:28:33 +00001355
1356
jadmanski0afbb632008-06-06 21:10:57 +00001357 def prolog(self):
1358 print "starting abort on host %s, job %s" % (
1359 self.queue_entry.host_id, self.queue_entry.job_id)
mbligh36768f02008-02-22 18:28:33 +00001360
mblighd64e5702008-04-04 21:39:28 +00001361
jadmanski0afbb632008-06-06 21:10:57 +00001362 def epilog(self):
1363 super(AbortTask, self).epilog()
1364 self.queue_entry.set_status('Aborted')
1365 self.success = True
1366
1367
1368 def run(self):
1369 for agent in self.agents_to_abort:
1370 if (agent.active_task):
1371 agent.active_task.abort()
mbligh36768f02008-02-22 18:28:33 +00001372
1373
showard97aed502008-11-04 02:01:24 +00001374class FinalReparseTask(AgentTask):
showard97aed502008-11-04 02:01:24 +00001375 _num_running_parses = 0
1376
1377 def __init__(self, queue_entries):
1378 self._queue_entries = queue_entries
showard170873e2009-01-07 00:22:26 +00001379 # don't use _set_ids, since we don't want to set the host_ids
1380 self.queue_entry_ids = [entry.id for entry in queue_entries]
showard97aed502008-11-04 02:01:24 +00001381 self._parse_started = False
1382
1383 assert len(queue_entries) > 0
1384 queue_entry = queue_entries[0]
showard97aed502008-11-04 02:01:24 +00001385
showard170873e2009-01-07 00:22:26 +00001386 self._execution_tag = queue_entry.execution_tag()
1387 self._results_dir = _drone_manager.absolute_path(self._execution_tag)
1388 self._autoserv_monitor = PidfileRunMonitor()
1389 self._autoserv_monitor.attach_to_existing_process(self._execution_tag)
1390 self._final_status = self._determine_final_status()
1391
showard97aed502008-11-04 02:01:24 +00001392 if _testing_mode:
1393 self.cmd = 'true'
showard170873e2009-01-07 00:22:26 +00001394 else:
1395 super(FinalReparseTask, self).__init__(
1396 cmd=self._generate_parse_command(),
1397 working_directory=self._execution_tag)
showard97aed502008-11-04 02:01:24 +00001398
showard170873e2009-01-07 00:22:26 +00001399 self.log_file = os.path.join(self._execution_tag, '.parse.log')
showard97aed502008-11-04 02:01:24 +00001400
1401
1402 @classmethod
1403 def _increment_running_parses(cls):
1404 cls._num_running_parses += 1
1405
1406
1407 @classmethod
1408 def _decrement_running_parses(cls):
1409 cls._num_running_parses -= 1
1410
1411
1412 @classmethod
1413 def _can_run_new_parse(cls):
showardd1ee1dd2009-01-07 21:33:08 +00001414 return (cls._num_running_parses <
1415 scheduler_config.config.max_parse_processes)
showard97aed502008-11-04 02:01:24 +00001416
1417
showard170873e2009-01-07 00:22:26 +00001418 def _determine_final_status(self):
1419 # we'll use a PidfileRunMonitor to read the autoserv exit status
1420 if self._autoserv_monitor.exit_code() == 0:
1421 return models.HostQueueEntry.Status.COMPLETED
1422 return models.HostQueueEntry.Status.FAILED
1423
1424
showard97aed502008-11-04 02:01:24 +00001425 def prolog(self):
1426 super(FinalReparseTask, self).prolog()
1427 for queue_entry in self._queue_entries:
1428 queue_entry.set_status(models.HostQueueEntry.Status.PARSING)
1429
1430
1431 def epilog(self):
1432 super(FinalReparseTask, self).epilog()
showard97aed502008-11-04 02:01:24 +00001433 for queue_entry in self._queue_entries:
showard170873e2009-01-07 00:22:26 +00001434 queue_entry.set_status(self._final_status)
showard97aed502008-11-04 02:01:24 +00001435
1436
showard2bab8f42008-11-12 18:15:22 +00001437 def _generate_parse_command(self):
showard170873e2009-01-07 00:22:26 +00001438 return [_parser_path, '--write-pidfile', '-l', '2', '-r', '-o',
1439 self._results_dir]
showard97aed502008-11-04 02:01:24 +00001440
1441
1442 def poll(self):
1443 # override poll to keep trying to start until the parse count goes down
1444 # and we can, at which point we revert to default behavior
1445 if self._parse_started:
1446 super(FinalReparseTask, self).poll()
1447 else:
1448 self._try_starting_parse()
1449
1450
1451 def run(self):
1452 # override run() to not actually run unless we can
1453 self._try_starting_parse()
1454
1455
1456 def _try_starting_parse(self):
1457 if not self._can_run_new_parse():
1458 return
showard170873e2009-01-07 00:22:26 +00001459
showard97aed502008-11-04 02:01:24 +00001460 # actually run the parse command
showard170873e2009-01-07 00:22:26 +00001461 self.monitor = PidfileRunMonitor()
1462 self.monitor.run(self.cmd, self._working_directory,
1463 log_file=self.log_file,
1464 pidfile_name='.parser_execute',
1465 paired_with_pidfile=self._autoserv_monitor.pidfile_id)
1466
showard97aed502008-11-04 02:01:24 +00001467 self._increment_running_parses()
1468 self._parse_started = True
1469
1470
1471 def finished(self, success):
1472 super(FinalReparseTask, self).finished(success)
1473 self._decrement_running_parses()
1474
1475
mbligh36768f02008-02-22 18:28:33 +00001476class DBObject(object):
jadmanski0afbb632008-06-06 21:10:57 +00001477 def __init__(self, id=None, row=None, new_record=False):
1478 assert (bool(id) != bool(row))
mbligh36768f02008-02-22 18:28:33 +00001479
jadmanski0afbb632008-06-06 21:10:57 +00001480 self.__table = self._get_table()
mbligh36768f02008-02-22 18:28:33 +00001481
jadmanski0afbb632008-06-06 21:10:57 +00001482 self.__new_record = new_record
mbligh36768f02008-02-22 18:28:33 +00001483
jadmanski0afbb632008-06-06 21:10:57 +00001484 if row is None:
1485 sql = 'SELECT * FROM %s WHERE ID=%%s' % self.__table
1486 rows = _db.execute(sql, (id,))
1487 if len(rows) == 0:
1488 raise "row not found (table=%s, id=%s)" % \
1489 (self.__table, id)
1490 row = rows[0]
mbligh36768f02008-02-22 18:28:33 +00001491
showard2bab8f42008-11-12 18:15:22 +00001492 self._update_fields_from_row(row)
1493
1494
1495 def _update_fields_from_row(self, row):
jadmanski0afbb632008-06-06 21:10:57 +00001496 assert len(row) == self.num_cols(), (
1497 "table = %s, row = %s/%d, fields = %s/%d" % (
showard2bab8f42008-11-12 18:15:22 +00001498 self.__table, row, len(row), self._fields(), self.num_cols()))
mbligh36768f02008-02-22 18:28:33 +00001499
showard2bab8f42008-11-12 18:15:22 +00001500 self._valid_fields = set()
1501 for field, value in zip(self._fields(), row):
1502 setattr(self, field, value)
1503 self._valid_fields.add(field)
mbligh36768f02008-02-22 18:28:33 +00001504
showard2bab8f42008-11-12 18:15:22 +00001505 self._valid_fields.remove('id')
mbligh36768f02008-02-22 18:28:33 +00001506
mblighe2586682008-02-29 22:45:46 +00001507
jadmanski0afbb632008-06-06 21:10:57 +00001508 @classmethod
1509 def _get_table(cls):
1510 raise NotImplementedError('Subclasses must override this')
mblighe2586682008-02-29 22:45:46 +00001511
1512
jadmanski0afbb632008-06-06 21:10:57 +00001513 @classmethod
1514 def _fields(cls):
1515 raise NotImplementedError('Subclasses must override this')
showard04c82c52008-05-29 19:38:12 +00001516
1517
jadmanski0afbb632008-06-06 21:10:57 +00001518 @classmethod
1519 def num_cols(cls):
1520 return len(cls._fields())
showard04c82c52008-05-29 19:38:12 +00001521
1522
jadmanski0afbb632008-06-06 21:10:57 +00001523 def count(self, where, table = None):
1524 if not table:
1525 table = self.__table
mbligh36768f02008-02-22 18:28:33 +00001526
jadmanski0afbb632008-06-06 21:10:57 +00001527 rows = _db.execute("""
1528 SELECT count(*) FROM %s
1529 WHERE %s
1530 """ % (table, where))
mbligh6f8bab42008-02-29 22:45:14 +00001531
jadmanski0afbb632008-06-06 21:10:57 +00001532 assert len(rows) == 1
1533
1534 return int(rows[0][0])
mbligh36768f02008-02-22 18:28:33 +00001535
1536
mblighf8c624d2008-07-03 16:58:45 +00001537 def update_field(self, field, value, condition=''):
showard2bab8f42008-11-12 18:15:22 +00001538 assert field in self._valid_fields
mbligh36768f02008-02-22 18:28:33 +00001539
showard2bab8f42008-11-12 18:15:22 +00001540 if getattr(self, field) == value:
jadmanski0afbb632008-06-06 21:10:57 +00001541 return
mbligh36768f02008-02-22 18:28:33 +00001542
mblighf8c624d2008-07-03 16:58:45 +00001543 query = "UPDATE %s SET %s = %%s WHERE id = %%s" % (self.__table, field)
1544 if condition:
1545 query += ' AND (%s)' % condition
jadmanski0afbb632008-06-06 21:10:57 +00001546 _db.execute(query, (value, self.id))
1547
showard2bab8f42008-11-12 18:15:22 +00001548 setattr(self, field, value)
mbligh36768f02008-02-22 18:28:33 +00001549
1550
jadmanski0afbb632008-06-06 21:10:57 +00001551 def save(self):
1552 if self.__new_record:
1553 keys = self._fields()[1:] # avoid id
1554 columns = ','.join([str(key) for key in keys])
1555 values = ['"%s"' % self.__dict__[key] for key in keys]
1556 values = ','.join(values)
1557 query = """INSERT INTO %s (%s) VALUES (%s)""" % \
1558 (self.__table, columns, values)
1559 _db.execute(query)
mbligh36768f02008-02-22 18:28:33 +00001560
1561
jadmanski0afbb632008-06-06 21:10:57 +00001562 def delete(self):
1563 query = 'DELETE FROM %s WHERE id=%%s' % self.__table
1564 _db.execute(query, (self.id,))
mblighe2586682008-02-29 22:45:46 +00001565
1566
showard63a34772008-08-18 19:32:50 +00001567 @staticmethod
1568 def _prefix_with(string, prefix):
1569 if string:
1570 string = prefix + string
1571 return string
1572
1573
jadmanski0afbb632008-06-06 21:10:57 +00001574 @classmethod
showard989f25d2008-10-01 11:38:11 +00001575 def fetch(cls, where='', params=(), joins='', order_by=''):
showard63a34772008-08-18 19:32:50 +00001576 order_by = cls._prefix_with(order_by, 'ORDER BY ')
1577 where = cls._prefix_with(where, 'WHERE ')
1578 query = ('SELECT %(table)s.* FROM %(table)s %(joins)s '
1579 '%(where)s %(order_by)s' % {'table' : cls._get_table(),
1580 'joins' : joins,
1581 'where' : where,
1582 'order_by' : order_by})
1583 rows = _db.execute(query, params)
jadmanski0afbb632008-06-06 21:10:57 +00001584 for row in rows:
1585 yield cls(row=row)
mblighe2586682008-02-29 22:45:46 +00001586
mbligh36768f02008-02-22 18:28:33 +00001587
1588class IneligibleHostQueue(DBObject):
jadmanski0afbb632008-06-06 21:10:57 +00001589 def __init__(self, id=None, row=None, new_record=None):
1590 super(IneligibleHostQueue, self).__init__(id=id, row=row,
1591 new_record=new_record)
mblighe2586682008-02-29 22:45:46 +00001592
1593
jadmanski0afbb632008-06-06 21:10:57 +00001594 @classmethod
1595 def _get_table(cls):
1596 return 'ineligible_host_queues'
mbligh36768f02008-02-22 18:28:33 +00001597
1598
jadmanski0afbb632008-06-06 21:10:57 +00001599 @classmethod
1600 def _fields(cls):
1601 return ['id', 'job_id', 'host_id']
showard04c82c52008-05-29 19:38:12 +00001602
1603
showard989f25d2008-10-01 11:38:11 +00001604class Label(DBObject):
1605 @classmethod
1606 def _get_table(cls):
1607 return 'labels'
1608
1609
1610 @classmethod
1611 def _fields(cls):
1612 return ['id', 'name', 'kernel_config', 'platform', 'invalid',
1613 'only_if_needed']
1614
1615
mbligh36768f02008-02-22 18:28:33 +00001616class Host(DBObject):
jadmanski0afbb632008-06-06 21:10:57 +00001617 def __init__(self, id=None, row=None):
1618 super(Host, self).__init__(id=id, row=row)
mblighe2586682008-02-29 22:45:46 +00001619
1620
jadmanski0afbb632008-06-06 21:10:57 +00001621 @classmethod
1622 def _get_table(cls):
1623 return 'hosts'
mbligh36768f02008-02-22 18:28:33 +00001624
1625
jadmanski0afbb632008-06-06 21:10:57 +00001626 @classmethod
1627 def _fields(cls):
1628 return ['id', 'hostname', 'locked', 'synch_id','status',
showard21baa452008-10-21 00:08:39 +00001629 'invalid', 'protection', 'locked_by_id', 'lock_time', 'dirty']
showard04c82c52008-05-29 19:38:12 +00001630
1631
jadmanski0afbb632008-06-06 21:10:57 +00001632 def current_task(self):
1633 rows = _db.execute("""
1634 SELECT * FROM host_queue_entries WHERE host_id=%s AND NOT complete AND active
1635 """, (self.id,))
1636
1637 if len(rows) == 0:
1638 return None
1639 else:
1640 assert len(rows) == 1
1641 results = rows[0];
mblighf8c624d2008-07-03 16:58:45 +00001642# print "current = %s" % results
jadmanski0afbb632008-06-06 21:10:57 +00001643 return HostQueueEntry(row=results)
mbligh36768f02008-02-22 18:28:33 +00001644
1645
jadmanski0afbb632008-06-06 21:10:57 +00001646 def yield_work(self):
1647 print "%s yielding work" % self.hostname
1648 if self.current_task():
1649 self.current_task().requeue()
1650
1651 def set_status(self,status):
1652 print '%s -> %s' % (self.hostname, status)
1653 self.update_field('status',status)
mbligh36768f02008-02-22 18:28:33 +00001654
1655
showard170873e2009-01-07 00:22:26 +00001656 def platform_and_labels(self):
showardd8e548a2008-09-09 03:04:57 +00001657 """
showard170873e2009-01-07 00:22:26 +00001658 Returns a tuple (platform_name, list_of_all_label_names).
showardd8e548a2008-09-09 03:04:57 +00001659 """
1660 rows = _db.execute("""
showard170873e2009-01-07 00:22:26 +00001661 SELECT labels.name, labels.platform
showardd8e548a2008-09-09 03:04:57 +00001662 FROM labels
1663 INNER JOIN hosts_labels ON labels.id = hosts_labels.label_id
showard170873e2009-01-07 00:22:26 +00001664 WHERE hosts_labels.host_id = %s
showardd8e548a2008-09-09 03:04:57 +00001665 ORDER BY labels.name
1666 """, (self.id,))
showard170873e2009-01-07 00:22:26 +00001667 platform = None
1668 all_labels = []
1669 for label_name, is_platform in rows:
1670 if is_platform:
1671 platform = label_name
1672 all_labels.append(label_name)
1673 return platform, all_labels
1674
1675
1676 def reverify_tasks(self):
1677 cleanup_task = CleanupTask(host=self)
1678 verify_task = VerifyTask(host=self)
1679 # just to make sure this host does not get taken away
1680 self.set_status('Cleaning')
1681 return [cleanup_task, verify_task]
showardd8e548a2008-09-09 03:04:57 +00001682
1683
mbligh36768f02008-02-22 18:28:33 +00001684class HostQueueEntry(DBObject):
jadmanski0afbb632008-06-06 21:10:57 +00001685 def __init__(self, id=None, row=None):
1686 assert id or row
1687 super(HostQueueEntry, self).__init__(id=id, row=row)
1688 self.job = Job(self.job_id)
mbligh36768f02008-02-22 18:28:33 +00001689
jadmanski0afbb632008-06-06 21:10:57 +00001690 if self.host_id:
1691 self.host = Host(self.host_id)
1692 else:
1693 self.host = None
mbligh36768f02008-02-22 18:28:33 +00001694
showard170873e2009-01-07 00:22:26 +00001695 self.queue_log_path = os.path.join(self.job.tag(),
jadmanski0afbb632008-06-06 21:10:57 +00001696 'queue.log.' + str(self.id))
mbligh36768f02008-02-22 18:28:33 +00001697
1698
jadmanski0afbb632008-06-06 21:10:57 +00001699 @classmethod
1700 def _get_table(cls):
1701 return 'host_queue_entries'
mblighe2586682008-02-29 22:45:46 +00001702
1703
jadmanski0afbb632008-06-06 21:10:57 +00001704 @classmethod
1705 def _fields(cls):
showard2bab8f42008-11-12 18:15:22 +00001706 return ['id', 'job_id', 'host_id', 'priority', 'status', 'meta_host',
1707 'active', 'complete', 'deleted', 'execution_subdir']
showard04c82c52008-05-29 19:38:12 +00001708
1709
showardc85c21b2008-11-24 22:17:37 +00001710 def _view_job_url(self):
1711 return "%s#tab_id=view_job&object_id=%s" % (_base_url, self.job.id)
1712
1713
jadmanski0afbb632008-06-06 21:10:57 +00001714 def set_host(self, host):
1715 if host:
1716 self.queue_log_record('Assigning host ' + host.hostname)
1717 self.update_field('host_id', host.id)
1718 self.update_field('active', True)
1719 self.block_host(host.id)
1720 else:
1721 self.queue_log_record('Releasing host')
1722 self.unblock_host(self.host.id)
1723 self.update_field('host_id', None)
mbligh36768f02008-02-22 18:28:33 +00001724
jadmanski0afbb632008-06-06 21:10:57 +00001725 self.host = host
mbligh36768f02008-02-22 18:28:33 +00001726
1727
jadmanski0afbb632008-06-06 21:10:57 +00001728 def get_host(self):
1729 return self.host
mbligh36768f02008-02-22 18:28:33 +00001730
1731
jadmanski0afbb632008-06-06 21:10:57 +00001732 def queue_log_record(self, log_line):
1733 now = str(datetime.datetime.now())
showard170873e2009-01-07 00:22:26 +00001734 _drone_manager.write_lines_to_file(self.queue_log_path,
1735 [now + ' ' + log_line])
mbligh36768f02008-02-22 18:28:33 +00001736
1737
jadmanski0afbb632008-06-06 21:10:57 +00001738 def block_host(self, host_id):
1739 print "creating block %s/%s" % (self.job.id, host_id)
1740 row = [0, self.job.id, host_id]
1741 block = IneligibleHostQueue(row=row, new_record=True)
1742 block.save()
mblighe2586682008-02-29 22:45:46 +00001743
1744
jadmanski0afbb632008-06-06 21:10:57 +00001745 def unblock_host(self, host_id):
1746 print "removing block %s/%s" % (self.job.id, host_id)
1747 blocks = IneligibleHostQueue.fetch(
1748 'job_id=%d and host_id=%d' % (self.job.id, host_id))
1749 for block in blocks:
1750 block.delete()
mblighe2586682008-02-29 22:45:46 +00001751
1752
showard2bab8f42008-11-12 18:15:22 +00001753 def set_execution_subdir(self, subdir=None):
1754 if subdir is None:
1755 assert self.get_host()
1756 subdir = self.get_host().hostname
1757 self.update_field('execution_subdir', subdir)
mbligh36768f02008-02-22 18:28:33 +00001758
1759
showard6355f6b2008-12-05 18:52:13 +00001760 def _get_hostname(self):
1761 if self.host:
1762 return self.host.hostname
1763 return 'no host'
1764
1765
showard170873e2009-01-07 00:22:26 +00001766 def __str__(self):
1767 return "%s/%d (%d)" % (self._get_hostname(), self.job.id, self.id)
1768
1769
jadmanski0afbb632008-06-06 21:10:57 +00001770 def set_status(self, status):
mblighf8c624d2008-07-03 16:58:45 +00001771 abort_statuses = ['Abort', 'Aborting', 'Aborted']
1772 if status not in abort_statuses:
1773 condition = ' AND '.join(['status <> "%s"' % x
1774 for x in abort_statuses])
1775 else:
1776 condition = ''
1777 self.update_field('status', status, condition=condition)
1778
showard170873e2009-01-07 00:22:26 +00001779 print "%s -> %s" % (self, self.status)
mblighf8c624d2008-07-03 16:58:45 +00001780
showardc85c21b2008-11-24 22:17:37 +00001781 if status in ['Queued', 'Parsing']:
jadmanski0afbb632008-06-06 21:10:57 +00001782 self.update_field('complete', False)
1783 self.update_field('active', False)
mbligh36768f02008-02-22 18:28:33 +00001784
jadmanski0afbb632008-06-06 21:10:57 +00001785 if status in ['Pending', 'Running', 'Verifying', 'Starting',
showarde58e3f82008-11-20 19:04:59 +00001786 'Aborting']:
jadmanski0afbb632008-06-06 21:10:57 +00001787 self.update_field('complete', False)
1788 self.update_field('active', True)
mbligh36768f02008-02-22 18:28:33 +00001789
showardc85c21b2008-11-24 22:17:37 +00001790 if status in ['Failed', 'Completed', 'Stopped', 'Aborted']:
jadmanski0afbb632008-06-06 21:10:57 +00001791 self.update_field('complete', True)
1792 self.update_field('active', False)
showardc85c21b2008-11-24 22:17:37 +00001793
1794 should_email_status = (status.lower() in _notify_email_statuses or
1795 'all' in _notify_email_statuses)
1796 if should_email_status:
1797 self._email_on_status(status)
1798
1799 self._email_on_job_complete()
1800
1801
1802 def _email_on_status(self, status):
showard6355f6b2008-12-05 18:52:13 +00001803 hostname = self._get_hostname()
showardc85c21b2008-11-24 22:17:37 +00001804
1805 subject = 'Autotest: Job ID: %s "%s" Host: %s %s' % (
1806 self.job.id, self.job.name, hostname, status)
1807 body = "Job ID: %s\nJob Name: %s\nHost: %s\nStatus: %s\n%s\n" % (
1808 self.job.id, self.job.name, hostname, status,
1809 self._view_job_url())
showard170873e2009-01-07 00:22:26 +00001810 email_manager.manager.send_email(self.job.email_list, subject, body)
showard542e8402008-09-19 20:16:18 +00001811
1812
1813 def _email_on_job_complete(self):
showardc85c21b2008-11-24 22:17:37 +00001814 if not self.job.is_finished():
1815 return
showard542e8402008-09-19 20:16:18 +00001816
showardc85c21b2008-11-24 22:17:37 +00001817 summary_text = []
showard6355f6b2008-12-05 18:52:13 +00001818 hosts_queue = HostQueueEntry.fetch('job_id = %s' % self.job.id)
showardc85c21b2008-11-24 22:17:37 +00001819 for queue_entry in hosts_queue:
1820 summary_text.append("Host: %s Status: %s" %
showard6355f6b2008-12-05 18:52:13 +00001821 (queue_entry._get_hostname(),
showardc85c21b2008-11-24 22:17:37 +00001822 queue_entry.status))
1823
1824 summary_text = "\n".join(summary_text)
1825 status_counts = models.Job.objects.get_status_counts(
1826 [self.job.id])[self.job.id]
1827 status = ', '.join('%d %s' % (count, status) for status, count
1828 in status_counts.iteritems())
1829
1830 subject = 'Autotest: Job ID: %s "%s" %s' % (
1831 self.job.id, self.job.name, status)
1832 body = "Job ID: %s\nJob Name: %s\nStatus: %s\n%s\nSummary:\n%s" % (
1833 self.job.id, self.job.name, status, self._view_job_url(),
1834 summary_text)
showard170873e2009-01-07 00:22:26 +00001835 email_manager.manager.send_email(self.job.email_list, subject, body)
mbligh36768f02008-02-22 18:28:33 +00001836
1837
jadmanski0afbb632008-06-06 21:10:57 +00001838 def run(self,assigned_host=None):
1839 if self.meta_host:
1840 assert assigned_host
1841 # ensure results dir exists for the queue log
jadmanski0afbb632008-06-06 21:10:57 +00001842 self.set_host(assigned_host)
mbligh36768f02008-02-22 18:28:33 +00001843
jadmanski0afbb632008-06-06 21:10:57 +00001844 print "%s/%s scheduled on %s, status=%s" % (self.job.name,
1845 self.meta_host, self.host.hostname, self.status)
mbligh36768f02008-02-22 18:28:33 +00001846
jadmanski0afbb632008-06-06 21:10:57 +00001847 return self.job.run(queue_entry=self)
mblighe2586682008-02-29 22:45:46 +00001848
jadmanski0afbb632008-06-06 21:10:57 +00001849 def requeue(self):
1850 self.set_status('Queued')
jadmanski0afbb632008-06-06 21:10:57 +00001851 if self.meta_host:
1852 self.set_host(None)
mbligh36768f02008-02-22 18:28:33 +00001853
1854
jadmanski0afbb632008-06-06 21:10:57 +00001855 def handle_host_failure(self):
1856 """\
1857 Called when this queue entry's host has failed verification and
1858 repair.
1859 """
1860 assert not self.meta_host
1861 self.set_status('Failed')
showard2bab8f42008-11-12 18:15:22 +00001862 self.job.stop_if_necessary()
mblighe2586682008-02-29 22:45:46 +00001863
1864
jadmanskif7fa2cc2008-10-01 14:13:23 +00001865 @property
1866 def aborted_by(self):
1867 self._load_abort_info()
1868 return self._aborted_by
1869
1870
1871 @property
1872 def aborted_on(self):
1873 self._load_abort_info()
1874 return self._aborted_on
1875
1876
1877 def _load_abort_info(self):
1878 """ Fetch info about who aborted the job. """
1879 if hasattr(self, "_aborted_by"):
1880 return
1881 rows = _db.execute("""
1882 SELECT users.login, aborted_host_queue_entries.aborted_on
1883 FROM aborted_host_queue_entries
1884 INNER JOIN users
1885 ON users.id = aborted_host_queue_entries.aborted_by_id
1886 WHERE aborted_host_queue_entries.queue_entry_id = %s
1887 """, (self.id,))
1888 if rows:
1889 self._aborted_by, self._aborted_on = rows[0]
1890 else:
1891 self._aborted_by = self._aborted_on = None
1892
1893
showardb2e2c322008-10-14 17:33:55 +00001894 def on_pending(self):
1895 """
1896 Called when an entry in a synchronous job has passed verify. If the
1897 job is ready to run, returns an agent to run the job. Returns None
1898 otherwise.
1899 """
1900 self.set_status('Pending')
showardcfd66a32008-10-15 20:31:48 +00001901 self.get_host().set_status('Pending')
showardb2e2c322008-10-14 17:33:55 +00001902 if self.job.is_ready():
1903 return self.job.run(self)
showard2bab8f42008-11-12 18:15:22 +00001904 self.job.stop_if_necessary()
showardb2e2c322008-10-14 17:33:55 +00001905 return None
1906
1907
showard170873e2009-01-07 00:22:26 +00001908 def abort(self, dispatcher, agents_to_abort=[]):
showard1be97432008-10-17 15:30:45 +00001909 host = self.get_host()
showard9d9ffd52008-11-09 23:14:35 +00001910 if self.active and host:
showard170873e2009-01-07 00:22:26 +00001911 dispatcher.add_agent(Agent(tasks=host.reverify_tasks()))
showard1be97432008-10-17 15:30:45 +00001912
showard170873e2009-01-07 00:22:26 +00001913 abort_task = AbortTask(self, agents_to_abort)
showard1be97432008-10-17 15:30:45 +00001914 self.set_status('Aborting')
showard170873e2009-01-07 00:22:26 +00001915 dispatcher.add_agent(Agent(tasks=[abort_task], num_processes=0))
1916
1917 def execution_tag(self):
1918 assert self.execution_subdir
1919 return "%s-%s/%s" % (self.job.id, self.job.owner, self.execution_subdir)
showard1be97432008-10-17 15:30:45 +00001920
1921
mbligh36768f02008-02-22 18:28:33 +00001922class Job(DBObject):
jadmanski0afbb632008-06-06 21:10:57 +00001923 def __init__(self, id=None, row=None):
1924 assert id or row
1925 super(Job, self).__init__(id=id, row=row)
mbligh36768f02008-02-22 18:28:33 +00001926
mblighe2586682008-02-29 22:45:46 +00001927
jadmanski0afbb632008-06-06 21:10:57 +00001928 @classmethod
1929 def _get_table(cls):
1930 return 'jobs'
mbligh36768f02008-02-22 18:28:33 +00001931
1932
jadmanski0afbb632008-06-06 21:10:57 +00001933 @classmethod
1934 def _fields(cls):
1935 return ['id', 'owner', 'name', 'priority', 'control_file',
showard2bab8f42008-11-12 18:15:22 +00001936 'control_type', 'created_on', 'synch_count', 'timeout',
showard21baa452008-10-21 00:08:39 +00001937 'run_verify', 'email_list', 'reboot_before', 'reboot_after']
showard04c82c52008-05-29 19:38:12 +00001938
1939
jadmanski0afbb632008-06-06 21:10:57 +00001940 def is_server_job(self):
1941 return self.control_type != 2
mbligh36768f02008-02-22 18:28:33 +00001942
1943
showard170873e2009-01-07 00:22:26 +00001944 def tag(self):
1945 return "%s-%s" % (self.id, self.owner)
1946
1947
jadmanski0afbb632008-06-06 21:10:57 +00001948 def get_host_queue_entries(self):
1949 rows = _db.execute("""
1950 SELECT * FROM host_queue_entries
1951 WHERE job_id= %s
1952 """, (self.id,))
1953 entries = [HostQueueEntry(row=i) for i in rows]
mbligh36768f02008-02-22 18:28:33 +00001954
jadmanski0afbb632008-06-06 21:10:57 +00001955 assert len(entries)>0
mbligh36768f02008-02-22 18:28:33 +00001956
jadmanski0afbb632008-06-06 21:10:57 +00001957 return entries
mbligh36768f02008-02-22 18:28:33 +00001958
1959
jadmanski0afbb632008-06-06 21:10:57 +00001960 def set_status(self, status, update_queues=False):
1961 self.update_field('status',status)
1962
1963 if update_queues:
1964 for queue_entry in self.get_host_queue_entries():
1965 queue_entry.set_status(status)
mbligh36768f02008-02-22 18:28:33 +00001966
1967
jadmanski0afbb632008-06-06 21:10:57 +00001968 def is_ready(self):
showard2bab8f42008-11-12 18:15:22 +00001969 pending_entries = models.HostQueueEntry.objects.filter(job=self.id,
1970 status='Pending')
1971 return (pending_entries.count() >= self.synch_count)
mbligh36768f02008-02-22 18:28:33 +00001972
1973
jadmanski0afbb632008-06-06 21:10:57 +00001974 def num_machines(self, clause = None):
1975 sql = "job_id=%s" % self.id
1976 if clause:
1977 sql += " AND (%s)" % clause
1978 return self.count(sql, table='host_queue_entries')
mbligh36768f02008-02-22 18:28:33 +00001979
1980
jadmanski0afbb632008-06-06 21:10:57 +00001981 def num_queued(self):
1982 return self.num_machines('not complete')
mbligh36768f02008-02-22 18:28:33 +00001983
1984
jadmanski0afbb632008-06-06 21:10:57 +00001985 def num_active(self):
1986 return self.num_machines('active')
mbligh36768f02008-02-22 18:28:33 +00001987
1988
jadmanski0afbb632008-06-06 21:10:57 +00001989 def num_complete(self):
1990 return self.num_machines('complete')
mbligh36768f02008-02-22 18:28:33 +00001991
1992
jadmanski0afbb632008-06-06 21:10:57 +00001993 def is_finished(self):
showardc85c21b2008-11-24 22:17:37 +00001994 return self.num_complete() == self.num_machines()
mbligh36768f02008-02-22 18:28:33 +00001995
mbligh36768f02008-02-22 18:28:33 +00001996
showard2bab8f42008-11-12 18:15:22 +00001997 def _stop_all_entries(self, entries_to_abort):
1998 """
1999 queue_entries: sequence of models.HostQueueEntry objects
2000 """
2001 for child_entry in entries_to_abort:
showard4f9e5372009-01-07 21:33:38 +00002002 assert not child_entry.complete, (
2003 '%s status=%s, active=%s, complete=%s' %
2004 (child_entry.id, child_entry.status, child_entry.active,
2005 child_entry.complete))
showard2bab8f42008-11-12 18:15:22 +00002006 if child_entry.status == models.HostQueueEntry.Status.PENDING:
2007 child_entry.host.status = models.Host.Status.READY
2008 child_entry.host.save()
2009 child_entry.status = models.HostQueueEntry.Status.STOPPED
2010 child_entry.save()
2011
2012
2013 def stop_if_necessary(self):
2014 not_yet_run = models.HostQueueEntry.objects.filter(
2015 job=self.id, status__in=(models.HostQueueEntry.Status.QUEUED,
2016 models.HostQueueEntry.Status.VERIFYING,
2017 models.HostQueueEntry.Status.PENDING))
2018 if not_yet_run.count() < self.synch_count:
2019 self._stop_all_entries(not_yet_run)
mblighe2586682008-02-29 22:45:46 +00002020
2021
jadmanski0afbb632008-06-06 21:10:57 +00002022 def write_to_machines_file(self, queue_entry):
2023 hostname = queue_entry.get_host().hostname
showard170873e2009-01-07 00:22:26 +00002024 file_path = os.path.join(self.tag(), '.machines')
2025 _drone_manager.write_lines_to_file(file_path, [hostname])
mbligh36768f02008-02-22 18:28:33 +00002026
2027
showard2bab8f42008-11-12 18:15:22 +00002028 def _next_group_name(self):
2029 query = models.HostQueueEntry.objects.filter(
2030 job=self.id).values('execution_subdir').distinct()
2031 subdirs = (entry['execution_subdir'] for entry in query)
2032 groups = (re.match(r'group(\d+)', subdir) for subdir in subdirs)
2033 ids = [int(match.group(1)) for match in groups if match]
2034 if ids:
2035 next_id = max(ids) + 1
2036 else:
2037 next_id = 0
2038 return "group%d" % next_id
2039
2040
showard170873e2009-01-07 00:22:26 +00002041 def _write_control_file(self, execution_tag):
2042 control_path = _drone_manager.attach_file_to_execution(
2043 execution_tag, self.control_file)
2044 return control_path
mbligh36768f02008-02-22 18:28:33 +00002045
showardb2e2c322008-10-14 17:33:55 +00002046
showard2bab8f42008-11-12 18:15:22 +00002047 def get_group_entries(self, queue_entry_from_group):
2048 execution_subdir = queue_entry_from_group.execution_subdir
showarde788ea62008-11-17 21:02:47 +00002049 return list(HostQueueEntry.fetch(
2050 where='job_id=%s AND execution_subdir=%s',
2051 params=(self.id, execution_subdir)))
showard2bab8f42008-11-12 18:15:22 +00002052
2053
showardb2e2c322008-10-14 17:33:55 +00002054 def _get_autoserv_params(self, queue_entries):
showard170873e2009-01-07 00:22:26 +00002055 assert queue_entries
2056 execution_tag = queue_entries[0].execution_tag()
2057 control_path = self._write_control_file(execution_tag)
jadmanski0afbb632008-06-06 21:10:57 +00002058 hostnames = ','.join([entry.get_host().hostname
2059 for entry in queue_entries])
mbligh36768f02008-02-22 18:28:33 +00002060
showard170873e2009-01-07 00:22:26 +00002061 params = [_autoserv_path, '-P', execution_tag, '-p', '-n',
2062 '-r', _drone_manager.absolute_path(execution_tag),
2063 '-u', self.owner, '-l', self.name, '-m', hostnames,
2064 _drone_manager.absolute_path(control_path)]
mbligh36768f02008-02-22 18:28:33 +00002065
jadmanski0afbb632008-06-06 21:10:57 +00002066 if not self.is_server_job():
2067 params.append('-c')
mbligh36768f02008-02-22 18:28:33 +00002068
showardb2e2c322008-10-14 17:33:55 +00002069 return params
mblighe2586682008-02-29 22:45:46 +00002070
mbligh36768f02008-02-22 18:28:33 +00002071
showard2bab8f42008-11-12 18:15:22 +00002072 def _get_pre_job_tasks(self, queue_entry):
showard21baa452008-10-21 00:08:39 +00002073 do_reboot = False
showard0fc38302008-10-23 00:44:07 +00002074 if self.reboot_before == models.RebootBefore.ALWAYS:
showard21baa452008-10-21 00:08:39 +00002075 do_reboot = True
showard0fc38302008-10-23 00:44:07 +00002076 elif self.reboot_before == models.RebootBefore.IF_DIRTY:
showard21baa452008-10-21 00:08:39 +00002077 do_reboot = queue_entry.get_host().dirty
2078
2079 tasks = []
2080 if do_reboot:
showard45ae8192008-11-05 19:32:53 +00002081 tasks.append(CleanupTask(queue_entry=queue_entry))
showard2bab8f42008-11-12 18:15:22 +00002082 tasks.append(VerifyTask(queue_entry=queue_entry))
showard21baa452008-10-21 00:08:39 +00002083 return tasks
2084
2085
showard2bab8f42008-11-12 18:15:22 +00002086 def _assign_new_group(self, queue_entries):
2087 if len(queue_entries) == 1:
2088 group_name = queue_entries[0].get_host().hostname
2089 else:
2090 group_name = self._next_group_name()
2091 print 'Running synchronous job %d hosts %s as %s' % (
2092 self.id, [entry.host.hostname for entry in queue_entries],
2093 group_name)
2094
2095 for queue_entry in queue_entries:
2096 queue_entry.set_execution_subdir(group_name)
2097
2098
2099 def _choose_group_to_run(self, include_queue_entry):
2100 chosen_entries = [include_queue_entry]
2101
2102 num_entries_needed = self.synch_count - 1
2103 if num_entries_needed > 0:
2104 pending_entries = HostQueueEntry.fetch(
2105 where='job_id = %s AND status = "Pending" AND id != %s',
2106 params=(self.id, include_queue_entry.id))
2107 chosen_entries += list(pending_entries)[:num_entries_needed]
2108
2109 self._assign_new_group(chosen_entries)
2110 return chosen_entries
2111
2112
2113 def run(self, queue_entry):
showardb2e2c322008-10-14 17:33:55 +00002114 if not self.is_ready():
showard9976ce92008-10-15 20:28:13 +00002115 if self.run_verify:
showarde58e3f82008-11-20 19:04:59 +00002116 queue_entry.set_status(models.HostQueueEntry.Status.VERIFYING)
showard170873e2009-01-07 00:22:26 +00002117 return Agent(self._get_pre_job_tasks(queue_entry))
showard9976ce92008-10-15 20:28:13 +00002118 else:
2119 return queue_entry.on_pending()
mbligh36768f02008-02-22 18:28:33 +00002120
showard2bab8f42008-11-12 18:15:22 +00002121 queue_entries = self._choose_group_to_run(queue_entry)
2122 return self._finish_run(queue_entries)
showardb2e2c322008-10-14 17:33:55 +00002123
2124
2125 def _finish_run(self, queue_entries, initial_tasks=[]):
showardb2ccdda2008-10-28 20:39:05 +00002126 for queue_entry in queue_entries:
2127 queue_entry.set_status('Starting')
showardb2e2c322008-10-14 17:33:55 +00002128 params = self._get_autoserv_params(queue_entries)
2129 queue_task = QueueTask(job=self, queue_entries=queue_entries,
2130 cmd=params)
2131 tasks = initial_tasks + [queue_task]
2132 entry_ids = [entry.id for entry in queue_entries]
2133
showard170873e2009-01-07 00:22:26 +00002134 return Agent(tasks, num_processes=len(queue_entries))
showardb2e2c322008-10-14 17:33:55 +00002135
2136
mbligh36768f02008-02-22 18:28:33 +00002137if __name__ == '__main__':
jadmanski0afbb632008-06-06 21:10:57 +00002138 main()