blob: cc0115917b5f7962ebb8c2f746dbadc87667df3f [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
mbligh8bcd23a2009-02-03 19:14:06 +00008import datetime, errno, optparse, os, pwd, Queue, re, shutil, signal
showard542e8402008-09-19 20:16:18 +00009import smtplib, socket, stat, subprocess, sys, tempfile, time, traceback
showarda3c58572009-03-12 20:36:59 +000010import itertools, logging, weakref
mbligh70feeee2008-06-11 16:20:49 +000011import common
mbligh8bcd23a2009-02-03 19:14:06 +000012import MySQLdb
showard21baa452008-10-21 00:08:39 +000013from autotest_lib.frontend import setup_django_environment
showard542e8402008-09-19 20:16:18 +000014from autotest_lib.client.common_lib import global_config
showard2bab8f42008-11-12 18:15:22 +000015from autotest_lib.client.common_lib import host_protections, utils, debug
showardb1e51872008-10-07 11:08:18 +000016from autotest_lib.database import database_connection
showard21baa452008-10-21 00:08:39 +000017from autotest_lib.frontend.afe import models
showard170873e2009-01-07 00:22:26 +000018from autotest_lib.scheduler import drone_manager, drones, email_manager
showardd1ee1dd2009-01-07 21:33:08 +000019from autotest_lib.scheduler import status_server, scheduler_config
mbligh70feeee2008-06-11 16:20:49 +000020
mblighb090f142008-02-27 21:33:46 +000021
mbligh36768f02008-02-22 18:28:33 +000022RESULTS_DIR = '.'
23AUTOSERV_NICE_LEVEL = 10
showard170873e2009-01-07 00:22:26 +000024DB_CONFIG_SECTION = 'AUTOTEST_WEB'
mbligh36768f02008-02-22 18:28:33 +000025
26AUTOTEST_PATH = os.path.join(os.path.dirname(__file__), '..')
27
28if os.environ.has_key('AUTOTEST_DIR'):
jadmanski0afbb632008-06-06 21:10:57 +000029 AUTOTEST_PATH = os.environ['AUTOTEST_DIR']
mbligh36768f02008-02-22 18:28:33 +000030AUTOTEST_SERVER_DIR = os.path.join(AUTOTEST_PATH, 'server')
31AUTOTEST_TKO_DIR = os.path.join(AUTOTEST_PATH, 'tko')
32
33if AUTOTEST_SERVER_DIR not in sys.path:
jadmanski0afbb632008-06-06 21:10:57 +000034 sys.path.insert(0, AUTOTEST_SERVER_DIR)
mbligh36768f02008-02-22 18:28:33 +000035
mbligh90a549d2008-03-25 23:52:34 +000036# how long to wait for autoserv to write a pidfile
37PIDFILE_TIMEOUT = 5 * 60 # 5 min
mblighbb421852008-03-11 22:36:16 +000038
showard35162b02009-03-03 02:17:30 +000039# error message to leave in results dir when an autoserv process disappears
40# mysteriously
41_LOST_PROCESS_ERROR = """\
42Autoserv failed abnormally during execution for this job, probably due to a
43system error on the Autotest server. Full results may not be available. Sorry.
44"""
45
mbligh6f8bab42008-02-29 22:45:14 +000046_db = None
mbligh36768f02008-02-22 18:28:33 +000047_shutdown = False
showard170873e2009-01-07 00:22:26 +000048_autoserv_path = os.path.join(drones.AUTOTEST_INSTALL_DIR, 'server', 'autoserv')
49_parser_path = os.path.join(drones.AUTOTEST_INSTALL_DIR, 'tko', 'parse')
mbligh4314a712008-02-29 22:44:30 +000050_testing_mode = False
showard542e8402008-09-19 20:16:18 +000051_base_url = None
showardc85c21b2008-11-24 22:17:37 +000052_notify_email_statuses = []
showard170873e2009-01-07 00:22:26 +000053_drone_manager = drone_manager.DroneManager()
mbligh36768f02008-02-22 18:28:33 +000054
55
56def main():
jadmanski0afbb632008-06-06 21:10:57 +000057 usage = 'usage: %prog [options] results_dir'
mbligh36768f02008-02-22 18:28:33 +000058
jadmanski0afbb632008-06-06 21:10:57 +000059 parser = optparse.OptionParser(usage)
60 parser.add_option('--recover-hosts', help='Try to recover dead hosts',
61 action='store_true')
62 parser.add_option('--logfile', help='Set a log file that all stdout ' +
63 'should be redirected to. Stderr will go to this ' +
64 'file + ".err"')
65 parser.add_option('--test', help='Indicate that scheduler is under ' +
66 'test and should use dummy autoserv and no parsing',
67 action='store_true')
68 (options, args) = parser.parse_args()
69 if len(args) != 1:
70 parser.print_usage()
71 return
mbligh36768f02008-02-22 18:28:33 +000072
jadmanski0afbb632008-06-06 21:10:57 +000073 global RESULTS_DIR
74 RESULTS_DIR = args[0]
mbligh36768f02008-02-22 18:28:33 +000075
jadmanski0afbb632008-06-06 21:10:57 +000076 c = global_config.global_config
showardd1ee1dd2009-01-07 21:33:08 +000077 notify_statuses_list = c.get_config_value(scheduler_config.CONFIG_SECTION,
78 "notify_email_statuses",
79 default='')
showardc85c21b2008-11-24 22:17:37 +000080 global _notify_email_statuses
showard170873e2009-01-07 00:22:26 +000081 _notify_email_statuses = [status for status in
82 re.split(r'[\s,;:]', notify_statuses_list.lower())
83 if status]
showardc85c21b2008-11-24 22:17:37 +000084
jadmanski0afbb632008-06-06 21:10:57 +000085 if options.test:
86 global _autoserv_path
87 _autoserv_path = 'autoserv_dummy'
88 global _testing_mode
89 _testing_mode = True
mbligh36768f02008-02-22 18:28:33 +000090
mbligh37eceaa2008-12-15 22:56:37 +000091 # AUTOTEST_WEB.base_url is still a supported config option as some people
92 # may wish to override the entire url.
showard542e8402008-09-19 20:16:18 +000093 global _base_url
showard170873e2009-01-07 00:22:26 +000094 config_base_url = c.get_config_value(DB_CONFIG_SECTION, 'base_url',
95 default='')
mbligh37eceaa2008-12-15 22:56:37 +000096 if config_base_url:
97 _base_url = config_base_url
showard542e8402008-09-19 20:16:18 +000098 else:
mbligh37eceaa2008-12-15 22:56:37 +000099 # For the common case of everything running on a single server you
100 # can just set the hostname in a single place in the config file.
101 server_name = c.get_config_value('SERVER', 'hostname')
102 if not server_name:
103 print 'Error: [SERVER] hostname missing from the config file.'
104 sys.exit(1)
105 _base_url = 'http://%s/afe/' % server_name
showard542e8402008-09-19 20:16:18 +0000106
showardc5afc462009-01-13 00:09:39 +0000107 server = status_server.StatusServer(_drone_manager)
showardd1ee1dd2009-01-07 21:33:08 +0000108 server.start()
109
jadmanski0afbb632008-06-06 21:10:57 +0000110 try:
showardc5afc462009-01-13 00:09:39 +0000111 init(options.logfile)
112 dispatcher = Dispatcher()
113 dispatcher.do_initial_recovery(recover_hosts=options.recover_hosts)
114
jadmanski0afbb632008-06-06 21:10:57 +0000115 while not _shutdown:
116 dispatcher.tick()
showardd1ee1dd2009-01-07 21:33:08 +0000117 time.sleep(scheduler_config.config.tick_pause_sec)
jadmanski0afbb632008-06-06 21:10:57 +0000118 except:
showard170873e2009-01-07 00:22:26 +0000119 email_manager.manager.log_stacktrace(
120 "Uncaught exception; terminating monitor_db")
jadmanski0afbb632008-06-06 21:10:57 +0000121
showard170873e2009-01-07 00:22:26 +0000122 email_manager.manager.send_queued_emails()
showard55b4b542009-01-08 23:30:30 +0000123 server.shutdown()
showard170873e2009-01-07 00:22:26 +0000124 _drone_manager.shutdown()
jadmanski0afbb632008-06-06 21:10:57 +0000125 _db.disconnect()
mbligh36768f02008-02-22 18:28:33 +0000126
127
128def handle_sigint(signum, frame):
jadmanski0afbb632008-06-06 21:10:57 +0000129 global _shutdown
130 _shutdown = True
131 print "Shutdown request received."
mbligh36768f02008-02-22 18:28:33 +0000132
133
134def init(logfile):
jadmanski0afbb632008-06-06 21:10:57 +0000135 if logfile:
136 enable_logging(logfile)
137 print "%s> dispatcher starting" % time.strftime("%X %x")
138 print "My PID is %d" % os.getpid()
mbligh36768f02008-02-22 18:28:33 +0000139
showardb1e51872008-10-07 11:08:18 +0000140 if _testing_mode:
141 global_config.global_config.override_config_value(
showard170873e2009-01-07 00:22:26 +0000142 DB_CONFIG_SECTION, 'database', 'stresstest_autotest_web')
showardb1e51872008-10-07 11:08:18 +0000143
jadmanski0afbb632008-06-06 21:10:57 +0000144 os.environ['PATH'] = AUTOTEST_SERVER_DIR + ':' + os.environ['PATH']
145 global _db
showard170873e2009-01-07 00:22:26 +0000146 _db = database_connection.DatabaseConnection(DB_CONFIG_SECTION)
jadmanski0afbb632008-06-06 21:10:57 +0000147 _db.connect()
mbligh36768f02008-02-22 18:28:33 +0000148
showardfa8629c2008-11-04 16:51:23 +0000149 # ensure Django connection is in autocommit
150 setup_django_environment.enable_autocommit()
151
showard2bab8f42008-11-12 18:15:22 +0000152 debug.configure('scheduler', format_string='%(message)s')
showard67831ae2009-01-16 03:07:38 +0000153 debug.get_logger().setLevel(logging.INFO)
showard2bab8f42008-11-12 18:15:22 +0000154
jadmanski0afbb632008-06-06 21:10:57 +0000155 print "Setting signal handler"
156 signal.signal(signal.SIGINT, handle_sigint)
157
showardd1ee1dd2009-01-07 21:33:08 +0000158 drones = global_config.global_config.get_config_value(
159 scheduler_config.CONFIG_SECTION, 'drones', default='localhost')
160 drone_list = [hostname.strip() for hostname in drones.split(',')]
showard170873e2009-01-07 00:22:26 +0000161 results_host = global_config.global_config.get_config_value(
showardd1ee1dd2009-01-07 21:33:08 +0000162 scheduler_config.CONFIG_SECTION, 'results_host', default='localhost')
showard170873e2009-01-07 00:22:26 +0000163 _drone_manager.initialize(RESULTS_DIR, drone_list, results_host)
164
jadmanski0afbb632008-06-06 21:10:57 +0000165 print "Connected! Running..."
mbligh36768f02008-02-22 18:28:33 +0000166
167
168def enable_logging(logfile):
jadmanski0afbb632008-06-06 21:10:57 +0000169 out_file = logfile
170 err_file = "%s.err" % logfile
171 print "Enabling logging to %s (%s)" % (out_file, err_file)
172 out_fd = open(out_file, "a", buffering=0)
173 err_fd = open(err_file, "a", buffering=0)
mbligh36768f02008-02-22 18:28:33 +0000174
jadmanski0afbb632008-06-06 21:10:57 +0000175 os.dup2(out_fd.fileno(), sys.stdout.fileno())
176 os.dup2(err_fd.fileno(), sys.stderr.fileno())
mbligh36768f02008-02-22 18:28:33 +0000177
jadmanski0afbb632008-06-06 21:10:57 +0000178 sys.stdout = out_fd
179 sys.stderr = err_fd
mbligh36768f02008-02-22 18:28:33 +0000180
181
mblighd5c95802008-03-05 00:33:46 +0000182def queue_entries_to_abort():
jadmanski0afbb632008-06-06 21:10:57 +0000183 rows = _db.execute("""
184 SELECT * FROM host_queue_entries WHERE status='Abort';
185 """)
showard2bab8f42008-11-12 18:15:22 +0000186
jadmanski0afbb632008-06-06 21:10:57 +0000187 qe = [HostQueueEntry(row=i) for i in rows]
188 return qe
mbligh36768f02008-02-22 18:28:33 +0000189
showard7cf9a9b2008-05-15 21:15:52 +0000190
showard63a34772008-08-18 19:32:50 +0000191class HostScheduler(object):
192 def _get_ready_hosts(self):
193 # avoid any host with a currently active queue entry against it
194 hosts = Host.fetch(
195 joins='LEFT JOIN host_queue_entries AS active_hqe '
196 'ON (hosts.id = active_hqe.host_id AND '
showardb1e51872008-10-07 11:08:18 +0000197 'active_hqe.active)',
showard63a34772008-08-18 19:32:50 +0000198 where="active_hqe.host_id IS NULL "
showardb1e51872008-10-07 11:08:18 +0000199 "AND NOT hosts.locked "
showard63a34772008-08-18 19:32:50 +0000200 "AND (hosts.status IS NULL OR hosts.status = 'Ready')")
201 return dict((host.id, host) for host in hosts)
202
203
204 @staticmethod
205 def _get_sql_id_list(id_list):
206 return ','.join(str(item_id) for item_id in id_list)
207
208
209 @classmethod
showard989f25d2008-10-01 11:38:11 +0000210 def _get_many2many_dict(cls, query, id_list, flip=False):
mbligh849a0f62008-08-28 20:12:19 +0000211 if not id_list:
212 return {}
showard63a34772008-08-18 19:32:50 +0000213 query %= cls._get_sql_id_list(id_list)
214 rows = _db.execute(query)
showard989f25d2008-10-01 11:38:11 +0000215 return cls._process_many2many_dict(rows, flip)
216
217
218 @staticmethod
219 def _process_many2many_dict(rows, flip=False):
showard63a34772008-08-18 19:32:50 +0000220 result = {}
221 for row in rows:
222 left_id, right_id = long(row[0]), long(row[1])
showard989f25d2008-10-01 11:38:11 +0000223 if flip:
224 left_id, right_id = right_id, left_id
showard63a34772008-08-18 19:32:50 +0000225 result.setdefault(left_id, set()).add(right_id)
226 return result
227
228
229 @classmethod
230 def _get_job_acl_groups(cls, job_ids):
231 query = """
showardd9ac4452009-02-07 02:04:37 +0000232 SELECT jobs.id, acl_groups_users.aclgroup_id
showard63a34772008-08-18 19:32:50 +0000233 FROM jobs
234 INNER JOIN users ON users.login = jobs.owner
235 INNER JOIN acl_groups_users ON acl_groups_users.user_id = users.id
236 WHERE jobs.id IN (%s)
237 """
238 return cls._get_many2many_dict(query, job_ids)
239
240
241 @classmethod
242 def _get_job_ineligible_hosts(cls, job_ids):
243 query = """
244 SELECT job_id, host_id
245 FROM ineligible_host_queues
246 WHERE job_id IN (%s)
247 """
248 return cls._get_many2many_dict(query, job_ids)
249
250
251 @classmethod
showard989f25d2008-10-01 11:38:11 +0000252 def _get_job_dependencies(cls, job_ids):
253 query = """
254 SELECT job_id, label_id
255 FROM jobs_dependency_labels
256 WHERE job_id IN (%s)
257 """
258 return cls._get_many2many_dict(query, job_ids)
259
260
261 @classmethod
showard63a34772008-08-18 19:32:50 +0000262 def _get_host_acls(cls, host_ids):
263 query = """
showardd9ac4452009-02-07 02:04:37 +0000264 SELECT host_id, aclgroup_id
showard63a34772008-08-18 19:32:50 +0000265 FROM acl_groups_hosts
266 WHERE host_id IN (%s)
267 """
268 return cls._get_many2many_dict(query, host_ids)
269
270
271 @classmethod
272 def _get_label_hosts(cls, host_ids):
showardfa8629c2008-11-04 16:51:23 +0000273 if not host_ids:
274 return {}, {}
showard63a34772008-08-18 19:32:50 +0000275 query = """
276 SELECT label_id, host_id
277 FROM hosts_labels
278 WHERE host_id IN (%s)
showard989f25d2008-10-01 11:38:11 +0000279 """ % cls._get_sql_id_list(host_ids)
280 rows = _db.execute(query)
281 labels_to_hosts = cls._process_many2many_dict(rows)
282 hosts_to_labels = cls._process_many2many_dict(rows, flip=True)
283 return labels_to_hosts, hosts_to_labels
284
285
286 @classmethod
287 def _get_labels(cls):
288 return dict((label.id, label) for label in Label.fetch())
showard63a34772008-08-18 19:32:50 +0000289
290
291 def refresh(self, pending_queue_entries):
292 self._hosts_available = self._get_ready_hosts()
293
294 relevant_jobs = [queue_entry.job_id
295 for queue_entry in pending_queue_entries]
296 self._job_acls = self._get_job_acl_groups(relevant_jobs)
297 self._ineligible_hosts = self._get_job_ineligible_hosts(relevant_jobs)
showard989f25d2008-10-01 11:38:11 +0000298 self._job_dependencies = self._get_job_dependencies(relevant_jobs)
showard63a34772008-08-18 19:32:50 +0000299
300 host_ids = self._hosts_available.keys()
301 self._host_acls = self._get_host_acls(host_ids)
showard989f25d2008-10-01 11:38:11 +0000302 self._label_hosts, self._host_labels = self._get_label_hosts(host_ids)
303
304 self._labels = self._get_labels()
showard63a34772008-08-18 19:32:50 +0000305
306
307 def _is_acl_accessible(self, host_id, queue_entry):
308 job_acls = self._job_acls.get(queue_entry.job_id, set())
309 host_acls = self._host_acls.get(host_id, set())
310 return len(host_acls.intersection(job_acls)) > 0
311
312
showard989f25d2008-10-01 11:38:11 +0000313 def _check_job_dependencies(self, job_dependencies, host_labels):
314 missing = job_dependencies - host_labels
315 return len(job_dependencies - host_labels) == 0
316
317
318 def _check_only_if_needed_labels(self, job_dependencies, host_labels,
319 queue_entry):
showardade14e22009-01-26 22:38:32 +0000320 if not queue_entry.meta_host:
321 # bypass only_if_needed labels when a specific host is selected
322 return True
323
showard989f25d2008-10-01 11:38:11 +0000324 for label_id in host_labels:
325 label = self._labels[label_id]
326 if not label.only_if_needed:
327 # we don't care about non-only_if_needed labels
328 continue
329 if queue_entry.meta_host == label_id:
330 # if the label was requested in a metahost it's OK
331 continue
332 if label_id not in job_dependencies:
333 return False
334 return True
335
336
337 def _is_host_eligible_for_job(self, host_id, queue_entry):
338 job_dependencies = self._job_dependencies.get(queue_entry.job_id, set())
339 host_labels = self._host_labels.get(host_id, set())
mblighc993bee2008-10-03 03:42:34 +0000340
341 acl = self._is_acl_accessible(host_id, queue_entry)
342 deps = self._check_job_dependencies(job_dependencies, host_labels)
343 only_if = self._check_only_if_needed_labels(job_dependencies,
344 host_labels, queue_entry)
345 return acl and deps and only_if
showard989f25d2008-10-01 11:38:11 +0000346
347
showard63a34772008-08-18 19:32:50 +0000348 def _schedule_non_metahost(self, queue_entry):
showard989f25d2008-10-01 11:38:11 +0000349 if not self._is_host_eligible_for_job(queue_entry.host_id, queue_entry):
showard63a34772008-08-18 19:32:50 +0000350 return None
351 return self._hosts_available.pop(queue_entry.host_id, None)
352
353
354 def _is_host_usable(self, host_id):
355 if host_id not in self._hosts_available:
356 # host was already used during this scheduling cycle
357 return False
358 if self._hosts_available[host_id].invalid:
359 # Invalid hosts cannot be used for metahosts. They're included in
360 # the original query because they can be used by non-metahosts.
361 return False
362 return True
363
364
365 def _schedule_metahost(self, queue_entry):
366 label_id = queue_entry.meta_host
367 hosts_in_label = self._label_hosts.get(label_id, set())
368 ineligible_host_ids = self._ineligible_hosts.get(queue_entry.job_id,
369 set())
370
371 # must iterate over a copy so we can mutate the original while iterating
372 for host_id in list(hosts_in_label):
373 if not self._is_host_usable(host_id):
374 hosts_in_label.remove(host_id)
375 continue
376 if host_id in ineligible_host_ids:
377 continue
showard989f25d2008-10-01 11:38:11 +0000378 if not self._is_host_eligible_for_job(host_id, queue_entry):
showard63a34772008-08-18 19:32:50 +0000379 continue
380
381 hosts_in_label.remove(host_id)
382 return self._hosts_available.pop(host_id)
383 return None
384
385
386 def find_eligible_host(self, queue_entry):
387 if not queue_entry.meta_host:
388 return self._schedule_non_metahost(queue_entry)
389 return self._schedule_metahost(queue_entry)
390
391
showard170873e2009-01-07 00:22:26 +0000392class Dispatcher(object):
jadmanski0afbb632008-06-06 21:10:57 +0000393 def __init__(self):
394 self._agents = []
showard3bb499f2008-07-03 19:42:20 +0000395 self._last_clean_time = time.time()
showard63a34772008-08-18 19:32:50 +0000396 self._host_scheduler = HostScheduler()
showard170873e2009-01-07 00:22:26 +0000397 self._host_agents = {}
398 self._queue_entry_agents = {}
mbligh36768f02008-02-22 18:28:33 +0000399
mbligh36768f02008-02-22 18:28:33 +0000400
jadmanski0afbb632008-06-06 21:10:57 +0000401 def do_initial_recovery(self, recover_hosts=True):
402 # always recover processes
403 self._recover_processes()
mblighbb421852008-03-11 22:36:16 +0000404
jadmanski0afbb632008-06-06 21:10:57 +0000405 if recover_hosts:
406 self._recover_hosts()
mbligh36768f02008-02-22 18:28:33 +0000407
408
jadmanski0afbb632008-06-06 21:10:57 +0000409 def tick(self):
showard170873e2009-01-07 00:22:26 +0000410 _drone_manager.refresh()
showarda3ab0d52008-11-03 19:03:47 +0000411 self._run_cleanup_maybe()
jadmanski0afbb632008-06-06 21:10:57 +0000412 self._find_aborting()
413 self._schedule_new_jobs()
414 self._handle_agents()
showard170873e2009-01-07 00:22:26 +0000415 _drone_manager.execute_actions()
416 email_manager.manager.send_queued_emails()
mbligh36768f02008-02-22 18:28:33 +0000417
showard97aed502008-11-04 02:01:24 +0000418
showarda3ab0d52008-11-03 19:03:47 +0000419 def _run_cleanup_maybe(self):
showardd1ee1dd2009-01-07 21:33:08 +0000420 should_cleanup = (self._last_clean_time +
421 scheduler_config.config.clean_interval * 60 <
422 time.time())
423 if should_cleanup:
showarda3ab0d52008-11-03 19:03:47 +0000424 print 'Running cleanup'
425 self._abort_timed_out_jobs()
426 self._abort_jobs_past_synch_start_timeout()
427 self._clear_inactive_blocks()
showardfa8629c2008-11-04 16:51:23 +0000428 self._check_for_db_inconsistencies()
showarda3ab0d52008-11-03 19:03:47 +0000429 self._last_clean_time = time.time()
430
mbligh36768f02008-02-22 18:28:33 +0000431
showard170873e2009-01-07 00:22:26 +0000432 def _register_agent_for_ids(self, agent_dict, object_ids, agent):
433 for object_id in object_ids:
434 agent_dict.setdefault(object_id, set()).add(agent)
435
436
437 def _unregister_agent_for_ids(self, agent_dict, object_ids, agent):
438 for object_id in object_ids:
439 assert object_id in agent_dict
440 agent_dict[object_id].remove(agent)
441
442
jadmanski0afbb632008-06-06 21:10:57 +0000443 def add_agent(self, agent):
444 self._agents.append(agent)
445 agent.dispatcher = self
showard170873e2009-01-07 00:22:26 +0000446 self._register_agent_for_ids(self._host_agents, agent.host_ids, agent)
447 self._register_agent_for_ids(self._queue_entry_agents,
448 agent.queue_entry_ids, agent)
mblighd5c95802008-03-05 00:33:46 +0000449
showard170873e2009-01-07 00:22:26 +0000450
451 def get_agents_for_entry(self, queue_entry):
452 """
453 Find agents corresponding to the specified queue_entry.
454 """
455 return self._queue_entry_agents.get(queue_entry.id, set())
456
457
458 def host_has_agent(self, host):
459 """
460 Determine if there is currently an Agent present using this host.
461 """
462 return bool(self._host_agents.get(host.id, None))
mbligh36768f02008-02-22 18:28:33 +0000463
464
jadmanski0afbb632008-06-06 21:10:57 +0000465 def remove_agent(self, agent):
466 self._agents.remove(agent)
showard170873e2009-01-07 00:22:26 +0000467 self._unregister_agent_for_ids(self._host_agents, agent.host_ids,
468 agent)
469 self._unregister_agent_for_ids(self._queue_entry_agents,
470 agent.queue_entry_ids, agent)
showardec113162008-05-08 00:52:49 +0000471
472
showard4c5374f2008-09-04 17:02:56 +0000473 def num_running_processes(self):
474 return sum(agent.num_processes for agent in self._agents
475 if agent.is_running())
mblighbb421852008-03-11 22:36:16 +0000476
477
showard170873e2009-01-07 00:22:26 +0000478 def _extract_execution_tag(self, command_line):
479 match = re.match(r'.* -P (\S+) ', command_line)
480 if not match:
481 return None
482 return match.group(1)
mblighbb421852008-03-11 22:36:16 +0000483
484
showard2bab8f42008-11-12 18:15:22 +0000485 def _recover_queue_entries(self, queue_entries, run_monitor):
486 assert len(queue_entries) > 0
showard2bab8f42008-11-12 18:15:22 +0000487 queue_task = RecoveryQueueTask(job=queue_entries[0].job,
488 queue_entries=queue_entries,
489 run_monitor=run_monitor)
jadmanski0afbb632008-06-06 21:10:57 +0000490 self.add_agent(Agent(tasks=[queue_task],
showard170873e2009-01-07 00:22:26 +0000491 num_processes=len(queue_entries)))
mblighbb421852008-03-11 22:36:16 +0000492
493
jadmanski0afbb632008-06-06 21:10:57 +0000494 def _recover_processes(self):
showard170873e2009-01-07 00:22:26 +0000495 self._register_pidfiles()
496 _drone_manager.refresh()
497 self._recover_running_entries()
498 self._recover_aborting_entries()
499 self._requeue_other_active_entries()
500 self._recover_parsing_entries()
501 self._reverify_remaining_hosts()
502 # reinitialize drones after killing orphaned processes, since they can
503 # leave around files when they die
504 _drone_manager.execute_actions()
505 _drone_manager.reinitialize_drones()
mblighbb421852008-03-11 22:36:16 +0000506
showard170873e2009-01-07 00:22:26 +0000507
508 def _register_pidfiles(self):
509 # during recovery we may need to read pidfiles for both running and
510 # parsing entries
511 queue_entries = HostQueueEntry.fetch(
512 where="status IN ('Running', 'Parsing')")
jadmanski0afbb632008-06-06 21:10:57 +0000513 for queue_entry in queue_entries:
showard170873e2009-01-07 00:22:26 +0000514 pidfile_id = _drone_manager.get_pidfile_id_from(
515 queue_entry.execution_tag())
516 _drone_manager.register_pidfile(pidfile_id)
517
518
519 def _recover_running_entries(self):
520 orphans = _drone_manager.get_orphaned_autoserv_processes()
521
522 queue_entries = HostQueueEntry.fetch(where="status = 'Running'")
523 requeue_entries = []
524 for queue_entry in queue_entries:
525 if self.get_agents_for_entry(queue_entry):
jadmanski0afbb632008-06-06 21:10:57 +0000526 # synchronous job we've already recovered
527 continue
showard170873e2009-01-07 00:22:26 +0000528 execution_tag = queue_entry.execution_tag()
529 run_monitor = PidfileRunMonitor()
530 run_monitor.attach_to_existing_process(execution_tag)
531 if not run_monitor.has_process():
532 # autoserv apparently never got run, so let it get requeued
533 continue
showarde788ea62008-11-17 21:02:47 +0000534 queue_entries = queue_entry.job.get_group_entries(queue_entry)
showard170873e2009-01-07 00:22:26 +0000535 print 'Recovering %s (process %s)' % (
536 ', '.join(str(entry) for entry in queue_entries),
537 run_monitor.get_process())
showard2bab8f42008-11-12 18:15:22 +0000538 self._recover_queue_entries(queue_entries, run_monitor)
showard170873e2009-01-07 00:22:26 +0000539 orphans.pop(execution_tag, None)
mbligh90a549d2008-03-25 23:52:34 +0000540
jadmanski0afbb632008-06-06 21:10:57 +0000541 # now kill any remaining autoserv processes
showard170873e2009-01-07 00:22:26 +0000542 for process in orphans.itervalues():
543 print 'Killing orphan %s' % process
544 _drone_manager.kill_process(process)
jadmanski0afbb632008-06-06 21:10:57 +0000545
showard170873e2009-01-07 00:22:26 +0000546
547 def _recover_aborting_entries(self):
548 queue_entries = HostQueueEntry.fetch(
549 where='status IN ("Abort", "Aborting")')
jadmanski0afbb632008-06-06 21:10:57 +0000550 for queue_entry in queue_entries:
showard170873e2009-01-07 00:22:26 +0000551 print 'Recovering aborting QE %s' % queue_entry
552 agent = queue_entry.abort(self)
jadmanski0afbb632008-06-06 21:10:57 +0000553
showard97aed502008-11-04 02:01:24 +0000554
showard170873e2009-01-07 00:22:26 +0000555 def _requeue_other_active_entries(self):
556 queue_entries = HostQueueEntry.fetch(
557 where='active AND NOT complete AND status != "Pending"')
558 for queue_entry in queue_entries:
559 if self.get_agents_for_entry(queue_entry):
560 # entry has already been recovered
561 continue
562 print 'Requeuing active QE %s (status=%s)' % (queue_entry,
563 queue_entry.status)
564 if queue_entry.host:
565 tasks = queue_entry.host.reverify_tasks()
566 self.add_agent(Agent(tasks))
567 agent = queue_entry.requeue()
568
569
570 def _reverify_remaining_hosts(self):
showard45ae8192008-11-05 19:32:53 +0000571 # reverify hosts that were in the middle of verify, repair or cleanup
jadmanski0afbb632008-06-06 21:10:57 +0000572 self._reverify_hosts_where("""(status = 'Repairing' OR
573 status = 'Verifying' OR
showard170873e2009-01-07 00:22:26 +0000574 status = 'Cleaning')""")
jadmanski0afbb632008-06-06 21:10:57 +0000575
showard170873e2009-01-07 00:22:26 +0000576 # recover "Running" hosts with no active queue entries, although this
577 # should never happen
578 message = ('Recovering running host %s - this probably indicates a '
579 'scheduler bug')
jadmanski0afbb632008-06-06 21:10:57 +0000580 self._reverify_hosts_where("""status = 'Running' AND
581 id NOT IN (SELECT host_id
582 FROM host_queue_entries
583 WHERE active)""",
584 print_message=message)
mblighbb421852008-03-11 22:36:16 +0000585
586
jadmanski0afbb632008-06-06 21:10:57 +0000587 def _reverify_hosts_where(self, where,
showard170873e2009-01-07 00:22:26 +0000588 print_message='Reverifying host %s'):
589 full_where='locked = 0 AND invalid = 0 AND ' + where
590 for host in Host.fetch(where=full_where):
591 if self.host_has_agent(host):
592 # host has already been recovered in some way
jadmanski0afbb632008-06-06 21:10:57 +0000593 continue
showard170873e2009-01-07 00:22:26 +0000594 if print_message:
jadmanski0afbb632008-06-06 21:10:57 +0000595 print print_message % host.hostname
showard170873e2009-01-07 00:22:26 +0000596 tasks = host.reverify_tasks()
597 self.add_agent(Agent(tasks))
mbligh36768f02008-02-22 18:28:33 +0000598
599
showard97aed502008-11-04 02:01:24 +0000600 def _recover_parsing_entries(self):
showard2bab8f42008-11-12 18:15:22 +0000601 recovered_entry_ids = set()
showard97aed502008-11-04 02:01:24 +0000602 for entry in HostQueueEntry.fetch(where='status = "Parsing"'):
showard2bab8f42008-11-12 18:15:22 +0000603 if entry.id in recovered_entry_ids:
604 continue
605 queue_entries = entry.job.get_group_entries(entry)
showard170873e2009-01-07 00:22:26 +0000606 recovered_entry_ids = recovered_entry_ids.union(
607 entry.id for entry in queue_entries)
608 print 'Recovering parsing entries %s' % (
609 ', '.join(str(entry) for entry in queue_entries))
showard97aed502008-11-04 02:01:24 +0000610
611 reparse_task = FinalReparseTask(queue_entries)
showard170873e2009-01-07 00:22:26 +0000612 self.add_agent(Agent([reparse_task], num_processes=0))
showard97aed502008-11-04 02:01:24 +0000613
614
jadmanski0afbb632008-06-06 21:10:57 +0000615 def _recover_hosts(self):
616 # recover "Repair Failed" hosts
617 message = 'Reverifying dead host %s'
618 self._reverify_hosts_where("status = 'Repair Failed'",
619 print_message=message)
mbligh62ba2ed2008-04-30 17:09:25 +0000620
621
showard3bb499f2008-07-03 19:42:20 +0000622 def _abort_timed_out_jobs(self):
623 """
624 Aborts all jobs that have timed out and not completed
625 """
showarda3ab0d52008-11-03 19:03:47 +0000626 query = models.Job.objects.filter(hostqueueentry__complete=False).extra(
627 where=['created_on + INTERVAL timeout HOUR < NOW()'])
628 for job in query.distinct():
629 print 'Aborting job %d due to job timeout' % job.id
630 job.abort(None)
showard3bb499f2008-07-03 19:42:20 +0000631
632
showard98863972008-10-29 21:14:56 +0000633 def _abort_jobs_past_synch_start_timeout(self):
634 """
635 Abort synchronous jobs that are past the start timeout (from global
636 config) and are holding a machine that's in everyone.
637 """
638 timeout_delta = datetime.timedelta(
showardd1ee1dd2009-01-07 21:33:08 +0000639 minutes=scheduler_config.config.synch_job_start_timeout_minutes)
showard98863972008-10-29 21:14:56 +0000640 timeout_start = datetime.datetime.now() - timeout_delta
641 query = models.Job.objects.filter(
showard98863972008-10-29 21:14:56 +0000642 created_on__lt=timeout_start,
643 hostqueueentry__status='Pending',
showardd9ac4452009-02-07 02:04:37 +0000644 hostqueueentry__host__aclgroup__name='Everyone')
showard98863972008-10-29 21:14:56 +0000645 for job in query.distinct():
646 print 'Aborting job %d due to start timeout' % job.id
showardff059d72008-12-03 18:18:53 +0000647 entries_to_abort = job.hostqueueentry_set.exclude(
648 status=models.HostQueueEntry.Status.RUNNING)
649 for queue_entry in entries_to_abort:
650 queue_entry.abort(None)
showard98863972008-10-29 21:14:56 +0000651
652
jadmanski0afbb632008-06-06 21:10:57 +0000653 def _clear_inactive_blocks(self):
654 """
655 Clear out blocks for all completed jobs.
656 """
657 # this would be simpler using NOT IN (subquery), but MySQL
658 # treats all IN subqueries as dependent, so this optimizes much
659 # better
660 _db.execute("""
661 DELETE ihq FROM ineligible_host_queues ihq
showard4eaaf522008-06-06 22:28:07 +0000662 LEFT JOIN (SELECT DISTINCT job_id FROM host_queue_entries
jadmanski0afbb632008-06-06 21:10:57 +0000663 WHERE NOT complete) hqe
664 USING (job_id) WHERE hqe.job_id IS NULL""")
showard04c82c52008-05-29 19:38:12 +0000665
666
showardb95b1bd2008-08-15 18:11:04 +0000667 def _get_pending_queue_entries(self):
showard63a34772008-08-18 19:32:50 +0000668 # prioritize by job priority, then non-metahost over metahost, then FIFO
669 return list(HostQueueEntry.fetch(
showard25cbdbd2009-02-17 20:57:21 +0000670 joins='INNER JOIN jobs ON (job_id=jobs.id)',
showardac9ce222008-12-03 18:19:44 +0000671 where='NOT complete AND NOT active AND status="Queued"',
showard25cbdbd2009-02-17 20:57:21 +0000672 order_by='jobs.priority DESC, meta_host, job_id'))
mbligh36768f02008-02-22 18:28:33 +0000673
674
jadmanski0afbb632008-06-06 21:10:57 +0000675 def _schedule_new_jobs(self):
showard63a34772008-08-18 19:32:50 +0000676 queue_entries = self._get_pending_queue_entries()
677 if not queue_entries:
showardb95b1bd2008-08-15 18:11:04 +0000678 return
showardb95b1bd2008-08-15 18:11:04 +0000679
showard63a34772008-08-18 19:32:50 +0000680 self._host_scheduler.refresh(queue_entries)
showardb95b1bd2008-08-15 18:11:04 +0000681
showard63a34772008-08-18 19:32:50 +0000682 for queue_entry in queue_entries:
683 assigned_host = self._host_scheduler.find_eligible_host(queue_entry)
showardb95b1bd2008-08-15 18:11:04 +0000684 if not assigned_host:
jadmanski0afbb632008-06-06 21:10:57 +0000685 continue
showardb95b1bd2008-08-15 18:11:04 +0000686 self._run_queue_entry(queue_entry, assigned_host)
687
688
689 def _run_queue_entry(self, queue_entry, host):
690 agent = queue_entry.run(assigned_host=host)
showard170873e2009-01-07 00:22:26 +0000691 # in some cases (synchronous jobs with run_verify=False), agent may be
692 # None
showard9976ce92008-10-15 20:28:13 +0000693 if agent:
694 self.add_agent(agent)
mblighd5c95802008-03-05 00:33:46 +0000695
696
jadmanski0afbb632008-06-06 21:10:57 +0000697 def _find_aborting(self):
jadmanski0afbb632008-06-06 21:10:57 +0000698 for entry in queue_entries_to_abort():
showard170873e2009-01-07 00:22:26 +0000699 agents_to_abort = list(self.get_agents_for_entry(entry))
showard1be97432008-10-17 15:30:45 +0000700 for agent in agents_to_abort:
701 self.remove_agent(agent)
702
showard170873e2009-01-07 00:22:26 +0000703 entry.abort(self, agents_to_abort)
jadmanski0afbb632008-06-06 21:10:57 +0000704
705
showard324bf812009-01-20 23:23:38 +0000706 def _can_start_agent(self, agent, num_started_this_cycle,
707 have_reached_limit):
showard4c5374f2008-09-04 17:02:56 +0000708 # always allow zero-process agents to run
709 if agent.num_processes == 0:
710 return True
711 # don't allow any nonzero-process agents to run after we've reached a
712 # limit (this avoids starvation of many-process agents)
713 if have_reached_limit:
714 return False
715 # total process throttling
showard324bf812009-01-20 23:23:38 +0000716 if agent.num_processes > _drone_manager.max_runnable_processes():
showard4c5374f2008-09-04 17:02:56 +0000717 return False
718 # if a single agent exceeds the per-cycle throttling, still allow it to
719 # run when it's the first agent in the cycle
720 if num_started_this_cycle == 0:
721 return True
722 # per-cycle throttling
723 if (num_started_this_cycle + agent.num_processes >
showardd1ee1dd2009-01-07 21:33:08 +0000724 scheduler_config.config.max_processes_started_per_cycle):
showard4c5374f2008-09-04 17:02:56 +0000725 return False
726 return True
727
728
jadmanski0afbb632008-06-06 21:10:57 +0000729 def _handle_agents(self):
jadmanski0afbb632008-06-06 21:10:57 +0000730 num_started_this_cycle = 0
showard4c5374f2008-09-04 17:02:56 +0000731 have_reached_limit = False
732 # iterate over copy, so we can remove agents during iteration
733 for agent in list(self._agents):
734 if agent.is_done():
jadmanski0afbb632008-06-06 21:10:57 +0000735 print "agent finished"
showard170873e2009-01-07 00:22:26 +0000736 self.remove_agent(agent)
showard4c5374f2008-09-04 17:02:56 +0000737 continue
738 if not agent.is_running():
showard324bf812009-01-20 23:23:38 +0000739 if not self._can_start_agent(agent, num_started_this_cycle,
showard4c5374f2008-09-04 17:02:56 +0000740 have_reached_limit):
741 have_reached_limit = True
742 continue
showard4c5374f2008-09-04 17:02:56 +0000743 num_started_this_cycle += agent.num_processes
744 agent.tick()
showard324bf812009-01-20 23:23:38 +0000745 print _drone_manager.total_running_processes(), 'running processes'
mbligh36768f02008-02-22 18:28:33 +0000746
747
showardfa8629c2008-11-04 16:51:23 +0000748 def _check_for_db_inconsistencies(self):
749 query = models.HostQueueEntry.objects.filter(active=True, complete=True)
750 if query.count() != 0:
751 subject = ('%d queue entries found with active=complete=1'
752 % query.count())
753 message = '\n'.join(str(entry.get_object_dict())
754 for entry in query[:50])
755 if len(query) > 50:
756 message += '\n(truncated)\n'
757
758 print subject
showard170873e2009-01-07 00:22:26 +0000759 email_manager.manager.enqueue_notify_email(subject, message)
showardfa8629c2008-11-04 16:51:23 +0000760
761
showard170873e2009-01-07 00:22:26 +0000762class PidfileRunMonitor(object):
763 """
764 Client must call either run() to start a new process or
765 attach_to_existing_process().
766 """
mbligh36768f02008-02-22 18:28:33 +0000767
showard170873e2009-01-07 00:22:26 +0000768 class _PidfileException(Exception):
769 """
770 Raised when there's some unexpected behavior with the pid file, but only
771 used internally (never allowed to escape this class).
772 """
mbligh36768f02008-02-22 18:28:33 +0000773
774
showard170873e2009-01-07 00:22:26 +0000775 def __init__(self):
showard35162b02009-03-03 02:17:30 +0000776 self.lost_process = False
showard170873e2009-01-07 00:22:26 +0000777 self._start_time = None
778 self.pidfile_id = None
779 self._state = drone_manager.PidfileContents()
showard2bab8f42008-11-12 18:15:22 +0000780
781
showard170873e2009-01-07 00:22:26 +0000782 def _add_nice_command(self, command, nice_level):
783 if not nice_level:
784 return command
785 return ['nice', '-n', str(nice_level)] + command
786
787
788 def _set_start_time(self):
789 self._start_time = time.time()
790
791
792 def run(self, command, working_directory, nice_level=None, log_file=None,
793 pidfile_name=None, paired_with_pidfile=None):
794 assert command is not None
795 if nice_level is not None:
796 command = ['nice', '-n', str(nice_level)] + command
797 self._set_start_time()
798 self.pidfile_id = _drone_manager.execute_command(
799 command, working_directory, log_file=log_file,
800 pidfile_name=pidfile_name, paired_with_pidfile=paired_with_pidfile)
801
802
803 def attach_to_existing_process(self, execution_tag):
804 self._set_start_time()
805 self.pidfile_id = _drone_manager.get_pidfile_id_from(execution_tag)
806 _drone_manager.register_pidfile(self.pidfile_id)
mblighbb421852008-03-11 22:36:16 +0000807
808
jadmanski0afbb632008-06-06 21:10:57 +0000809 def kill(self):
showard170873e2009-01-07 00:22:26 +0000810 if self.has_process():
811 _drone_manager.kill_process(self.get_process())
mblighbb421852008-03-11 22:36:16 +0000812
mbligh36768f02008-02-22 18:28:33 +0000813
showard170873e2009-01-07 00:22:26 +0000814 def has_process(self):
showard21baa452008-10-21 00:08:39 +0000815 self._get_pidfile_info()
showard170873e2009-01-07 00:22:26 +0000816 return self._state.process is not None
showard21baa452008-10-21 00:08:39 +0000817
818
showard170873e2009-01-07 00:22:26 +0000819 def get_process(self):
showard21baa452008-10-21 00:08:39 +0000820 self._get_pidfile_info()
showard35162b02009-03-03 02:17:30 +0000821 assert self._state.process is not None
showard170873e2009-01-07 00:22:26 +0000822 return self._state.process
mblighbb421852008-03-11 22:36:16 +0000823
824
showard170873e2009-01-07 00:22:26 +0000825 def _read_pidfile(self, use_second_read=False):
826 assert self.pidfile_id is not None, (
827 'You must call run() or attach_to_existing_process()')
828 contents = _drone_manager.get_pidfile_contents(
829 self.pidfile_id, use_second_read=use_second_read)
830 if contents.is_invalid():
831 self._state = drone_manager.PidfileContents()
832 raise self._PidfileException(contents)
833 self._state = contents
mbligh90a549d2008-03-25 23:52:34 +0000834
835
showard21baa452008-10-21 00:08:39 +0000836 def _handle_pidfile_error(self, error, message=''):
showard170873e2009-01-07 00:22:26 +0000837 message = error + '\nProcess: %s\nPidfile: %s\n%s' % (
838 self._state.process, self.pidfile_id, message)
showard21baa452008-10-21 00:08:39 +0000839 print message
showard170873e2009-01-07 00:22:26 +0000840 email_manager.manager.enqueue_notify_email(error, message)
showard35162b02009-03-03 02:17:30 +0000841 self.on_lost_process(self._state.process)
showard21baa452008-10-21 00:08:39 +0000842
843
844 def _get_pidfile_info_helper(self):
showard35162b02009-03-03 02:17:30 +0000845 if self.lost_process:
showard21baa452008-10-21 00:08:39 +0000846 return
mblighbb421852008-03-11 22:36:16 +0000847
showard21baa452008-10-21 00:08:39 +0000848 self._read_pidfile()
mblighbb421852008-03-11 22:36:16 +0000849
showard170873e2009-01-07 00:22:26 +0000850 if self._state.process is None:
851 self._handle_no_process()
showard21baa452008-10-21 00:08:39 +0000852 return
mbligh90a549d2008-03-25 23:52:34 +0000853
showard21baa452008-10-21 00:08:39 +0000854 if self._state.exit_status is None:
jadmanski0afbb632008-06-06 21:10:57 +0000855 # double check whether or not autoserv is running
showard170873e2009-01-07 00:22:26 +0000856 if _drone_manager.is_process_running(self._state.process):
showard21baa452008-10-21 00:08:39 +0000857 return
mbligh90a549d2008-03-25 23:52:34 +0000858
showard170873e2009-01-07 00:22:26 +0000859 # pid but no running process - maybe process *just* exited
860 self._read_pidfile(use_second_read=True)
showard21baa452008-10-21 00:08:39 +0000861 if self._state.exit_status is None:
jadmanski0afbb632008-06-06 21:10:57 +0000862 # autoserv exited without writing an exit code
863 # to the pidfile
showard21baa452008-10-21 00:08:39 +0000864 self._handle_pidfile_error(
865 'autoserv died without writing exit code')
mblighbb421852008-03-11 22:36:16 +0000866
showard21baa452008-10-21 00:08:39 +0000867
868 def _get_pidfile_info(self):
869 """\
870 After completion, self._state will contain:
871 pid=None, exit_status=None if autoserv has not yet run
872 pid!=None, exit_status=None if autoserv is running
873 pid!=None, exit_status!=None if autoserv has completed
874 """
875 try:
876 self._get_pidfile_info_helper()
showard170873e2009-01-07 00:22:26 +0000877 except self._PidfileException, exc:
showard21baa452008-10-21 00:08:39 +0000878 self._handle_pidfile_error('Pidfile error', traceback.format_exc())
mblighbb421852008-03-11 22:36:16 +0000879
880
showard170873e2009-01-07 00:22:26 +0000881 def _handle_no_process(self):
jadmanski0afbb632008-06-06 21:10:57 +0000882 """\
883 Called when no pidfile is found or no pid is in the pidfile.
884 """
showard170873e2009-01-07 00:22:26 +0000885 message = 'No pid found at %s' % self.pidfile_id
jadmanski0afbb632008-06-06 21:10:57 +0000886 print message
showard170873e2009-01-07 00:22:26 +0000887 if time.time() - self._start_time > PIDFILE_TIMEOUT:
888 email_manager.manager.enqueue_notify_email(
jadmanski0afbb632008-06-06 21:10:57 +0000889 'Process has failed to write pidfile', message)
showard35162b02009-03-03 02:17:30 +0000890 self.on_lost_process()
mbligh90a549d2008-03-25 23:52:34 +0000891
892
showard35162b02009-03-03 02:17:30 +0000893 def on_lost_process(self, process=None):
jadmanski0afbb632008-06-06 21:10:57 +0000894 """\
895 Called when autoserv has exited without writing an exit status,
896 or we've timed out waiting for autoserv to write a pid to the
897 pidfile. In either case, we just return failure and the caller
898 should signal some kind of warning.
mbligh90a549d2008-03-25 23:52:34 +0000899
showard170873e2009-01-07 00:22:26 +0000900 process is unimportant here, as it shouldn't be used by anyone.
jadmanski0afbb632008-06-06 21:10:57 +0000901 """
902 self.lost_process = True
showard170873e2009-01-07 00:22:26 +0000903 self._state.process = process
showard21baa452008-10-21 00:08:39 +0000904 self._state.exit_status = 1
905 self._state.num_tests_failed = 0
mbligh90a549d2008-03-25 23:52:34 +0000906
907
jadmanski0afbb632008-06-06 21:10:57 +0000908 def exit_code(self):
showard21baa452008-10-21 00:08:39 +0000909 self._get_pidfile_info()
910 return self._state.exit_status
911
912
913 def num_tests_failed(self):
914 self._get_pidfile_info()
915 assert self._state.num_tests_failed is not None
916 return self._state.num_tests_failed
mblighbb421852008-03-11 22:36:16 +0000917
918
mbligh36768f02008-02-22 18:28:33 +0000919class Agent(object):
showard170873e2009-01-07 00:22:26 +0000920 def __init__(self, tasks, num_processes=1):
jadmanski0afbb632008-06-06 21:10:57 +0000921 self.active_task = None
922 self.queue = Queue.Queue(0)
923 self.dispatcher = None
showard4c5374f2008-09-04 17:02:56 +0000924 self.num_processes = num_processes
jadmanski0afbb632008-06-06 21:10:57 +0000925
showard170873e2009-01-07 00:22:26 +0000926 self.queue_entry_ids = self._union_ids(task.queue_entry_ids
927 for task in tasks)
928 self.host_ids = self._union_ids(task.host_ids for task in tasks)
929
jadmanski0afbb632008-06-06 21:10:57 +0000930 for task in tasks:
931 self.add_task(task)
mbligh36768f02008-02-22 18:28:33 +0000932
933
showard170873e2009-01-07 00:22:26 +0000934 def _union_ids(self, id_lists):
935 return set(itertools.chain(*id_lists))
936
937
jadmanski0afbb632008-06-06 21:10:57 +0000938 def add_task(self, task):
939 self.queue.put_nowait(task)
940 task.agent = self
mbligh36768f02008-02-22 18:28:33 +0000941
942
jadmanski0afbb632008-06-06 21:10:57 +0000943 def tick(self):
showard21baa452008-10-21 00:08:39 +0000944 while not self.is_done():
945 if self.active_task and not self.active_task.is_done():
946 self.active_task.poll()
947 if not self.active_task.is_done():
948 return
949 self._next_task()
mbligh36768f02008-02-22 18:28:33 +0000950
951
jadmanski0afbb632008-06-06 21:10:57 +0000952 def _next_task(self):
953 print "agent picking task"
954 if self.active_task:
955 assert self.active_task.is_done()
mbligh36768f02008-02-22 18:28:33 +0000956
jadmanski0afbb632008-06-06 21:10:57 +0000957 if not self.active_task.success:
958 self.on_task_failure()
mblighe2586682008-02-29 22:45:46 +0000959
jadmanski0afbb632008-06-06 21:10:57 +0000960 self.active_task = None
961 if not self.is_done():
962 self.active_task = self.queue.get_nowait()
963 if self.active_task:
964 self.active_task.start()
mbligh36768f02008-02-22 18:28:33 +0000965
966
jadmanski0afbb632008-06-06 21:10:57 +0000967 def on_task_failure(self):
968 self.queue = Queue.Queue(0)
969 for task in self.active_task.failure_tasks:
970 self.add_task(task)
mbligh16c722d2008-03-05 00:58:44 +0000971
mblighe2586682008-02-29 22:45:46 +0000972
showard4c5374f2008-09-04 17:02:56 +0000973 def is_running(self):
jadmanski0afbb632008-06-06 21:10:57 +0000974 return self.active_task is not None
showardec113162008-05-08 00:52:49 +0000975
976
jadmanski0afbb632008-06-06 21:10:57 +0000977 def is_done(self):
mblighd876f452008-12-03 15:09:17 +0000978 return self.active_task is None and self.queue.empty()
mbligh36768f02008-02-22 18:28:33 +0000979
980
jadmanski0afbb632008-06-06 21:10:57 +0000981 def start(self):
982 assert self.dispatcher
mbligh36768f02008-02-22 18:28:33 +0000983
jadmanski0afbb632008-06-06 21:10:57 +0000984 self._next_task()
mbligh36768f02008-02-22 18:28:33 +0000985
jadmanski0afbb632008-06-06 21:10:57 +0000986
mbligh36768f02008-02-22 18:28:33 +0000987class AgentTask(object):
showard170873e2009-01-07 00:22:26 +0000988 def __init__(self, cmd, working_directory=None, failure_tasks=[]):
jadmanski0afbb632008-06-06 21:10:57 +0000989 self.done = False
990 self.failure_tasks = failure_tasks
991 self.started = False
992 self.cmd = cmd
showard170873e2009-01-07 00:22:26 +0000993 self._working_directory = working_directory
jadmanski0afbb632008-06-06 21:10:57 +0000994 self.task = None
995 self.agent = None
996 self.monitor = None
997 self.success = None
showard170873e2009-01-07 00:22:26 +0000998 self.queue_entry_ids = []
999 self.host_ids = []
1000 self.log_file = None
1001
1002
1003 def _set_ids(self, host=None, queue_entries=None):
1004 if queue_entries and queue_entries != [None]:
1005 self.host_ids = [entry.host.id for entry in queue_entries]
1006 self.queue_entry_ids = [entry.id for entry in queue_entries]
1007 else:
1008 assert host
1009 self.host_ids = [host.id]
mbligh36768f02008-02-22 18:28:33 +00001010
1011
jadmanski0afbb632008-06-06 21:10:57 +00001012 def poll(self):
jadmanski0afbb632008-06-06 21:10:57 +00001013 if self.monitor:
1014 self.tick(self.monitor.exit_code())
1015 else:
1016 self.finished(False)
mbligh36768f02008-02-22 18:28:33 +00001017
1018
jadmanski0afbb632008-06-06 21:10:57 +00001019 def tick(self, exit_code):
showard170873e2009-01-07 00:22:26 +00001020 if exit_code is None:
jadmanski0afbb632008-06-06 21:10:57 +00001021 return
jadmanski0afbb632008-06-06 21:10:57 +00001022 if exit_code == 0:
1023 success = True
1024 else:
1025 success = False
mbligh36768f02008-02-22 18:28:33 +00001026
jadmanski0afbb632008-06-06 21:10:57 +00001027 self.finished(success)
mbligh36768f02008-02-22 18:28:33 +00001028
1029
jadmanski0afbb632008-06-06 21:10:57 +00001030 def is_done(self):
1031 return self.done
mbligh36768f02008-02-22 18:28:33 +00001032
1033
jadmanski0afbb632008-06-06 21:10:57 +00001034 def finished(self, success):
1035 self.done = True
1036 self.success = success
1037 self.epilog()
mbligh36768f02008-02-22 18:28:33 +00001038
1039
jadmanski0afbb632008-06-06 21:10:57 +00001040 def prolog(self):
1041 pass
mblighd64e5702008-04-04 21:39:28 +00001042
1043
jadmanski0afbb632008-06-06 21:10:57 +00001044 def create_temp_resultsdir(self, suffix=''):
showard170873e2009-01-07 00:22:26 +00001045 self.temp_results_dir = _drone_manager.get_temporary_path('agent_task')
mblighd64e5702008-04-04 21:39:28 +00001046
mbligh36768f02008-02-22 18:28:33 +00001047
jadmanski0afbb632008-06-06 21:10:57 +00001048 def cleanup(self):
showard170873e2009-01-07 00:22:26 +00001049 if self.monitor and self.log_file:
1050 _drone_manager.copy_to_results_repository(
1051 self.monitor.get_process(), self.log_file)
mbligh36768f02008-02-22 18:28:33 +00001052
1053
jadmanski0afbb632008-06-06 21:10:57 +00001054 def epilog(self):
1055 self.cleanup()
mbligh36768f02008-02-22 18:28:33 +00001056
1057
jadmanski0afbb632008-06-06 21:10:57 +00001058 def start(self):
1059 assert self.agent
1060
1061 if not self.started:
1062 self.prolog()
1063 self.run()
1064
1065 self.started = True
1066
1067
1068 def abort(self):
1069 if self.monitor:
1070 self.monitor.kill()
1071 self.done = True
1072 self.cleanup()
1073
1074
showard170873e2009-01-07 00:22:26 +00001075 def set_host_log_file(self, base_name, host):
1076 filename = '%s.%s' % (time.time(), base_name)
1077 self.log_file = os.path.join('hosts', host.hostname, filename)
1078
1079
showardde634ee2009-01-30 01:44:24 +00001080 def _get_consistent_execution_tag(self, queue_entries):
1081 first_execution_tag = queue_entries[0].execution_tag()
1082 for queue_entry in queue_entries[1:]:
1083 assert queue_entry.execution_tag() == first_execution_tag, (
1084 '%s (%s) != %s (%s)' % (queue_entry.execution_tag(),
1085 queue_entry,
1086 first_execution_tag,
1087 queue_entries[0]))
1088 return first_execution_tag
1089
1090
showard678df4f2009-02-04 21:36:39 +00001091 def _copy_and_parse_results(self, queue_entries):
showardde634ee2009-01-30 01:44:24 +00001092 assert len(queue_entries) > 0
1093 assert self.monitor
1094 execution_tag = self._get_consistent_execution_tag(queue_entries)
showard678df4f2009-02-04 21:36:39 +00001095 results_path = execution_tag + '/'
1096 _drone_manager.copy_to_results_repository(self.monitor.get_process(),
1097 results_path)
showardde634ee2009-01-30 01:44:24 +00001098
1099 reparse_task = FinalReparseTask(queue_entries)
1100 self.agent.dispatcher.add_agent(Agent([reparse_task], num_processes=0))
1101
1102
jadmanski0afbb632008-06-06 21:10:57 +00001103 def run(self):
1104 if self.cmd:
showard170873e2009-01-07 00:22:26 +00001105 self.monitor = PidfileRunMonitor()
1106 self.monitor.run(self.cmd, self._working_directory,
1107 nice_level=AUTOSERV_NICE_LEVEL,
1108 log_file=self.log_file)
mbligh36768f02008-02-22 18:28:33 +00001109
1110
1111class RepairTask(AgentTask):
showarde788ea62008-11-17 21:02:47 +00001112 def __init__(self, host, queue_entry=None):
jadmanski0afbb632008-06-06 21:10:57 +00001113 """\
showard170873e2009-01-07 00:22:26 +00001114 queue_entry: queue entry to mark failed if this repair fails.
jadmanski0afbb632008-06-06 21:10:57 +00001115 """
jadmanskifb7cfb12008-07-09 14:13:21 +00001116 protection = host_protections.Protection.get_string(host.protection)
jadmanski542537f2008-07-24 14:14:56 +00001117 # normalize the protection name
1118 protection = host_protections.Protection.get_attr_name(protection)
showard170873e2009-01-07 00:22:26 +00001119
jadmanski0afbb632008-06-06 21:10:57 +00001120 self.host = host
showarde788ea62008-11-17 21:02:47 +00001121 self.queue_entry = queue_entry
showard170873e2009-01-07 00:22:26 +00001122 self._set_ids(host=host, queue_entries=[queue_entry])
1123
1124 self.create_temp_resultsdir('.repair')
1125 cmd = [_autoserv_path , '-p', '-R', '-m', host.hostname,
1126 '-r', _drone_manager.absolute_path(self.temp_results_dir),
1127 '--host-protection', protection]
1128 super(RepairTask, self).__init__(cmd, self.temp_results_dir)
1129
1130 self._set_ids(host=host, queue_entries=[queue_entry])
1131 self.set_host_log_file('repair', self.host)
mblighe2586682008-02-29 22:45:46 +00001132
mbligh36768f02008-02-22 18:28:33 +00001133
jadmanski0afbb632008-06-06 21:10:57 +00001134 def prolog(self):
1135 print "repair_task starting"
1136 self.host.set_status('Repairing')
showarde788ea62008-11-17 21:02:47 +00001137 if self.queue_entry:
1138 self.queue_entry.requeue()
mbligh36768f02008-02-22 18:28:33 +00001139
1140
showardde634ee2009-01-30 01:44:24 +00001141 def _fail_queue_entry(self):
1142 assert self.queue_entry
1143 self.queue_entry.set_execution_subdir()
showard678df4f2009-02-04 21:36:39 +00001144 # copy results logs into the normal place for job results
1145 _drone_manager.copy_results_on_drone(
1146 self.monitor.get_process(),
1147 source_path=self.temp_results_dir + '/',
1148 destination_path=self.queue_entry.execution_tag() + '/')
1149
1150 self._copy_and_parse_results([self.queue_entry])
showardde634ee2009-01-30 01:44:24 +00001151 self.queue_entry.handle_host_failure()
1152
1153
jadmanski0afbb632008-06-06 21:10:57 +00001154 def epilog(self):
1155 super(RepairTask, self).epilog()
1156 if self.success:
1157 self.host.set_status('Ready')
1158 else:
1159 self.host.set_status('Repair Failed')
showarde788ea62008-11-17 21:02:47 +00001160 if self.queue_entry and not self.queue_entry.meta_host:
showardde634ee2009-01-30 01:44:24 +00001161 self._fail_queue_entry()
mbligh36768f02008-02-22 18:28:33 +00001162
1163
showard8fe93b52008-11-18 17:53:22 +00001164class PreJobTask(AgentTask):
showard170873e2009-01-07 00:22:26 +00001165 def epilog(self):
1166 super(PreJobTask, self).epilog()
showard8fe93b52008-11-18 17:53:22 +00001167 should_copy_results = (self.queue_entry and not self.success
1168 and not self.queue_entry.meta_host)
1169 if should_copy_results:
1170 self.queue_entry.set_execution_subdir()
showard170873e2009-01-07 00:22:26 +00001171 destination = os.path.join(self.queue_entry.execution_tag(),
1172 os.path.basename(self.log_file))
1173 _drone_manager.copy_to_results_repository(
1174 self.monitor.get_process(), self.log_file,
1175 destination_path=destination)
showard8fe93b52008-11-18 17:53:22 +00001176
1177
1178class VerifyTask(PreJobTask):
showard9976ce92008-10-15 20:28:13 +00001179 def __init__(self, queue_entry=None, host=None):
jadmanski0afbb632008-06-06 21:10:57 +00001180 assert bool(queue_entry) != bool(host)
jadmanski0afbb632008-06-06 21:10:57 +00001181 self.host = host or queue_entry.host
1182 self.queue_entry = queue_entry
mbligh36768f02008-02-22 18:28:33 +00001183
jadmanski0afbb632008-06-06 21:10:57 +00001184 self.create_temp_resultsdir('.verify')
showard170873e2009-01-07 00:22:26 +00001185 cmd = [_autoserv_path, '-p', '-v', '-m', self.host.hostname, '-r',
1186 _drone_manager.absolute_path(self.temp_results_dir)]
showarde788ea62008-11-17 21:02:47 +00001187 failure_tasks = [RepairTask(self.host, queue_entry=queue_entry)]
showard170873e2009-01-07 00:22:26 +00001188 super(VerifyTask, self).__init__(cmd, self.temp_results_dir,
1189 failure_tasks=failure_tasks)
mblighe2586682008-02-29 22:45:46 +00001190
showard170873e2009-01-07 00:22:26 +00001191 self.set_host_log_file('verify', self.host)
1192 self._set_ids(host=host, queue_entries=[queue_entry])
mblighe2586682008-02-29 22:45:46 +00001193
1194
jadmanski0afbb632008-06-06 21:10:57 +00001195 def prolog(self):
showard8fe93b52008-11-18 17:53:22 +00001196 super(VerifyTask, self).prolog()
jadmanski0afbb632008-06-06 21:10:57 +00001197 print "starting verify on %s" % (self.host.hostname)
1198 if self.queue_entry:
1199 self.queue_entry.set_status('Verifying')
jadmanski0afbb632008-06-06 21:10:57 +00001200 self.host.set_status('Verifying')
mbligh36768f02008-02-22 18:28:33 +00001201
1202
jadmanski0afbb632008-06-06 21:10:57 +00001203 def epilog(self):
1204 super(VerifyTask, self).epilog()
mbligh36768f02008-02-22 18:28:33 +00001205
jadmanski0afbb632008-06-06 21:10:57 +00001206 if self.success:
1207 self.host.set_status('Ready')
mbligh36768f02008-02-22 18:28:33 +00001208
1209
mbligh36768f02008-02-22 18:28:33 +00001210class QueueTask(AgentTask):
jadmanski0afbb632008-06-06 21:10:57 +00001211 def __init__(self, job, queue_entries, cmd):
jadmanski0afbb632008-06-06 21:10:57 +00001212 self.job = job
1213 self.queue_entries = queue_entries
showard170873e2009-01-07 00:22:26 +00001214 super(QueueTask, self).__init__(cmd, self._execution_tag())
1215 self._set_ids(queue_entries=queue_entries)
mbligh36768f02008-02-22 18:28:33 +00001216
1217
showard170873e2009-01-07 00:22:26 +00001218 def _format_keyval(self, key, value):
1219 return '%s=%s' % (key, value)
mbligh36768f02008-02-22 18:28:33 +00001220
1221
showard73ec0442009-02-07 02:05:20 +00001222 def _keyval_path(self):
1223 return os.path.join(self._execution_tag(), 'keyval')
1224
1225
1226 def _write_keyvals_before_job_helper(self, keyval_dict, keyval_path):
1227 keyval_contents = '\n'.join(self._format_keyval(key, value)
1228 for key, value in keyval_dict.iteritems())
1229 # always end with a newline to allow additional keyvals to be written
1230 keyval_contents += '\n'
1231 _drone_manager.attach_file_to_execution(self._execution_tag(),
1232 keyval_contents,
1233 file_path=keyval_path)
1234
1235
1236 def _write_keyvals_before_job(self, keyval_dict):
1237 self._write_keyvals_before_job_helper(keyval_dict, self._keyval_path())
1238
1239
1240 def _write_keyval_after_job(self, field, value):
showard170873e2009-01-07 00:22:26 +00001241 assert self.monitor and self.monitor.has_process()
showard170873e2009-01-07 00:22:26 +00001242 _drone_manager.write_lines_to_file(
showard73ec0442009-02-07 02:05:20 +00001243 self._keyval_path(), [self._format_keyval(field, value)],
showard35162b02009-03-03 02:17:30 +00001244 paired_with_process=self.monitor.get_process())
showardd8e548a2008-09-09 03:04:57 +00001245
1246
showard170873e2009-01-07 00:22:26 +00001247 def _write_host_keyvals(self, host):
1248 keyval_path = os.path.join(self._execution_tag(), 'host_keyvals',
1249 host.hostname)
1250 platform, all_labels = host.platform_and_labels()
showard73ec0442009-02-07 02:05:20 +00001251 keyval_dict = dict(platform=platform, labels=','.join(all_labels))
1252 self._write_keyvals_before_job_helper(keyval_dict, keyval_path)
showardd8e548a2008-09-09 03:04:57 +00001253
1254
showard170873e2009-01-07 00:22:26 +00001255 def _execution_tag(self):
1256 return self.queue_entries[0].execution_tag()
mblighbb421852008-03-11 22:36:16 +00001257
1258
jadmanski0afbb632008-06-06 21:10:57 +00001259 def prolog(self):
showard73ec0442009-02-07 02:05:20 +00001260 queued = int(time.mktime(self.job.created_on.timetuple()))
1261 self._write_keyvals_before_job({'job_queued': queued})
jadmanski0afbb632008-06-06 21:10:57 +00001262 for queue_entry in self.queue_entries:
showard170873e2009-01-07 00:22:26 +00001263 self._write_host_keyvals(queue_entry.host)
jadmanski0afbb632008-06-06 21:10:57 +00001264 queue_entry.set_status('Running')
1265 queue_entry.host.set_status('Running')
showard21baa452008-10-21 00:08:39 +00001266 queue_entry.host.update_field('dirty', 1)
showard2bab8f42008-11-12 18:15:22 +00001267 if self.job.synch_count == 1:
jadmanski0afbb632008-06-06 21:10:57 +00001268 assert len(self.queue_entries) == 1
1269 self.job.write_to_machines_file(self.queue_entries[0])
mbligh36768f02008-02-22 18:28:33 +00001270
1271
showard35162b02009-03-03 02:17:30 +00001272 def _write_lost_process_error_file(self):
1273 error_file_path = os.path.join(self._execution_tag(), 'job_failure')
1274 _drone_manager.write_lines_to_file(error_file_path,
1275 [_LOST_PROCESS_ERROR])
1276
1277
showard97aed502008-11-04 02:01:24 +00001278 def _finish_task(self, success):
showard35162b02009-03-03 02:17:30 +00001279 if self.monitor.has_process():
1280 self._write_keyval_after_job("job_finished", int(time.time()))
1281 self._copy_and_parse_results(self.queue_entries)
1282
1283 if self.monitor.lost_process:
1284 self._write_lost_process_error_file()
1285 for queue_entry in self.queue_entries:
1286 queue_entry.set_status(models.HostQueueEntry.Status.FAILED)
jadmanskif7fa2cc2008-10-01 14:13:23 +00001287
1288
showardcbd74612008-11-19 21:42:02 +00001289 def _write_status_comment(self, comment):
showard170873e2009-01-07 00:22:26 +00001290 _drone_manager.write_lines_to_file(
1291 os.path.join(self._execution_tag(), 'status.log'),
1292 ['INFO\t----\t----\t' + comment],
showard35162b02009-03-03 02:17:30 +00001293 paired_with_process=self.monitor.get_process())
showardcbd74612008-11-19 21:42:02 +00001294
1295
jadmanskif7fa2cc2008-10-01 14:13:23 +00001296 def _log_abort(self):
showard170873e2009-01-07 00:22:26 +00001297 if not self.monitor or not self.monitor.has_process():
1298 return
1299
jadmanskif7fa2cc2008-10-01 14:13:23 +00001300 # build up sets of all the aborted_by and aborted_on values
1301 aborted_by, aborted_on = set(), set()
1302 for queue_entry in self.queue_entries:
1303 if queue_entry.aborted_by:
1304 aborted_by.add(queue_entry.aborted_by)
1305 t = int(time.mktime(queue_entry.aborted_on.timetuple()))
1306 aborted_on.add(t)
1307
1308 # extract some actual, unique aborted by value and write it out
1309 assert len(aborted_by) <= 1
1310 if len(aborted_by) == 1:
showardcbd74612008-11-19 21:42:02 +00001311 aborted_by_value = aborted_by.pop()
1312 aborted_on_value = max(aborted_on)
1313 else:
1314 aborted_by_value = 'autotest_system'
1315 aborted_on_value = int(time.time())
showard170873e2009-01-07 00:22:26 +00001316
showarda0382352009-02-11 23:36:43 +00001317 self._write_keyval_after_job("aborted_by", aborted_by_value)
1318 self._write_keyval_after_job("aborted_on", aborted_on_value)
showard170873e2009-01-07 00:22:26 +00001319
showardcbd74612008-11-19 21:42:02 +00001320 aborted_on_string = str(datetime.datetime.fromtimestamp(
1321 aborted_on_value))
1322 self._write_status_comment('Job aborted by %s on %s' %
1323 (aborted_by_value, aborted_on_string))
jadmanskic2ac77f2008-05-16 21:44:04 +00001324
1325
jadmanski0afbb632008-06-06 21:10:57 +00001326 def abort(self):
1327 super(QueueTask, self).abort()
jadmanskif7fa2cc2008-10-01 14:13:23 +00001328 self._log_abort()
showard97aed502008-11-04 02:01:24 +00001329 self._finish_task(False)
jadmanskic2ac77f2008-05-16 21:44:04 +00001330
1331
showard21baa452008-10-21 00:08:39 +00001332 def _reboot_hosts(self):
1333 reboot_after = self.job.reboot_after
1334 do_reboot = False
showard0fc38302008-10-23 00:44:07 +00001335 if reboot_after == models.RebootAfter.ALWAYS:
showard21baa452008-10-21 00:08:39 +00001336 do_reboot = True
showard0fc38302008-10-23 00:44:07 +00001337 elif reboot_after == models.RebootAfter.IF_ALL_TESTS_PASSED:
showard21baa452008-10-21 00:08:39 +00001338 num_tests_failed = self.monitor.num_tests_failed()
1339 do_reboot = (self.success and num_tests_failed == 0)
1340
showard8ebca792008-11-04 21:54:22 +00001341 for queue_entry in self.queue_entries:
1342 if do_reboot:
showard45ae8192008-11-05 19:32:53 +00001343 # don't pass the queue entry to the CleanupTask. if the cleanup
showardfa8629c2008-11-04 16:51:23 +00001344 # fails, the job doesn't care -- it's over.
showard45ae8192008-11-05 19:32:53 +00001345 cleanup_task = CleanupTask(host=queue_entry.get_host())
1346 self.agent.dispatcher.add_agent(Agent([cleanup_task]))
showard8ebca792008-11-04 21:54:22 +00001347 else:
1348 queue_entry.host.set_status('Ready')
showard21baa452008-10-21 00:08:39 +00001349
1350
jadmanski0afbb632008-06-06 21:10:57 +00001351 def epilog(self):
1352 super(QueueTask, self).epilog()
showard97aed502008-11-04 02:01:24 +00001353 self._finish_task(self.success)
showard21baa452008-10-21 00:08:39 +00001354 self._reboot_hosts()
mblighbb421852008-03-11 22:36:16 +00001355
showard97aed502008-11-04 02:01:24 +00001356 print "queue_task finished with succes=%s" % self.success
mbligh36768f02008-02-22 18:28:33 +00001357
1358
mblighbb421852008-03-11 22:36:16 +00001359class RecoveryQueueTask(QueueTask):
jadmanski0afbb632008-06-06 21:10:57 +00001360 def __init__(self, job, queue_entries, run_monitor):
showard170873e2009-01-07 00:22:26 +00001361 super(RecoveryQueueTask, self).__init__(job, queue_entries, cmd=None)
jadmanski0afbb632008-06-06 21:10:57 +00001362 self.run_monitor = run_monitor
mblighbb421852008-03-11 22:36:16 +00001363
1364
jadmanski0afbb632008-06-06 21:10:57 +00001365 def run(self):
1366 self.monitor = self.run_monitor
mblighbb421852008-03-11 22:36:16 +00001367
1368
jadmanski0afbb632008-06-06 21:10:57 +00001369 def prolog(self):
1370 # recovering an existing process - don't do prolog
1371 pass
mblighbb421852008-03-11 22:36:16 +00001372
1373
showard8fe93b52008-11-18 17:53:22 +00001374class CleanupTask(PreJobTask):
showardfa8629c2008-11-04 16:51:23 +00001375 def __init__(self, host=None, queue_entry=None):
1376 assert bool(host) ^ bool(queue_entry)
1377 if queue_entry:
1378 host = queue_entry.get_host()
showardfa8629c2008-11-04 16:51:23 +00001379 self.queue_entry = queue_entry
jadmanski0afbb632008-06-06 21:10:57 +00001380 self.host = host
showard170873e2009-01-07 00:22:26 +00001381
1382 self.create_temp_resultsdir('.cleanup')
1383 self.cmd = [_autoserv_path, '-p', '--cleanup', '-m', host.hostname,
1384 '-r', _drone_manager.absolute_path(self.temp_results_dir)]
showarde788ea62008-11-17 21:02:47 +00001385 repair_task = RepairTask(host, queue_entry=queue_entry)
showard170873e2009-01-07 00:22:26 +00001386 super(CleanupTask, self).__init__(self.cmd, self.temp_results_dir,
1387 failure_tasks=[repair_task])
1388
1389 self._set_ids(host=host, queue_entries=[queue_entry])
1390 self.set_host_log_file('cleanup', self.host)
mbligh16c722d2008-03-05 00:58:44 +00001391
mblighd5c95802008-03-05 00:33:46 +00001392
jadmanski0afbb632008-06-06 21:10:57 +00001393 def prolog(self):
showard8fe93b52008-11-18 17:53:22 +00001394 super(CleanupTask, self).prolog()
showard45ae8192008-11-05 19:32:53 +00001395 print "starting cleanup task for host: %s" % self.host.hostname
1396 self.host.set_status("Cleaning")
mblighd5c95802008-03-05 00:33:46 +00001397
mblighd5c95802008-03-05 00:33:46 +00001398
showard21baa452008-10-21 00:08:39 +00001399 def epilog(self):
showard45ae8192008-11-05 19:32:53 +00001400 super(CleanupTask, self).epilog()
showard21baa452008-10-21 00:08:39 +00001401 if self.success:
showardfa8629c2008-11-04 16:51:23 +00001402 self.host.set_status('Ready')
showard21baa452008-10-21 00:08:39 +00001403 self.host.update_field('dirty', 0)
1404
1405
mblighd5c95802008-03-05 00:33:46 +00001406class AbortTask(AgentTask):
jadmanski0afbb632008-06-06 21:10:57 +00001407 def __init__(self, queue_entry, agents_to_abort):
jadmanski0afbb632008-06-06 21:10:57 +00001408 super(AbortTask, self).__init__('')
showard170873e2009-01-07 00:22:26 +00001409 self.queue_entry = queue_entry
1410 # don't use _set_ids, since we don't want to set the host_ids
1411 self.queue_entry_ids = [queue_entry.id]
1412 self.agents_to_abort = agents_to_abort
mbligh36768f02008-02-22 18:28:33 +00001413
1414
jadmanski0afbb632008-06-06 21:10:57 +00001415 def prolog(self):
1416 print "starting abort on host %s, job %s" % (
1417 self.queue_entry.host_id, self.queue_entry.job_id)
mbligh36768f02008-02-22 18:28:33 +00001418
mblighd64e5702008-04-04 21:39:28 +00001419
jadmanski0afbb632008-06-06 21:10:57 +00001420 def epilog(self):
1421 super(AbortTask, self).epilog()
1422 self.queue_entry.set_status('Aborted')
1423 self.success = True
1424
1425
1426 def run(self):
1427 for agent in self.agents_to_abort:
1428 if (agent.active_task):
1429 agent.active_task.abort()
mbligh36768f02008-02-22 18:28:33 +00001430
1431
showard97aed502008-11-04 02:01:24 +00001432class FinalReparseTask(AgentTask):
showard97aed502008-11-04 02:01:24 +00001433 _num_running_parses = 0
1434
1435 def __init__(self, queue_entries):
1436 self._queue_entries = queue_entries
showard170873e2009-01-07 00:22:26 +00001437 # don't use _set_ids, since we don't want to set the host_ids
1438 self.queue_entry_ids = [entry.id for entry in queue_entries]
showard97aed502008-11-04 02:01:24 +00001439 self._parse_started = False
1440
1441 assert len(queue_entries) > 0
1442 queue_entry = queue_entries[0]
showard97aed502008-11-04 02:01:24 +00001443
showard170873e2009-01-07 00:22:26 +00001444 self._execution_tag = queue_entry.execution_tag()
1445 self._results_dir = _drone_manager.absolute_path(self._execution_tag)
1446 self._autoserv_monitor = PidfileRunMonitor()
1447 self._autoserv_monitor.attach_to_existing_process(self._execution_tag)
1448 self._final_status = self._determine_final_status()
1449
showard97aed502008-11-04 02:01:24 +00001450 if _testing_mode:
1451 self.cmd = 'true'
showard170873e2009-01-07 00:22:26 +00001452 else:
1453 super(FinalReparseTask, self).__init__(
1454 cmd=self._generate_parse_command(),
1455 working_directory=self._execution_tag)
showard97aed502008-11-04 02:01:24 +00001456
showard170873e2009-01-07 00:22:26 +00001457 self.log_file = os.path.join(self._execution_tag, '.parse.log')
showard97aed502008-11-04 02:01:24 +00001458
1459
1460 @classmethod
1461 def _increment_running_parses(cls):
1462 cls._num_running_parses += 1
1463
1464
1465 @classmethod
1466 def _decrement_running_parses(cls):
1467 cls._num_running_parses -= 1
1468
1469
1470 @classmethod
1471 def _can_run_new_parse(cls):
showardd1ee1dd2009-01-07 21:33:08 +00001472 return (cls._num_running_parses <
1473 scheduler_config.config.max_parse_processes)
showard97aed502008-11-04 02:01:24 +00001474
1475
showard170873e2009-01-07 00:22:26 +00001476 def _determine_final_status(self):
1477 # we'll use a PidfileRunMonitor to read the autoserv exit status
1478 if self._autoserv_monitor.exit_code() == 0:
1479 return models.HostQueueEntry.Status.COMPLETED
1480 return models.HostQueueEntry.Status.FAILED
1481
1482
showard97aed502008-11-04 02:01:24 +00001483 def prolog(self):
1484 super(FinalReparseTask, self).prolog()
1485 for queue_entry in self._queue_entries:
1486 queue_entry.set_status(models.HostQueueEntry.Status.PARSING)
1487
1488
1489 def epilog(self):
1490 super(FinalReparseTask, self).epilog()
showard97aed502008-11-04 02:01:24 +00001491 for queue_entry in self._queue_entries:
showard170873e2009-01-07 00:22:26 +00001492 queue_entry.set_status(self._final_status)
showard97aed502008-11-04 02:01:24 +00001493
1494
showard2bab8f42008-11-12 18:15:22 +00001495 def _generate_parse_command(self):
showard170873e2009-01-07 00:22:26 +00001496 return [_parser_path, '--write-pidfile', '-l', '2', '-r', '-o',
1497 self._results_dir]
showard97aed502008-11-04 02:01:24 +00001498
1499
1500 def poll(self):
1501 # override poll to keep trying to start until the parse count goes down
1502 # and we can, at which point we revert to default behavior
1503 if self._parse_started:
1504 super(FinalReparseTask, self).poll()
1505 else:
1506 self._try_starting_parse()
1507
1508
1509 def run(self):
1510 # override run() to not actually run unless we can
1511 self._try_starting_parse()
1512
1513
1514 def _try_starting_parse(self):
1515 if not self._can_run_new_parse():
1516 return
showard170873e2009-01-07 00:22:26 +00001517
showard678df4f2009-02-04 21:36:39 +00001518 # make sure we actually have results to parse
showard35162b02009-03-03 02:17:30 +00001519 # this should never happen in normal operation
showard678df4f2009-02-04 21:36:39 +00001520 if not self._autoserv_monitor.has_process():
1521 email_manager.manager.enqueue_notify_email(
1522 'No results to parse',
1523 'No results to parse at %s' % self._autoserv_monitor.pidfile_id)
1524 self.finished(False)
1525 return
1526
showard97aed502008-11-04 02:01:24 +00001527 # actually run the parse command
showard170873e2009-01-07 00:22:26 +00001528 self.monitor = PidfileRunMonitor()
1529 self.monitor.run(self.cmd, self._working_directory,
1530 log_file=self.log_file,
1531 pidfile_name='.parser_execute',
1532 paired_with_pidfile=self._autoserv_monitor.pidfile_id)
1533
showard97aed502008-11-04 02:01:24 +00001534 self._increment_running_parses()
1535 self._parse_started = True
1536
1537
1538 def finished(self, success):
1539 super(FinalReparseTask, self).finished(success)
showard678df4f2009-02-04 21:36:39 +00001540 if self._parse_started:
1541 self._decrement_running_parses()
showard97aed502008-11-04 02:01:24 +00001542
1543
showardc9ae1782009-01-30 01:42:37 +00001544class SetEntryPendingTask(AgentTask):
1545 def __init__(self, queue_entry):
1546 super(SetEntryPendingTask, self).__init__(cmd='')
1547 self._queue_entry = queue_entry
1548 self._set_ids(queue_entries=[queue_entry])
1549
1550
1551 def run(self):
1552 agent = self._queue_entry.on_pending()
1553 if agent:
1554 self.agent.dispatcher.add_agent(agent)
1555 self.finished(True)
1556
1557
showarda3c58572009-03-12 20:36:59 +00001558class DBError(Exception):
1559 """Raised by the DBObject constructor when its select fails."""
1560
1561
mbligh36768f02008-02-22 18:28:33 +00001562class DBObject(object):
showarda3c58572009-03-12 20:36:59 +00001563 """A miniature object relational model for the database."""
showard6ae5ea92009-02-25 00:11:51 +00001564
1565 # Subclasses MUST override these:
1566 _table_name = ''
1567 _fields = ()
1568
showarda3c58572009-03-12 20:36:59 +00001569 # A mapping from (type, id) to the instance of the object for that
1570 # particular id. This prevents us from creating new Job() and Host()
1571 # instances for every HostQueueEntry object that we instantiate as
1572 # multiple HQEs often share the same Job.
1573 _instances_by_type_and_id = weakref.WeakValueDictionary()
1574 _initialized = False
showard6ae5ea92009-02-25 00:11:51 +00001575
showarda3c58572009-03-12 20:36:59 +00001576
1577 def __new__(cls, id=None, **kwargs):
1578 """
1579 Look to see if we already have an instance for this particular type
1580 and id. If so, use it instead of creating a duplicate instance.
1581 """
1582 if id is not None:
1583 instance = cls._instances_by_type_and_id.get((cls, id))
1584 if instance:
1585 return instance
1586 return super(DBObject, cls).__new__(cls, id=id, **kwargs)
1587
1588
1589 def __init__(self, id=None, row=None, new_record=False, always_query=True):
jadmanski0afbb632008-06-06 21:10:57 +00001590 assert (bool(id) != bool(row))
showard6ae5ea92009-02-25 00:11:51 +00001591 assert self._table_name, '_table_name must be defined in your class'
1592 assert self._fields, '_fields must be defined in your class'
showarda3c58572009-03-12 20:36:59 +00001593 if not new_record:
1594 if self._initialized and not always_query:
1595 return # We've already been initialized.
1596 if id is None:
1597 id = row[0]
1598 # Tell future constructors to use us instead of re-querying while
1599 # this instance is still around.
1600 self._instances_by_type_and_id[(type(self), id)] = self
mbligh36768f02008-02-22 18:28:33 +00001601
showard6ae5ea92009-02-25 00:11:51 +00001602 self.__table = self._table_name
mbligh36768f02008-02-22 18:28:33 +00001603
jadmanski0afbb632008-06-06 21:10:57 +00001604 self.__new_record = new_record
mbligh36768f02008-02-22 18:28:33 +00001605
jadmanski0afbb632008-06-06 21:10:57 +00001606 if row is None:
1607 sql = 'SELECT * FROM %s WHERE ID=%%s' % self.__table
1608 rows = _db.execute(sql, (id,))
showarda3c58572009-03-12 20:36:59 +00001609 if not rows:
1610 raise DBError("row not found (table=%s, id=%s)"
1611 % (self.__table, id))
jadmanski0afbb632008-06-06 21:10:57 +00001612 row = rows[0]
mbligh36768f02008-02-22 18:28:33 +00001613
showarda3c58572009-03-12 20:36:59 +00001614 if self._initialized:
1615 differences = self._compare_fields_in_row(row)
1616 if differences:
1617 print ('initialized %s %s instance requery is updating: %s' %
1618 (type(self), self.id, differences))
showard2bab8f42008-11-12 18:15:22 +00001619 self._update_fields_from_row(row)
showarda3c58572009-03-12 20:36:59 +00001620 self._initialized = True
1621
1622
1623 @classmethod
1624 def _clear_instance_cache(cls):
1625 """Used for testing, clear the internal instance cache."""
1626 cls._instances_by_type_and_id.clear()
1627
1628
1629 def _assert_row_length(self, row):
1630 assert len(row) == len(self._fields), (
1631 "table = %s, row = %s/%d, fields = %s/%d" % (
1632 self.__table, row, len(row), self._fields, len(self._fields)))
1633
1634
1635 def _compare_fields_in_row(self, row):
1636 """
1637 Given a row as returned by a SELECT query, compare it to our existing
1638 in memory fields.
1639
1640 @param row - A sequence of values corresponding to fields named in
1641 The class attribute _fields.
1642
1643 @returns A dictionary listing the differences keyed by field name
1644 containing tuples of (current_value, row_value).
1645 """
1646 self._assert_row_length(row)
1647 differences = {}
1648 for field, row_value in itertools.izip(self._fields, row):
1649 current_value = getattr(self, field)
1650 if current_value != row_value:
1651 differences[field] = (current_value, row_value)
1652 return differences
showard2bab8f42008-11-12 18:15:22 +00001653
1654
1655 def _update_fields_from_row(self, row):
showarda3c58572009-03-12 20:36:59 +00001656 """
1657 Update our field attributes using a single row returned by SELECT.
1658
1659 @param row - A sequence of values corresponding to fields named in
1660 the class fields list.
1661 """
1662 self._assert_row_length(row)
mbligh36768f02008-02-22 18:28:33 +00001663
showard2bab8f42008-11-12 18:15:22 +00001664 self._valid_fields = set()
showarda3c58572009-03-12 20:36:59 +00001665 for field, value in itertools.izip(self._fields, row):
showard2bab8f42008-11-12 18:15:22 +00001666 setattr(self, field, value)
1667 self._valid_fields.add(field)
mbligh36768f02008-02-22 18:28:33 +00001668
showard2bab8f42008-11-12 18:15:22 +00001669 self._valid_fields.remove('id')
mbligh36768f02008-02-22 18:28:33 +00001670
mblighe2586682008-02-29 22:45:46 +00001671
jadmanski0afbb632008-06-06 21:10:57 +00001672 def count(self, where, table = None):
1673 if not table:
1674 table = self.__table
mbligh36768f02008-02-22 18:28:33 +00001675
jadmanski0afbb632008-06-06 21:10:57 +00001676 rows = _db.execute("""
1677 SELECT count(*) FROM %s
1678 WHERE %s
1679 """ % (table, where))
mbligh6f8bab42008-02-29 22:45:14 +00001680
jadmanski0afbb632008-06-06 21:10:57 +00001681 assert len(rows) == 1
1682
1683 return int(rows[0][0])
mbligh36768f02008-02-22 18:28:33 +00001684
1685
mblighf8c624d2008-07-03 16:58:45 +00001686 def update_field(self, field, value, condition=''):
showard2bab8f42008-11-12 18:15:22 +00001687 assert field in self._valid_fields
mbligh36768f02008-02-22 18:28:33 +00001688
showard2bab8f42008-11-12 18:15:22 +00001689 if getattr(self, field) == value:
jadmanski0afbb632008-06-06 21:10:57 +00001690 return
mbligh36768f02008-02-22 18:28:33 +00001691
mblighf8c624d2008-07-03 16:58:45 +00001692 query = "UPDATE %s SET %s = %%s WHERE id = %%s" % (self.__table, field)
1693 if condition:
1694 query += ' AND (%s)' % condition
jadmanski0afbb632008-06-06 21:10:57 +00001695 _db.execute(query, (value, self.id))
1696
showard2bab8f42008-11-12 18:15:22 +00001697 setattr(self, field, value)
mbligh36768f02008-02-22 18:28:33 +00001698
1699
jadmanski0afbb632008-06-06 21:10:57 +00001700 def save(self):
1701 if self.__new_record:
showard6ae5ea92009-02-25 00:11:51 +00001702 keys = self._fields[1:] # avoid id
jadmanski0afbb632008-06-06 21:10:57 +00001703 columns = ','.join([str(key) for key in keys])
1704 values = ['"%s"' % self.__dict__[key] for key in keys]
1705 values = ','.join(values)
1706 query = """INSERT INTO %s (%s) VALUES (%s)""" % \
1707 (self.__table, columns, values)
1708 _db.execute(query)
mbligh36768f02008-02-22 18:28:33 +00001709
1710
jadmanski0afbb632008-06-06 21:10:57 +00001711 def delete(self):
showarda3c58572009-03-12 20:36:59 +00001712 self._instances_by_type_and_id.pop((type(self), id), None)
1713 self._initialized = False
1714 self._valid_fields.clear()
jadmanski0afbb632008-06-06 21:10:57 +00001715 query = 'DELETE FROM %s WHERE id=%%s' % self.__table
1716 _db.execute(query, (self.id,))
mblighe2586682008-02-29 22:45:46 +00001717
1718
showard63a34772008-08-18 19:32:50 +00001719 @staticmethod
1720 def _prefix_with(string, prefix):
1721 if string:
1722 string = prefix + string
1723 return string
1724
1725
jadmanski0afbb632008-06-06 21:10:57 +00001726 @classmethod
showard989f25d2008-10-01 11:38:11 +00001727 def fetch(cls, where='', params=(), joins='', order_by=''):
showard63a34772008-08-18 19:32:50 +00001728 order_by = cls._prefix_with(order_by, 'ORDER BY ')
1729 where = cls._prefix_with(where, 'WHERE ')
1730 query = ('SELECT %(table)s.* FROM %(table)s %(joins)s '
showard6ae5ea92009-02-25 00:11:51 +00001731 '%(where)s %(order_by)s' % {'table' : cls._table_name,
showard63a34772008-08-18 19:32:50 +00001732 'joins' : joins,
1733 'where' : where,
1734 'order_by' : order_by})
1735 rows = _db.execute(query, params)
jadmanski0afbb632008-06-06 21:10:57 +00001736 for row in rows:
1737 yield cls(row=row)
mblighe2586682008-02-29 22:45:46 +00001738
mbligh36768f02008-02-22 18:28:33 +00001739
1740class IneligibleHostQueue(DBObject):
showard6ae5ea92009-02-25 00:11:51 +00001741 _table_name = 'ineligible_host_queues'
1742 _fields = ('id', 'job_id', 'host_id')
showard04c82c52008-05-29 19:38:12 +00001743
1744
showard989f25d2008-10-01 11:38:11 +00001745class Label(DBObject):
showard6ae5ea92009-02-25 00:11:51 +00001746 _table_name = 'labels'
1747 _fields = ('id', 'name', 'kernel_config', 'platform', 'invalid',
1748 'only_if_needed')
showard989f25d2008-10-01 11:38:11 +00001749
1750
mbligh36768f02008-02-22 18:28:33 +00001751class Host(DBObject):
showard6ae5ea92009-02-25 00:11:51 +00001752 _table_name = 'hosts'
1753 _fields = ('id', 'hostname', 'locked', 'synch_id', 'status',
1754 'invalid', 'protection', 'locked_by_id', 'lock_time', 'dirty')
1755
1756
jadmanski0afbb632008-06-06 21:10:57 +00001757 def current_task(self):
1758 rows = _db.execute("""
1759 SELECT * FROM host_queue_entries WHERE host_id=%s AND NOT complete AND active
1760 """, (self.id,))
1761
1762 if len(rows) == 0:
1763 return None
1764 else:
1765 assert len(rows) == 1
1766 results = rows[0];
jadmanski0afbb632008-06-06 21:10:57 +00001767 return HostQueueEntry(row=results)
mbligh36768f02008-02-22 18:28:33 +00001768
1769
jadmanski0afbb632008-06-06 21:10:57 +00001770 def yield_work(self):
1771 print "%s yielding work" % self.hostname
1772 if self.current_task():
1773 self.current_task().requeue()
1774
showard6ae5ea92009-02-25 00:11:51 +00001775
jadmanski0afbb632008-06-06 21:10:57 +00001776 def set_status(self,status):
1777 print '%s -> %s' % (self.hostname, status)
1778 self.update_field('status',status)
mbligh36768f02008-02-22 18:28:33 +00001779
1780
showard170873e2009-01-07 00:22:26 +00001781 def platform_and_labels(self):
showardd8e548a2008-09-09 03:04:57 +00001782 """
showard170873e2009-01-07 00:22:26 +00001783 Returns a tuple (platform_name, list_of_all_label_names).
showardd8e548a2008-09-09 03:04:57 +00001784 """
1785 rows = _db.execute("""
showard170873e2009-01-07 00:22:26 +00001786 SELECT labels.name, labels.platform
showardd8e548a2008-09-09 03:04:57 +00001787 FROM labels
1788 INNER JOIN hosts_labels ON labels.id = hosts_labels.label_id
showard170873e2009-01-07 00:22:26 +00001789 WHERE hosts_labels.host_id = %s
showardd8e548a2008-09-09 03:04:57 +00001790 ORDER BY labels.name
1791 """, (self.id,))
showard170873e2009-01-07 00:22:26 +00001792 platform = None
1793 all_labels = []
1794 for label_name, is_platform in rows:
1795 if is_platform:
1796 platform = label_name
1797 all_labels.append(label_name)
1798 return platform, all_labels
1799
1800
1801 def reverify_tasks(self):
1802 cleanup_task = CleanupTask(host=self)
1803 verify_task = VerifyTask(host=self)
1804 # just to make sure this host does not get taken away
1805 self.set_status('Cleaning')
1806 return [cleanup_task, verify_task]
showardd8e548a2008-09-09 03:04:57 +00001807
1808
mbligh36768f02008-02-22 18:28:33 +00001809class HostQueueEntry(DBObject):
showard6ae5ea92009-02-25 00:11:51 +00001810 _table_name = 'host_queue_entries'
1811 _fields = ('id', 'job_id', 'host_id', 'status', 'meta_host',
1812 'active', 'complete', 'deleted', 'execution_subdir')
1813
1814
showarda3c58572009-03-12 20:36:59 +00001815 def __init__(self, id=None, row=None, **kwargs):
jadmanski0afbb632008-06-06 21:10:57 +00001816 assert id or row
showarda3c58572009-03-12 20:36:59 +00001817 super(HostQueueEntry, self).__init__(id=id, row=row, **kwargs)
jadmanski0afbb632008-06-06 21:10:57 +00001818 self.job = Job(self.job_id)
mbligh36768f02008-02-22 18:28:33 +00001819
jadmanski0afbb632008-06-06 21:10:57 +00001820 if self.host_id:
1821 self.host = Host(self.host_id)
1822 else:
1823 self.host = None
mbligh36768f02008-02-22 18:28:33 +00001824
showard170873e2009-01-07 00:22:26 +00001825 self.queue_log_path = os.path.join(self.job.tag(),
jadmanski0afbb632008-06-06 21:10:57 +00001826 'queue.log.' + str(self.id))
mbligh36768f02008-02-22 18:28:33 +00001827
1828
showardc85c21b2008-11-24 22:17:37 +00001829 def _view_job_url(self):
1830 return "%s#tab_id=view_job&object_id=%s" % (_base_url, self.job.id)
1831
1832
jadmanski0afbb632008-06-06 21:10:57 +00001833 def set_host(self, host):
1834 if host:
1835 self.queue_log_record('Assigning host ' + host.hostname)
1836 self.update_field('host_id', host.id)
1837 self.update_field('active', True)
1838 self.block_host(host.id)
1839 else:
1840 self.queue_log_record('Releasing host')
1841 self.unblock_host(self.host.id)
1842 self.update_field('host_id', None)
mbligh36768f02008-02-22 18:28:33 +00001843
jadmanski0afbb632008-06-06 21:10:57 +00001844 self.host = host
mbligh36768f02008-02-22 18:28:33 +00001845
1846
jadmanski0afbb632008-06-06 21:10:57 +00001847 def get_host(self):
1848 return self.host
mbligh36768f02008-02-22 18:28:33 +00001849
1850
jadmanski0afbb632008-06-06 21:10:57 +00001851 def queue_log_record(self, log_line):
1852 now = str(datetime.datetime.now())
showard170873e2009-01-07 00:22:26 +00001853 _drone_manager.write_lines_to_file(self.queue_log_path,
1854 [now + ' ' + log_line])
mbligh36768f02008-02-22 18:28:33 +00001855
1856
jadmanski0afbb632008-06-06 21:10:57 +00001857 def block_host(self, host_id):
1858 print "creating block %s/%s" % (self.job.id, host_id)
1859 row = [0, self.job.id, host_id]
1860 block = IneligibleHostQueue(row=row, new_record=True)
1861 block.save()
mblighe2586682008-02-29 22:45:46 +00001862
1863
jadmanski0afbb632008-06-06 21:10:57 +00001864 def unblock_host(self, host_id):
1865 print "removing block %s/%s" % (self.job.id, host_id)
1866 blocks = IneligibleHostQueue.fetch(
1867 'job_id=%d and host_id=%d' % (self.job.id, host_id))
1868 for block in blocks:
1869 block.delete()
mblighe2586682008-02-29 22:45:46 +00001870
1871
showard2bab8f42008-11-12 18:15:22 +00001872 def set_execution_subdir(self, subdir=None):
1873 if subdir is None:
1874 assert self.get_host()
1875 subdir = self.get_host().hostname
1876 self.update_field('execution_subdir', subdir)
mbligh36768f02008-02-22 18:28:33 +00001877
1878
showard6355f6b2008-12-05 18:52:13 +00001879 def _get_hostname(self):
1880 if self.host:
1881 return self.host.hostname
1882 return 'no host'
1883
1884
showard170873e2009-01-07 00:22:26 +00001885 def __str__(self):
1886 return "%s/%d (%d)" % (self._get_hostname(), self.job.id, self.id)
1887
1888
jadmanski0afbb632008-06-06 21:10:57 +00001889 def set_status(self, status):
mblighf8c624d2008-07-03 16:58:45 +00001890 abort_statuses = ['Abort', 'Aborting', 'Aborted']
1891 if status not in abort_statuses:
1892 condition = ' AND '.join(['status <> "%s"' % x
1893 for x in abort_statuses])
1894 else:
1895 condition = ''
1896 self.update_field('status', status, condition=condition)
1897
showard170873e2009-01-07 00:22:26 +00001898 print "%s -> %s" % (self, self.status)
mblighf8c624d2008-07-03 16:58:45 +00001899
showardc85c21b2008-11-24 22:17:37 +00001900 if status in ['Queued', 'Parsing']:
jadmanski0afbb632008-06-06 21:10:57 +00001901 self.update_field('complete', False)
1902 self.update_field('active', False)
mbligh36768f02008-02-22 18:28:33 +00001903
jadmanski0afbb632008-06-06 21:10:57 +00001904 if status in ['Pending', 'Running', 'Verifying', 'Starting',
showarde58e3f82008-11-20 19:04:59 +00001905 'Aborting']:
jadmanski0afbb632008-06-06 21:10:57 +00001906 self.update_field('complete', False)
1907 self.update_field('active', True)
mbligh36768f02008-02-22 18:28:33 +00001908
showardc85c21b2008-11-24 22:17:37 +00001909 if status in ['Failed', 'Completed', 'Stopped', 'Aborted']:
jadmanski0afbb632008-06-06 21:10:57 +00001910 self.update_field('complete', True)
1911 self.update_field('active', False)
showardc85c21b2008-11-24 22:17:37 +00001912
1913 should_email_status = (status.lower() in _notify_email_statuses or
1914 'all' in _notify_email_statuses)
1915 if should_email_status:
1916 self._email_on_status(status)
1917
1918 self._email_on_job_complete()
1919
1920
1921 def _email_on_status(self, status):
showard6355f6b2008-12-05 18:52:13 +00001922 hostname = self._get_hostname()
showardc85c21b2008-11-24 22:17:37 +00001923
1924 subject = 'Autotest: Job ID: %s "%s" Host: %s %s' % (
1925 self.job.id, self.job.name, hostname, status)
1926 body = "Job ID: %s\nJob Name: %s\nHost: %s\nStatus: %s\n%s\n" % (
1927 self.job.id, self.job.name, hostname, status,
1928 self._view_job_url())
showard170873e2009-01-07 00:22:26 +00001929 email_manager.manager.send_email(self.job.email_list, subject, body)
showard542e8402008-09-19 20:16:18 +00001930
1931
1932 def _email_on_job_complete(self):
showardc85c21b2008-11-24 22:17:37 +00001933 if not self.job.is_finished():
1934 return
showard542e8402008-09-19 20:16:18 +00001935
showardc85c21b2008-11-24 22:17:37 +00001936 summary_text = []
showard6355f6b2008-12-05 18:52:13 +00001937 hosts_queue = HostQueueEntry.fetch('job_id = %s' % self.job.id)
showardc85c21b2008-11-24 22:17:37 +00001938 for queue_entry in hosts_queue:
1939 summary_text.append("Host: %s Status: %s" %
showard6355f6b2008-12-05 18:52:13 +00001940 (queue_entry._get_hostname(),
showardc85c21b2008-11-24 22:17:37 +00001941 queue_entry.status))
1942
1943 summary_text = "\n".join(summary_text)
1944 status_counts = models.Job.objects.get_status_counts(
1945 [self.job.id])[self.job.id]
1946 status = ', '.join('%d %s' % (count, status) for status, count
1947 in status_counts.iteritems())
1948
1949 subject = 'Autotest: Job ID: %s "%s" %s' % (
1950 self.job.id, self.job.name, status)
1951 body = "Job ID: %s\nJob Name: %s\nStatus: %s\n%s\nSummary:\n%s" % (
1952 self.job.id, self.job.name, status, self._view_job_url(),
1953 summary_text)
showard170873e2009-01-07 00:22:26 +00001954 email_manager.manager.send_email(self.job.email_list, subject, body)
mbligh36768f02008-02-22 18:28:33 +00001955
1956
jadmanski0afbb632008-06-06 21:10:57 +00001957 def run(self,assigned_host=None):
1958 if self.meta_host:
1959 assert assigned_host
1960 # ensure results dir exists for the queue log
jadmanski0afbb632008-06-06 21:10:57 +00001961 self.set_host(assigned_host)
mbligh36768f02008-02-22 18:28:33 +00001962
jadmanski0afbb632008-06-06 21:10:57 +00001963 print "%s/%s scheduled on %s, status=%s" % (self.job.name,
1964 self.meta_host, self.host.hostname, self.status)
mbligh36768f02008-02-22 18:28:33 +00001965
jadmanski0afbb632008-06-06 21:10:57 +00001966 return self.job.run(queue_entry=self)
mblighe2586682008-02-29 22:45:46 +00001967
showard6ae5ea92009-02-25 00:11:51 +00001968
jadmanski0afbb632008-06-06 21:10:57 +00001969 def requeue(self):
1970 self.set_status('Queued')
showardde634ee2009-01-30 01:44:24 +00001971 # verify/cleanup failure sets the execution subdir, so reset it here
1972 self.set_execution_subdir('')
jadmanski0afbb632008-06-06 21:10:57 +00001973 if self.meta_host:
1974 self.set_host(None)
mbligh36768f02008-02-22 18:28:33 +00001975
1976
jadmanski0afbb632008-06-06 21:10:57 +00001977 def handle_host_failure(self):
1978 """\
1979 Called when this queue entry's host has failed verification and
1980 repair.
1981 """
1982 assert not self.meta_host
1983 self.set_status('Failed')
showard2bab8f42008-11-12 18:15:22 +00001984 self.job.stop_if_necessary()
mblighe2586682008-02-29 22:45:46 +00001985
1986
jadmanskif7fa2cc2008-10-01 14:13:23 +00001987 @property
1988 def aborted_by(self):
1989 self._load_abort_info()
1990 return self._aborted_by
1991
1992
1993 @property
1994 def aborted_on(self):
1995 self._load_abort_info()
1996 return self._aborted_on
1997
1998
1999 def _load_abort_info(self):
2000 """ Fetch info about who aborted the job. """
2001 if hasattr(self, "_aborted_by"):
2002 return
2003 rows = _db.execute("""
2004 SELECT users.login, aborted_host_queue_entries.aborted_on
2005 FROM aborted_host_queue_entries
2006 INNER JOIN users
2007 ON users.id = aborted_host_queue_entries.aborted_by_id
2008 WHERE aborted_host_queue_entries.queue_entry_id = %s
2009 """, (self.id,))
2010 if rows:
2011 self._aborted_by, self._aborted_on = rows[0]
2012 else:
2013 self._aborted_by = self._aborted_on = None
2014
2015
showardb2e2c322008-10-14 17:33:55 +00002016 def on_pending(self):
2017 """
2018 Called when an entry in a synchronous job has passed verify. If the
2019 job is ready to run, returns an agent to run the job. Returns None
2020 otherwise.
2021 """
2022 self.set_status('Pending')
showardcfd66a32008-10-15 20:31:48 +00002023 self.get_host().set_status('Pending')
showardb2e2c322008-10-14 17:33:55 +00002024 if self.job.is_ready():
2025 return self.job.run(self)
showard2bab8f42008-11-12 18:15:22 +00002026 self.job.stop_if_necessary()
showardb2e2c322008-10-14 17:33:55 +00002027 return None
2028
2029
showard170873e2009-01-07 00:22:26 +00002030 def abort(self, dispatcher, agents_to_abort=[]):
showard1be97432008-10-17 15:30:45 +00002031 host = self.get_host()
showard9d9ffd52008-11-09 23:14:35 +00002032 if self.active and host:
showard170873e2009-01-07 00:22:26 +00002033 dispatcher.add_agent(Agent(tasks=host.reverify_tasks()))
showard1be97432008-10-17 15:30:45 +00002034
showard170873e2009-01-07 00:22:26 +00002035 abort_task = AbortTask(self, agents_to_abort)
showard1be97432008-10-17 15:30:45 +00002036 self.set_status('Aborting')
showard170873e2009-01-07 00:22:26 +00002037 dispatcher.add_agent(Agent(tasks=[abort_task], num_processes=0))
2038
2039 def execution_tag(self):
2040 assert self.execution_subdir
2041 return "%s-%s/%s" % (self.job.id, self.job.owner, self.execution_subdir)
showard1be97432008-10-17 15:30:45 +00002042
2043
mbligh36768f02008-02-22 18:28:33 +00002044class Job(DBObject):
showard6ae5ea92009-02-25 00:11:51 +00002045 _table_name = 'jobs'
2046 _fields = ('id', 'owner', 'name', 'priority', 'control_file',
2047 'control_type', 'created_on', 'synch_count', 'timeout',
2048 'run_verify', 'email_list', 'reboot_before', 'reboot_after')
2049
2050
showarda3c58572009-03-12 20:36:59 +00002051 def __init__(self, id=None, row=None, **kwargs):
jadmanski0afbb632008-06-06 21:10:57 +00002052 assert id or row
showarda3c58572009-03-12 20:36:59 +00002053 super(Job, self).__init__(id=id, row=row, **kwargs)
mbligh36768f02008-02-22 18:28:33 +00002054
mblighe2586682008-02-29 22:45:46 +00002055
jadmanski0afbb632008-06-06 21:10:57 +00002056 def is_server_job(self):
2057 return self.control_type != 2
mbligh36768f02008-02-22 18:28:33 +00002058
2059
showard170873e2009-01-07 00:22:26 +00002060 def tag(self):
2061 return "%s-%s" % (self.id, self.owner)
2062
2063
jadmanski0afbb632008-06-06 21:10:57 +00002064 def get_host_queue_entries(self):
2065 rows = _db.execute("""
2066 SELECT * FROM host_queue_entries
2067 WHERE job_id= %s
2068 """, (self.id,))
2069 entries = [HostQueueEntry(row=i) for i in rows]
mbligh36768f02008-02-22 18:28:33 +00002070
jadmanski0afbb632008-06-06 21:10:57 +00002071 assert len(entries)>0
mbligh36768f02008-02-22 18:28:33 +00002072
jadmanski0afbb632008-06-06 21:10:57 +00002073 return entries
mbligh36768f02008-02-22 18:28:33 +00002074
2075
jadmanski0afbb632008-06-06 21:10:57 +00002076 def set_status(self, status, update_queues=False):
2077 self.update_field('status',status)
2078
2079 if update_queues:
2080 for queue_entry in self.get_host_queue_entries():
2081 queue_entry.set_status(status)
mbligh36768f02008-02-22 18:28:33 +00002082
2083
jadmanski0afbb632008-06-06 21:10:57 +00002084 def is_ready(self):
showard2bab8f42008-11-12 18:15:22 +00002085 pending_entries = models.HostQueueEntry.objects.filter(job=self.id,
2086 status='Pending')
2087 return (pending_entries.count() >= self.synch_count)
mbligh36768f02008-02-22 18:28:33 +00002088
2089
jadmanski0afbb632008-06-06 21:10:57 +00002090 def num_machines(self, clause = None):
2091 sql = "job_id=%s" % self.id
2092 if clause:
2093 sql += " AND (%s)" % clause
2094 return self.count(sql, table='host_queue_entries')
mbligh36768f02008-02-22 18:28:33 +00002095
2096
jadmanski0afbb632008-06-06 21:10:57 +00002097 def num_queued(self):
2098 return self.num_machines('not complete')
mbligh36768f02008-02-22 18:28:33 +00002099
2100
jadmanski0afbb632008-06-06 21:10:57 +00002101 def num_active(self):
2102 return self.num_machines('active')
mbligh36768f02008-02-22 18:28:33 +00002103
2104
jadmanski0afbb632008-06-06 21:10:57 +00002105 def num_complete(self):
2106 return self.num_machines('complete')
mbligh36768f02008-02-22 18:28:33 +00002107
2108
jadmanski0afbb632008-06-06 21:10:57 +00002109 def is_finished(self):
showardc85c21b2008-11-24 22:17:37 +00002110 return self.num_complete() == self.num_machines()
mbligh36768f02008-02-22 18:28:33 +00002111
mbligh36768f02008-02-22 18:28:33 +00002112
showard6bb7c292009-01-30 01:44:51 +00002113 def _not_yet_run_entries(self, include_verifying=True):
2114 statuses = [models.HostQueueEntry.Status.QUEUED,
2115 models.HostQueueEntry.Status.PENDING]
2116 if include_verifying:
2117 statuses.append(models.HostQueueEntry.Status.VERIFYING)
2118 return models.HostQueueEntry.objects.filter(job=self.id,
2119 status__in=statuses)
2120
2121
2122 def _stop_all_entries(self):
2123 entries_to_stop = self._not_yet_run_entries(
2124 include_verifying=False)
2125 for child_entry in entries_to_stop:
showard4f9e5372009-01-07 21:33:38 +00002126 assert not child_entry.complete, (
2127 '%s status=%s, active=%s, complete=%s' %
2128 (child_entry.id, child_entry.status, child_entry.active,
2129 child_entry.complete))
showard2bab8f42008-11-12 18:15:22 +00002130 if child_entry.status == models.HostQueueEntry.Status.PENDING:
2131 child_entry.host.status = models.Host.Status.READY
2132 child_entry.host.save()
2133 child_entry.status = models.HostQueueEntry.Status.STOPPED
2134 child_entry.save()
2135
showard2bab8f42008-11-12 18:15:22 +00002136 def stop_if_necessary(self):
showard6bb7c292009-01-30 01:44:51 +00002137 not_yet_run = self._not_yet_run_entries()
showard2bab8f42008-11-12 18:15:22 +00002138 if not_yet_run.count() < self.synch_count:
showard6bb7c292009-01-30 01:44:51 +00002139 self._stop_all_entries()
mblighe2586682008-02-29 22:45:46 +00002140
2141
jadmanski0afbb632008-06-06 21:10:57 +00002142 def write_to_machines_file(self, queue_entry):
2143 hostname = queue_entry.get_host().hostname
showard170873e2009-01-07 00:22:26 +00002144 file_path = os.path.join(self.tag(), '.machines')
2145 _drone_manager.write_lines_to_file(file_path, [hostname])
mbligh36768f02008-02-22 18:28:33 +00002146
2147
showard2bab8f42008-11-12 18:15:22 +00002148 def _next_group_name(self):
2149 query = models.HostQueueEntry.objects.filter(
2150 job=self.id).values('execution_subdir').distinct()
2151 subdirs = (entry['execution_subdir'] for entry in query)
2152 groups = (re.match(r'group(\d+)', subdir) for subdir in subdirs)
2153 ids = [int(match.group(1)) for match in groups if match]
2154 if ids:
2155 next_id = max(ids) + 1
2156 else:
2157 next_id = 0
2158 return "group%d" % next_id
2159
2160
showard170873e2009-01-07 00:22:26 +00002161 def _write_control_file(self, execution_tag):
2162 control_path = _drone_manager.attach_file_to_execution(
2163 execution_tag, self.control_file)
2164 return control_path
mbligh36768f02008-02-22 18:28:33 +00002165
showardb2e2c322008-10-14 17:33:55 +00002166
showard2bab8f42008-11-12 18:15:22 +00002167 def get_group_entries(self, queue_entry_from_group):
2168 execution_subdir = queue_entry_from_group.execution_subdir
showarde788ea62008-11-17 21:02:47 +00002169 return list(HostQueueEntry.fetch(
2170 where='job_id=%s AND execution_subdir=%s',
2171 params=(self.id, execution_subdir)))
showard2bab8f42008-11-12 18:15:22 +00002172
2173
showardb2e2c322008-10-14 17:33:55 +00002174 def _get_autoserv_params(self, queue_entries):
showard170873e2009-01-07 00:22:26 +00002175 assert queue_entries
2176 execution_tag = queue_entries[0].execution_tag()
2177 control_path = self._write_control_file(execution_tag)
jadmanski0afbb632008-06-06 21:10:57 +00002178 hostnames = ','.join([entry.get_host().hostname
2179 for entry in queue_entries])
mbligh36768f02008-02-22 18:28:33 +00002180
showard170873e2009-01-07 00:22:26 +00002181 params = [_autoserv_path, '-P', execution_tag, '-p', '-n',
2182 '-r', _drone_manager.absolute_path(execution_tag),
2183 '-u', self.owner, '-l', self.name, '-m', hostnames,
2184 _drone_manager.absolute_path(control_path)]
mbligh36768f02008-02-22 18:28:33 +00002185
jadmanski0afbb632008-06-06 21:10:57 +00002186 if not self.is_server_job():
2187 params.append('-c')
mbligh36768f02008-02-22 18:28:33 +00002188
showardb2e2c322008-10-14 17:33:55 +00002189 return params
mblighe2586682008-02-29 22:45:46 +00002190
mbligh36768f02008-02-22 18:28:33 +00002191
showardc9ae1782009-01-30 01:42:37 +00002192 def _should_run_cleanup(self, queue_entry):
showard0fc38302008-10-23 00:44:07 +00002193 if self.reboot_before == models.RebootBefore.ALWAYS:
showardc9ae1782009-01-30 01:42:37 +00002194 return True
showard0fc38302008-10-23 00:44:07 +00002195 elif self.reboot_before == models.RebootBefore.IF_DIRTY:
showardc9ae1782009-01-30 01:42:37 +00002196 return queue_entry.get_host().dirty
2197 return False
showard21baa452008-10-21 00:08:39 +00002198
showardc9ae1782009-01-30 01:42:37 +00002199
2200 def _should_run_verify(self, queue_entry):
2201 do_not_verify = (queue_entry.host.protection ==
2202 host_protections.Protection.DO_NOT_VERIFY)
2203 if do_not_verify:
2204 return False
2205 return self.run_verify
2206
2207
2208 def _get_pre_job_tasks(self, queue_entry):
showard21baa452008-10-21 00:08:39 +00002209 tasks = []
showardc9ae1782009-01-30 01:42:37 +00002210 if self._should_run_cleanup(queue_entry):
showard45ae8192008-11-05 19:32:53 +00002211 tasks.append(CleanupTask(queue_entry=queue_entry))
showardc9ae1782009-01-30 01:42:37 +00002212 if self._should_run_verify(queue_entry):
2213 tasks.append(VerifyTask(queue_entry=queue_entry))
2214 tasks.append(SetEntryPendingTask(queue_entry))
showard21baa452008-10-21 00:08:39 +00002215 return tasks
2216
2217
showard2bab8f42008-11-12 18:15:22 +00002218 def _assign_new_group(self, queue_entries):
2219 if len(queue_entries) == 1:
2220 group_name = queue_entries[0].get_host().hostname
2221 else:
2222 group_name = self._next_group_name()
2223 print 'Running synchronous job %d hosts %s as %s' % (
2224 self.id, [entry.host.hostname for entry in queue_entries],
2225 group_name)
2226
2227 for queue_entry in queue_entries:
2228 queue_entry.set_execution_subdir(group_name)
2229
2230
2231 def _choose_group_to_run(self, include_queue_entry):
2232 chosen_entries = [include_queue_entry]
2233
2234 num_entries_needed = self.synch_count - 1
2235 if num_entries_needed > 0:
2236 pending_entries = HostQueueEntry.fetch(
2237 where='job_id = %s AND status = "Pending" AND id != %s',
2238 params=(self.id, include_queue_entry.id))
2239 chosen_entries += list(pending_entries)[:num_entries_needed]
2240
2241 self._assign_new_group(chosen_entries)
2242 return chosen_entries
2243
2244
2245 def run(self, queue_entry):
showardb2e2c322008-10-14 17:33:55 +00002246 if not self.is_ready():
showardc9ae1782009-01-30 01:42:37 +00002247 queue_entry.set_status(models.HostQueueEntry.Status.VERIFYING)
2248 return Agent(self._get_pre_job_tasks(queue_entry))
mbligh36768f02008-02-22 18:28:33 +00002249
showard2bab8f42008-11-12 18:15:22 +00002250 queue_entries = self._choose_group_to_run(queue_entry)
2251 return self._finish_run(queue_entries)
showardb2e2c322008-10-14 17:33:55 +00002252
2253
2254 def _finish_run(self, queue_entries, initial_tasks=[]):
showardb2ccdda2008-10-28 20:39:05 +00002255 for queue_entry in queue_entries:
2256 queue_entry.set_status('Starting')
showardb2e2c322008-10-14 17:33:55 +00002257 params = self._get_autoserv_params(queue_entries)
2258 queue_task = QueueTask(job=self, queue_entries=queue_entries,
2259 cmd=params)
2260 tasks = initial_tasks + [queue_task]
2261 entry_ids = [entry.id for entry in queue_entries]
2262
showard170873e2009-01-07 00:22:26 +00002263 return Agent(tasks, num_processes=len(queue_entries))
showardb2e2c322008-10-14 17:33:55 +00002264
2265
mbligh36768f02008-02-22 18:28:33 +00002266if __name__ == '__main__':
jadmanski0afbb632008-06-06 21:10:57 +00002267 main()