blob: 5665bf2cdcf4f0128b168d209afc1be899de791d [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')
showard170873e2009-01-07 00:22:26 +0000145 debug.get_logger().setLevel(logging.WARNING)
showard2bab8f42008-11-12 18:15:22 +0000146
jadmanski0afbb632008-06-06 21:10:57 +0000147 print "Setting signal handler"
148 signal.signal(signal.SIGINT, handle_sigint)
149
showardd1ee1dd2009-01-07 21:33:08 +0000150 drones = global_config.global_config.get_config_value(
151 scheduler_config.CONFIG_SECTION, 'drones', default='localhost')
152 drone_list = [hostname.strip() for hostname in drones.split(',')]
showard170873e2009-01-07 00:22:26 +0000153 results_host = global_config.global_config.get_config_value(
showardd1ee1dd2009-01-07 21:33:08 +0000154 scheduler_config.CONFIG_SECTION, 'results_host', default='localhost')
showard170873e2009-01-07 00:22:26 +0000155 _drone_manager.initialize(RESULTS_DIR, drone_list, results_host)
156
jadmanski0afbb632008-06-06 21:10:57 +0000157 print "Connected! Running..."
mbligh36768f02008-02-22 18:28:33 +0000158
159
160def enable_logging(logfile):
jadmanski0afbb632008-06-06 21:10:57 +0000161 out_file = logfile
162 err_file = "%s.err" % logfile
163 print "Enabling logging to %s (%s)" % (out_file, err_file)
164 out_fd = open(out_file, "a", buffering=0)
165 err_fd = open(err_file, "a", buffering=0)
mbligh36768f02008-02-22 18:28:33 +0000166
jadmanski0afbb632008-06-06 21:10:57 +0000167 os.dup2(out_fd.fileno(), sys.stdout.fileno())
168 os.dup2(err_fd.fileno(), sys.stderr.fileno())
mbligh36768f02008-02-22 18:28:33 +0000169
jadmanski0afbb632008-06-06 21:10:57 +0000170 sys.stdout = out_fd
171 sys.stderr = err_fd
mbligh36768f02008-02-22 18:28:33 +0000172
173
mblighd5c95802008-03-05 00:33:46 +0000174def queue_entries_to_abort():
jadmanski0afbb632008-06-06 21:10:57 +0000175 rows = _db.execute("""
176 SELECT * FROM host_queue_entries WHERE status='Abort';
177 """)
showard2bab8f42008-11-12 18:15:22 +0000178
jadmanski0afbb632008-06-06 21:10:57 +0000179 qe = [HostQueueEntry(row=i) for i in rows]
180 return qe
mbligh36768f02008-02-22 18:28:33 +0000181
showard7cf9a9b2008-05-15 21:15:52 +0000182
showard63a34772008-08-18 19:32:50 +0000183class HostScheduler(object):
184 def _get_ready_hosts(self):
185 # avoid any host with a currently active queue entry against it
186 hosts = Host.fetch(
187 joins='LEFT JOIN host_queue_entries AS active_hqe '
188 'ON (hosts.id = active_hqe.host_id AND '
showardb1e51872008-10-07 11:08:18 +0000189 'active_hqe.active)',
showard63a34772008-08-18 19:32:50 +0000190 where="active_hqe.host_id IS NULL "
showardb1e51872008-10-07 11:08:18 +0000191 "AND NOT hosts.locked "
showard63a34772008-08-18 19:32:50 +0000192 "AND (hosts.status IS NULL OR hosts.status = 'Ready')")
193 return dict((host.id, host) for host in hosts)
194
195
196 @staticmethod
197 def _get_sql_id_list(id_list):
198 return ','.join(str(item_id) for item_id in id_list)
199
200
201 @classmethod
showard989f25d2008-10-01 11:38:11 +0000202 def _get_many2many_dict(cls, query, id_list, flip=False):
mbligh849a0f62008-08-28 20:12:19 +0000203 if not id_list:
204 return {}
showard63a34772008-08-18 19:32:50 +0000205 query %= cls._get_sql_id_list(id_list)
206 rows = _db.execute(query)
showard989f25d2008-10-01 11:38:11 +0000207 return cls._process_many2many_dict(rows, flip)
208
209
210 @staticmethod
211 def _process_many2many_dict(rows, flip=False):
showard63a34772008-08-18 19:32:50 +0000212 result = {}
213 for row in rows:
214 left_id, right_id = long(row[0]), long(row[1])
showard989f25d2008-10-01 11:38:11 +0000215 if flip:
216 left_id, right_id = right_id, left_id
showard63a34772008-08-18 19:32:50 +0000217 result.setdefault(left_id, set()).add(right_id)
218 return result
219
220
221 @classmethod
222 def _get_job_acl_groups(cls, job_ids):
223 query = """
224 SELECT jobs.id, acl_groups_users.acl_group_id
225 FROM jobs
226 INNER JOIN users ON users.login = jobs.owner
227 INNER JOIN acl_groups_users ON acl_groups_users.user_id = users.id
228 WHERE jobs.id IN (%s)
229 """
230 return cls._get_many2many_dict(query, job_ids)
231
232
233 @classmethod
234 def _get_job_ineligible_hosts(cls, job_ids):
235 query = """
236 SELECT job_id, host_id
237 FROM ineligible_host_queues
238 WHERE job_id IN (%s)
239 """
240 return cls._get_many2many_dict(query, job_ids)
241
242
243 @classmethod
showard989f25d2008-10-01 11:38:11 +0000244 def _get_job_dependencies(cls, job_ids):
245 query = """
246 SELECT job_id, label_id
247 FROM jobs_dependency_labels
248 WHERE job_id IN (%s)
249 """
250 return cls._get_many2many_dict(query, job_ids)
251
252
253 @classmethod
showard63a34772008-08-18 19:32:50 +0000254 def _get_host_acls(cls, host_ids):
255 query = """
256 SELECT host_id, acl_group_id
257 FROM acl_groups_hosts
258 WHERE host_id IN (%s)
259 """
260 return cls._get_many2many_dict(query, host_ids)
261
262
263 @classmethod
264 def _get_label_hosts(cls, host_ids):
showardfa8629c2008-11-04 16:51:23 +0000265 if not host_ids:
266 return {}, {}
showard63a34772008-08-18 19:32:50 +0000267 query = """
268 SELECT label_id, host_id
269 FROM hosts_labels
270 WHERE host_id IN (%s)
showard989f25d2008-10-01 11:38:11 +0000271 """ % cls._get_sql_id_list(host_ids)
272 rows = _db.execute(query)
273 labels_to_hosts = cls._process_many2many_dict(rows)
274 hosts_to_labels = cls._process_many2many_dict(rows, flip=True)
275 return labels_to_hosts, hosts_to_labels
276
277
278 @classmethod
279 def _get_labels(cls):
280 return dict((label.id, label) for label in Label.fetch())
showard63a34772008-08-18 19:32:50 +0000281
282
283 def refresh(self, pending_queue_entries):
284 self._hosts_available = self._get_ready_hosts()
285
286 relevant_jobs = [queue_entry.job_id
287 for queue_entry in pending_queue_entries]
288 self._job_acls = self._get_job_acl_groups(relevant_jobs)
289 self._ineligible_hosts = self._get_job_ineligible_hosts(relevant_jobs)
showard989f25d2008-10-01 11:38:11 +0000290 self._job_dependencies = self._get_job_dependencies(relevant_jobs)
showard63a34772008-08-18 19:32:50 +0000291
292 host_ids = self._hosts_available.keys()
293 self._host_acls = self._get_host_acls(host_ids)
showard989f25d2008-10-01 11:38:11 +0000294 self._label_hosts, self._host_labels = self._get_label_hosts(host_ids)
295
296 self._labels = self._get_labels()
showard63a34772008-08-18 19:32:50 +0000297
298
299 def _is_acl_accessible(self, host_id, queue_entry):
300 job_acls = self._job_acls.get(queue_entry.job_id, set())
301 host_acls = self._host_acls.get(host_id, set())
302 return len(host_acls.intersection(job_acls)) > 0
303
304
showard989f25d2008-10-01 11:38:11 +0000305 def _check_job_dependencies(self, job_dependencies, host_labels):
306 missing = job_dependencies - host_labels
307 return len(job_dependencies - host_labels) == 0
308
309
310 def _check_only_if_needed_labels(self, job_dependencies, host_labels,
311 queue_entry):
312 for label_id in host_labels:
313 label = self._labels[label_id]
314 if not label.only_if_needed:
315 # we don't care about non-only_if_needed labels
316 continue
317 if queue_entry.meta_host == label_id:
318 # if the label was requested in a metahost it's OK
319 continue
320 if label_id not in job_dependencies:
321 return False
322 return True
323
324
325 def _is_host_eligible_for_job(self, host_id, queue_entry):
326 job_dependencies = self._job_dependencies.get(queue_entry.job_id, set())
327 host_labels = self._host_labels.get(host_id, set())
mblighc993bee2008-10-03 03:42:34 +0000328
329 acl = self._is_acl_accessible(host_id, queue_entry)
330 deps = self._check_job_dependencies(job_dependencies, host_labels)
331 only_if = self._check_only_if_needed_labels(job_dependencies,
332 host_labels, queue_entry)
333 return acl and deps and only_if
showard989f25d2008-10-01 11:38:11 +0000334
335
showard63a34772008-08-18 19:32:50 +0000336 def _schedule_non_metahost(self, queue_entry):
showard989f25d2008-10-01 11:38:11 +0000337 if not self._is_host_eligible_for_job(queue_entry.host_id, queue_entry):
showard63a34772008-08-18 19:32:50 +0000338 return None
339 return self._hosts_available.pop(queue_entry.host_id, None)
340
341
342 def _is_host_usable(self, host_id):
343 if host_id not in self._hosts_available:
344 # host was already used during this scheduling cycle
345 return False
346 if self._hosts_available[host_id].invalid:
347 # Invalid hosts cannot be used for metahosts. They're included in
348 # the original query because they can be used by non-metahosts.
349 return False
350 return True
351
352
353 def _schedule_metahost(self, queue_entry):
354 label_id = queue_entry.meta_host
355 hosts_in_label = self._label_hosts.get(label_id, set())
356 ineligible_host_ids = self._ineligible_hosts.get(queue_entry.job_id,
357 set())
358
359 # must iterate over a copy so we can mutate the original while iterating
360 for host_id in list(hosts_in_label):
361 if not self._is_host_usable(host_id):
362 hosts_in_label.remove(host_id)
363 continue
364 if host_id in ineligible_host_ids:
365 continue
showard989f25d2008-10-01 11:38:11 +0000366 if not self._is_host_eligible_for_job(host_id, queue_entry):
showard63a34772008-08-18 19:32:50 +0000367 continue
368
369 hosts_in_label.remove(host_id)
370 return self._hosts_available.pop(host_id)
371 return None
372
373
374 def find_eligible_host(self, queue_entry):
375 if not queue_entry.meta_host:
376 return self._schedule_non_metahost(queue_entry)
377 return self._schedule_metahost(queue_entry)
378
379
showard170873e2009-01-07 00:22:26 +0000380class Dispatcher(object):
jadmanski0afbb632008-06-06 21:10:57 +0000381 def __init__(self):
382 self._agents = []
showard3bb499f2008-07-03 19:42:20 +0000383 self._last_clean_time = time.time()
showard63a34772008-08-18 19:32:50 +0000384 self._host_scheduler = HostScheduler()
showard170873e2009-01-07 00:22:26 +0000385 self._host_agents = {}
386 self._queue_entry_agents = {}
mbligh36768f02008-02-22 18:28:33 +0000387
mbligh36768f02008-02-22 18:28:33 +0000388
jadmanski0afbb632008-06-06 21:10:57 +0000389 def do_initial_recovery(self, recover_hosts=True):
390 # always recover processes
391 self._recover_processes()
mblighbb421852008-03-11 22:36:16 +0000392
jadmanski0afbb632008-06-06 21:10:57 +0000393 if recover_hosts:
394 self._recover_hosts()
mbligh36768f02008-02-22 18:28:33 +0000395
396
jadmanski0afbb632008-06-06 21:10:57 +0000397 def tick(self):
showard170873e2009-01-07 00:22:26 +0000398 _drone_manager.refresh()
showarda3ab0d52008-11-03 19:03:47 +0000399 self._run_cleanup_maybe()
jadmanski0afbb632008-06-06 21:10:57 +0000400 self._find_aborting()
401 self._schedule_new_jobs()
402 self._handle_agents()
showard170873e2009-01-07 00:22:26 +0000403 _drone_manager.execute_actions()
404 email_manager.manager.send_queued_emails()
mbligh36768f02008-02-22 18:28:33 +0000405
showard97aed502008-11-04 02:01:24 +0000406
showarda3ab0d52008-11-03 19:03:47 +0000407 def _run_cleanup_maybe(self):
showardd1ee1dd2009-01-07 21:33:08 +0000408 should_cleanup = (self._last_clean_time +
409 scheduler_config.config.clean_interval * 60 <
410 time.time())
411 if should_cleanup:
showarda3ab0d52008-11-03 19:03:47 +0000412 print 'Running cleanup'
413 self._abort_timed_out_jobs()
414 self._abort_jobs_past_synch_start_timeout()
415 self._clear_inactive_blocks()
showardfa8629c2008-11-04 16:51:23 +0000416 self._check_for_db_inconsistencies()
showarda3ab0d52008-11-03 19:03:47 +0000417 self._last_clean_time = time.time()
418
mbligh36768f02008-02-22 18:28:33 +0000419
showard170873e2009-01-07 00:22:26 +0000420 def _register_agent_for_ids(self, agent_dict, object_ids, agent):
421 for object_id in object_ids:
422 agent_dict.setdefault(object_id, set()).add(agent)
423
424
425 def _unregister_agent_for_ids(self, agent_dict, object_ids, agent):
426 for object_id in object_ids:
427 assert object_id in agent_dict
428 agent_dict[object_id].remove(agent)
429
430
jadmanski0afbb632008-06-06 21:10:57 +0000431 def add_agent(self, agent):
432 self._agents.append(agent)
433 agent.dispatcher = self
showard170873e2009-01-07 00:22:26 +0000434 self._register_agent_for_ids(self._host_agents, agent.host_ids, agent)
435 self._register_agent_for_ids(self._queue_entry_agents,
436 agent.queue_entry_ids, agent)
mblighd5c95802008-03-05 00:33:46 +0000437
showard170873e2009-01-07 00:22:26 +0000438
439 def get_agents_for_entry(self, queue_entry):
440 """
441 Find agents corresponding to the specified queue_entry.
442 """
443 return self._queue_entry_agents.get(queue_entry.id, set())
444
445
446 def host_has_agent(self, host):
447 """
448 Determine if there is currently an Agent present using this host.
449 """
450 return bool(self._host_agents.get(host.id, None))
mbligh36768f02008-02-22 18:28:33 +0000451
452
jadmanski0afbb632008-06-06 21:10:57 +0000453 def remove_agent(self, agent):
454 self._agents.remove(agent)
showard170873e2009-01-07 00:22:26 +0000455 self._unregister_agent_for_ids(self._host_agents, agent.host_ids,
456 agent)
457 self._unregister_agent_for_ids(self._queue_entry_agents,
458 agent.queue_entry_ids, agent)
showardec113162008-05-08 00:52:49 +0000459
460
showard4c5374f2008-09-04 17:02:56 +0000461 def num_running_processes(self):
462 return sum(agent.num_processes for agent in self._agents
463 if agent.is_running())
mblighbb421852008-03-11 22:36:16 +0000464
465
showard170873e2009-01-07 00:22:26 +0000466 def _extract_execution_tag(self, command_line):
467 match = re.match(r'.* -P (\S+) ', command_line)
468 if not match:
469 return None
470 return match.group(1)
mblighbb421852008-03-11 22:36:16 +0000471
472
showard2bab8f42008-11-12 18:15:22 +0000473 def _recover_queue_entries(self, queue_entries, run_monitor):
474 assert len(queue_entries) > 0
showard2bab8f42008-11-12 18:15:22 +0000475 queue_task = RecoveryQueueTask(job=queue_entries[0].job,
476 queue_entries=queue_entries,
477 run_monitor=run_monitor)
jadmanski0afbb632008-06-06 21:10:57 +0000478 self.add_agent(Agent(tasks=[queue_task],
showard170873e2009-01-07 00:22:26 +0000479 num_processes=len(queue_entries)))
mblighbb421852008-03-11 22:36:16 +0000480
481
jadmanski0afbb632008-06-06 21:10:57 +0000482 def _recover_processes(self):
showard170873e2009-01-07 00:22:26 +0000483 self._register_pidfiles()
484 _drone_manager.refresh()
485 self._recover_running_entries()
486 self._recover_aborting_entries()
487 self._requeue_other_active_entries()
488 self._recover_parsing_entries()
489 self._reverify_remaining_hosts()
490 # reinitialize drones after killing orphaned processes, since they can
491 # leave around files when they die
492 _drone_manager.execute_actions()
493 _drone_manager.reinitialize_drones()
mblighbb421852008-03-11 22:36:16 +0000494
showard170873e2009-01-07 00:22:26 +0000495
496 def _register_pidfiles(self):
497 # during recovery we may need to read pidfiles for both running and
498 # parsing entries
499 queue_entries = HostQueueEntry.fetch(
500 where="status IN ('Running', 'Parsing')")
jadmanski0afbb632008-06-06 21:10:57 +0000501 for queue_entry in queue_entries:
showard170873e2009-01-07 00:22:26 +0000502 pidfile_id = _drone_manager.get_pidfile_id_from(
503 queue_entry.execution_tag())
504 _drone_manager.register_pidfile(pidfile_id)
505
506
507 def _recover_running_entries(self):
508 orphans = _drone_manager.get_orphaned_autoserv_processes()
509
510 queue_entries = HostQueueEntry.fetch(where="status = 'Running'")
511 requeue_entries = []
512 for queue_entry in queue_entries:
513 if self.get_agents_for_entry(queue_entry):
jadmanski0afbb632008-06-06 21:10:57 +0000514 # synchronous job we've already recovered
515 continue
showard170873e2009-01-07 00:22:26 +0000516 execution_tag = queue_entry.execution_tag()
517 run_monitor = PidfileRunMonitor()
518 run_monitor.attach_to_existing_process(execution_tag)
519 if not run_monitor.has_process():
520 # autoserv apparently never got run, so let it get requeued
521 continue
showarde788ea62008-11-17 21:02:47 +0000522 queue_entries = queue_entry.job.get_group_entries(queue_entry)
showard170873e2009-01-07 00:22:26 +0000523 print 'Recovering %s (process %s)' % (
524 ', '.join(str(entry) for entry in queue_entries),
525 run_monitor.get_process())
showard2bab8f42008-11-12 18:15:22 +0000526 self._recover_queue_entries(queue_entries, run_monitor)
showard170873e2009-01-07 00:22:26 +0000527 orphans.pop(execution_tag, None)
mbligh90a549d2008-03-25 23:52:34 +0000528
jadmanski0afbb632008-06-06 21:10:57 +0000529 # now kill any remaining autoserv processes
showard170873e2009-01-07 00:22:26 +0000530 for process in orphans.itervalues():
531 print 'Killing orphan %s' % process
532 _drone_manager.kill_process(process)
jadmanski0afbb632008-06-06 21:10:57 +0000533
showard170873e2009-01-07 00:22:26 +0000534
535 def _recover_aborting_entries(self):
536 queue_entries = HostQueueEntry.fetch(
537 where='status IN ("Abort", "Aborting")')
jadmanski0afbb632008-06-06 21:10:57 +0000538 for queue_entry in queue_entries:
showard170873e2009-01-07 00:22:26 +0000539 print 'Recovering aborting QE %s' % queue_entry
540 agent = queue_entry.abort(self)
jadmanski0afbb632008-06-06 21:10:57 +0000541
showard97aed502008-11-04 02:01:24 +0000542
showard170873e2009-01-07 00:22:26 +0000543 def _requeue_other_active_entries(self):
544 queue_entries = HostQueueEntry.fetch(
545 where='active AND NOT complete AND status != "Pending"')
546 for queue_entry in queue_entries:
547 if self.get_agents_for_entry(queue_entry):
548 # entry has already been recovered
549 continue
550 print 'Requeuing active QE %s (status=%s)' % (queue_entry,
551 queue_entry.status)
552 if queue_entry.host:
553 tasks = queue_entry.host.reverify_tasks()
554 self.add_agent(Agent(tasks))
555 agent = queue_entry.requeue()
556
557
558 def _reverify_remaining_hosts(self):
showard45ae8192008-11-05 19:32:53 +0000559 # reverify hosts that were in the middle of verify, repair or cleanup
jadmanski0afbb632008-06-06 21:10:57 +0000560 self._reverify_hosts_where("""(status = 'Repairing' OR
561 status = 'Verifying' OR
showard170873e2009-01-07 00:22:26 +0000562 status = 'Cleaning')""")
jadmanski0afbb632008-06-06 21:10:57 +0000563
showard170873e2009-01-07 00:22:26 +0000564 # recover "Running" hosts with no active queue entries, although this
565 # should never happen
566 message = ('Recovering running host %s - this probably indicates a '
567 'scheduler bug')
jadmanski0afbb632008-06-06 21:10:57 +0000568 self._reverify_hosts_where("""status = 'Running' AND
569 id NOT IN (SELECT host_id
570 FROM host_queue_entries
571 WHERE active)""",
572 print_message=message)
mblighbb421852008-03-11 22:36:16 +0000573
574
jadmanski0afbb632008-06-06 21:10:57 +0000575 def _reverify_hosts_where(self, where,
showard170873e2009-01-07 00:22:26 +0000576 print_message='Reverifying host %s'):
577 full_where='locked = 0 AND invalid = 0 AND ' + where
578 for host in Host.fetch(where=full_where):
579 if self.host_has_agent(host):
580 # host has already been recovered in some way
jadmanski0afbb632008-06-06 21:10:57 +0000581 continue
showard170873e2009-01-07 00:22:26 +0000582 if print_message:
jadmanski0afbb632008-06-06 21:10:57 +0000583 print print_message % host.hostname
showard170873e2009-01-07 00:22:26 +0000584 tasks = host.reverify_tasks()
585 self.add_agent(Agent(tasks))
mbligh36768f02008-02-22 18:28:33 +0000586
587
showard97aed502008-11-04 02:01:24 +0000588 def _recover_parsing_entries(self):
showard2bab8f42008-11-12 18:15:22 +0000589 recovered_entry_ids = set()
showard97aed502008-11-04 02:01:24 +0000590 for entry in HostQueueEntry.fetch(where='status = "Parsing"'):
showard2bab8f42008-11-12 18:15:22 +0000591 if entry.id in recovered_entry_ids:
592 continue
593 queue_entries = entry.job.get_group_entries(entry)
showard170873e2009-01-07 00:22:26 +0000594 recovered_entry_ids = recovered_entry_ids.union(
595 entry.id for entry in queue_entries)
596 print 'Recovering parsing entries %s' % (
597 ', '.join(str(entry) for entry in queue_entries))
showard97aed502008-11-04 02:01:24 +0000598
599 reparse_task = FinalReparseTask(queue_entries)
showard170873e2009-01-07 00:22:26 +0000600 self.add_agent(Agent([reparse_task], num_processes=0))
showard97aed502008-11-04 02:01:24 +0000601
602
jadmanski0afbb632008-06-06 21:10:57 +0000603 def _recover_hosts(self):
604 # recover "Repair Failed" hosts
605 message = 'Reverifying dead host %s'
606 self._reverify_hosts_where("status = 'Repair Failed'",
607 print_message=message)
mbligh62ba2ed2008-04-30 17:09:25 +0000608
609
showard3bb499f2008-07-03 19:42:20 +0000610 def _abort_timed_out_jobs(self):
611 """
612 Aborts all jobs that have timed out and not completed
613 """
showarda3ab0d52008-11-03 19:03:47 +0000614 query = models.Job.objects.filter(hostqueueentry__complete=False).extra(
615 where=['created_on + INTERVAL timeout HOUR < NOW()'])
616 for job in query.distinct():
617 print 'Aborting job %d due to job timeout' % job.id
618 job.abort(None)
showard3bb499f2008-07-03 19:42:20 +0000619
620
showard98863972008-10-29 21:14:56 +0000621 def _abort_jobs_past_synch_start_timeout(self):
622 """
623 Abort synchronous jobs that are past the start timeout (from global
624 config) and are holding a machine that's in everyone.
625 """
626 timeout_delta = datetime.timedelta(
showardd1ee1dd2009-01-07 21:33:08 +0000627 minutes=scheduler_config.config.synch_job_start_timeout_minutes)
showard98863972008-10-29 21:14:56 +0000628 timeout_start = datetime.datetime.now() - timeout_delta
629 query = models.Job.objects.filter(
showard98863972008-10-29 21:14:56 +0000630 created_on__lt=timeout_start,
631 hostqueueentry__status='Pending',
632 hostqueueentry__host__acl_group__name='Everyone')
633 for job in query.distinct():
634 print 'Aborting job %d due to start timeout' % job.id
showardff059d72008-12-03 18:18:53 +0000635 entries_to_abort = job.hostqueueentry_set.exclude(
636 status=models.HostQueueEntry.Status.RUNNING)
637 for queue_entry in entries_to_abort:
638 queue_entry.abort(None)
showard98863972008-10-29 21:14:56 +0000639
640
jadmanski0afbb632008-06-06 21:10:57 +0000641 def _clear_inactive_blocks(self):
642 """
643 Clear out blocks for all completed jobs.
644 """
645 # this would be simpler using NOT IN (subquery), but MySQL
646 # treats all IN subqueries as dependent, so this optimizes much
647 # better
648 _db.execute("""
649 DELETE ihq FROM ineligible_host_queues ihq
showard4eaaf522008-06-06 22:28:07 +0000650 LEFT JOIN (SELECT DISTINCT job_id FROM host_queue_entries
jadmanski0afbb632008-06-06 21:10:57 +0000651 WHERE NOT complete) hqe
652 USING (job_id) WHERE hqe.job_id IS NULL""")
showard04c82c52008-05-29 19:38:12 +0000653
654
showardb95b1bd2008-08-15 18:11:04 +0000655 def _get_pending_queue_entries(self):
showard63a34772008-08-18 19:32:50 +0000656 # prioritize by job priority, then non-metahost over metahost, then FIFO
657 return list(HostQueueEntry.fetch(
showardac9ce222008-12-03 18:19:44 +0000658 where='NOT complete AND NOT active AND status="Queued"',
showard3dd6b882008-10-27 19:21:39 +0000659 order_by='priority DESC, meta_host, job_id'))
mbligh36768f02008-02-22 18:28:33 +0000660
661
jadmanski0afbb632008-06-06 21:10:57 +0000662 def _schedule_new_jobs(self):
showard63a34772008-08-18 19:32:50 +0000663 queue_entries = self._get_pending_queue_entries()
664 if not queue_entries:
showardb95b1bd2008-08-15 18:11:04 +0000665 return
showardb95b1bd2008-08-15 18:11:04 +0000666
showard63a34772008-08-18 19:32:50 +0000667 self._host_scheduler.refresh(queue_entries)
showardb95b1bd2008-08-15 18:11:04 +0000668
showard63a34772008-08-18 19:32:50 +0000669 for queue_entry in queue_entries:
670 assigned_host = self._host_scheduler.find_eligible_host(queue_entry)
showardb95b1bd2008-08-15 18:11:04 +0000671 if not assigned_host:
jadmanski0afbb632008-06-06 21:10:57 +0000672 continue
showardb95b1bd2008-08-15 18:11:04 +0000673 self._run_queue_entry(queue_entry, assigned_host)
674
675
676 def _run_queue_entry(self, queue_entry, host):
677 agent = queue_entry.run(assigned_host=host)
showard170873e2009-01-07 00:22:26 +0000678 # in some cases (synchronous jobs with run_verify=False), agent may be
679 # None
showard9976ce92008-10-15 20:28:13 +0000680 if agent:
681 self.add_agent(agent)
mblighd5c95802008-03-05 00:33:46 +0000682
683
jadmanski0afbb632008-06-06 21:10:57 +0000684 def _find_aborting(self):
jadmanski0afbb632008-06-06 21:10:57 +0000685 for entry in queue_entries_to_abort():
showard170873e2009-01-07 00:22:26 +0000686 agents_to_abort = list(self.get_agents_for_entry(entry))
showard1be97432008-10-17 15:30:45 +0000687 for agent in agents_to_abort:
688 self.remove_agent(agent)
689
showard170873e2009-01-07 00:22:26 +0000690 entry.abort(self, agents_to_abort)
jadmanski0afbb632008-06-06 21:10:57 +0000691
692
showard4c5374f2008-09-04 17:02:56 +0000693 def _can_start_agent(self, agent, num_running_processes,
694 num_started_this_cycle, have_reached_limit):
695 # always allow zero-process agents to run
696 if agent.num_processes == 0:
697 return True
showard2fa51692009-01-13 23:48:08 +0000698 # don't allow processes to run if we've disabled all drones
699 if _drone_manager.num_enabled_drones() == 0:
700 return False
showard4c5374f2008-09-04 17:02:56 +0000701 # don't allow any nonzero-process agents to run after we've reached a
702 # limit (this avoids starvation of many-process agents)
703 if have_reached_limit:
704 return False
705 # total process throttling
706 if (num_running_processes + agent.num_processes >
showardd1ee1dd2009-01-07 21:33:08 +0000707 scheduler_config.config.max_running_processes):
showard4c5374f2008-09-04 17:02:56 +0000708 return False
709 # if a single agent exceeds the per-cycle throttling, still allow it to
710 # run when it's the first agent in the cycle
711 if num_started_this_cycle == 0:
712 return True
713 # per-cycle throttling
714 if (num_started_this_cycle + agent.num_processes >
showardd1ee1dd2009-01-07 21:33:08 +0000715 scheduler_config.config.max_processes_started_per_cycle):
showard4c5374f2008-09-04 17:02:56 +0000716 return False
717 return True
718
719
jadmanski0afbb632008-06-06 21:10:57 +0000720 def _handle_agents(self):
showard4c5374f2008-09-04 17:02:56 +0000721 num_running_processes = self.num_running_processes()
jadmanski0afbb632008-06-06 21:10:57 +0000722 num_started_this_cycle = 0
showard4c5374f2008-09-04 17:02:56 +0000723 have_reached_limit = False
724 # iterate over copy, so we can remove agents during iteration
725 for agent in list(self._agents):
726 if agent.is_done():
jadmanski0afbb632008-06-06 21:10:57 +0000727 print "agent finished"
showard170873e2009-01-07 00:22:26 +0000728 self.remove_agent(agent)
showard4c5374f2008-09-04 17:02:56 +0000729 continue
730 if not agent.is_running():
731 if not self._can_start_agent(agent, num_running_processes,
732 num_started_this_cycle,
733 have_reached_limit):
734 have_reached_limit = True
735 continue
736 num_running_processes += agent.num_processes
737 num_started_this_cycle += agent.num_processes
738 agent.tick()
739 print num_running_processes, 'running processes'
mbligh36768f02008-02-22 18:28:33 +0000740
741
showardfa8629c2008-11-04 16:51:23 +0000742 def _check_for_db_inconsistencies(self):
743 query = models.HostQueueEntry.objects.filter(active=True, complete=True)
744 if query.count() != 0:
745 subject = ('%d queue entries found with active=complete=1'
746 % query.count())
747 message = '\n'.join(str(entry.get_object_dict())
748 for entry in query[:50])
749 if len(query) > 50:
750 message += '\n(truncated)\n'
751
752 print subject
showard170873e2009-01-07 00:22:26 +0000753 email_manager.manager.enqueue_notify_email(subject, message)
showardfa8629c2008-11-04 16:51:23 +0000754
755
showard170873e2009-01-07 00:22:26 +0000756class PidfileRunMonitor(object):
757 """
758 Client must call either run() to start a new process or
759 attach_to_existing_process().
760 """
mbligh36768f02008-02-22 18:28:33 +0000761
showard170873e2009-01-07 00:22:26 +0000762 class _PidfileException(Exception):
763 """
764 Raised when there's some unexpected behavior with the pid file, but only
765 used internally (never allowed to escape this class).
766 """
mbligh36768f02008-02-22 18:28:33 +0000767
768
showard170873e2009-01-07 00:22:26 +0000769 def __init__(self):
770 self._lost_process = False
771 self._start_time = None
772 self.pidfile_id = None
773 self._state = drone_manager.PidfileContents()
showard2bab8f42008-11-12 18:15:22 +0000774
775
showard170873e2009-01-07 00:22:26 +0000776 def _add_nice_command(self, command, nice_level):
777 if not nice_level:
778 return command
779 return ['nice', '-n', str(nice_level)] + command
780
781
782 def _set_start_time(self):
783 self._start_time = time.time()
784
785
786 def run(self, command, working_directory, nice_level=None, log_file=None,
787 pidfile_name=None, paired_with_pidfile=None):
788 assert command is not None
789 if nice_level is not None:
790 command = ['nice', '-n', str(nice_level)] + command
791 self._set_start_time()
792 self.pidfile_id = _drone_manager.execute_command(
793 command, working_directory, log_file=log_file,
794 pidfile_name=pidfile_name, paired_with_pidfile=paired_with_pidfile)
795
796
797 def attach_to_existing_process(self, execution_tag):
798 self._set_start_time()
799 self.pidfile_id = _drone_manager.get_pidfile_id_from(execution_tag)
800 _drone_manager.register_pidfile(self.pidfile_id)
mblighbb421852008-03-11 22:36:16 +0000801
802
jadmanski0afbb632008-06-06 21:10:57 +0000803 def kill(self):
showard170873e2009-01-07 00:22:26 +0000804 if self.has_process():
805 _drone_manager.kill_process(self.get_process())
mblighbb421852008-03-11 22:36:16 +0000806
mbligh36768f02008-02-22 18:28:33 +0000807
showard170873e2009-01-07 00:22:26 +0000808 def has_process(self):
showard21baa452008-10-21 00:08:39 +0000809 self._get_pidfile_info()
showard170873e2009-01-07 00:22:26 +0000810 return self._state.process is not None
showard21baa452008-10-21 00:08:39 +0000811
812
showard170873e2009-01-07 00:22:26 +0000813 def get_process(self):
showard21baa452008-10-21 00:08:39 +0000814 self._get_pidfile_info()
showard170873e2009-01-07 00:22:26 +0000815 assert self.has_process()
816 return self._state.process
mblighbb421852008-03-11 22:36:16 +0000817
818
showard170873e2009-01-07 00:22:26 +0000819 def _read_pidfile(self, use_second_read=False):
820 assert self.pidfile_id is not None, (
821 'You must call run() or attach_to_existing_process()')
822 contents = _drone_manager.get_pidfile_contents(
823 self.pidfile_id, use_second_read=use_second_read)
824 if contents.is_invalid():
825 self._state = drone_manager.PidfileContents()
826 raise self._PidfileException(contents)
827 self._state = contents
mbligh90a549d2008-03-25 23:52:34 +0000828
829
showard21baa452008-10-21 00:08:39 +0000830 def _handle_pidfile_error(self, error, message=''):
showard170873e2009-01-07 00:22:26 +0000831 message = error + '\nProcess: %s\nPidfile: %s\n%s' % (
832 self._state.process, self.pidfile_id, message)
showard21baa452008-10-21 00:08:39 +0000833 print message
showard170873e2009-01-07 00:22:26 +0000834 email_manager.manager.enqueue_notify_email(error, message)
835 if self._state.process is not None:
836 process = self._state.process
showard21baa452008-10-21 00:08:39 +0000837 else:
showard170873e2009-01-07 00:22:26 +0000838 process = _drone_manager.get_dummy_process()
839 self.on_lost_process(process)
showard21baa452008-10-21 00:08:39 +0000840
841
842 def _get_pidfile_info_helper(self):
showard170873e2009-01-07 00:22:26 +0000843 if self._lost_process:
showard21baa452008-10-21 00:08:39 +0000844 return
mblighbb421852008-03-11 22:36:16 +0000845
showard21baa452008-10-21 00:08:39 +0000846 self._read_pidfile()
mblighbb421852008-03-11 22:36:16 +0000847
showard170873e2009-01-07 00:22:26 +0000848 if self._state.process is None:
849 self._handle_no_process()
showard21baa452008-10-21 00:08:39 +0000850 return
mbligh90a549d2008-03-25 23:52:34 +0000851
showard21baa452008-10-21 00:08:39 +0000852 if self._state.exit_status is None:
jadmanski0afbb632008-06-06 21:10:57 +0000853 # double check whether or not autoserv is running
showard170873e2009-01-07 00:22:26 +0000854 if _drone_manager.is_process_running(self._state.process):
showard21baa452008-10-21 00:08:39 +0000855 return
mbligh90a549d2008-03-25 23:52:34 +0000856
showard170873e2009-01-07 00:22:26 +0000857 # pid but no running process - maybe process *just* exited
858 self._read_pidfile(use_second_read=True)
showard21baa452008-10-21 00:08:39 +0000859 if self._state.exit_status is None:
jadmanski0afbb632008-06-06 21:10:57 +0000860 # autoserv exited without writing an exit code
861 # to the pidfile
showard21baa452008-10-21 00:08:39 +0000862 self._handle_pidfile_error(
863 'autoserv died without writing exit code')
mblighbb421852008-03-11 22:36:16 +0000864
showard21baa452008-10-21 00:08:39 +0000865
866 def _get_pidfile_info(self):
867 """\
868 After completion, self._state will contain:
869 pid=None, exit_status=None if autoserv has not yet run
870 pid!=None, exit_status=None if autoserv is running
871 pid!=None, exit_status!=None if autoserv has completed
872 """
873 try:
874 self._get_pidfile_info_helper()
showard170873e2009-01-07 00:22:26 +0000875 except self._PidfileException, exc:
showard21baa452008-10-21 00:08:39 +0000876 self._handle_pidfile_error('Pidfile error', traceback.format_exc())
mblighbb421852008-03-11 22:36:16 +0000877
878
showard170873e2009-01-07 00:22:26 +0000879 def _handle_no_process(self):
jadmanski0afbb632008-06-06 21:10:57 +0000880 """\
881 Called when no pidfile is found or no pid is in the pidfile.
882 """
showard170873e2009-01-07 00:22:26 +0000883 message = 'No pid found at %s' % self.pidfile_id
jadmanski0afbb632008-06-06 21:10:57 +0000884 print message
showard170873e2009-01-07 00:22:26 +0000885 if time.time() - self._start_time > PIDFILE_TIMEOUT:
886 email_manager.manager.enqueue_notify_email(
jadmanski0afbb632008-06-06 21:10:57 +0000887 'Process has failed to write pidfile', message)
showard170873e2009-01-07 00:22:26 +0000888 self.on_lost_process(_drone_manager.get_dummy_process())
mbligh90a549d2008-03-25 23:52:34 +0000889
890
showard170873e2009-01-07 00:22:26 +0000891 def on_lost_process(self, process):
jadmanski0afbb632008-06-06 21:10:57 +0000892 """\
893 Called when autoserv has exited without writing an exit status,
894 or we've timed out waiting for autoserv to write a pid to the
895 pidfile. In either case, we just return failure and the caller
896 should signal some kind of warning.
mbligh90a549d2008-03-25 23:52:34 +0000897
showard170873e2009-01-07 00:22:26 +0000898 process is unimportant here, as it shouldn't be used by anyone.
jadmanski0afbb632008-06-06 21:10:57 +0000899 """
900 self.lost_process = True
showard170873e2009-01-07 00:22:26 +0000901 self._state.process = process
showard21baa452008-10-21 00:08:39 +0000902 self._state.exit_status = 1
903 self._state.num_tests_failed = 0
mbligh90a549d2008-03-25 23:52:34 +0000904
905
jadmanski0afbb632008-06-06 21:10:57 +0000906 def exit_code(self):
showard21baa452008-10-21 00:08:39 +0000907 self._get_pidfile_info()
908 return self._state.exit_status
909
910
911 def num_tests_failed(self):
912 self._get_pidfile_info()
913 assert self._state.num_tests_failed is not None
914 return self._state.num_tests_failed
mblighbb421852008-03-11 22:36:16 +0000915
916
mbligh36768f02008-02-22 18:28:33 +0000917class Agent(object):
showard170873e2009-01-07 00:22:26 +0000918 def __init__(self, tasks, num_processes=1):
jadmanski0afbb632008-06-06 21:10:57 +0000919 self.active_task = None
920 self.queue = Queue.Queue(0)
921 self.dispatcher = None
showard4c5374f2008-09-04 17:02:56 +0000922 self.num_processes = num_processes
jadmanski0afbb632008-06-06 21:10:57 +0000923
showard170873e2009-01-07 00:22:26 +0000924 self.queue_entry_ids = self._union_ids(task.queue_entry_ids
925 for task in tasks)
926 self.host_ids = self._union_ids(task.host_ids for task in tasks)
927
jadmanski0afbb632008-06-06 21:10:57 +0000928 for task in tasks:
929 self.add_task(task)
mbligh36768f02008-02-22 18:28:33 +0000930
931
showard170873e2009-01-07 00:22:26 +0000932 def _union_ids(self, id_lists):
933 return set(itertools.chain(*id_lists))
934
935
jadmanski0afbb632008-06-06 21:10:57 +0000936 def add_task(self, task):
937 self.queue.put_nowait(task)
938 task.agent = self
mbligh36768f02008-02-22 18:28:33 +0000939
940
jadmanski0afbb632008-06-06 21:10:57 +0000941 def tick(self):
showard21baa452008-10-21 00:08:39 +0000942 while not self.is_done():
943 if self.active_task and not self.active_task.is_done():
944 self.active_task.poll()
945 if not self.active_task.is_done():
946 return
947 self._next_task()
mbligh36768f02008-02-22 18:28:33 +0000948
949
jadmanski0afbb632008-06-06 21:10:57 +0000950 def _next_task(self):
951 print "agent picking task"
952 if self.active_task:
953 assert self.active_task.is_done()
mbligh36768f02008-02-22 18:28:33 +0000954
jadmanski0afbb632008-06-06 21:10:57 +0000955 if not self.active_task.success:
956 self.on_task_failure()
mblighe2586682008-02-29 22:45:46 +0000957
jadmanski0afbb632008-06-06 21:10:57 +0000958 self.active_task = None
959 if not self.is_done():
960 self.active_task = self.queue.get_nowait()
961 if self.active_task:
962 self.active_task.start()
mbligh36768f02008-02-22 18:28:33 +0000963
964
jadmanski0afbb632008-06-06 21:10:57 +0000965 def on_task_failure(self):
966 self.queue = Queue.Queue(0)
967 for task in self.active_task.failure_tasks:
968 self.add_task(task)
mbligh16c722d2008-03-05 00:58:44 +0000969
mblighe2586682008-02-29 22:45:46 +0000970
showard4c5374f2008-09-04 17:02:56 +0000971 def is_running(self):
jadmanski0afbb632008-06-06 21:10:57 +0000972 return self.active_task is not None
showardec113162008-05-08 00:52:49 +0000973
974
jadmanski0afbb632008-06-06 21:10:57 +0000975 def is_done(self):
mblighd876f452008-12-03 15:09:17 +0000976 return self.active_task is None and self.queue.empty()
mbligh36768f02008-02-22 18:28:33 +0000977
978
jadmanski0afbb632008-06-06 21:10:57 +0000979 def start(self):
980 assert self.dispatcher
mbligh36768f02008-02-22 18:28:33 +0000981
jadmanski0afbb632008-06-06 21:10:57 +0000982 self._next_task()
mbligh36768f02008-02-22 18:28:33 +0000983
jadmanski0afbb632008-06-06 21:10:57 +0000984
mbligh36768f02008-02-22 18:28:33 +0000985class AgentTask(object):
showard170873e2009-01-07 00:22:26 +0000986 def __init__(self, cmd, working_directory=None, failure_tasks=[]):
jadmanski0afbb632008-06-06 21:10:57 +0000987 self.done = False
988 self.failure_tasks = failure_tasks
989 self.started = False
990 self.cmd = cmd
showard170873e2009-01-07 00:22:26 +0000991 self._working_directory = working_directory
jadmanski0afbb632008-06-06 21:10:57 +0000992 self.task = None
993 self.agent = None
994 self.monitor = None
995 self.success = None
showard170873e2009-01-07 00:22:26 +0000996 self.queue_entry_ids = []
997 self.host_ids = []
998 self.log_file = None
999
1000
1001 def _set_ids(self, host=None, queue_entries=None):
1002 if queue_entries and queue_entries != [None]:
1003 self.host_ids = [entry.host.id for entry in queue_entries]
1004 self.queue_entry_ids = [entry.id for entry in queue_entries]
1005 else:
1006 assert host
1007 self.host_ids = [host.id]
mbligh36768f02008-02-22 18:28:33 +00001008
1009
jadmanski0afbb632008-06-06 21:10:57 +00001010 def poll(self):
jadmanski0afbb632008-06-06 21:10:57 +00001011 if self.monitor:
1012 self.tick(self.monitor.exit_code())
1013 else:
1014 self.finished(False)
mbligh36768f02008-02-22 18:28:33 +00001015
1016
jadmanski0afbb632008-06-06 21:10:57 +00001017 def tick(self, exit_code):
showard170873e2009-01-07 00:22:26 +00001018 if exit_code is None:
jadmanski0afbb632008-06-06 21:10:57 +00001019 return
jadmanski0afbb632008-06-06 21:10:57 +00001020 if exit_code == 0:
1021 success = True
1022 else:
1023 success = False
mbligh36768f02008-02-22 18:28:33 +00001024
jadmanski0afbb632008-06-06 21:10:57 +00001025 self.finished(success)
mbligh36768f02008-02-22 18:28:33 +00001026
1027
jadmanski0afbb632008-06-06 21:10:57 +00001028 def is_done(self):
1029 return self.done
mbligh36768f02008-02-22 18:28:33 +00001030
1031
jadmanski0afbb632008-06-06 21:10:57 +00001032 def finished(self, success):
1033 self.done = True
1034 self.success = success
1035 self.epilog()
mbligh36768f02008-02-22 18:28:33 +00001036
1037
jadmanski0afbb632008-06-06 21:10:57 +00001038 def prolog(self):
1039 pass
mblighd64e5702008-04-04 21:39:28 +00001040
1041
jadmanski0afbb632008-06-06 21:10:57 +00001042 def create_temp_resultsdir(self, suffix=''):
showard170873e2009-01-07 00:22:26 +00001043 self.temp_results_dir = _drone_manager.get_temporary_path('agent_task')
mblighd64e5702008-04-04 21:39:28 +00001044
mbligh36768f02008-02-22 18:28:33 +00001045
jadmanski0afbb632008-06-06 21:10:57 +00001046 def cleanup(self):
showard170873e2009-01-07 00:22:26 +00001047 if self.monitor and self.log_file:
1048 _drone_manager.copy_to_results_repository(
1049 self.monitor.get_process(), self.log_file)
mbligh36768f02008-02-22 18:28:33 +00001050
1051
jadmanski0afbb632008-06-06 21:10:57 +00001052 def epilog(self):
1053 self.cleanup()
mbligh36768f02008-02-22 18:28:33 +00001054
1055
jadmanski0afbb632008-06-06 21:10:57 +00001056 def start(self):
1057 assert self.agent
1058
1059 if not self.started:
1060 self.prolog()
1061 self.run()
1062
1063 self.started = True
1064
1065
1066 def abort(self):
1067 if self.monitor:
1068 self.monitor.kill()
1069 self.done = True
1070 self.cleanup()
1071
1072
showard170873e2009-01-07 00:22:26 +00001073 def set_host_log_file(self, base_name, host):
1074 filename = '%s.%s' % (time.time(), base_name)
1075 self.log_file = os.path.join('hosts', host.hostname, filename)
1076
1077
jadmanski0afbb632008-06-06 21:10:57 +00001078 def run(self):
1079 if self.cmd:
showard170873e2009-01-07 00:22:26 +00001080 self.monitor = PidfileRunMonitor()
1081 self.monitor.run(self.cmd, self._working_directory,
1082 nice_level=AUTOSERV_NICE_LEVEL,
1083 log_file=self.log_file)
mbligh36768f02008-02-22 18:28:33 +00001084
1085
1086class RepairTask(AgentTask):
showarde788ea62008-11-17 21:02:47 +00001087 def __init__(self, host, queue_entry=None):
jadmanski0afbb632008-06-06 21:10:57 +00001088 """\
showard170873e2009-01-07 00:22:26 +00001089 queue_entry: queue entry to mark failed if this repair fails.
jadmanski0afbb632008-06-06 21:10:57 +00001090 """
jadmanskifb7cfb12008-07-09 14:13:21 +00001091 protection = host_protections.Protection.get_string(host.protection)
jadmanski542537f2008-07-24 14:14:56 +00001092 # normalize the protection name
1093 protection = host_protections.Protection.get_attr_name(protection)
showard170873e2009-01-07 00:22:26 +00001094
jadmanski0afbb632008-06-06 21:10:57 +00001095 self.host = host
showarde788ea62008-11-17 21:02:47 +00001096 self.queue_entry = queue_entry
showard170873e2009-01-07 00:22:26 +00001097 self._set_ids(host=host, queue_entries=[queue_entry])
1098
1099 self.create_temp_resultsdir('.repair')
1100 cmd = [_autoserv_path , '-p', '-R', '-m', host.hostname,
1101 '-r', _drone_manager.absolute_path(self.temp_results_dir),
1102 '--host-protection', protection]
1103 super(RepairTask, self).__init__(cmd, self.temp_results_dir)
1104
1105 self._set_ids(host=host, queue_entries=[queue_entry])
1106 self.set_host_log_file('repair', self.host)
mblighe2586682008-02-29 22:45:46 +00001107
mbligh36768f02008-02-22 18:28:33 +00001108
jadmanski0afbb632008-06-06 21:10:57 +00001109 def prolog(self):
1110 print "repair_task starting"
1111 self.host.set_status('Repairing')
showarde788ea62008-11-17 21:02:47 +00001112 if self.queue_entry:
1113 self.queue_entry.requeue()
mbligh36768f02008-02-22 18:28:33 +00001114
1115
jadmanski0afbb632008-06-06 21:10:57 +00001116 def epilog(self):
1117 super(RepairTask, self).epilog()
1118 if self.success:
1119 self.host.set_status('Ready')
1120 else:
1121 self.host.set_status('Repair Failed')
showarde788ea62008-11-17 21:02:47 +00001122 if self.queue_entry and not self.queue_entry.meta_host:
1123 self.queue_entry.handle_host_failure()
mbligh36768f02008-02-22 18:28:33 +00001124
1125
showard8fe93b52008-11-18 17:53:22 +00001126class PreJobTask(AgentTask):
showard170873e2009-01-07 00:22:26 +00001127 def epilog(self):
1128 super(PreJobTask, self).epilog()
showard8fe93b52008-11-18 17:53:22 +00001129 should_copy_results = (self.queue_entry and not self.success
1130 and not self.queue_entry.meta_host)
1131 if should_copy_results:
1132 self.queue_entry.set_execution_subdir()
showard170873e2009-01-07 00:22:26 +00001133 destination = os.path.join(self.queue_entry.execution_tag(),
1134 os.path.basename(self.log_file))
1135 _drone_manager.copy_to_results_repository(
1136 self.monitor.get_process(), self.log_file,
1137 destination_path=destination)
showard8fe93b52008-11-18 17:53:22 +00001138
1139
1140class VerifyTask(PreJobTask):
showard9976ce92008-10-15 20:28:13 +00001141 def __init__(self, queue_entry=None, host=None):
jadmanski0afbb632008-06-06 21:10:57 +00001142 assert bool(queue_entry) != bool(host)
jadmanski0afbb632008-06-06 21:10:57 +00001143 self.host = host or queue_entry.host
1144 self.queue_entry = queue_entry
mbligh36768f02008-02-22 18:28:33 +00001145
jadmanski0afbb632008-06-06 21:10:57 +00001146 self.create_temp_resultsdir('.verify')
showard170873e2009-01-07 00:22:26 +00001147 cmd = [_autoserv_path, '-p', '-v', '-m', self.host.hostname, '-r',
1148 _drone_manager.absolute_path(self.temp_results_dir)]
showarde788ea62008-11-17 21:02:47 +00001149 failure_tasks = [RepairTask(self.host, queue_entry=queue_entry)]
showard170873e2009-01-07 00:22:26 +00001150 super(VerifyTask, self).__init__(cmd, self.temp_results_dir,
1151 failure_tasks=failure_tasks)
mblighe2586682008-02-29 22:45:46 +00001152
showard170873e2009-01-07 00:22:26 +00001153 self.set_host_log_file('verify', self.host)
1154 self._set_ids(host=host, queue_entries=[queue_entry])
mblighe2586682008-02-29 22:45:46 +00001155
1156
jadmanski0afbb632008-06-06 21:10:57 +00001157 def prolog(self):
showard8fe93b52008-11-18 17:53:22 +00001158 super(VerifyTask, self).prolog()
jadmanski0afbb632008-06-06 21:10:57 +00001159 print "starting verify on %s" % (self.host.hostname)
1160 if self.queue_entry:
1161 self.queue_entry.set_status('Verifying')
jadmanski0afbb632008-06-06 21:10:57 +00001162 self.host.set_status('Verifying')
mbligh36768f02008-02-22 18:28:33 +00001163
1164
jadmanski0afbb632008-06-06 21:10:57 +00001165 def epilog(self):
1166 super(VerifyTask, self).epilog()
mbligh36768f02008-02-22 18:28:33 +00001167
jadmanski0afbb632008-06-06 21:10:57 +00001168 if self.success:
1169 self.host.set_status('Ready')
showard2bab8f42008-11-12 18:15:22 +00001170 if self.queue_entry:
1171 agent = self.queue_entry.on_pending()
1172 if agent:
1173 self.agent.dispatcher.add_agent(agent)
mbligh36768f02008-02-22 18:28:33 +00001174
1175
mbligh36768f02008-02-22 18:28:33 +00001176class QueueTask(AgentTask):
jadmanski0afbb632008-06-06 21:10:57 +00001177 def __init__(self, job, queue_entries, cmd):
jadmanski0afbb632008-06-06 21:10:57 +00001178 self.job = job
1179 self.queue_entries = queue_entries
showard170873e2009-01-07 00:22:26 +00001180 super(QueueTask, self).__init__(cmd, self._execution_tag())
1181 self._set_ids(queue_entries=queue_entries)
mbligh36768f02008-02-22 18:28:33 +00001182
1183
showard170873e2009-01-07 00:22:26 +00001184 def _format_keyval(self, key, value):
1185 return '%s=%s' % (key, value)
mbligh36768f02008-02-22 18:28:33 +00001186
1187
showard170873e2009-01-07 00:22:26 +00001188 def _write_keyval(self, field, value):
1189 keyval_path = os.path.join(self._execution_tag(), 'keyval')
1190 assert self.monitor and self.monitor.has_process()
1191 paired_with_pidfile = self.monitor.pidfile_id
1192 _drone_manager.write_lines_to_file(
1193 keyval_path, [self._format_keyval(field, value)],
1194 paired_with_pidfile=paired_with_pidfile)
showardd8e548a2008-09-09 03:04:57 +00001195
1196
showard170873e2009-01-07 00:22:26 +00001197 def _write_host_keyvals(self, host):
1198 keyval_path = os.path.join(self._execution_tag(), 'host_keyvals',
1199 host.hostname)
1200 platform, all_labels = host.platform_and_labels()
1201 keyvals = dict(platform=platform, labels=','.join(all_labels))
1202 keyval_content = '\n'.join(self._format_keyval(key, value)
1203 for key, value in keyvals.iteritems())
1204 _drone_manager.attach_file_to_execution(self._execution_tag(),
1205 keyval_content,
1206 file_path=keyval_path)
showardd8e548a2008-09-09 03:04:57 +00001207
1208
showard170873e2009-01-07 00:22:26 +00001209 def _execution_tag(self):
1210 return self.queue_entries[0].execution_tag()
mblighbb421852008-03-11 22:36:16 +00001211
1212
jadmanski0afbb632008-06-06 21:10:57 +00001213 def prolog(self):
jadmanski0afbb632008-06-06 21:10:57 +00001214 for queue_entry in self.queue_entries:
showard170873e2009-01-07 00:22:26 +00001215 self._write_host_keyvals(queue_entry.host)
jadmanski0afbb632008-06-06 21:10:57 +00001216 queue_entry.set_status('Running')
1217 queue_entry.host.set_status('Running')
showard21baa452008-10-21 00:08:39 +00001218 queue_entry.host.update_field('dirty', 1)
showard2bab8f42008-11-12 18:15:22 +00001219 if self.job.synch_count == 1:
jadmanski0afbb632008-06-06 21:10:57 +00001220 assert len(self.queue_entries) == 1
1221 self.job.write_to_machines_file(self.queue_entries[0])
mbligh36768f02008-02-22 18:28:33 +00001222
1223
showard97aed502008-11-04 02:01:24 +00001224 def _finish_task(self, success):
showard170873e2009-01-07 00:22:26 +00001225 queued = time.mktime(self.job.created_on.timetuple())
jadmanski0afbb632008-06-06 21:10:57 +00001226 finished = time.time()
showard170873e2009-01-07 00:22:26 +00001227 self._write_keyval("job_queued", int(queued))
1228 self._write_keyval("job_finished", int(finished))
1229
1230 _drone_manager.copy_to_results_repository(self.monitor.get_process(),
1231 self._execution_tag() + '/')
jadmanskic2ac77f2008-05-16 21:44:04 +00001232
jadmanski0afbb632008-06-06 21:10:57 +00001233 # parse the results of the job
showard97aed502008-11-04 02:01:24 +00001234 reparse_task = FinalReparseTask(self.queue_entries)
showard170873e2009-01-07 00:22:26 +00001235 self.agent.dispatcher.add_agent(Agent([reparse_task], num_processes=0))
jadmanskif7fa2cc2008-10-01 14:13:23 +00001236
1237
showardcbd74612008-11-19 21:42:02 +00001238 def _write_status_comment(self, comment):
showard170873e2009-01-07 00:22:26 +00001239 _drone_manager.write_lines_to_file(
1240 os.path.join(self._execution_tag(), 'status.log'),
1241 ['INFO\t----\t----\t' + comment],
1242 paired_with_pidfile=self.monitor.pidfile_id)
showardcbd74612008-11-19 21:42:02 +00001243
1244
jadmanskif7fa2cc2008-10-01 14:13:23 +00001245 def _log_abort(self):
showard170873e2009-01-07 00:22:26 +00001246 if not self.monitor or not self.monitor.has_process():
1247 return
1248
jadmanskif7fa2cc2008-10-01 14:13:23 +00001249 # build up sets of all the aborted_by and aborted_on values
1250 aborted_by, aborted_on = set(), set()
1251 for queue_entry in self.queue_entries:
1252 if queue_entry.aborted_by:
1253 aborted_by.add(queue_entry.aborted_by)
1254 t = int(time.mktime(queue_entry.aborted_on.timetuple()))
1255 aborted_on.add(t)
1256
1257 # extract some actual, unique aborted by value and write it out
1258 assert len(aborted_by) <= 1
1259 if len(aborted_by) == 1:
showardcbd74612008-11-19 21:42:02 +00001260 aborted_by_value = aborted_by.pop()
1261 aborted_on_value = max(aborted_on)
1262 else:
1263 aborted_by_value = 'autotest_system'
1264 aborted_on_value = int(time.time())
showard170873e2009-01-07 00:22:26 +00001265
1266 self._write_keyval("aborted_by", aborted_by_value)
1267 self._write_keyval("aborted_on", aborted_on_value)
1268
showardcbd74612008-11-19 21:42:02 +00001269 aborted_on_string = str(datetime.datetime.fromtimestamp(
1270 aborted_on_value))
1271 self._write_status_comment('Job aborted by %s on %s' %
1272 (aborted_by_value, aborted_on_string))
jadmanskic2ac77f2008-05-16 21:44:04 +00001273
1274
jadmanski0afbb632008-06-06 21:10:57 +00001275 def abort(self):
1276 super(QueueTask, self).abort()
jadmanskif7fa2cc2008-10-01 14:13:23 +00001277 self._log_abort()
showard97aed502008-11-04 02:01:24 +00001278 self._finish_task(False)
jadmanskic2ac77f2008-05-16 21:44:04 +00001279
1280
showard21baa452008-10-21 00:08:39 +00001281 def _reboot_hosts(self):
1282 reboot_after = self.job.reboot_after
1283 do_reboot = False
showard0fc38302008-10-23 00:44:07 +00001284 if reboot_after == models.RebootAfter.ALWAYS:
showard21baa452008-10-21 00:08:39 +00001285 do_reboot = True
showard0fc38302008-10-23 00:44:07 +00001286 elif reboot_after == models.RebootAfter.IF_ALL_TESTS_PASSED:
showard21baa452008-10-21 00:08:39 +00001287 num_tests_failed = self.monitor.num_tests_failed()
1288 do_reboot = (self.success and num_tests_failed == 0)
1289
showard8ebca792008-11-04 21:54:22 +00001290 for queue_entry in self.queue_entries:
1291 if do_reboot:
showard45ae8192008-11-05 19:32:53 +00001292 # don't pass the queue entry to the CleanupTask. if the cleanup
showardfa8629c2008-11-04 16:51:23 +00001293 # fails, the job doesn't care -- it's over.
showard45ae8192008-11-05 19:32:53 +00001294 cleanup_task = CleanupTask(host=queue_entry.get_host())
1295 self.agent.dispatcher.add_agent(Agent([cleanup_task]))
showard8ebca792008-11-04 21:54:22 +00001296 else:
1297 queue_entry.host.set_status('Ready')
showard21baa452008-10-21 00:08:39 +00001298
1299
jadmanski0afbb632008-06-06 21:10:57 +00001300 def epilog(self):
1301 super(QueueTask, self).epilog()
showard97aed502008-11-04 02:01:24 +00001302 self._finish_task(self.success)
showard21baa452008-10-21 00:08:39 +00001303 self._reboot_hosts()
mblighbb421852008-03-11 22:36:16 +00001304
showard97aed502008-11-04 02:01:24 +00001305 print "queue_task finished with succes=%s" % self.success
mbligh36768f02008-02-22 18:28:33 +00001306
1307
mblighbb421852008-03-11 22:36:16 +00001308class RecoveryQueueTask(QueueTask):
jadmanski0afbb632008-06-06 21:10:57 +00001309 def __init__(self, job, queue_entries, run_monitor):
showard170873e2009-01-07 00:22:26 +00001310 super(RecoveryQueueTask, self).__init__(job, queue_entries, cmd=None)
jadmanski0afbb632008-06-06 21:10:57 +00001311 self.run_monitor = run_monitor
mblighbb421852008-03-11 22:36:16 +00001312
1313
jadmanski0afbb632008-06-06 21:10:57 +00001314 def run(self):
1315 self.monitor = self.run_monitor
mblighbb421852008-03-11 22:36:16 +00001316
1317
jadmanski0afbb632008-06-06 21:10:57 +00001318 def prolog(self):
1319 # recovering an existing process - don't do prolog
1320 pass
mblighbb421852008-03-11 22:36:16 +00001321
1322
showard8fe93b52008-11-18 17:53:22 +00001323class CleanupTask(PreJobTask):
showardfa8629c2008-11-04 16:51:23 +00001324 def __init__(self, host=None, queue_entry=None):
1325 assert bool(host) ^ bool(queue_entry)
1326 if queue_entry:
1327 host = queue_entry.get_host()
showardfa8629c2008-11-04 16:51:23 +00001328 self.queue_entry = queue_entry
jadmanski0afbb632008-06-06 21:10:57 +00001329 self.host = host
showard170873e2009-01-07 00:22:26 +00001330
1331 self.create_temp_resultsdir('.cleanup')
1332 self.cmd = [_autoserv_path, '-p', '--cleanup', '-m', host.hostname,
1333 '-r', _drone_manager.absolute_path(self.temp_results_dir)]
showarde788ea62008-11-17 21:02:47 +00001334 repair_task = RepairTask(host, queue_entry=queue_entry)
showard170873e2009-01-07 00:22:26 +00001335 super(CleanupTask, self).__init__(self.cmd, self.temp_results_dir,
1336 failure_tasks=[repair_task])
1337
1338 self._set_ids(host=host, queue_entries=[queue_entry])
1339 self.set_host_log_file('cleanup', self.host)
mbligh16c722d2008-03-05 00:58:44 +00001340
mblighd5c95802008-03-05 00:33:46 +00001341
jadmanski0afbb632008-06-06 21:10:57 +00001342 def prolog(self):
showard8fe93b52008-11-18 17:53:22 +00001343 super(CleanupTask, self).prolog()
showard45ae8192008-11-05 19:32:53 +00001344 print "starting cleanup task for host: %s" % self.host.hostname
1345 self.host.set_status("Cleaning")
mblighd5c95802008-03-05 00:33:46 +00001346
mblighd5c95802008-03-05 00:33:46 +00001347
showard21baa452008-10-21 00:08:39 +00001348 def epilog(self):
showard45ae8192008-11-05 19:32:53 +00001349 super(CleanupTask, self).epilog()
showard21baa452008-10-21 00:08:39 +00001350 if self.success:
showardfa8629c2008-11-04 16:51:23 +00001351 self.host.set_status('Ready')
showard21baa452008-10-21 00:08:39 +00001352 self.host.update_field('dirty', 0)
1353
1354
mblighd5c95802008-03-05 00:33:46 +00001355class AbortTask(AgentTask):
jadmanski0afbb632008-06-06 21:10:57 +00001356 def __init__(self, queue_entry, agents_to_abort):
jadmanski0afbb632008-06-06 21:10:57 +00001357 super(AbortTask, self).__init__('')
showard170873e2009-01-07 00:22:26 +00001358 self.queue_entry = queue_entry
1359 # don't use _set_ids, since we don't want to set the host_ids
1360 self.queue_entry_ids = [queue_entry.id]
1361 self.agents_to_abort = agents_to_abort
mbligh36768f02008-02-22 18:28:33 +00001362
1363
jadmanski0afbb632008-06-06 21:10:57 +00001364 def prolog(self):
1365 print "starting abort on host %s, job %s" % (
1366 self.queue_entry.host_id, self.queue_entry.job_id)
mbligh36768f02008-02-22 18:28:33 +00001367
mblighd64e5702008-04-04 21:39:28 +00001368
jadmanski0afbb632008-06-06 21:10:57 +00001369 def epilog(self):
1370 super(AbortTask, self).epilog()
1371 self.queue_entry.set_status('Aborted')
1372 self.success = True
1373
1374
1375 def run(self):
1376 for agent in self.agents_to_abort:
1377 if (agent.active_task):
1378 agent.active_task.abort()
mbligh36768f02008-02-22 18:28:33 +00001379
1380
showard97aed502008-11-04 02:01:24 +00001381class FinalReparseTask(AgentTask):
showard97aed502008-11-04 02:01:24 +00001382 _num_running_parses = 0
1383
1384 def __init__(self, queue_entries):
1385 self._queue_entries = queue_entries
showard170873e2009-01-07 00:22:26 +00001386 # don't use _set_ids, since we don't want to set the host_ids
1387 self.queue_entry_ids = [entry.id for entry in queue_entries]
showard97aed502008-11-04 02:01:24 +00001388 self._parse_started = False
1389
1390 assert len(queue_entries) > 0
1391 queue_entry = queue_entries[0]
showard97aed502008-11-04 02:01:24 +00001392
showard170873e2009-01-07 00:22:26 +00001393 self._execution_tag = queue_entry.execution_tag()
1394 self._results_dir = _drone_manager.absolute_path(self._execution_tag)
1395 self._autoserv_monitor = PidfileRunMonitor()
1396 self._autoserv_monitor.attach_to_existing_process(self._execution_tag)
1397 self._final_status = self._determine_final_status()
1398
showard97aed502008-11-04 02:01:24 +00001399 if _testing_mode:
1400 self.cmd = 'true'
showard170873e2009-01-07 00:22:26 +00001401 else:
1402 super(FinalReparseTask, self).__init__(
1403 cmd=self._generate_parse_command(),
1404 working_directory=self._execution_tag)
showard97aed502008-11-04 02:01:24 +00001405
showard170873e2009-01-07 00:22:26 +00001406 self.log_file = os.path.join(self._execution_tag, '.parse.log')
showard97aed502008-11-04 02:01:24 +00001407
1408
1409 @classmethod
1410 def _increment_running_parses(cls):
1411 cls._num_running_parses += 1
1412
1413
1414 @classmethod
1415 def _decrement_running_parses(cls):
1416 cls._num_running_parses -= 1
1417
1418
1419 @classmethod
1420 def _can_run_new_parse(cls):
showardd1ee1dd2009-01-07 21:33:08 +00001421 return (cls._num_running_parses <
1422 scheduler_config.config.max_parse_processes)
showard97aed502008-11-04 02:01:24 +00001423
1424
showard170873e2009-01-07 00:22:26 +00001425 def _determine_final_status(self):
1426 # we'll use a PidfileRunMonitor to read the autoserv exit status
1427 if self._autoserv_monitor.exit_code() == 0:
1428 return models.HostQueueEntry.Status.COMPLETED
1429 return models.HostQueueEntry.Status.FAILED
1430
1431
showard97aed502008-11-04 02:01:24 +00001432 def prolog(self):
1433 super(FinalReparseTask, self).prolog()
1434 for queue_entry in self._queue_entries:
1435 queue_entry.set_status(models.HostQueueEntry.Status.PARSING)
1436
1437
1438 def epilog(self):
1439 super(FinalReparseTask, self).epilog()
showard97aed502008-11-04 02:01:24 +00001440 for queue_entry in self._queue_entries:
showard170873e2009-01-07 00:22:26 +00001441 queue_entry.set_status(self._final_status)
showard97aed502008-11-04 02:01:24 +00001442
1443
showard2bab8f42008-11-12 18:15:22 +00001444 def _generate_parse_command(self):
showard170873e2009-01-07 00:22:26 +00001445 return [_parser_path, '--write-pidfile', '-l', '2', '-r', '-o',
1446 self._results_dir]
showard97aed502008-11-04 02:01:24 +00001447
1448
1449 def poll(self):
1450 # override poll to keep trying to start until the parse count goes down
1451 # and we can, at which point we revert to default behavior
1452 if self._parse_started:
1453 super(FinalReparseTask, self).poll()
1454 else:
1455 self._try_starting_parse()
1456
1457
1458 def run(self):
1459 # override run() to not actually run unless we can
1460 self._try_starting_parse()
1461
1462
1463 def _try_starting_parse(self):
1464 if not self._can_run_new_parse():
1465 return
showard170873e2009-01-07 00:22:26 +00001466
showard97aed502008-11-04 02:01:24 +00001467 # actually run the parse command
showard170873e2009-01-07 00:22:26 +00001468 self.monitor = PidfileRunMonitor()
1469 self.monitor.run(self.cmd, self._working_directory,
1470 log_file=self.log_file,
1471 pidfile_name='.parser_execute',
1472 paired_with_pidfile=self._autoserv_monitor.pidfile_id)
1473
showard97aed502008-11-04 02:01:24 +00001474 self._increment_running_parses()
1475 self._parse_started = True
1476
1477
1478 def finished(self, success):
1479 super(FinalReparseTask, self).finished(success)
1480 self._decrement_running_parses()
1481
1482
mbligh36768f02008-02-22 18:28:33 +00001483class DBObject(object):
jadmanski0afbb632008-06-06 21:10:57 +00001484 def __init__(self, id=None, row=None, new_record=False):
1485 assert (bool(id) != bool(row))
mbligh36768f02008-02-22 18:28:33 +00001486
jadmanski0afbb632008-06-06 21:10:57 +00001487 self.__table = self._get_table()
mbligh36768f02008-02-22 18:28:33 +00001488
jadmanski0afbb632008-06-06 21:10:57 +00001489 self.__new_record = new_record
mbligh36768f02008-02-22 18:28:33 +00001490
jadmanski0afbb632008-06-06 21:10:57 +00001491 if row is None:
1492 sql = 'SELECT * FROM %s WHERE ID=%%s' % self.__table
1493 rows = _db.execute(sql, (id,))
1494 if len(rows) == 0:
1495 raise "row not found (table=%s, id=%s)" % \
1496 (self.__table, id)
1497 row = rows[0]
mbligh36768f02008-02-22 18:28:33 +00001498
showard2bab8f42008-11-12 18:15:22 +00001499 self._update_fields_from_row(row)
1500
1501
1502 def _update_fields_from_row(self, row):
jadmanski0afbb632008-06-06 21:10:57 +00001503 assert len(row) == self.num_cols(), (
1504 "table = %s, row = %s/%d, fields = %s/%d" % (
showard2bab8f42008-11-12 18:15:22 +00001505 self.__table, row, len(row), self._fields(), self.num_cols()))
mbligh36768f02008-02-22 18:28:33 +00001506
showard2bab8f42008-11-12 18:15:22 +00001507 self._valid_fields = set()
1508 for field, value in zip(self._fields(), row):
1509 setattr(self, field, value)
1510 self._valid_fields.add(field)
mbligh36768f02008-02-22 18:28:33 +00001511
showard2bab8f42008-11-12 18:15:22 +00001512 self._valid_fields.remove('id')
mbligh36768f02008-02-22 18:28:33 +00001513
mblighe2586682008-02-29 22:45:46 +00001514
jadmanski0afbb632008-06-06 21:10:57 +00001515 @classmethod
1516 def _get_table(cls):
1517 raise NotImplementedError('Subclasses must override this')
mblighe2586682008-02-29 22:45:46 +00001518
1519
jadmanski0afbb632008-06-06 21:10:57 +00001520 @classmethod
1521 def _fields(cls):
1522 raise NotImplementedError('Subclasses must override this')
showard04c82c52008-05-29 19:38:12 +00001523
1524
jadmanski0afbb632008-06-06 21:10:57 +00001525 @classmethod
1526 def num_cols(cls):
1527 return len(cls._fields())
showard04c82c52008-05-29 19:38:12 +00001528
1529
jadmanski0afbb632008-06-06 21:10:57 +00001530 def count(self, where, table = None):
1531 if not table:
1532 table = self.__table
mbligh36768f02008-02-22 18:28:33 +00001533
jadmanski0afbb632008-06-06 21:10:57 +00001534 rows = _db.execute("""
1535 SELECT count(*) FROM %s
1536 WHERE %s
1537 """ % (table, where))
mbligh6f8bab42008-02-29 22:45:14 +00001538
jadmanski0afbb632008-06-06 21:10:57 +00001539 assert len(rows) == 1
1540
1541 return int(rows[0][0])
mbligh36768f02008-02-22 18:28:33 +00001542
1543
mblighf8c624d2008-07-03 16:58:45 +00001544 def update_field(self, field, value, condition=''):
showard2bab8f42008-11-12 18:15:22 +00001545 assert field in self._valid_fields
mbligh36768f02008-02-22 18:28:33 +00001546
showard2bab8f42008-11-12 18:15:22 +00001547 if getattr(self, field) == value:
jadmanski0afbb632008-06-06 21:10:57 +00001548 return
mbligh36768f02008-02-22 18:28:33 +00001549
mblighf8c624d2008-07-03 16:58:45 +00001550 query = "UPDATE %s SET %s = %%s WHERE id = %%s" % (self.__table, field)
1551 if condition:
1552 query += ' AND (%s)' % condition
jadmanski0afbb632008-06-06 21:10:57 +00001553 _db.execute(query, (value, self.id))
1554
showard2bab8f42008-11-12 18:15:22 +00001555 setattr(self, field, value)
mbligh36768f02008-02-22 18:28:33 +00001556
1557
jadmanski0afbb632008-06-06 21:10:57 +00001558 def save(self):
1559 if self.__new_record:
1560 keys = self._fields()[1:] # avoid id
1561 columns = ','.join([str(key) for key in keys])
1562 values = ['"%s"' % self.__dict__[key] for key in keys]
1563 values = ','.join(values)
1564 query = """INSERT INTO %s (%s) VALUES (%s)""" % \
1565 (self.__table, columns, values)
1566 _db.execute(query)
mbligh36768f02008-02-22 18:28:33 +00001567
1568
jadmanski0afbb632008-06-06 21:10:57 +00001569 def delete(self):
1570 query = 'DELETE FROM %s WHERE id=%%s' % self.__table
1571 _db.execute(query, (self.id,))
mblighe2586682008-02-29 22:45:46 +00001572
1573
showard63a34772008-08-18 19:32:50 +00001574 @staticmethod
1575 def _prefix_with(string, prefix):
1576 if string:
1577 string = prefix + string
1578 return string
1579
1580
jadmanski0afbb632008-06-06 21:10:57 +00001581 @classmethod
showard989f25d2008-10-01 11:38:11 +00001582 def fetch(cls, where='', params=(), joins='', order_by=''):
showard63a34772008-08-18 19:32:50 +00001583 order_by = cls._prefix_with(order_by, 'ORDER BY ')
1584 where = cls._prefix_with(where, 'WHERE ')
1585 query = ('SELECT %(table)s.* FROM %(table)s %(joins)s '
1586 '%(where)s %(order_by)s' % {'table' : cls._get_table(),
1587 'joins' : joins,
1588 'where' : where,
1589 'order_by' : order_by})
1590 rows = _db.execute(query, params)
jadmanski0afbb632008-06-06 21:10:57 +00001591 for row in rows:
1592 yield cls(row=row)
mblighe2586682008-02-29 22:45:46 +00001593
mbligh36768f02008-02-22 18:28:33 +00001594
1595class IneligibleHostQueue(DBObject):
jadmanski0afbb632008-06-06 21:10:57 +00001596 def __init__(self, id=None, row=None, new_record=None):
1597 super(IneligibleHostQueue, self).__init__(id=id, row=row,
1598 new_record=new_record)
mblighe2586682008-02-29 22:45:46 +00001599
1600
jadmanski0afbb632008-06-06 21:10:57 +00001601 @classmethod
1602 def _get_table(cls):
1603 return 'ineligible_host_queues'
mbligh36768f02008-02-22 18:28:33 +00001604
1605
jadmanski0afbb632008-06-06 21:10:57 +00001606 @classmethod
1607 def _fields(cls):
1608 return ['id', 'job_id', 'host_id']
showard04c82c52008-05-29 19:38:12 +00001609
1610
showard989f25d2008-10-01 11:38:11 +00001611class Label(DBObject):
1612 @classmethod
1613 def _get_table(cls):
1614 return 'labels'
1615
1616
1617 @classmethod
1618 def _fields(cls):
1619 return ['id', 'name', 'kernel_config', 'platform', 'invalid',
1620 'only_if_needed']
1621
1622
mbligh36768f02008-02-22 18:28:33 +00001623class Host(DBObject):
jadmanski0afbb632008-06-06 21:10:57 +00001624 def __init__(self, id=None, row=None):
1625 super(Host, self).__init__(id=id, row=row)
mblighe2586682008-02-29 22:45:46 +00001626
1627
jadmanski0afbb632008-06-06 21:10:57 +00001628 @classmethod
1629 def _get_table(cls):
1630 return 'hosts'
mbligh36768f02008-02-22 18:28:33 +00001631
1632
jadmanski0afbb632008-06-06 21:10:57 +00001633 @classmethod
1634 def _fields(cls):
1635 return ['id', 'hostname', 'locked', 'synch_id','status',
showard21baa452008-10-21 00:08:39 +00001636 'invalid', 'protection', 'locked_by_id', 'lock_time', 'dirty']
showard04c82c52008-05-29 19:38:12 +00001637
1638
jadmanski0afbb632008-06-06 21:10:57 +00001639 def current_task(self):
1640 rows = _db.execute("""
1641 SELECT * FROM host_queue_entries WHERE host_id=%s AND NOT complete AND active
1642 """, (self.id,))
1643
1644 if len(rows) == 0:
1645 return None
1646 else:
1647 assert len(rows) == 1
1648 results = rows[0];
mblighf8c624d2008-07-03 16:58:45 +00001649# print "current = %s" % results
jadmanski0afbb632008-06-06 21:10:57 +00001650 return HostQueueEntry(row=results)
mbligh36768f02008-02-22 18:28:33 +00001651
1652
jadmanski0afbb632008-06-06 21:10:57 +00001653 def yield_work(self):
1654 print "%s yielding work" % self.hostname
1655 if self.current_task():
1656 self.current_task().requeue()
1657
1658 def set_status(self,status):
1659 print '%s -> %s' % (self.hostname, status)
1660 self.update_field('status',status)
mbligh36768f02008-02-22 18:28:33 +00001661
1662
showard170873e2009-01-07 00:22:26 +00001663 def platform_and_labels(self):
showardd8e548a2008-09-09 03:04:57 +00001664 """
showard170873e2009-01-07 00:22:26 +00001665 Returns a tuple (platform_name, list_of_all_label_names).
showardd8e548a2008-09-09 03:04:57 +00001666 """
1667 rows = _db.execute("""
showard170873e2009-01-07 00:22:26 +00001668 SELECT labels.name, labels.platform
showardd8e548a2008-09-09 03:04:57 +00001669 FROM labels
1670 INNER JOIN hosts_labels ON labels.id = hosts_labels.label_id
showard170873e2009-01-07 00:22:26 +00001671 WHERE hosts_labels.host_id = %s
showardd8e548a2008-09-09 03:04:57 +00001672 ORDER BY labels.name
1673 """, (self.id,))
showard170873e2009-01-07 00:22:26 +00001674 platform = None
1675 all_labels = []
1676 for label_name, is_platform in rows:
1677 if is_platform:
1678 platform = label_name
1679 all_labels.append(label_name)
1680 return platform, all_labels
1681
1682
1683 def reverify_tasks(self):
1684 cleanup_task = CleanupTask(host=self)
1685 verify_task = VerifyTask(host=self)
1686 # just to make sure this host does not get taken away
1687 self.set_status('Cleaning')
1688 return [cleanup_task, verify_task]
showardd8e548a2008-09-09 03:04:57 +00001689
1690
mbligh36768f02008-02-22 18:28:33 +00001691class HostQueueEntry(DBObject):
jadmanski0afbb632008-06-06 21:10:57 +00001692 def __init__(self, id=None, row=None):
1693 assert id or row
1694 super(HostQueueEntry, self).__init__(id=id, row=row)
1695 self.job = Job(self.job_id)
mbligh36768f02008-02-22 18:28:33 +00001696
jadmanski0afbb632008-06-06 21:10:57 +00001697 if self.host_id:
1698 self.host = Host(self.host_id)
1699 else:
1700 self.host = None
mbligh36768f02008-02-22 18:28:33 +00001701
showard170873e2009-01-07 00:22:26 +00001702 self.queue_log_path = os.path.join(self.job.tag(),
jadmanski0afbb632008-06-06 21:10:57 +00001703 'queue.log.' + str(self.id))
mbligh36768f02008-02-22 18:28:33 +00001704
1705
jadmanski0afbb632008-06-06 21:10:57 +00001706 @classmethod
1707 def _get_table(cls):
1708 return 'host_queue_entries'
mblighe2586682008-02-29 22:45:46 +00001709
1710
jadmanski0afbb632008-06-06 21:10:57 +00001711 @classmethod
1712 def _fields(cls):
showard2bab8f42008-11-12 18:15:22 +00001713 return ['id', 'job_id', 'host_id', 'priority', 'status', 'meta_host',
1714 'active', 'complete', 'deleted', 'execution_subdir']
showard04c82c52008-05-29 19:38:12 +00001715
1716
showardc85c21b2008-11-24 22:17:37 +00001717 def _view_job_url(self):
1718 return "%s#tab_id=view_job&object_id=%s" % (_base_url, self.job.id)
1719
1720
jadmanski0afbb632008-06-06 21:10:57 +00001721 def set_host(self, host):
1722 if host:
1723 self.queue_log_record('Assigning host ' + host.hostname)
1724 self.update_field('host_id', host.id)
1725 self.update_field('active', True)
1726 self.block_host(host.id)
1727 else:
1728 self.queue_log_record('Releasing host')
1729 self.unblock_host(self.host.id)
1730 self.update_field('host_id', None)
mbligh36768f02008-02-22 18:28:33 +00001731
jadmanski0afbb632008-06-06 21:10:57 +00001732 self.host = host
mbligh36768f02008-02-22 18:28:33 +00001733
1734
jadmanski0afbb632008-06-06 21:10:57 +00001735 def get_host(self):
1736 return self.host
mbligh36768f02008-02-22 18:28:33 +00001737
1738
jadmanski0afbb632008-06-06 21:10:57 +00001739 def queue_log_record(self, log_line):
1740 now = str(datetime.datetime.now())
showard170873e2009-01-07 00:22:26 +00001741 _drone_manager.write_lines_to_file(self.queue_log_path,
1742 [now + ' ' + log_line])
mbligh36768f02008-02-22 18:28:33 +00001743
1744
jadmanski0afbb632008-06-06 21:10:57 +00001745 def block_host(self, host_id):
1746 print "creating block %s/%s" % (self.job.id, host_id)
1747 row = [0, self.job.id, host_id]
1748 block = IneligibleHostQueue(row=row, new_record=True)
1749 block.save()
mblighe2586682008-02-29 22:45:46 +00001750
1751
jadmanski0afbb632008-06-06 21:10:57 +00001752 def unblock_host(self, host_id):
1753 print "removing block %s/%s" % (self.job.id, host_id)
1754 blocks = IneligibleHostQueue.fetch(
1755 'job_id=%d and host_id=%d' % (self.job.id, host_id))
1756 for block in blocks:
1757 block.delete()
mblighe2586682008-02-29 22:45:46 +00001758
1759
showard2bab8f42008-11-12 18:15:22 +00001760 def set_execution_subdir(self, subdir=None):
1761 if subdir is None:
1762 assert self.get_host()
1763 subdir = self.get_host().hostname
1764 self.update_field('execution_subdir', subdir)
mbligh36768f02008-02-22 18:28:33 +00001765
1766
showard6355f6b2008-12-05 18:52:13 +00001767 def _get_hostname(self):
1768 if self.host:
1769 return self.host.hostname
1770 return 'no host'
1771
1772
showard170873e2009-01-07 00:22:26 +00001773 def __str__(self):
1774 return "%s/%d (%d)" % (self._get_hostname(), self.job.id, self.id)
1775
1776
jadmanski0afbb632008-06-06 21:10:57 +00001777 def set_status(self, status):
mblighf8c624d2008-07-03 16:58:45 +00001778 abort_statuses = ['Abort', 'Aborting', 'Aborted']
1779 if status not in abort_statuses:
1780 condition = ' AND '.join(['status <> "%s"' % x
1781 for x in abort_statuses])
1782 else:
1783 condition = ''
1784 self.update_field('status', status, condition=condition)
1785
showard170873e2009-01-07 00:22:26 +00001786 print "%s -> %s" % (self, self.status)
mblighf8c624d2008-07-03 16:58:45 +00001787
showardc85c21b2008-11-24 22:17:37 +00001788 if status in ['Queued', 'Parsing']:
jadmanski0afbb632008-06-06 21:10:57 +00001789 self.update_field('complete', False)
1790 self.update_field('active', False)
mbligh36768f02008-02-22 18:28:33 +00001791
jadmanski0afbb632008-06-06 21:10:57 +00001792 if status in ['Pending', 'Running', 'Verifying', 'Starting',
showarde58e3f82008-11-20 19:04:59 +00001793 'Aborting']:
jadmanski0afbb632008-06-06 21:10:57 +00001794 self.update_field('complete', False)
1795 self.update_field('active', True)
mbligh36768f02008-02-22 18:28:33 +00001796
showardc85c21b2008-11-24 22:17:37 +00001797 if status in ['Failed', 'Completed', 'Stopped', 'Aborted']:
jadmanski0afbb632008-06-06 21:10:57 +00001798 self.update_field('complete', True)
1799 self.update_field('active', False)
showardc85c21b2008-11-24 22:17:37 +00001800
1801 should_email_status = (status.lower() in _notify_email_statuses or
1802 'all' in _notify_email_statuses)
1803 if should_email_status:
1804 self._email_on_status(status)
1805
1806 self._email_on_job_complete()
1807
1808
1809 def _email_on_status(self, status):
showard6355f6b2008-12-05 18:52:13 +00001810 hostname = self._get_hostname()
showardc85c21b2008-11-24 22:17:37 +00001811
1812 subject = 'Autotest: Job ID: %s "%s" Host: %s %s' % (
1813 self.job.id, self.job.name, hostname, status)
1814 body = "Job ID: %s\nJob Name: %s\nHost: %s\nStatus: %s\n%s\n" % (
1815 self.job.id, self.job.name, hostname, status,
1816 self._view_job_url())
showard170873e2009-01-07 00:22:26 +00001817 email_manager.manager.send_email(self.job.email_list, subject, body)
showard542e8402008-09-19 20:16:18 +00001818
1819
1820 def _email_on_job_complete(self):
showardc85c21b2008-11-24 22:17:37 +00001821 if not self.job.is_finished():
1822 return
showard542e8402008-09-19 20:16:18 +00001823
showardc85c21b2008-11-24 22:17:37 +00001824 summary_text = []
showard6355f6b2008-12-05 18:52:13 +00001825 hosts_queue = HostQueueEntry.fetch('job_id = %s' % self.job.id)
showardc85c21b2008-11-24 22:17:37 +00001826 for queue_entry in hosts_queue:
1827 summary_text.append("Host: %s Status: %s" %
showard6355f6b2008-12-05 18:52:13 +00001828 (queue_entry._get_hostname(),
showardc85c21b2008-11-24 22:17:37 +00001829 queue_entry.status))
1830
1831 summary_text = "\n".join(summary_text)
1832 status_counts = models.Job.objects.get_status_counts(
1833 [self.job.id])[self.job.id]
1834 status = ', '.join('%d %s' % (count, status) for status, count
1835 in status_counts.iteritems())
1836
1837 subject = 'Autotest: Job ID: %s "%s" %s' % (
1838 self.job.id, self.job.name, status)
1839 body = "Job ID: %s\nJob Name: %s\nStatus: %s\n%s\nSummary:\n%s" % (
1840 self.job.id, self.job.name, status, self._view_job_url(),
1841 summary_text)
showard170873e2009-01-07 00:22:26 +00001842 email_manager.manager.send_email(self.job.email_list, subject, body)
mbligh36768f02008-02-22 18:28:33 +00001843
1844
jadmanski0afbb632008-06-06 21:10:57 +00001845 def run(self,assigned_host=None):
1846 if self.meta_host:
1847 assert assigned_host
1848 # ensure results dir exists for the queue log
jadmanski0afbb632008-06-06 21:10:57 +00001849 self.set_host(assigned_host)
mbligh36768f02008-02-22 18:28:33 +00001850
jadmanski0afbb632008-06-06 21:10:57 +00001851 print "%s/%s scheduled on %s, status=%s" % (self.job.name,
1852 self.meta_host, self.host.hostname, self.status)
mbligh36768f02008-02-22 18:28:33 +00001853
jadmanski0afbb632008-06-06 21:10:57 +00001854 return self.job.run(queue_entry=self)
mblighe2586682008-02-29 22:45:46 +00001855
jadmanski0afbb632008-06-06 21:10:57 +00001856 def requeue(self):
1857 self.set_status('Queued')
jadmanski0afbb632008-06-06 21:10:57 +00001858 if self.meta_host:
1859 self.set_host(None)
mbligh36768f02008-02-22 18:28:33 +00001860
1861
jadmanski0afbb632008-06-06 21:10:57 +00001862 def handle_host_failure(self):
1863 """\
1864 Called when this queue entry's host has failed verification and
1865 repair.
1866 """
1867 assert not self.meta_host
1868 self.set_status('Failed')
showard2bab8f42008-11-12 18:15:22 +00001869 self.job.stop_if_necessary()
mblighe2586682008-02-29 22:45:46 +00001870
1871
jadmanskif7fa2cc2008-10-01 14:13:23 +00001872 @property
1873 def aborted_by(self):
1874 self._load_abort_info()
1875 return self._aborted_by
1876
1877
1878 @property
1879 def aborted_on(self):
1880 self._load_abort_info()
1881 return self._aborted_on
1882
1883
1884 def _load_abort_info(self):
1885 """ Fetch info about who aborted the job. """
1886 if hasattr(self, "_aborted_by"):
1887 return
1888 rows = _db.execute("""
1889 SELECT users.login, aborted_host_queue_entries.aborted_on
1890 FROM aborted_host_queue_entries
1891 INNER JOIN users
1892 ON users.id = aborted_host_queue_entries.aborted_by_id
1893 WHERE aborted_host_queue_entries.queue_entry_id = %s
1894 """, (self.id,))
1895 if rows:
1896 self._aborted_by, self._aborted_on = rows[0]
1897 else:
1898 self._aborted_by = self._aborted_on = None
1899
1900
showardb2e2c322008-10-14 17:33:55 +00001901 def on_pending(self):
1902 """
1903 Called when an entry in a synchronous job has passed verify. If the
1904 job is ready to run, returns an agent to run the job. Returns None
1905 otherwise.
1906 """
1907 self.set_status('Pending')
showardcfd66a32008-10-15 20:31:48 +00001908 self.get_host().set_status('Pending')
showardb2e2c322008-10-14 17:33:55 +00001909 if self.job.is_ready():
1910 return self.job.run(self)
showard2bab8f42008-11-12 18:15:22 +00001911 self.job.stop_if_necessary()
showardb2e2c322008-10-14 17:33:55 +00001912 return None
1913
1914
showard170873e2009-01-07 00:22:26 +00001915 def abort(self, dispatcher, agents_to_abort=[]):
showard1be97432008-10-17 15:30:45 +00001916 host = self.get_host()
showard9d9ffd52008-11-09 23:14:35 +00001917 if self.active and host:
showard170873e2009-01-07 00:22:26 +00001918 dispatcher.add_agent(Agent(tasks=host.reverify_tasks()))
showard1be97432008-10-17 15:30:45 +00001919
showard170873e2009-01-07 00:22:26 +00001920 abort_task = AbortTask(self, agents_to_abort)
showard1be97432008-10-17 15:30:45 +00001921 self.set_status('Aborting')
showard170873e2009-01-07 00:22:26 +00001922 dispatcher.add_agent(Agent(tasks=[abort_task], num_processes=0))
1923
1924 def execution_tag(self):
1925 assert self.execution_subdir
1926 return "%s-%s/%s" % (self.job.id, self.job.owner, self.execution_subdir)
showard1be97432008-10-17 15:30:45 +00001927
1928
mbligh36768f02008-02-22 18:28:33 +00001929class Job(DBObject):
jadmanski0afbb632008-06-06 21:10:57 +00001930 def __init__(self, id=None, row=None):
1931 assert id or row
1932 super(Job, self).__init__(id=id, row=row)
mbligh36768f02008-02-22 18:28:33 +00001933
mblighe2586682008-02-29 22:45:46 +00001934
jadmanski0afbb632008-06-06 21:10:57 +00001935 @classmethod
1936 def _get_table(cls):
1937 return 'jobs'
mbligh36768f02008-02-22 18:28:33 +00001938
1939
jadmanski0afbb632008-06-06 21:10:57 +00001940 @classmethod
1941 def _fields(cls):
1942 return ['id', 'owner', 'name', 'priority', 'control_file',
showard2bab8f42008-11-12 18:15:22 +00001943 'control_type', 'created_on', 'synch_count', 'timeout',
showard21baa452008-10-21 00:08:39 +00001944 'run_verify', 'email_list', 'reboot_before', 'reboot_after']
showard04c82c52008-05-29 19:38:12 +00001945
1946
jadmanski0afbb632008-06-06 21:10:57 +00001947 def is_server_job(self):
1948 return self.control_type != 2
mbligh36768f02008-02-22 18:28:33 +00001949
1950
showard170873e2009-01-07 00:22:26 +00001951 def tag(self):
1952 return "%s-%s" % (self.id, self.owner)
1953
1954
jadmanski0afbb632008-06-06 21:10:57 +00001955 def get_host_queue_entries(self):
1956 rows = _db.execute("""
1957 SELECT * FROM host_queue_entries
1958 WHERE job_id= %s
1959 """, (self.id,))
1960 entries = [HostQueueEntry(row=i) for i in rows]
mbligh36768f02008-02-22 18:28:33 +00001961
jadmanski0afbb632008-06-06 21:10:57 +00001962 assert len(entries)>0
mbligh36768f02008-02-22 18:28:33 +00001963
jadmanski0afbb632008-06-06 21:10:57 +00001964 return entries
mbligh36768f02008-02-22 18:28:33 +00001965
1966
jadmanski0afbb632008-06-06 21:10:57 +00001967 def set_status(self, status, update_queues=False):
1968 self.update_field('status',status)
1969
1970 if update_queues:
1971 for queue_entry in self.get_host_queue_entries():
1972 queue_entry.set_status(status)
mbligh36768f02008-02-22 18:28:33 +00001973
1974
jadmanski0afbb632008-06-06 21:10:57 +00001975 def is_ready(self):
showard2bab8f42008-11-12 18:15:22 +00001976 pending_entries = models.HostQueueEntry.objects.filter(job=self.id,
1977 status='Pending')
1978 return (pending_entries.count() >= self.synch_count)
mbligh36768f02008-02-22 18:28:33 +00001979
1980
jadmanski0afbb632008-06-06 21:10:57 +00001981 def num_machines(self, clause = None):
1982 sql = "job_id=%s" % self.id
1983 if clause:
1984 sql += " AND (%s)" % clause
1985 return self.count(sql, table='host_queue_entries')
mbligh36768f02008-02-22 18:28:33 +00001986
1987
jadmanski0afbb632008-06-06 21:10:57 +00001988 def num_queued(self):
1989 return self.num_machines('not complete')
mbligh36768f02008-02-22 18:28:33 +00001990
1991
jadmanski0afbb632008-06-06 21:10:57 +00001992 def num_active(self):
1993 return self.num_machines('active')
mbligh36768f02008-02-22 18:28:33 +00001994
1995
jadmanski0afbb632008-06-06 21:10:57 +00001996 def num_complete(self):
1997 return self.num_machines('complete')
mbligh36768f02008-02-22 18:28:33 +00001998
1999
jadmanski0afbb632008-06-06 21:10:57 +00002000 def is_finished(self):
showardc85c21b2008-11-24 22:17:37 +00002001 return self.num_complete() == self.num_machines()
mbligh36768f02008-02-22 18:28:33 +00002002
mbligh36768f02008-02-22 18:28:33 +00002003
showard2bab8f42008-11-12 18:15:22 +00002004 def _stop_all_entries(self, entries_to_abort):
2005 """
2006 queue_entries: sequence of models.HostQueueEntry objects
2007 """
2008 for child_entry in entries_to_abort:
showard4f9e5372009-01-07 21:33:38 +00002009 assert not child_entry.complete, (
2010 '%s status=%s, active=%s, complete=%s' %
2011 (child_entry.id, child_entry.status, child_entry.active,
2012 child_entry.complete))
showard2bab8f42008-11-12 18:15:22 +00002013 if child_entry.status == models.HostQueueEntry.Status.PENDING:
2014 child_entry.host.status = models.Host.Status.READY
2015 child_entry.host.save()
2016 child_entry.status = models.HostQueueEntry.Status.STOPPED
2017 child_entry.save()
2018
2019
2020 def stop_if_necessary(self):
2021 not_yet_run = models.HostQueueEntry.objects.filter(
2022 job=self.id, status__in=(models.HostQueueEntry.Status.QUEUED,
2023 models.HostQueueEntry.Status.VERIFYING,
2024 models.HostQueueEntry.Status.PENDING))
2025 if not_yet_run.count() < self.synch_count:
2026 self._stop_all_entries(not_yet_run)
mblighe2586682008-02-29 22:45:46 +00002027
2028
jadmanski0afbb632008-06-06 21:10:57 +00002029 def write_to_machines_file(self, queue_entry):
2030 hostname = queue_entry.get_host().hostname
showard170873e2009-01-07 00:22:26 +00002031 file_path = os.path.join(self.tag(), '.machines')
2032 _drone_manager.write_lines_to_file(file_path, [hostname])
mbligh36768f02008-02-22 18:28:33 +00002033
2034
showard2bab8f42008-11-12 18:15:22 +00002035 def _next_group_name(self):
2036 query = models.HostQueueEntry.objects.filter(
2037 job=self.id).values('execution_subdir').distinct()
2038 subdirs = (entry['execution_subdir'] for entry in query)
2039 groups = (re.match(r'group(\d+)', subdir) for subdir in subdirs)
2040 ids = [int(match.group(1)) for match in groups if match]
2041 if ids:
2042 next_id = max(ids) + 1
2043 else:
2044 next_id = 0
2045 return "group%d" % next_id
2046
2047
showard170873e2009-01-07 00:22:26 +00002048 def _write_control_file(self, execution_tag):
2049 control_path = _drone_manager.attach_file_to_execution(
2050 execution_tag, self.control_file)
2051 return control_path
mbligh36768f02008-02-22 18:28:33 +00002052
showardb2e2c322008-10-14 17:33:55 +00002053
showard2bab8f42008-11-12 18:15:22 +00002054 def get_group_entries(self, queue_entry_from_group):
2055 execution_subdir = queue_entry_from_group.execution_subdir
showarde788ea62008-11-17 21:02:47 +00002056 return list(HostQueueEntry.fetch(
2057 where='job_id=%s AND execution_subdir=%s',
2058 params=(self.id, execution_subdir)))
showard2bab8f42008-11-12 18:15:22 +00002059
2060
showardb2e2c322008-10-14 17:33:55 +00002061 def _get_autoserv_params(self, queue_entries):
showard170873e2009-01-07 00:22:26 +00002062 assert queue_entries
2063 execution_tag = queue_entries[0].execution_tag()
2064 control_path = self._write_control_file(execution_tag)
jadmanski0afbb632008-06-06 21:10:57 +00002065 hostnames = ','.join([entry.get_host().hostname
2066 for entry in queue_entries])
mbligh36768f02008-02-22 18:28:33 +00002067
showard170873e2009-01-07 00:22:26 +00002068 params = [_autoserv_path, '-P', execution_tag, '-p', '-n',
2069 '-r', _drone_manager.absolute_path(execution_tag),
2070 '-u', self.owner, '-l', self.name, '-m', hostnames,
2071 _drone_manager.absolute_path(control_path)]
mbligh36768f02008-02-22 18:28:33 +00002072
jadmanski0afbb632008-06-06 21:10:57 +00002073 if not self.is_server_job():
2074 params.append('-c')
mbligh36768f02008-02-22 18:28:33 +00002075
showardb2e2c322008-10-14 17:33:55 +00002076 return params
mblighe2586682008-02-29 22:45:46 +00002077
mbligh36768f02008-02-22 18:28:33 +00002078
showard2bab8f42008-11-12 18:15:22 +00002079 def _get_pre_job_tasks(self, queue_entry):
showard21baa452008-10-21 00:08:39 +00002080 do_reboot = False
showard0fc38302008-10-23 00:44:07 +00002081 if self.reboot_before == models.RebootBefore.ALWAYS:
showard21baa452008-10-21 00:08:39 +00002082 do_reboot = True
showard0fc38302008-10-23 00:44:07 +00002083 elif self.reboot_before == models.RebootBefore.IF_DIRTY:
showard21baa452008-10-21 00:08:39 +00002084 do_reboot = queue_entry.get_host().dirty
2085
2086 tasks = []
2087 if do_reboot:
showard45ae8192008-11-05 19:32:53 +00002088 tasks.append(CleanupTask(queue_entry=queue_entry))
showard2bab8f42008-11-12 18:15:22 +00002089 tasks.append(VerifyTask(queue_entry=queue_entry))
showard21baa452008-10-21 00:08:39 +00002090 return tasks
2091
2092
showard2bab8f42008-11-12 18:15:22 +00002093 def _assign_new_group(self, queue_entries):
2094 if len(queue_entries) == 1:
2095 group_name = queue_entries[0].get_host().hostname
2096 else:
2097 group_name = self._next_group_name()
2098 print 'Running synchronous job %d hosts %s as %s' % (
2099 self.id, [entry.host.hostname for entry in queue_entries],
2100 group_name)
2101
2102 for queue_entry in queue_entries:
2103 queue_entry.set_execution_subdir(group_name)
2104
2105
2106 def _choose_group_to_run(self, include_queue_entry):
2107 chosen_entries = [include_queue_entry]
2108
2109 num_entries_needed = self.synch_count - 1
2110 if num_entries_needed > 0:
2111 pending_entries = HostQueueEntry.fetch(
2112 where='job_id = %s AND status = "Pending" AND id != %s',
2113 params=(self.id, include_queue_entry.id))
2114 chosen_entries += list(pending_entries)[:num_entries_needed]
2115
2116 self._assign_new_group(chosen_entries)
2117 return chosen_entries
2118
2119
2120 def run(self, queue_entry):
showardb2e2c322008-10-14 17:33:55 +00002121 if not self.is_ready():
showard9976ce92008-10-15 20:28:13 +00002122 if self.run_verify:
showarde58e3f82008-11-20 19:04:59 +00002123 queue_entry.set_status(models.HostQueueEntry.Status.VERIFYING)
showard170873e2009-01-07 00:22:26 +00002124 return Agent(self._get_pre_job_tasks(queue_entry))
showard9976ce92008-10-15 20:28:13 +00002125 else:
2126 return queue_entry.on_pending()
mbligh36768f02008-02-22 18:28:33 +00002127
showard2bab8f42008-11-12 18:15:22 +00002128 queue_entries = self._choose_group_to_run(queue_entry)
2129 return self._finish_run(queue_entries)
showardb2e2c322008-10-14 17:33:55 +00002130
2131
2132 def _finish_run(self, queue_entries, initial_tasks=[]):
showardb2ccdda2008-10-28 20:39:05 +00002133 for queue_entry in queue_entries:
2134 queue_entry.set_status('Starting')
showardb2e2c322008-10-14 17:33:55 +00002135 params = self._get_autoserv_params(queue_entries)
2136 queue_task = QueueTask(job=self, queue_entries=queue_entries,
2137 cmd=params)
2138 tasks = initial_tasks + [queue_task]
2139 entry_ids = [entry.id for entry in queue_entries]
2140
showard170873e2009-01-07 00:22:26 +00002141 return Agent(tasks, num_processes=len(queue_entries))
showardb2e2c322008-10-14 17:33:55 +00002142
2143
mbligh36768f02008-02-22 18:28:33 +00002144if __name__ == '__main__':
jadmanski0afbb632008-06-06 21:10:57 +00002145 main()