blob: ee62ed816166d056a1637091d61f69d8b60b960b [file] [log] [blame]
mbligh36768f02008-02-22 18:28:33 +00001#!/usr/bin/python -u
2
3"""
4Autotest scheduler
5"""
showard909c7a62008-07-15 21:52:38 +00006
mbligh36768f02008-02-22 18:28:33 +00007
showard542e8402008-09-19 20:16:18 +00008import datetime, errno, MySQLdb, optparse, os, pwd, Queue, re, shutil, signal
9import smtplib, socket, stat, subprocess, sys, tempfile, time, traceback
showard170873e2009-01-07 00:22:26 +000010import itertools, logging
mbligh70feeee2008-06-11 16:20:49 +000011import common
showard21baa452008-10-21 00:08:39 +000012from autotest_lib.frontend import setup_django_environment
showard542e8402008-09-19 20:16:18 +000013from autotest_lib.client.common_lib import global_config
showard2bab8f42008-11-12 18:15:22 +000014from autotest_lib.client.common_lib import host_protections, utils, debug
showardb1e51872008-10-07 11:08:18 +000015from autotest_lib.database import database_connection
showard21baa452008-10-21 00:08:39 +000016from autotest_lib.frontend.afe import models
showard170873e2009-01-07 00:22:26 +000017from autotest_lib.scheduler import drone_manager, drones, email_manager
showardd1ee1dd2009-01-07 21:33:08 +000018from autotest_lib.scheduler import status_server, scheduler_config
mbligh70feeee2008-06-11 16:20:49 +000019
mblighb090f142008-02-27 21:33:46 +000020
mbligh36768f02008-02-22 18:28:33 +000021RESULTS_DIR = '.'
22AUTOSERV_NICE_LEVEL = 10
showard170873e2009-01-07 00:22:26 +000023DB_CONFIG_SECTION = 'AUTOTEST_WEB'
mbligh36768f02008-02-22 18:28:33 +000024
25AUTOTEST_PATH = os.path.join(os.path.dirname(__file__), '..')
26
27if os.environ.has_key('AUTOTEST_DIR'):
jadmanski0afbb632008-06-06 21:10:57 +000028 AUTOTEST_PATH = os.environ['AUTOTEST_DIR']
mbligh36768f02008-02-22 18:28:33 +000029AUTOTEST_SERVER_DIR = os.path.join(AUTOTEST_PATH, 'server')
30AUTOTEST_TKO_DIR = os.path.join(AUTOTEST_PATH, 'tko')
31
32if AUTOTEST_SERVER_DIR not in sys.path:
jadmanski0afbb632008-06-06 21:10:57 +000033 sys.path.insert(0, AUTOTEST_SERVER_DIR)
mbligh36768f02008-02-22 18:28:33 +000034
mbligh90a549d2008-03-25 23:52:34 +000035# how long to wait for autoserv to write a pidfile
36PIDFILE_TIMEOUT = 5 * 60 # 5 min
mblighbb421852008-03-11 22:36:16 +000037
mbligh6f8bab42008-02-29 22:45:14 +000038_db = None
mbligh36768f02008-02-22 18:28:33 +000039_shutdown = False
showard170873e2009-01-07 00:22:26 +000040_autoserv_path = os.path.join(drones.AUTOTEST_INSTALL_DIR, 'server', 'autoserv')
41_parser_path = os.path.join(drones.AUTOTEST_INSTALL_DIR, 'tko', 'parse')
mbligh4314a712008-02-29 22:44:30 +000042_testing_mode = False
showard542e8402008-09-19 20:16:18 +000043_base_url = None
showardc85c21b2008-11-24 22:17:37 +000044_notify_email_statuses = []
showard170873e2009-01-07 00:22:26 +000045_drone_manager = drone_manager.DroneManager()
mbligh36768f02008-02-22 18:28:33 +000046
47
48def main():
jadmanski0afbb632008-06-06 21:10:57 +000049 usage = 'usage: %prog [options] results_dir'
mbligh36768f02008-02-22 18:28:33 +000050
jadmanski0afbb632008-06-06 21:10:57 +000051 parser = optparse.OptionParser(usage)
52 parser.add_option('--recover-hosts', help='Try to recover dead hosts',
53 action='store_true')
54 parser.add_option('--logfile', help='Set a log file that all stdout ' +
55 'should be redirected to. Stderr will go to this ' +
56 'file + ".err"')
57 parser.add_option('--test', help='Indicate that scheduler is under ' +
58 'test and should use dummy autoserv and no parsing',
59 action='store_true')
60 (options, args) = parser.parse_args()
61 if len(args) != 1:
62 parser.print_usage()
63 return
mbligh36768f02008-02-22 18:28:33 +000064
jadmanski0afbb632008-06-06 21:10:57 +000065 global RESULTS_DIR
66 RESULTS_DIR = args[0]
mbligh36768f02008-02-22 18:28:33 +000067
jadmanski0afbb632008-06-06 21:10:57 +000068 c = global_config.global_config
showardd1ee1dd2009-01-07 21:33:08 +000069 notify_statuses_list = c.get_config_value(scheduler_config.CONFIG_SECTION,
70 "notify_email_statuses",
71 default='')
showardc85c21b2008-11-24 22:17:37 +000072 global _notify_email_statuses
showard170873e2009-01-07 00:22:26 +000073 _notify_email_statuses = [status for status in
74 re.split(r'[\s,;:]', notify_statuses_list.lower())
75 if status]
showardc85c21b2008-11-24 22:17:37 +000076
jadmanski0afbb632008-06-06 21:10:57 +000077 if options.test:
78 global _autoserv_path
79 _autoserv_path = 'autoserv_dummy'
80 global _testing_mode
81 _testing_mode = True
mbligh36768f02008-02-22 18:28:33 +000082
mbligh37eceaa2008-12-15 22:56:37 +000083 # AUTOTEST_WEB.base_url is still a supported config option as some people
84 # may wish to override the entire url.
showard542e8402008-09-19 20:16:18 +000085 global _base_url
showard170873e2009-01-07 00:22:26 +000086 config_base_url = c.get_config_value(DB_CONFIG_SECTION, 'base_url',
87 default='')
mbligh37eceaa2008-12-15 22:56:37 +000088 if config_base_url:
89 _base_url = config_base_url
showard542e8402008-09-19 20:16:18 +000090 else:
mbligh37eceaa2008-12-15 22:56:37 +000091 # For the common case of everything running on a single server you
92 # can just set the hostname in a single place in the config file.
93 server_name = c.get_config_value('SERVER', 'hostname')
94 if not server_name:
95 print 'Error: [SERVER] hostname missing from the config file.'
96 sys.exit(1)
97 _base_url = 'http://%s/afe/' % server_name
showard542e8402008-09-19 20:16:18 +000098
showardd1ee1dd2009-01-07 21:33:08 +000099 server = status_server.StatusServer()
100 server.start()
101
jadmanski0afbb632008-06-06 21:10:57 +0000102 init(options.logfile)
103 dispatcher = Dispatcher()
104 dispatcher.do_initial_recovery(recover_hosts=options.recover_hosts)
105
106 try:
107 while not _shutdown:
108 dispatcher.tick()
showardd1ee1dd2009-01-07 21:33:08 +0000109 time.sleep(scheduler_config.config.tick_pause_sec)
jadmanski0afbb632008-06-06 21:10:57 +0000110 except:
showard170873e2009-01-07 00:22:26 +0000111 email_manager.manager.log_stacktrace(
112 "Uncaught exception; terminating monitor_db")
jadmanski0afbb632008-06-06 21:10:57 +0000113
showard170873e2009-01-07 00:22:26 +0000114 email_manager.manager.send_queued_emails()
115 _drone_manager.shutdown()
jadmanski0afbb632008-06-06 21:10:57 +0000116 _db.disconnect()
mbligh36768f02008-02-22 18:28:33 +0000117
118
119def handle_sigint(signum, frame):
jadmanski0afbb632008-06-06 21:10:57 +0000120 global _shutdown
121 _shutdown = True
122 print "Shutdown request received."
mbligh36768f02008-02-22 18:28:33 +0000123
124
125def init(logfile):
jadmanski0afbb632008-06-06 21:10:57 +0000126 if logfile:
127 enable_logging(logfile)
128 print "%s> dispatcher starting" % time.strftime("%X %x")
129 print "My PID is %d" % os.getpid()
mbligh36768f02008-02-22 18:28:33 +0000130
showardb1e51872008-10-07 11:08:18 +0000131 if _testing_mode:
132 global_config.global_config.override_config_value(
showard170873e2009-01-07 00:22:26 +0000133 DB_CONFIG_SECTION, 'database', 'stresstest_autotest_web')
showardb1e51872008-10-07 11:08:18 +0000134
jadmanski0afbb632008-06-06 21:10:57 +0000135 os.environ['PATH'] = AUTOTEST_SERVER_DIR + ':' + os.environ['PATH']
136 global _db
showard170873e2009-01-07 00:22:26 +0000137 _db = database_connection.DatabaseConnection(DB_CONFIG_SECTION)
jadmanski0afbb632008-06-06 21:10:57 +0000138 _db.connect()
mbligh36768f02008-02-22 18:28:33 +0000139
showardfa8629c2008-11-04 16:51:23 +0000140 # ensure Django connection is in autocommit
141 setup_django_environment.enable_autocommit()
142
showard2bab8f42008-11-12 18:15:22 +0000143 debug.configure('scheduler', format_string='%(message)s')
showard170873e2009-01-07 00:22:26 +0000144 debug.get_logger().setLevel(logging.WARNING)
showard2bab8f42008-11-12 18:15:22 +0000145
jadmanski0afbb632008-06-06 21:10:57 +0000146 print "Setting signal handler"
147 signal.signal(signal.SIGINT, handle_sigint)
148
showardd1ee1dd2009-01-07 21:33:08 +0000149 drones = global_config.global_config.get_config_value(
150 scheduler_config.CONFIG_SECTION, 'drones', default='localhost')
151 drone_list = [hostname.strip() for hostname in drones.split(',')]
showard170873e2009-01-07 00:22:26 +0000152 results_host = global_config.global_config.get_config_value(
showardd1ee1dd2009-01-07 21:33:08 +0000153 scheduler_config.CONFIG_SECTION, 'results_host', default='localhost')
showard170873e2009-01-07 00:22:26 +0000154 _drone_manager.initialize(RESULTS_DIR, drone_list, results_host)
155
jadmanski0afbb632008-06-06 21:10:57 +0000156 print "Connected! Running..."
mbligh36768f02008-02-22 18:28:33 +0000157
158
159def enable_logging(logfile):
jadmanski0afbb632008-06-06 21:10:57 +0000160 out_file = logfile
161 err_file = "%s.err" % logfile
162 print "Enabling logging to %s (%s)" % (out_file, err_file)
163 out_fd = open(out_file, "a", buffering=0)
164 err_fd = open(err_file, "a", buffering=0)
mbligh36768f02008-02-22 18:28:33 +0000165
jadmanski0afbb632008-06-06 21:10:57 +0000166 os.dup2(out_fd.fileno(), sys.stdout.fileno())
167 os.dup2(err_fd.fileno(), sys.stderr.fileno())
mbligh36768f02008-02-22 18:28:33 +0000168
jadmanski0afbb632008-06-06 21:10:57 +0000169 sys.stdout = out_fd
170 sys.stderr = err_fd
mbligh36768f02008-02-22 18:28:33 +0000171
172
mblighd5c95802008-03-05 00:33:46 +0000173def queue_entries_to_abort():
jadmanski0afbb632008-06-06 21:10:57 +0000174 rows = _db.execute("""
175 SELECT * FROM host_queue_entries WHERE status='Abort';
176 """)
showard2bab8f42008-11-12 18:15:22 +0000177
jadmanski0afbb632008-06-06 21:10:57 +0000178 qe = [HostQueueEntry(row=i) for i in rows]
179 return qe
mbligh36768f02008-02-22 18:28:33 +0000180
showard7cf9a9b2008-05-15 21:15:52 +0000181
showard63a34772008-08-18 19:32:50 +0000182class HostScheduler(object):
183 def _get_ready_hosts(self):
184 # avoid any host with a currently active queue entry against it
185 hosts = Host.fetch(
186 joins='LEFT JOIN host_queue_entries AS active_hqe '
187 'ON (hosts.id = active_hqe.host_id AND '
showardb1e51872008-10-07 11:08:18 +0000188 'active_hqe.active)',
showard63a34772008-08-18 19:32:50 +0000189 where="active_hqe.host_id IS NULL "
showardb1e51872008-10-07 11:08:18 +0000190 "AND NOT hosts.locked "
showard63a34772008-08-18 19:32:50 +0000191 "AND (hosts.status IS NULL OR hosts.status = 'Ready')")
192 return dict((host.id, host) for host in hosts)
193
194
195 @staticmethod
196 def _get_sql_id_list(id_list):
197 return ','.join(str(item_id) for item_id in id_list)
198
199
200 @classmethod
showard989f25d2008-10-01 11:38:11 +0000201 def _get_many2many_dict(cls, query, id_list, flip=False):
mbligh849a0f62008-08-28 20:12:19 +0000202 if not id_list:
203 return {}
showard63a34772008-08-18 19:32:50 +0000204 query %= cls._get_sql_id_list(id_list)
205 rows = _db.execute(query)
showard989f25d2008-10-01 11:38:11 +0000206 return cls._process_many2many_dict(rows, flip)
207
208
209 @staticmethod
210 def _process_many2many_dict(rows, flip=False):
showard63a34772008-08-18 19:32:50 +0000211 result = {}
212 for row in rows:
213 left_id, right_id = long(row[0]), long(row[1])
showard989f25d2008-10-01 11:38:11 +0000214 if flip:
215 left_id, right_id = right_id, left_id
showard63a34772008-08-18 19:32:50 +0000216 result.setdefault(left_id, set()).add(right_id)
217 return result
218
219
220 @classmethod
221 def _get_job_acl_groups(cls, job_ids):
222 query = """
223 SELECT jobs.id, acl_groups_users.acl_group_id
224 FROM jobs
225 INNER JOIN users ON users.login = jobs.owner
226 INNER JOIN acl_groups_users ON acl_groups_users.user_id = users.id
227 WHERE jobs.id IN (%s)
228 """
229 return cls._get_many2many_dict(query, job_ids)
230
231
232 @classmethod
233 def _get_job_ineligible_hosts(cls, job_ids):
234 query = """
235 SELECT job_id, host_id
236 FROM ineligible_host_queues
237 WHERE job_id IN (%s)
238 """
239 return cls._get_many2many_dict(query, job_ids)
240
241
242 @classmethod
showard989f25d2008-10-01 11:38:11 +0000243 def _get_job_dependencies(cls, job_ids):
244 query = """
245 SELECT job_id, label_id
246 FROM jobs_dependency_labels
247 WHERE job_id IN (%s)
248 """
249 return cls._get_many2many_dict(query, job_ids)
250
251
252 @classmethod
showard63a34772008-08-18 19:32:50 +0000253 def _get_host_acls(cls, host_ids):
254 query = """
255 SELECT host_id, acl_group_id
256 FROM acl_groups_hosts
257 WHERE host_id IN (%s)
258 """
259 return cls._get_many2many_dict(query, host_ids)
260
261
262 @classmethod
263 def _get_label_hosts(cls, host_ids):
showardfa8629c2008-11-04 16:51:23 +0000264 if not host_ids:
265 return {}, {}
showard63a34772008-08-18 19:32:50 +0000266 query = """
267 SELECT label_id, host_id
268 FROM hosts_labels
269 WHERE host_id IN (%s)
showard989f25d2008-10-01 11:38:11 +0000270 """ % cls._get_sql_id_list(host_ids)
271 rows = _db.execute(query)
272 labels_to_hosts = cls._process_many2many_dict(rows)
273 hosts_to_labels = cls._process_many2many_dict(rows, flip=True)
274 return labels_to_hosts, hosts_to_labels
275
276
277 @classmethod
278 def _get_labels(cls):
279 return dict((label.id, label) for label in Label.fetch())
showard63a34772008-08-18 19:32:50 +0000280
281
282 def refresh(self, pending_queue_entries):
283 self._hosts_available = self._get_ready_hosts()
284
285 relevant_jobs = [queue_entry.job_id
286 for queue_entry in pending_queue_entries]
287 self._job_acls = self._get_job_acl_groups(relevant_jobs)
288 self._ineligible_hosts = self._get_job_ineligible_hosts(relevant_jobs)
showard989f25d2008-10-01 11:38:11 +0000289 self._job_dependencies = self._get_job_dependencies(relevant_jobs)
showard63a34772008-08-18 19:32:50 +0000290
291 host_ids = self._hosts_available.keys()
292 self._host_acls = self._get_host_acls(host_ids)
showard989f25d2008-10-01 11:38:11 +0000293 self._label_hosts, self._host_labels = self._get_label_hosts(host_ids)
294
295 self._labels = self._get_labels()
showard63a34772008-08-18 19:32:50 +0000296
297
298 def _is_acl_accessible(self, host_id, queue_entry):
299 job_acls = self._job_acls.get(queue_entry.job_id, set())
300 host_acls = self._host_acls.get(host_id, set())
301 return len(host_acls.intersection(job_acls)) > 0
302
303
showard989f25d2008-10-01 11:38:11 +0000304 def _check_job_dependencies(self, job_dependencies, host_labels):
305 missing = job_dependencies - host_labels
306 return len(job_dependencies - host_labels) == 0
307
308
309 def _check_only_if_needed_labels(self, job_dependencies, host_labels,
310 queue_entry):
311 for label_id in host_labels:
312 label = self._labels[label_id]
313 if not label.only_if_needed:
314 # we don't care about non-only_if_needed labels
315 continue
316 if queue_entry.meta_host == label_id:
317 # if the label was requested in a metahost it's OK
318 continue
319 if label_id not in job_dependencies:
320 return False
321 return True
322
323
324 def _is_host_eligible_for_job(self, host_id, queue_entry):
325 job_dependencies = self._job_dependencies.get(queue_entry.job_id, set())
326 host_labels = self._host_labels.get(host_id, set())
mblighc993bee2008-10-03 03:42:34 +0000327
328 acl = self._is_acl_accessible(host_id, queue_entry)
329 deps = self._check_job_dependencies(job_dependencies, host_labels)
330 only_if = self._check_only_if_needed_labels(job_dependencies,
331 host_labels, queue_entry)
332 return acl and deps and only_if
showard989f25d2008-10-01 11:38:11 +0000333
334
showard63a34772008-08-18 19:32:50 +0000335 def _schedule_non_metahost(self, queue_entry):
showard989f25d2008-10-01 11:38:11 +0000336 if not self._is_host_eligible_for_job(queue_entry.host_id, queue_entry):
showard63a34772008-08-18 19:32:50 +0000337 return None
338 return self._hosts_available.pop(queue_entry.host_id, None)
339
340
341 def _is_host_usable(self, host_id):
342 if host_id not in self._hosts_available:
343 # host was already used during this scheduling cycle
344 return False
345 if self._hosts_available[host_id].invalid:
346 # Invalid hosts cannot be used for metahosts. They're included in
347 # the original query because they can be used by non-metahosts.
348 return False
349 return True
350
351
352 def _schedule_metahost(self, queue_entry):
353 label_id = queue_entry.meta_host
354 hosts_in_label = self._label_hosts.get(label_id, set())
355 ineligible_host_ids = self._ineligible_hosts.get(queue_entry.job_id,
356 set())
357
358 # must iterate over a copy so we can mutate the original while iterating
359 for host_id in list(hosts_in_label):
360 if not self._is_host_usable(host_id):
361 hosts_in_label.remove(host_id)
362 continue
363 if host_id in ineligible_host_ids:
364 continue
showard989f25d2008-10-01 11:38:11 +0000365 if not self._is_host_eligible_for_job(host_id, queue_entry):
showard63a34772008-08-18 19:32:50 +0000366 continue
367
368 hosts_in_label.remove(host_id)
369 return self._hosts_available.pop(host_id)
370 return None
371
372
373 def find_eligible_host(self, queue_entry):
374 if not queue_entry.meta_host:
375 return self._schedule_non_metahost(queue_entry)
376 return self._schedule_metahost(queue_entry)
377
378
showard170873e2009-01-07 00:22:26 +0000379class Dispatcher(object):
jadmanski0afbb632008-06-06 21:10:57 +0000380 def __init__(self):
381 self._agents = []
showard3bb499f2008-07-03 19:42:20 +0000382 self._last_clean_time = time.time()
showard63a34772008-08-18 19:32:50 +0000383 self._host_scheduler = HostScheduler()
showard170873e2009-01-07 00:22:26 +0000384 self._host_agents = {}
385 self._queue_entry_agents = {}
mbligh36768f02008-02-22 18:28:33 +0000386
mbligh36768f02008-02-22 18:28:33 +0000387
jadmanski0afbb632008-06-06 21:10:57 +0000388 def do_initial_recovery(self, recover_hosts=True):
389 # always recover processes
390 self._recover_processes()
mblighbb421852008-03-11 22:36:16 +0000391
jadmanski0afbb632008-06-06 21:10:57 +0000392 if recover_hosts:
393 self._recover_hosts()
mbligh36768f02008-02-22 18:28:33 +0000394
395
jadmanski0afbb632008-06-06 21:10:57 +0000396 def tick(self):
showard170873e2009-01-07 00:22:26 +0000397 _drone_manager.refresh()
showarda3ab0d52008-11-03 19:03:47 +0000398 self._run_cleanup_maybe()
jadmanski0afbb632008-06-06 21:10:57 +0000399 self._find_aborting()
400 self._schedule_new_jobs()
401 self._handle_agents()
showard170873e2009-01-07 00:22:26 +0000402 _drone_manager.execute_actions()
403 email_manager.manager.send_queued_emails()
mbligh36768f02008-02-22 18:28:33 +0000404
showard97aed502008-11-04 02:01:24 +0000405
showarda3ab0d52008-11-03 19:03:47 +0000406 def _run_cleanup_maybe(self):
showardd1ee1dd2009-01-07 21:33:08 +0000407 should_cleanup = (self._last_clean_time +
408 scheduler_config.config.clean_interval * 60 <
409 time.time())
410 if should_cleanup:
showarda3ab0d52008-11-03 19:03:47 +0000411 print 'Running cleanup'
412 self._abort_timed_out_jobs()
413 self._abort_jobs_past_synch_start_timeout()
414 self._clear_inactive_blocks()
showardfa8629c2008-11-04 16:51:23 +0000415 self._check_for_db_inconsistencies()
showarda3ab0d52008-11-03 19:03:47 +0000416 self._last_clean_time = time.time()
417
mbligh36768f02008-02-22 18:28:33 +0000418
showard170873e2009-01-07 00:22:26 +0000419 def _register_agent_for_ids(self, agent_dict, object_ids, agent):
420 for object_id in object_ids:
421 agent_dict.setdefault(object_id, set()).add(agent)
422
423
424 def _unregister_agent_for_ids(self, agent_dict, object_ids, agent):
425 for object_id in object_ids:
426 assert object_id in agent_dict
427 agent_dict[object_id].remove(agent)
428
429
jadmanski0afbb632008-06-06 21:10:57 +0000430 def add_agent(self, agent):
431 self._agents.append(agent)
432 agent.dispatcher = self
showard170873e2009-01-07 00:22:26 +0000433 self._register_agent_for_ids(self._host_agents, agent.host_ids, agent)
434 self._register_agent_for_ids(self._queue_entry_agents,
435 agent.queue_entry_ids, agent)
mblighd5c95802008-03-05 00:33:46 +0000436
showard170873e2009-01-07 00:22:26 +0000437
438 def get_agents_for_entry(self, queue_entry):
439 """
440 Find agents corresponding to the specified queue_entry.
441 """
442 return self._queue_entry_agents.get(queue_entry.id, set())
443
444
445 def host_has_agent(self, host):
446 """
447 Determine if there is currently an Agent present using this host.
448 """
449 return bool(self._host_agents.get(host.id, None))
mbligh36768f02008-02-22 18:28:33 +0000450
451
jadmanski0afbb632008-06-06 21:10:57 +0000452 def remove_agent(self, agent):
453 self._agents.remove(agent)
showard170873e2009-01-07 00:22:26 +0000454 self._unregister_agent_for_ids(self._host_agents, agent.host_ids,
455 agent)
456 self._unregister_agent_for_ids(self._queue_entry_agents,
457 agent.queue_entry_ids, agent)
showardec113162008-05-08 00:52:49 +0000458
459
showard4c5374f2008-09-04 17:02:56 +0000460 def num_running_processes(self):
461 return sum(agent.num_processes for agent in self._agents
462 if agent.is_running())
mblighbb421852008-03-11 22:36:16 +0000463
464
showard170873e2009-01-07 00:22:26 +0000465 def _extract_execution_tag(self, command_line):
466 match = re.match(r'.* -P (\S+) ', command_line)
467 if not match:
468 return None
469 return match.group(1)
mblighbb421852008-03-11 22:36:16 +0000470
471
showard2bab8f42008-11-12 18:15:22 +0000472 def _recover_queue_entries(self, queue_entries, run_monitor):
473 assert len(queue_entries) > 0
showard2bab8f42008-11-12 18:15:22 +0000474 queue_task = RecoveryQueueTask(job=queue_entries[0].job,
475 queue_entries=queue_entries,
476 run_monitor=run_monitor)
jadmanski0afbb632008-06-06 21:10:57 +0000477 self.add_agent(Agent(tasks=[queue_task],
showard170873e2009-01-07 00:22:26 +0000478 num_processes=len(queue_entries)))
mblighbb421852008-03-11 22:36:16 +0000479
480
jadmanski0afbb632008-06-06 21:10:57 +0000481 def _recover_processes(self):
showard170873e2009-01-07 00:22:26 +0000482 self._register_pidfiles()
483 _drone_manager.refresh()
484 self._recover_running_entries()
485 self._recover_aborting_entries()
486 self._requeue_other_active_entries()
487 self._recover_parsing_entries()
488 self._reverify_remaining_hosts()
489 # reinitialize drones after killing orphaned processes, since they can
490 # leave around files when they die
491 _drone_manager.execute_actions()
492 _drone_manager.reinitialize_drones()
mblighbb421852008-03-11 22:36:16 +0000493
showard170873e2009-01-07 00:22:26 +0000494
495 def _register_pidfiles(self):
496 # during recovery we may need to read pidfiles for both running and
497 # parsing entries
498 queue_entries = HostQueueEntry.fetch(
499 where="status IN ('Running', 'Parsing')")
jadmanski0afbb632008-06-06 21:10:57 +0000500 for queue_entry in queue_entries:
showard170873e2009-01-07 00:22:26 +0000501 pidfile_id = _drone_manager.get_pidfile_id_from(
502 queue_entry.execution_tag())
503 _drone_manager.register_pidfile(pidfile_id)
504
505
506 def _recover_running_entries(self):
507 orphans = _drone_manager.get_orphaned_autoserv_processes()
508
509 queue_entries = HostQueueEntry.fetch(where="status = 'Running'")
510 requeue_entries = []
511 for queue_entry in queue_entries:
512 if self.get_agents_for_entry(queue_entry):
jadmanski0afbb632008-06-06 21:10:57 +0000513 # synchronous job we've already recovered
514 continue
showard170873e2009-01-07 00:22:26 +0000515 execution_tag = queue_entry.execution_tag()
516 run_monitor = PidfileRunMonitor()
517 run_monitor.attach_to_existing_process(execution_tag)
518 if not run_monitor.has_process():
519 # autoserv apparently never got run, so let it get requeued
520 continue
showarde788ea62008-11-17 21:02:47 +0000521 queue_entries = queue_entry.job.get_group_entries(queue_entry)
showard170873e2009-01-07 00:22:26 +0000522 print 'Recovering %s (process %s)' % (
523 ', '.join(str(entry) for entry in queue_entries),
524 run_monitor.get_process())
showard2bab8f42008-11-12 18:15:22 +0000525 self._recover_queue_entries(queue_entries, run_monitor)
showard170873e2009-01-07 00:22:26 +0000526 orphans.pop(execution_tag, None)
mbligh90a549d2008-03-25 23:52:34 +0000527
jadmanski0afbb632008-06-06 21:10:57 +0000528 # now kill any remaining autoserv processes
showard170873e2009-01-07 00:22:26 +0000529 for process in orphans.itervalues():
530 print 'Killing orphan %s' % process
531 _drone_manager.kill_process(process)
jadmanski0afbb632008-06-06 21:10:57 +0000532
showard170873e2009-01-07 00:22:26 +0000533
534 def _recover_aborting_entries(self):
535 queue_entries = HostQueueEntry.fetch(
536 where='status IN ("Abort", "Aborting")')
jadmanski0afbb632008-06-06 21:10:57 +0000537 for queue_entry in queue_entries:
showard170873e2009-01-07 00:22:26 +0000538 print 'Recovering aborting QE %s' % queue_entry
539 agent = queue_entry.abort(self)
jadmanski0afbb632008-06-06 21:10:57 +0000540
showard97aed502008-11-04 02:01:24 +0000541
showard170873e2009-01-07 00:22:26 +0000542 def _requeue_other_active_entries(self):
543 queue_entries = HostQueueEntry.fetch(
544 where='active AND NOT complete AND status != "Pending"')
545 for queue_entry in queue_entries:
546 if self.get_agents_for_entry(queue_entry):
547 # entry has already been recovered
548 continue
549 print 'Requeuing active QE %s (status=%s)' % (queue_entry,
550 queue_entry.status)
551 if queue_entry.host:
552 tasks = queue_entry.host.reverify_tasks()
553 self.add_agent(Agent(tasks))
554 agent = queue_entry.requeue()
555
556
557 def _reverify_remaining_hosts(self):
showard45ae8192008-11-05 19:32:53 +0000558 # reverify hosts that were in the middle of verify, repair or cleanup
jadmanski0afbb632008-06-06 21:10:57 +0000559 self._reverify_hosts_where("""(status = 'Repairing' OR
560 status = 'Verifying' OR
showard170873e2009-01-07 00:22:26 +0000561 status = 'Cleaning')""")
jadmanski0afbb632008-06-06 21:10:57 +0000562
showard170873e2009-01-07 00:22:26 +0000563 # recover "Running" hosts with no active queue entries, although this
564 # should never happen
565 message = ('Recovering running host %s - this probably indicates a '
566 'scheduler bug')
jadmanski0afbb632008-06-06 21:10:57 +0000567 self._reverify_hosts_where("""status = 'Running' AND
568 id NOT IN (SELECT host_id
569 FROM host_queue_entries
570 WHERE active)""",
571 print_message=message)
mblighbb421852008-03-11 22:36:16 +0000572
573
jadmanski0afbb632008-06-06 21:10:57 +0000574 def _reverify_hosts_where(self, where,
showard170873e2009-01-07 00:22:26 +0000575 print_message='Reverifying host %s'):
576 full_where='locked = 0 AND invalid = 0 AND ' + where
577 for host in Host.fetch(where=full_where):
578 if self.host_has_agent(host):
579 # host has already been recovered in some way
jadmanski0afbb632008-06-06 21:10:57 +0000580 continue
showard170873e2009-01-07 00:22:26 +0000581 if print_message:
jadmanski0afbb632008-06-06 21:10:57 +0000582 print print_message % host.hostname
showard170873e2009-01-07 00:22:26 +0000583 tasks = host.reverify_tasks()
584 self.add_agent(Agent(tasks))
mbligh36768f02008-02-22 18:28:33 +0000585
586
showard97aed502008-11-04 02:01:24 +0000587 def _recover_parsing_entries(self):
showard2bab8f42008-11-12 18:15:22 +0000588 recovered_entry_ids = set()
showard97aed502008-11-04 02:01:24 +0000589 for entry in HostQueueEntry.fetch(where='status = "Parsing"'):
showard2bab8f42008-11-12 18:15:22 +0000590 if entry.id in recovered_entry_ids:
591 continue
592 queue_entries = entry.job.get_group_entries(entry)
showard170873e2009-01-07 00:22:26 +0000593 recovered_entry_ids = recovered_entry_ids.union(
594 entry.id for entry in queue_entries)
595 print 'Recovering parsing entries %s' % (
596 ', '.join(str(entry) for entry in queue_entries))
showard97aed502008-11-04 02:01:24 +0000597
598 reparse_task = FinalReparseTask(queue_entries)
showard170873e2009-01-07 00:22:26 +0000599 self.add_agent(Agent([reparse_task], num_processes=0))
showard97aed502008-11-04 02:01:24 +0000600
601
jadmanski0afbb632008-06-06 21:10:57 +0000602 def _recover_hosts(self):
603 # recover "Repair Failed" hosts
604 message = 'Reverifying dead host %s'
605 self._reverify_hosts_where("status = 'Repair Failed'",
606 print_message=message)
mbligh62ba2ed2008-04-30 17:09:25 +0000607
608
showard3bb499f2008-07-03 19:42:20 +0000609 def _abort_timed_out_jobs(self):
610 """
611 Aborts all jobs that have timed out and not completed
612 """
showarda3ab0d52008-11-03 19:03:47 +0000613 query = models.Job.objects.filter(hostqueueentry__complete=False).extra(
614 where=['created_on + INTERVAL timeout HOUR < NOW()'])
615 for job in query.distinct():
616 print 'Aborting job %d due to job timeout' % job.id
617 job.abort(None)
showard3bb499f2008-07-03 19:42:20 +0000618
619
showard98863972008-10-29 21:14:56 +0000620 def _abort_jobs_past_synch_start_timeout(self):
621 """
622 Abort synchronous jobs that are past the start timeout (from global
623 config) and are holding a machine that's in everyone.
624 """
625 timeout_delta = datetime.timedelta(
showardd1ee1dd2009-01-07 21:33:08 +0000626 minutes=scheduler_config.config.synch_job_start_timeout_minutes)
showard98863972008-10-29 21:14:56 +0000627 timeout_start = datetime.datetime.now() - timeout_delta
628 query = models.Job.objects.filter(
showard98863972008-10-29 21:14:56 +0000629 created_on__lt=timeout_start,
630 hostqueueentry__status='Pending',
631 hostqueueentry__host__acl_group__name='Everyone')
632 for job in query.distinct():
633 print 'Aborting job %d due to start timeout' % job.id
showardff059d72008-12-03 18:18:53 +0000634 entries_to_abort = job.hostqueueentry_set.exclude(
635 status=models.HostQueueEntry.Status.RUNNING)
636 for queue_entry in entries_to_abort:
637 queue_entry.abort(None)
showard98863972008-10-29 21:14:56 +0000638
639
jadmanski0afbb632008-06-06 21:10:57 +0000640 def _clear_inactive_blocks(self):
641 """
642 Clear out blocks for all completed jobs.
643 """
644 # this would be simpler using NOT IN (subquery), but MySQL
645 # treats all IN subqueries as dependent, so this optimizes much
646 # better
647 _db.execute("""
648 DELETE ihq FROM ineligible_host_queues ihq
showard4eaaf522008-06-06 22:28:07 +0000649 LEFT JOIN (SELECT DISTINCT job_id FROM host_queue_entries
jadmanski0afbb632008-06-06 21:10:57 +0000650 WHERE NOT complete) hqe
651 USING (job_id) WHERE hqe.job_id IS NULL""")
showard04c82c52008-05-29 19:38:12 +0000652
653
showardb95b1bd2008-08-15 18:11:04 +0000654 def _get_pending_queue_entries(self):
showard63a34772008-08-18 19:32:50 +0000655 # prioritize by job priority, then non-metahost over metahost, then FIFO
656 return list(HostQueueEntry.fetch(
showardac9ce222008-12-03 18:19:44 +0000657 where='NOT complete AND NOT active AND status="Queued"',
showard3dd6b882008-10-27 19:21:39 +0000658 order_by='priority DESC, meta_host, job_id'))
mbligh36768f02008-02-22 18:28:33 +0000659
660
jadmanski0afbb632008-06-06 21:10:57 +0000661 def _schedule_new_jobs(self):
showard63a34772008-08-18 19:32:50 +0000662 queue_entries = self._get_pending_queue_entries()
663 if not queue_entries:
showardb95b1bd2008-08-15 18:11:04 +0000664 return
showardb95b1bd2008-08-15 18:11:04 +0000665
showard63a34772008-08-18 19:32:50 +0000666 self._host_scheduler.refresh(queue_entries)
showardb95b1bd2008-08-15 18:11:04 +0000667
showard63a34772008-08-18 19:32:50 +0000668 for queue_entry in queue_entries:
669 assigned_host = self._host_scheduler.find_eligible_host(queue_entry)
showardb95b1bd2008-08-15 18:11:04 +0000670 if not assigned_host:
jadmanski0afbb632008-06-06 21:10:57 +0000671 continue
showardb95b1bd2008-08-15 18:11:04 +0000672 self._run_queue_entry(queue_entry, assigned_host)
673
674
675 def _run_queue_entry(self, queue_entry, host):
676 agent = queue_entry.run(assigned_host=host)
showard170873e2009-01-07 00:22:26 +0000677 # in some cases (synchronous jobs with run_verify=False), agent may be
678 # None
showard9976ce92008-10-15 20:28:13 +0000679 if agent:
680 self.add_agent(agent)
mblighd5c95802008-03-05 00:33:46 +0000681
682
jadmanski0afbb632008-06-06 21:10:57 +0000683 def _find_aborting(self):
jadmanski0afbb632008-06-06 21:10:57 +0000684 for entry in queue_entries_to_abort():
showard170873e2009-01-07 00:22:26 +0000685 agents_to_abort = list(self.get_agents_for_entry(entry))
showard1be97432008-10-17 15:30:45 +0000686 for agent in agents_to_abort:
687 self.remove_agent(agent)
688
showard170873e2009-01-07 00:22:26 +0000689 entry.abort(self, agents_to_abort)
jadmanski0afbb632008-06-06 21:10:57 +0000690
691
showard4c5374f2008-09-04 17:02:56 +0000692 def _can_start_agent(self, agent, num_running_processes,
693 num_started_this_cycle, have_reached_limit):
694 # always allow zero-process agents to run
695 if agent.num_processes == 0:
696 return True
697 # don't allow any nonzero-process agents to run after we've reached a
698 # limit (this avoids starvation of many-process agents)
699 if have_reached_limit:
700 return False
701 # total process throttling
702 if (num_running_processes + agent.num_processes >
showardd1ee1dd2009-01-07 21:33:08 +0000703 scheduler_config.config.max_running_processes):
showard4c5374f2008-09-04 17:02:56 +0000704 return False
705 # if a single agent exceeds the per-cycle throttling, still allow it to
706 # run when it's the first agent in the cycle
707 if num_started_this_cycle == 0:
708 return True
709 # per-cycle throttling
710 if (num_started_this_cycle + agent.num_processes >
showardd1ee1dd2009-01-07 21:33:08 +0000711 scheduler_config.config.max_processes_started_per_cycle):
showard4c5374f2008-09-04 17:02:56 +0000712 return False
713 return True
714
715
jadmanski0afbb632008-06-06 21:10:57 +0000716 def _handle_agents(self):
showard4c5374f2008-09-04 17:02:56 +0000717 num_running_processes = self.num_running_processes()
jadmanski0afbb632008-06-06 21:10:57 +0000718 num_started_this_cycle = 0
showard4c5374f2008-09-04 17:02:56 +0000719 have_reached_limit = False
720 # iterate over copy, so we can remove agents during iteration
721 for agent in list(self._agents):
722 if agent.is_done():
jadmanski0afbb632008-06-06 21:10:57 +0000723 print "agent finished"
showard170873e2009-01-07 00:22:26 +0000724 self.remove_agent(agent)
showard4c5374f2008-09-04 17:02:56 +0000725 continue
726 if not agent.is_running():
727 if not self._can_start_agent(agent, num_running_processes,
728 num_started_this_cycle,
729 have_reached_limit):
730 have_reached_limit = True
731 continue
732 num_running_processes += agent.num_processes
733 num_started_this_cycle += agent.num_processes
734 agent.tick()
735 print num_running_processes, 'running processes'
mbligh36768f02008-02-22 18:28:33 +0000736
737
showardfa8629c2008-11-04 16:51:23 +0000738 def _check_for_db_inconsistencies(self):
739 query = models.HostQueueEntry.objects.filter(active=True, complete=True)
740 if query.count() != 0:
741 subject = ('%d queue entries found with active=complete=1'
742 % query.count())
743 message = '\n'.join(str(entry.get_object_dict())
744 for entry in query[:50])
745 if len(query) > 50:
746 message += '\n(truncated)\n'
747
748 print subject
showard170873e2009-01-07 00:22:26 +0000749 email_manager.manager.enqueue_notify_email(subject, message)
showardfa8629c2008-11-04 16:51:23 +0000750
751
showard170873e2009-01-07 00:22:26 +0000752class PidfileRunMonitor(object):
753 """
754 Client must call either run() to start a new process or
755 attach_to_existing_process().
756 """
mbligh36768f02008-02-22 18:28:33 +0000757
showard170873e2009-01-07 00:22:26 +0000758 class _PidfileException(Exception):
759 """
760 Raised when there's some unexpected behavior with the pid file, but only
761 used internally (never allowed to escape this class).
762 """
mbligh36768f02008-02-22 18:28:33 +0000763
764
showard170873e2009-01-07 00:22:26 +0000765 def __init__(self):
766 self._lost_process = False
767 self._start_time = None
768 self.pidfile_id = None
769 self._state = drone_manager.PidfileContents()
showard2bab8f42008-11-12 18:15:22 +0000770
771
showard170873e2009-01-07 00:22:26 +0000772 def _add_nice_command(self, command, nice_level):
773 if not nice_level:
774 return command
775 return ['nice', '-n', str(nice_level)] + command
776
777
778 def _set_start_time(self):
779 self._start_time = time.time()
780
781
782 def run(self, command, working_directory, nice_level=None, log_file=None,
783 pidfile_name=None, paired_with_pidfile=None):
784 assert command is not None
785 if nice_level is not None:
786 command = ['nice', '-n', str(nice_level)] + command
787 self._set_start_time()
788 self.pidfile_id = _drone_manager.execute_command(
789 command, working_directory, log_file=log_file,
790 pidfile_name=pidfile_name, paired_with_pidfile=paired_with_pidfile)
791
792
793 def attach_to_existing_process(self, execution_tag):
794 self._set_start_time()
795 self.pidfile_id = _drone_manager.get_pidfile_id_from(execution_tag)
796 _drone_manager.register_pidfile(self.pidfile_id)
mblighbb421852008-03-11 22:36:16 +0000797
798
jadmanski0afbb632008-06-06 21:10:57 +0000799 def kill(self):
showard170873e2009-01-07 00:22:26 +0000800 if self.has_process():
801 _drone_manager.kill_process(self.get_process())
mblighbb421852008-03-11 22:36:16 +0000802
mbligh36768f02008-02-22 18:28:33 +0000803
showard170873e2009-01-07 00:22:26 +0000804 def has_process(self):
showard21baa452008-10-21 00:08:39 +0000805 self._get_pidfile_info()
showard170873e2009-01-07 00:22:26 +0000806 return self._state.process is not None
showard21baa452008-10-21 00:08:39 +0000807
808
showard170873e2009-01-07 00:22:26 +0000809 def get_process(self):
showard21baa452008-10-21 00:08:39 +0000810 self._get_pidfile_info()
showard170873e2009-01-07 00:22:26 +0000811 assert self.has_process()
812 return self._state.process
mblighbb421852008-03-11 22:36:16 +0000813
814
showard170873e2009-01-07 00:22:26 +0000815 def _read_pidfile(self, use_second_read=False):
816 assert self.pidfile_id is not None, (
817 'You must call run() or attach_to_existing_process()')
818 contents = _drone_manager.get_pidfile_contents(
819 self.pidfile_id, use_second_read=use_second_read)
820 if contents.is_invalid():
821 self._state = drone_manager.PidfileContents()
822 raise self._PidfileException(contents)
823 self._state = contents
mbligh90a549d2008-03-25 23:52:34 +0000824
825
showard21baa452008-10-21 00:08:39 +0000826 def _handle_pidfile_error(self, error, message=''):
showard170873e2009-01-07 00:22:26 +0000827 message = error + '\nProcess: %s\nPidfile: %s\n%s' % (
828 self._state.process, self.pidfile_id, message)
showard21baa452008-10-21 00:08:39 +0000829 print message
showard170873e2009-01-07 00:22:26 +0000830 email_manager.manager.enqueue_notify_email(error, message)
831 if self._state.process is not None:
832 process = self._state.process
showard21baa452008-10-21 00:08:39 +0000833 else:
showard170873e2009-01-07 00:22:26 +0000834 process = _drone_manager.get_dummy_process()
835 self.on_lost_process(process)
showard21baa452008-10-21 00:08:39 +0000836
837
838 def _get_pidfile_info_helper(self):
showard170873e2009-01-07 00:22:26 +0000839 if self._lost_process:
showard21baa452008-10-21 00:08:39 +0000840 return
mblighbb421852008-03-11 22:36:16 +0000841
showard21baa452008-10-21 00:08:39 +0000842 self._read_pidfile()
mblighbb421852008-03-11 22:36:16 +0000843
showard170873e2009-01-07 00:22:26 +0000844 if self._state.process is None:
845 self._handle_no_process()
showard21baa452008-10-21 00:08:39 +0000846 return
mbligh90a549d2008-03-25 23:52:34 +0000847
showard21baa452008-10-21 00:08:39 +0000848 if self._state.exit_status is None:
jadmanski0afbb632008-06-06 21:10:57 +0000849 # double check whether or not autoserv is running
showard170873e2009-01-07 00:22:26 +0000850 if _drone_manager.is_process_running(self._state.process):
showard21baa452008-10-21 00:08:39 +0000851 return
mbligh90a549d2008-03-25 23:52:34 +0000852
showard170873e2009-01-07 00:22:26 +0000853 # pid but no running process - maybe process *just* exited
854 self._read_pidfile(use_second_read=True)
showard21baa452008-10-21 00:08:39 +0000855 if self._state.exit_status is None:
jadmanski0afbb632008-06-06 21:10:57 +0000856 # autoserv exited without writing an exit code
857 # to the pidfile
showard21baa452008-10-21 00:08:39 +0000858 self._handle_pidfile_error(
859 'autoserv died without writing exit code')
mblighbb421852008-03-11 22:36:16 +0000860
showard21baa452008-10-21 00:08:39 +0000861
862 def _get_pidfile_info(self):
863 """\
864 After completion, self._state will contain:
865 pid=None, exit_status=None if autoserv has not yet run
866 pid!=None, exit_status=None if autoserv is running
867 pid!=None, exit_status!=None if autoserv has completed
868 """
869 try:
870 self._get_pidfile_info_helper()
showard170873e2009-01-07 00:22:26 +0000871 except self._PidfileException, exc:
showard21baa452008-10-21 00:08:39 +0000872 self._handle_pidfile_error('Pidfile error', traceback.format_exc())
mblighbb421852008-03-11 22:36:16 +0000873
874
showard170873e2009-01-07 00:22:26 +0000875 def _handle_no_process(self):
jadmanski0afbb632008-06-06 21:10:57 +0000876 """\
877 Called when no pidfile is found or no pid is in the pidfile.
878 """
showard170873e2009-01-07 00:22:26 +0000879 message = 'No pid found at %s' % self.pidfile_id
jadmanski0afbb632008-06-06 21:10:57 +0000880 print message
showard170873e2009-01-07 00:22:26 +0000881 if time.time() - self._start_time > PIDFILE_TIMEOUT:
882 email_manager.manager.enqueue_notify_email(
jadmanski0afbb632008-06-06 21:10:57 +0000883 'Process has failed to write pidfile', message)
showard170873e2009-01-07 00:22:26 +0000884 self.on_lost_process(_drone_manager.get_dummy_process())
mbligh90a549d2008-03-25 23:52:34 +0000885
886
showard170873e2009-01-07 00:22:26 +0000887 def on_lost_process(self, process):
jadmanski0afbb632008-06-06 21:10:57 +0000888 """\
889 Called when autoserv has exited without writing an exit status,
890 or we've timed out waiting for autoserv to write a pid to the
891 pidfile. In either case, we just return failure and the caller
892 should signal some kind of warning.
mbligh90a549d2008-03-25 23:52:34 +0000893
showard170873e2009-01-07 00:22:26 +0000894 process is unimportant here, as it shouldn't be used by anyone.
jadmanski0afbb632008-06-06 21:10:57 +0000895 """
896 self.lost_process = True
showard170873e2009-01-07 00:22:26 +0000897 self._state.process = process
showard21baa452008-10-21 00:08:39 +0000898 self._state.exit_status = 1
899 self._state.num_tests_failed = 0
mbligh90a549d2008-03-25 23:52:34 +0000900
901
jadmanski0afbb632008-06-06 21:10:57 +0000902 def exit_code(self):
showard21baa452008-10-21 00:08:39 +0000903 self._get_pidfile_info()
904 return self._state.exit_status
905
906
907 def num_tests_failed(self):
908 self._get_pidfile_info()
909 assert self._state.num_tests_failed is not None
910 return self._state.num_tests_failed
mblighbb421852008-03-11 22:36:16 +0000911
912
mbligh36768f02008-02-22 18:28:33 +0000913class Agent(object):
showard170873e2009-01-07 00:22:26 +0000914 def __init__(self, tasks, num_processes=1):
jadmanski0afbb632008-06-06 21:10:57 +0000915 self.active_task = None
916 self.queue = Queue.Queue(0)
917 self.dispatcher = None
showard4c5374f2008-09-04 17:02:56 +0000918 self.num_processes = num_processes
jadmanski0afbb632008-06-06 21:10:57 +0000919
showard170873e2009-01-07 00:22:26 +0000920 self.queue_entry_ids = self._union_ids(task.queue_entry_ids
921 for task in tasks)
922 self.host_ids = self._union_ids(task.host_ids for task in tasks)
923
jadmanski0afbb632008-06-06 21:10:57 +0000924 for task in tasks:
925 self.add_task(task)
mbligh36768f02008-02-22 18:28:33 +0000926
927
showard170873e2009-01-07 00:22:26 +0000928 def _union_ids(self, id_lists):
929 return set(itertools.chain(*id_lists))
930
931
jadmanski0afbb632008-06-06 21:10:57 +0000932 def add_task(self, task):
933 self.queue.put_nowait(task)
934 task.agent = self
mbligh36768f02008-02-22 18:28:33 +0000935
936
jadmanski0afbb632008-06-06 21:10:57 +0000937 def tick(self):
showard21baa452008-10-21 00:08:39 +0000938 while not self.is_done():
939 if self.active_task and not self.active_task.is_done():
940 self.active_task.poll()
941 if not self.active_task.is_done():
942 return
943 self._next_task()
mbligh36768f02008-02-22 18:28:33 +0000944
945
jadmanski0afbb632008-06-06 21:10:57 +0000946 def _next_task(self):
947 print "agent picking task"
948 if self.active_task:
949 assert self.active_task.is_done()
mbligh36768f02008-02-22 18:28:33 +0000950
jadmanski0afbb632008-06-06 21:10:57 +0000951 if not self.active_task.success:
952 self.on_task_failure()
mblighe2586682008-02-29 22:45:46 +0000953
jadmanski0afbb632008-06-06 21:10:57 +0000954 self.active_task = None
955 if not self.is_done():
956 self.active_task = self.queue.get_nowait()
957 if self.active_task:
958 self.active_task.start()
mbligh36768f02008-02-22 18:28:33 +0000959
960
jadmanski0afbb632008-06-06 21:10:57 +0000961 def on_task_failure(self):
962 self.queue = Queue.Queue(0)
963 for task in self.active_task.failure_tasks:
964 self.add_task(task)
mbligh16c722d2008-03-05 00:58:44 +0000965
mblighe2586682008-02-29 22:45:46 +0000966
showard4c5374f2008-09-04 17:02:56 +0000967 def is_running(self):
jadmanski0afbb632008-06-06 21:10:57 +0000968 return self.active_task is not None
showardec113162008-05-08 00:52:49 +0000969
970
jadmanski0afbb632008-06-06 21:10:57 +0000971 def is_done(self):
mblighd876f452008-12-03 15:09:17 +0000972 return self.active_task is None and self.queue.empty()
mbligh36768f02008-02-22 18:28:33 +0000973
974
jadmanski0afbb632008-06-06 21:10:57 +0000975 def start(self):
976 assert self.dispatcher
mbligh36768f02008-02-22 18:28:33 +0000977
jadmanski0afbb632008-06-06 21:10:57 +0000978 self._next_task()
mbligh36768f02008-02-22 18:28:33 +0000979
jadmanski0afbb632008-06-06 21:10:57 +0000980
mbligh36768f02008-02-22 18:28:33 +0000981class AgentTask(object):
showard170873e2009-01-07 00:22:26 +0000982 def __init__(self, cmd, working_directory=None, failure_tasks=[]):
jadmanski0afbb632008-06-06 21:10:57 +0000983 self.done = False
984 self.failure_tasks = failure_tasks
985 self.started = False
986 self.cmd = cmd
showard170873e2009-01-07 00:22:26 +0000987 self._working_directory = working_directory
jadmanski0afbb632008-06-06 21:10:57 +0000988 self.task = None
989 self.agent = None
990 self.monitor = None
991 self.success = None
showard170873e2009-01-07 00:22:26 +0000992 self.queue_entry_ids = []
993 self.host_ids = []
994 self.log_file = None
995
996
997 def _set_ids(self, host=None, queue_entries=None):
998 if queue_entries and queue_entries != [None]:
999 self.host_ids = [entry.host.id for entry in queue_entries]
1000 self.queue_entry_ids = [entry.id for entry in queue_entries]
1001 else:
1002 assert host
1003 self.host_ids = [host.id]
mbligh36768f02008-02-22 18:28:33 +00001004
1005
jadmanski0afbb632008-06-06 21:10:57 +00001006 def poll(self):
jadmanski0afbb632008-06-06 21:10:57 +00001007 if self.monitor:
1008 self.tick(self.monitor.exit_code())
1009 else:
1010 self.finished(False)
mbligh36768f02008-02-22 18:28:33 +00001011
1012
jadmanski0afbb632008-06-06 21:10:57 +00001013 def tick(self, exit_code):
showard170873e2009-01-07 00:22:26 +00001014 if exit_code is None:
jadmanski0afbb632008-06-06 21:10:57 +00001015 return
jadmanski0afbb632008-06-06 21:10:57 +00001016 if exit_code == 0:
1017 success = True
1018 else:
1019 success = False
mbligh36768f02008-02-22 18:28:33 +00001020
jadmanski0afbb632008-06-06 21:10:57 +00001021 self.finished(success)
mbligh36768f02008-02-22 18:28:33 +00001022
1023
jadmanski0afbb632008-06-06 21:10:57 +00001024 def is_done(self):
1025 return self.done
mbligh36768f02008-02-22 18:28:33 +00001026
1027
jadmanski0afbb632008-06-06 21:10:57 +00001028 def finished(self, success):
1029 self.done = True
1030 self.success = success
1031 self.epilog()
mbligh36768f02008-02-22 18:28:33 +00001032
1033
jadmanski0afbb632008-06-06 21:10:57 +00001034 def prolog(self):
1035 pass
mblighd64e5702008-04-04 21:39:28 +00001036
1037
jadmanski0afbb632008-06-06 21:10:57 +00001038 def create_temp_resultsdir(self, suffix=''):
showard170873e2009-01-07 00:22:26 +00001039 self.temp_results_dir = _drone_manager.get_temporary_path('agent_task')
mblighd64e5702008-04-04 21:39:28 +00001040
mbligh36768f02008-02-22 18:28:33 +00001041
jadmanski0afbb632008-06-06 21:10:57 +00001042 def cleanup(self):
showard170873e2009-01-07 00:22:26 +00001043 if self.monitor and self.log_file:
1044 _drone_manager.copy_to_results_repository(
1045 self.monitor.get_process(), self.log_file)
mbligh36768f02008-02-22 18:28:33 +00001046
1047
jadmanski0afbb632008-06-06 21:10:57 +00001048 def epilog(self):
1049 self.cleanup()
mbligh36768f02008-02-22 18:28:33 +00001050
1051
jadmanski0afbb632008-06-06 21:10:57 +00001052 def start(self):
1053 assert self.agent
1054
1055 if not self.started:
1056 self.prolog()
1057 self.run()
1058
1059 self.started = True
1060
1061
1062 def abort(self):
1063 if self.monitor:
1064 self.monitor.kill()
1065 self.done = True
1066 self.cleanup()
1067
1068
showard170873e2009-01-07 00:22:26 +00001069 def set_host_log_file(self, base_name, host):
1070 filename = '%s.%s' % (time.time(), base_name)
1071 self.log_file = os.path.join('hosts', host.hostname, filename)
1072
1073
jadmanski0afbb632008-06-06 21:10:57 +00001074 def run(self):
1075 if self.cmd:
showard170873e2009-01-07 00:22:26 +00001076 self.monitor = PidfileRunMonitor()
1077 self.monitor.run(self.cmd, self._working_directory,
1078 nice_level=AUTOSERV_NICE_LEVEL,
1079 log_file=self.log_file)
mbligh36768f02008-02-22 18:28:33 +00001080
1081
1082class RepairTask(AgentTask):
showarde788ea62008-11-17 21:02:47 +00001083 def __init__(self, host, queue_entry=None):
jadmanski0afbb632008-06-06 21:10:57 +00001084 """\
showard170873e2009-01-07 00:22:26 +00001085 queue_entry: queue entry to mark failed if this repair fails.
jadmanski0afbb632008-06-06 21:10:57 +00001086 """
jadmanskifb7cfb12008-07-09 14:13:21 +00001087 protection = host_protections.Protection.get_string(host.protection)
jadmanski542537f2008-07-24 14:14:56 +00001088 # normalize the protection name
1089 protection = host_protections.Protection.get_attr_name(protection)
showard170873e2009-01-07 00:22:26 +00001090
jadmanski0afbb632008-06-06 21:10:57 +00001091 self.host = host
showarde788ea62008-11-17 21:02:47 +00001092 self.queue_entry = queue_entry
showard170873e2009-01-07 00:22:26 +00001093 self._set_ids(host=host, queue_entries=[queue_entry])
1094
1095 self.create_temp_resultsdir('.repair')
1096 cmd = [_autoserv_path , '-p', '-R', '-m', host.hostname,
1097 '-r', _drone_manager.absolute_path(self.temp_results_dir),
1098 '--host-protection', protection]
1099 super(RepairTask, self).__init__(cmd, self.temp_results_dir)
1100
1101 self._set_ids(host=host, queue_entries=[queue_entry])
1102 self.set_host_log_file('repair', self.host)
mblighe2586682008-02-29 22:45:46 +00001103
mbligh36768f02008-02-22 18:28:33 +00001104
jadmanski0afbb632008-06-06 21:10:57 +00001105 def prolog(self):
1106 print "repair_task starting"
1107 self.host.set_status('Repairing')
showarde788ea62008-11-17 21:02:47 +00001108 if self.queue_entry:
1109 self.queue_entry.requeue()
mbligh36768f02008-02-22 18:28:33 +00001110
1111
jadmanski0afbb632008-06-06 21:10:57 +00001112 def epilog(self):
1113 super(RepairTask, self).epilog()
1114 if self.success:
1115 self.host.set_status('Ready')
1116 else:
1117 self.host.set_status('Repair Failed')
showarde788ea62008-11-17 21:02:47 +00001118 if self.queue_entry and not self.queue_entry.meta_host:
1119 self.queue_entry.handle_host_failure()
mbligh36768f02008-02-22 18:28:33 +00001120
1121
showard8fe93b52008-11-18 17:53:22 +00001122class PreJobTask(AgentTask):
showard170873e2009-01-07 00:22:26 +00001123 def epilog(self):
1124 super(PreJobTask, self).epilog()
showard8fe93b52008-11-18 17:53:22 +00001125 should_copy_results = (self.queue_entry and not self.success
1126 and not self.queue_entry.meta_host)
1127 if should_copy_results:
1128 self.queue_entry.set_execution_subdir()
showard170873e2009-01-07 00:22:26 +00001129 destination = os.path.join(self.queue_entry.execution_tag(),
1130 os.path.basename(self.log_file))
1131 _drone_manager.copy_to_results_repository(
1132 self.monitor.get_process(), self.log_file,
1133 destination_path=destination)
showard8fe93b52008-11-18 17:53:22 +00001134
1135
1136class VerifyTask(PreJobTask):
showard9976ce92008-10-15 20:28:13 +00001137 def __init__(self, queue_entry=None, host=None):
jadmanski0afbb632008-06-06 21:10:57 +00001138 assert bool(queue_entry) != bool(host)
jadmanski0afbb632008-06-06 21:10:57 +00001139 self.host = host or queue_entry.host
1140 self.queue_entry = queue_entry
mbligh36768f02008-02-22 18:28:33 +00001141
jadmanski0afbb632008-06-06 21:10:57 +00001142 self.create_temp_resultsdir('.verify')
showard170873e2009-01-07 00:22:26 +00001143 cmd = [_autoserv_path, '-p', '-v', '-m', self.host.hostname, '-r',
1144 _drone_manager.absolute_path(self.temp_results_dir)]
showarde788ea62008-11-17 21:02:47 +00001145 failure_tasks = [RepairTask(self.host, queue_entry=queue_entry)]
showard170873e2009-01-07 00:22:26 +00001146 super(VerifyTask, self).__init__(cmd, self.temp_results_dir,
1147 failure_tasks=failure_tasks)
mblighe2586682008-02-29 22:45:46 +00001148
showard170873e2009-01-07 00:22:26 +00001149 self.set_host_log_file('verify', self.host)
1150 self._set_ids(host=host, queue_entries=[queue_entry])
mblighe2586682008-02-29 22:45:46 +00001151
1152
jadmanski0afbb632008-06-06 21:10:57 +00001153 def prolog(self):
showard8fe93b52008-11-18 17:53:22 +00001154 super(VerifyTask, self).prolog()
jadmanski0afbb632008-06-06 21:10:57 +00001155 print "starting verify on %s" % (self.host.hostname)
1156 if self.queue_entry:
1157 self.queue_entry.set_status('Verifying')
jadmanski0afbb632008-06-06 21:10:57 +00001158 self.host.set_status('Verifying')
mbligh36768f02008-02-22 18:28:33 +00001159
1160
jadmanski0afbb632008-06-06 21:10:57 +00001161 def epilog(self):
1162 super(VerifyTask, self).epilog()
mbligh36768f02008-02-22 18:28:33 +00001163
jadmanski0afbb632008-06-06 21:10:57 +00001164 if self.success:
1165 self.host.set_status('Ready')
showard2bab8f42008-11-12 18:15:22 +00001166 if self.queue_entry:
1167 agent = self.queue_entry.on_pending()
1168 if agent:
1169 self.agent.dispatcher.add_agent(agent)
mbligh36768f02008-02-22 18:28:33 +00001170
1171
mbligh36768f02008-02-22 18:28:33 +00001172class QueueTask(AgentTask):
jadmanski0afbb632008-06-06 21:10:57 +00001173 def __init__(self, job, queue_entries, cmd):
jadmanski0afbb632008-06-06 21:10:57 +00001174 self.job = job
1175 self.queue_entries = queue_entries
showard170873e2009-01-07 00:22:26 +00001176 super(QueueTask, self).__init__(cmd, self._execution_tag())
1177 self._set_ids(queue_entries=queue_entries)
mbligh36768f02008-02-22 18:28:33 +00001178
1179
showard170873e2009-01-07 00:22:26 +00001180 def _format_keyval(self, key, value):
1181 return '%s=%s' % (key, value)
mbligh36768f02008-02-22 18:28:33 +00001182
1183
showard170873e2009-01-07 00:22:26 +00001184 def _write_keyval(self, field, value):
1185 keyval_path = os.path.join(self._execution_tag(), 'keyval')
1186 assert self.monitor and self.monitor.has_process()
1187 paired_with_pidfile = self.monitor.pidfile_id
1188 _drone_manager.write_lines_to_file(
1189 keyval_path, [self._format_keyval(field, value)],
1190 paired_with_pidfile=paired_with_pidfile)
showardd8e548a2008-09-09 03:04:57 +00001191
1192
showard170873e2009-01-07 00:22:26 +00001193 def _write_host_keyvals(self, host):
1194 keyval_path = os.path.join(self._execution_tag(), 'host_keyvals',
1195 host.hostname)
1196 platform, all_labels = host.platform_and_labels()
1197 keyvals = dict(platform=platform, labels=','.join(all_labels))
1198 keyval_content = '\n'.join(self._format_keyval(key, value)
1199 for key, value in keyvals.iteritems())
1200 _drone_manager.attach_file_to_execution(self._execution_tag(),
1201 keyval_content,
1202 file_path=keyval_path)
showardd8e548a2008-09-09 03:04:57 +00001203
1204
showard170873e2009-01-07 00:22:26 +00001205 def _execution_tag(self):
1206 return self.queue_entries[0].execution_tag()
mblighbb421852008-03-11 22:36:16 +00001207
1208
jadmanski0afbb632008-06-06 21:10:57 +00001209 def prolog(self):
jadmanski0afbb632008-06-06 21:10:57 +00001210 for queue_entry in self.queue_entries:
showard170873e2009-01-07 00:22:26 +00001211 self._write_host_keyvals(queue_entry.host)
jadmanski0afbb632008-06-06 21:10:57 +00001212 queue_entry.set_status('Running')
1213 queue_entry.host.set_status('Running')
showard21baa452008-10-21 00:08:39 +00001214 queue_entry.host.update_field('dirty', 1)
showard2bab8f42008-11-12 18:15:22 +00001215 if self.job.synch_count == 1:
jadmanski0afbb632008-06-06 21:10:57 +00001216 assert len(self.queue_entries) == 1
1217 self.job.write_to_machines_file(self.queue_entries[0])
mbligh36768f02008-02-22 18:28:33 +00001218
1219
showard97aed502008-11-04 02:01:24 +00001220 def _finish_task(self, success):
showard170873e2009-01-07 00:22:26 +00001221 queued = time.mktime(self.job.created_on.timetuple())
jadmanski0afbb632008-06-06 21:10:57 +00001222 finished = time.time()
showard170873e2009-01-07 00:22:26 +00001223 self._write_keyval("job_queued", int(queued))
1224 self._write_keyval("job_finished", int(finished))
1225
1226 _drone_manager.copy_to_results_repository(self.monitor.get_process(),
1227 self._execution_tag() + '/')
jadmanskic2ac77f2008-05-16 21:44:04 +00001228
jadmanski0afbb632008-06-06 21:10:57 +00001229 # parse the results of the job
showard97aed502008-11-04 02:01:24 +00001230 reparse_task = FinalReparseTask(self.queue_entries)
showard170873e2009-01-07 00:22:26 +00001231 self.agent.dispatcher.add_agent(Agent([reparse_task], num_processes=0))
jadmanskif7fa2cc2008-10-01 14:13:23 +00001232
1233
showardcbd74612008-11-19 21:42:02 +00001234 def _write_status_comment(self, comment):
showard170873e2009-01-07 00:22:26 +00001235 _drone_manager.write_lines_to_file(
1236 os.path.join(self._execution_tag(), 'status.log'),
1237 ['INFO\t----\t----\t' + comment],
1238 paired_with_pidfile=self.monitor.pidfile_id)
showardcbd74612008-11-19 21:42:02 +00001239
1240
jadmanskif7fa2cc2008-10-01 14:13:23 +00001241 def _log_abort(self):
showard170873e2009-01-07 00:22:26 +00001242 if not self.monitor or not self.monitor.has_process():
1243 return
1244
jadmanskif7fa2cc2008-10-01 14:13:23 +00001245 # build up sets of all the aborted_by and aborted_on values
1246 aborted_by, aborted_on = set(), set()
1247 for queue_entry in self.queue_entries:
1248 if queue_entry.aborted_by:
1249 aborted_by.add(queue_entry.aborted_by)
1250 t = int(time.mktime(queue_entry.aborted_on.timetuple()))
1251 aborted_on.add(t)
1252
1253 # extract some actual, unique aborted by value and write it out
1254 assert len(aborted_by) <= 1
1255 if len(aborted_by) == 1:
showardcbd74612008-11-19 21:42:02 +00001256 aborted_by_value = aborted_by.pop()
1257 aborted_on_value = max(aborted_on)
1258 else:
1259 aborted_by_value = 'autotest_system'
1260 aborted_on_value = int(time.time())
showard170873e2009-01-07 00:22:26 +00001261
1262 self._write_keyval("aborted_by", aborted_by_value)
1263 self._write_keyval("aborted_on", aborted_on_value)
1264
showardcbd74612008-11-19 21:42:02 +00001265 aborted_on_string = str(datetime.datetime.fromtimestamp(
1266 aborted_on_value))
1267 self._write_status_comment('Job aborted by %s on %s' %
1268 (aborted_by_value, aborted_on_string))
jadmanskic2ac77f2008-05-16 21:44:04 +00001269
1270
jadmanski0afbb632008-06-06 21:10:57 +00001271 def abort(self):
1272 super(QueueTask, self).abort()
jadmanskif7fa2cc2008-10-01 14:13:23 +00001273 self._log_abort()
showard97aed502008-11-04 02:01:24 +00001274 self._finish_task(False)
jadmanskic2ac77f2008-05-16 21:44:04 +00001275
1276
showard21baa452008-10-21 00:08:39 +00001277 def _reboot_hosts(self):
1278 reboot_after = self.job.reboot_after
1279 do_reboot = False
showard0fc38302008-10-23 00:44:07 +00001280 if reboot_after == models.RebootAfter.ALWAYS:
showard21baa452008-10-21 00:08:39 +00001281 do_reboot = True
showard0fc38302008-10-23 00:44:07 +00001282 elif reboot_after == models.RebootAfter.IF_ALL_TESTS_PASSED:
showard21baa452008-10-21 00:08:39 +00001283 num_tests_failed = self.monitor.num_tests_failed()
1284 do_reboot = (self.success and num_tests_failed == 0)
1285
showard8ebca792008-11-04 21:54:22 +00001286 for queue_entry in self.queue_entries:
1287 if do_reboot:
showard45ae8192008-11-05 19:32:53 +00001288 # don't pass the queue entry to the CleanupTask. if the cleanup
showardfa8629c2008-11-04 16:51:23 +00001289 # fails, the job doesn't care -- it's over.
showard45ae8192008-11-05 19:32:53 +00001290 cleanup_task = CleanupTask(host=queue_entry.get_host())
1291 self.agent.dispatcher.add_agent(Agent([cleanup_task]))
showard8ebca792008-11-04 21:54:22 +00001292 else:
1293 queue_entry.host.set_status('Ready')
showard21baa452008-10-21 00:08:39 +00001294
1295
jadmanski0afbb632008-06-06 21:10:57 +00001296 def epilog(self):
1297 super(QueueTask, self).epilog()
showard97aed502008-11-04 02:01:24 +00001298 self._finish_task(self.success)
showard21baa452008-10-21 00:08:39 +00001299 self._reboot_hosts()
mblighbb421852008-03-11 22:36:16 +00001300
showard97aed502008-11-04 02:01:24 +00001301 print "queue_task finished with succes=%s" % self.success
mbligh36768f02008-02-22 18:28:33 +00001302
1303
mblighbb421852008-03-11 22:36:16 +00001304class RecoveryQueueTask(QueueTask):
jadmanski0afbb632008-06-06 21:10:57 +00001305 def __init__(self, job, queue_entries, run_monitor):
showard170873e2009-01-07 00:22:26 +00001306 super(RecoveryQueueTask, self).__init__(job, queue_entries, cmd=None)
jadmanski0afbb632008-06-06 21:10:57 +00001307 self.run_monitor = run_monitor
mblighbb421852008-03-11 22:36:16 +00001308
1309
jadmanski0afbb632008-06-06 21:10:57 +00001310 def run(self):
1311 self.monitor = self.run_monitor
mblighbb421852008-03-11 22:36:16 +00001312
1313
jadmanski0afbb632008-06-06 21:10:57 +00001314 def prolog(self):
1315 # recovering an existing process - don't do prolog
1316 pass
mblighbb421852008-03-11 22:36:16 +00001317
1318
showard8fe93b52008-11-18 17:53:22 +00001319class CleanupTask(PreJobTask):
showardfa8629c2008-11-04 16:51:23 +00001320 def __init__(self, host=None, queue_entry=None):
1321 assert bool(host) ^ bool(queue_entry)
1322 if queue_entry:
1323 host = queue_entry.get_host()
showardfa8629c2008-11-04 16:51:23 +00001324 self.queue_entry = queue_entry
jadmanski0afbb632008-06-06 21:10:57 +00001325 self.host = host
showard170873e2009-01-07 00:22:26 +00001326
1327 self.create_temp_resultsdir('.cleanup')
1328 self.cmd = [_autoserv_path, '-p', '--cleanup', '-m', host.hostname,
1329 '-r', _drone_manager.absolute_path(self.temp_results_dir)]
showarde788ea62008-11-17 21:02:47 +00001330 repair_task = RepairTask(host, queue_entry=queue_entry)
showard170873e2009-01-07 00:22:26 +00001331 super(CleanupTask, self).__init__(self.cmd, self.temp_results_dir,
1332 failure_tasks=[repair_task])
1333
1334 self._set_ids(host=host, queue_entries=[queue_entry])
1335 self.set_host_log_file('cleanup', self.host)
mbligh16c722d2008-03-05 00:58:44 +00001336
mblighd5c95802008-03-05 00:33:46 +00001337
jadmanski0afbb632008-06-06 21:10:57 +00001338 def prolog(self):
showard8fe93b52008-11-18 17:53:22 +00001339 super(CleanupTask, self).prolog()
showard45ae8192008-11-05 19:32:53 +00001340 print "starting cleanup task for host: %s" % self.host.hostname
1341 self.host.set_status("Cleaning")
mblighd5c95802008-03-05 00:33:46 +00001342
mblighd5c95802008-03-05 00:33:46 +00001343
showard21baa452008-10-21 00:08:39 +00001344 def epilog(self):
showard45ae8192008-11-05 19:32:53 +00001345 super(CleanupTask, self).epilog()
showard21baa452008-10-21 00:08:39 +00001346 if self.success:
showardfa8629c2008-11-04 16:51:23 +00001347 self.host.set_status('Ready')
showard21baa452008-10-21 00:08:39 +00001348 self.host.update_field('dirty', 0)
1349
1350
mblighd5c95802008-03-05 00:33:46 +00001351class AbortTask(AgentTask):
jadmanski0afbb632008-06-06 21:10:57 +00001352 def __init__(self, queue_entry, agents_to_abort):
jadmanski0afbb632008-06-06 21:10:57 +00001353 super(AbortTask, self).__init__('')
showard170873e2009-01-07 00:22:26 +00001354 self.queue_entry = queue_entry
1355 # don't use _set_ids, since we don't want to set the host_ids
1356 self.queue_entry_ids = [queue_entry.id]
1357 self.agents_to_abort = agents_to_abort
mbligh36768f02008-02-22 18:28:33 +00001358
1359
jadmanski0afbb632008-06-06 21:10:57 +00001360 def prolog(self):
1361 print "starting abort on host %s, job %s" % (
1362 self.queue_entry.host_id, self.queue_entry.job_id)
mbligh36768f02008-02-22 18:28:33 +00001363
mblighd64e5702008-04-04 21:39:28 +00001364
jadmanski0afbb632008-06-06 21:10:57 +00001365 def epilog(self):
1366 super(AbortTask, self).epilog()
1367 self.queue_entry.set_status('Aborted')
1368 self.success = True
1369
1370
1371 def run(self):
1372 for agent in self.agents_to_abort:
1373 if (agent.active_task):
1374 agent.active_task.abort()
mbligh36768f02008-02-22 18:28:33 +00001375
1376
showard97aed502008-11-04 02:01:24 +00001377class FinalReparseTask(AgentTask):
showard97aed502008-11-04 02:01:24 +00001378 _num_running_parses = 0
1379
1380 def __init__(self, queue_entries):
1381 self._queue_entries = queue_entries
showard170873e2009-01-07 00:22:26 +00001382 # don't use _set_ids, since we don't want to set the host_ids
1383 self.queue_entry_ids = [entry.id for entry in queue_entries]
showard97aed502008-11-04 02:01:24 +00001384 self._parse_started = False
1385
1386 assert len(queue_entries) > 0
1387 queue_entry = queue_entries[0]
showard97aed502008-11-04 02:01:24 +00001388
showard170873e2009-01-07 00:22:26 +00001389 self._execution_tag = queue_entry.execution_tag()
1390 self._results_dir = _drone_manager.absolute_path(self._execution_tag)
1391 self._autoserv_monitor = PidfileRunMonitor()
1392 self._autoserv_monitor.attach_to_existing_process(self._execution_tag)
1393 self._final_status = self._determine_final_status()
1394
showard97aed502008-11-04 02:01:24 +00001395 if _testing_mode:
1396 self.cmd = 'true'
showard170873e2009-01-07 00:22:26 +00001397 else:
1398 super(FinalReparseTask, self).__init__(
1399 cmd=self._generate_parse_command(),
1400 working_directory=self._execution_tag)
showard97aed502008-11-04 02:01:24 +00001401
showard170873e2009-01-07 00:22:26 +00001402 self.log_file = os.path.join(self._execution_tag, '.parse.log')
showard97aed502008-11-04 02:01:24 +00001403
1404
1405 @classmethod
1406 def _increment_running_parses(cls):
1407 cls._num_running_parses += 1
1408
1409
1410 @classmethod
1411 def _decrement_running_parses(cls):
1412 cls._num_running_parses -= 1
1413
1414
1415 @classmethod
1416 def _can_run_new_parse(cls):
showardd1ee1dd2009-01-07 21:33:08 +00001417 return (cls._num_running_parses <
1418 scheduler_config.config.max_parse_processes)
showard97aed502008-11-04 02:01:24 +00001419
1420
showard170873e2009-01-07 00:22:26 +00001421 def _determine_final_status(self):
1422 # we'll use a PidfileRunMonitor to read the autoserv exit status
1423 if self._autoserv_monitor.exit_code() == 0:
1424 return models.HostQueueEntry.Status.COMPLETED
1425 return models.HostQueueEntry.Status.FAILED
1426
1427
showard97aed502008-11-04 02:01:24 +00001428 def prolog(self):
1429 super(FinalReparseTask, self).prolog()
1430 for queue_entry in self._queue_entries:
1431 queue_entry.set_status(models.HostQueueEntry.Status.PARSING)
1432
1433
1434 def epilog(self):
1435 super(FinalReparseTask, self).epilog()
showard97aed502008-11-04 02:01:24 +00001436 for queue_entry in self._queue_entries:
showard170873e2009-01-07 00:22:26 +00001437 queue_entry.set_status(self._final_status)
showard97aed502008-11-04 02:01:24 +00001438
1439
showard2bab8f42008-11-12 18:15:22 +00001440 def _generate_parse_command(self):
showard170873e2009-01-07 00:22:26 +00001441 return [_parser_path, '--write-pidfile', '-l', '2', '-r', '-o',
1442 self._results_dir]
showard97aed502008-11-04 02:01:24 +00001443
1444
1445 def poll(self):
1446 # override poll to keep trying to start until the parse count goes down
1447 # and we can, at which point we revert to default behavior
1448 if self._parse_started:
1449 super(FinalReparseTask, self).poll()
1450 else:
1451 self._try_starting_parse()
1452
1453
1454 def run(self):
1455 # override run() to not actually run unless we can
1456 self._try_starting_parse()
1457
1458
1459 def _try_starting_parse(self):
1460 if not self._can_run_new_parse():
1461 return
showard170873e2009-01-07 00:22:26 +00001462
showard97aed502008-11-04 02:01:24 +00001463 # actually run the parse command
showard170873e2009-01-07 00:22:26 +00001464 self.monitor = PidfileRunMonitor()
1465 self.monitor.run(self.cmd, self._working_directory,
1466 log_file=self.log_file,
1467 pidfile_name='.parser_execute',
1468 paired_with_pidfile=self._autoserv_monitor.pidfile_id)
1469
showard97aed502008-11-04 02:01:24 +00001470 self._increment_running_parses()
1471 self._parse_started = True
1472
1473
1474 def finished(self, success):
1475 super(FinalReparseTask, self).finished(success)
1476 self._decrement_running_parses()
1477
1478
mbligh36768f02008-02-22 18:28:33 +00001479class DBObject(object):
jadmanski0afbb632008-06-06 21:10:57 +00001480 def __init__(self, id=None, row=None, new_record=False):
1481 assert (bool(id) != bool(row))
mbligh36768f02008-02-22 18:28:33 +00001482
jadmanski0afbb632008-06-06 21:10:57 +00001483 self.__table = self._get_table()
mbligh36768f02008-02-22 18:28:33 +00001484
jadmanski0afbb632008-06-06 21:10:57 +00001485 self.__new_record = new_record
mbligh36768f02008-02-22 18:28:33 +00001486
jadmanski0afbb632008-06-06 21:10:57 +00001487 if row is None:
1488 sql = 'SELECT * FROM %s WHERE ID=%%s' % self.__table
1489 rows = _db.execute(sql, (id,))
1490 if len(rows) == 0:
1491 raise "row not found (table=%s, id=%s)" % \
1492 (self.__table, id)
1493 row = rows[0]
mbligh36768f02008-02-22 18:28:33 +00001494
showard2bab8f42008-11-12 18:15:22 +00001495 self._update_fields_from_row(row)
1496
1497
1498 def _update_fields_from_row(self, row):
jadmanski0afbb632008-06-06 21:10:57 +00001499 assert len(row) == self.num_cols(), (
1500 "table = %s, row = %s/%d, fields = %s/%d" % (
showard2bab8f42008-11-12 18:15:22 +00001501 self.__table, row, len(row), self._fields(), self.num_cols()))
mbligh36768f02008-02-22 18:28:33 +00001502
showard2bab8f42008-11-12 18:15:22 +00001503 self._valid_fields = set()
1504 for field, value in zip(self._fields(), row):
1505 setattr(self, field, value)
1506 self._valid_fields.add(field)
mbligh36768f02008-02-22 18:28:33 +00001507
showard2bab8f42008-11-12 18:15:22 +00001508 self._valid_fields.remove('id')
mbligh36768f02008-02-22 18:28:33 +00001509
mblighe2586682008-02-29 22:45:46 +00001510
jadmanski0afbb632008-06-06 21:10:57 +00001511 @classmethod
1512 def _get_table(cls):
1513 raise NotImplementedError('Subclasses must override this')
mblighe2586682008-02-29 22:45:46 +00001514
1515
jadmanski0afbb632008-06-06 21:10:57 +00001516 @classmethod
1517 def _fields(cls):
1518 raise NotImplementedError('Subclasses must override this')
showard04c82c52008-05-29 19:38:12 +00001519
1520
jadmanski0afbb632008-06-06 21:10:57 +00001521 @classmethod
1522 def num_cols(cls):
1523 return len(cls._fields())
showard04c82c52008-05-29 19:38:12 +00001524
1525
jadmanski0afbb632008-06-06 21:10:57 +00001526 def count(self, where, table = None):
1527 if not table:
1528 table = self.__table
mbligh36768f02008-02-22 18:28:33 +00001529
jadmanski0afbb632008-06-06 21:10:57 +00001530 rows = _db.execute("""
1531 SELECT count(*) FROM %s
1532 WHERE %s
1533 """ % (table, where))
mbligh6f8bab42008-02-29 22:45:14 +00001534
jadmanski0afbb632008-06-06 21:10:57 +00001535 assert len(rows) == 1
1536
1537 return int(rows[0][0])
mbligh36768f02008-02-22 18:28:33 +00001538
1539
mblighf8c624d2008-07-03 16:58:45 +00001540 def update_field(self, field, value, condition=''):
showard2bab8f42008-11-12 18:15:22 +00001541 assert field in self._valid_fields
mbligh36768f02008-02-22 18:28:33 +00001542
showard2bab8f42008-11-12 18:15:22 +00001543 if getattr(self, field) == value:
jadmanski0afbb632008-06-06 21:10:57 +00001544 return
mbligh36768f02008-02-22 18:28:33 +00001545
mblighf8c624d2008-07-03 16:58:45 +00001546 query = "UPDATE %s SET %s = %%s WHERE id = %%s" % (self.__table, field)
1547 if condition:
1548 query += ' AND (%s)' % condition
jadmanski0afbb632008-06-06 21:10:57 +00001549 _db.execute(query, (value, self.id))
1550
showard2bab8f42008-11-12 18:15:22 +00001551 setattr(self, field, value)
mbligh36768f02008-02-22 18:28:33 +00001552
1553
jadmanski0afbb632008-06-06 21:10:57 +00001554 def save(self):
1555 if self.__new_record:
1556 keys = self._fields()[1:] # avoid id
1557 columns = ','.join([str(key) for key in keys])
1558 values = ['"%s"' % self.__dict__[key] for key in keys]
1559 values = ','.join(values)
1560 query = """INSERT INTO %s (%s) VALUES (%s)""" % \
1561 (self.__table, columns, values)
1562 _db.execute(query)
mbligh36768f02008-02-22 18:28:33 +00001563
1564
jadmanski0afbb632008-06-06 21:10:57 +00001565 def delete(self):
1566 query = 'DELETE FROM %s WHERE id=%%s' % self.__table
1567 _db.execute(query, (self.id,))
mblighe2586682008-02-29 22:45:46 +00001568
1569
showard63a34772008-08-18 19:32:50 +00001570 @staticmethod
1571 def _prefix_with(string, prefix):
1572 if string:
1573 string = prefix + string
1574 return string
1575
1576
jadmanski0afbb632008-06-06 21:10:57 +00001577 @classmethod
showard989f25d2008-10-01 11:38:11 +00001578 def fetch(cls, where='', params=(), joins='', order_by=''):
showard63a34772008-08-18 19:32:50 +00001579 order_by = cls._prefix_with(order_by, 'ORDER BY ')
1580 where = cls._prefix_with(where, 'WHERE ')
1581 query = ('SELECT %(table)s.* FROM %(table)s %(joins)s '
1582 '%(where)s %(order_by)s' % {'table' : cls._get_table(),
1583 'joins' : joins,
1584 'where' : where,
1585 'order_by' : order_by})
1586 rows = _db.execute(query, params)
jadmanski0afbb632008-06-06 21:10:57 +00001587 for row in rows:
1588 yield cls(row=row)
mblighe2586682008-02-29 22:45:46 +00001589
mbligh36768f02008-02-22 18:28:33 +00001590
1591class IneligibleHostQueue(DBObject):
jadmanski0afbb632008-06-06 21:10:57 +00001592 def __init__(self, id=None, row=None, new_record=None):
1593 super(IneligibleHostQueue, self).__init__(id=id, row=row,
1594 new_record=new_record)
mblighe2586682008-02-29 22:45:46 +00001595
1596
jadmanski0afbb632008-06-06 21:10:57 +00001597 @classmethod
1598 def _get_table(cls):
1599 return 'ineligible_host_queues'
mbligh36768f02008-02-22 18:28:33 +00001600
1601
jadmanski0afbb632008-06-06 21:10:57 +00001602 @classmethod
1603 def _fields(cls):
1604 return ['id', 'job_id', 'host_id']
showard04c82c52008-05-29 19:38:12 +00001605
1606
showard989f25d2008-10-01 11:38:11 +00001607class Label(DBObject):
1608 @classmethod
1609 def _get_table(cls):
1610 return 'labels'
1611
1612
1613 @classmethod
1614 def _fields(cls):
1615 return ['id', 'name', 'kernel_config', 'platform', 'invalid',
1616 'only_if_needed']
1617
1618
mbligh36768f02008-02-22 18:28:33 +00001619class Host(DBObject):
jadmanski0afbb632008-06-06 21:10:57 +00001620 def __init__(self, id=None, row=None):
1621 super(Host, self).__init__(id=id, row=row)
mblighe2586682008-02-29 22:45:46 +00001622
1623
jadmanski0afbb632008-06-06 21:10:57 +00001624 @classmethod
1625 def _get_table(cls):
1626 return 'hosts'
mbligh36768f02008-02-22 18:28:33 +00001627
1628
jadmanski0afbb632008-06-06 21:10:57 +00001629 @classmethod
1630 def _fields(cls):
1631 return ['id', 'hostname', 'locked', 'synch_id','status',
showard21baa452008-10-21 00:08:39 +00001632 'invalid', 'protection', 'locked_by_id', 'lock_time', 'dirty']
showard04c82c52008-05-29 19:38:12 +00001633
1634
jadmanski0afbb632008-06-06 21:10:57 +00001635 def current_task(self):
1636 rows = _db.execute("""
1637 SELECT * FROM host_queue_entries WHERE host_id=%s AND NOT complete AND active
1638 """, (self.id,))
1639
1640 if len(rows) == 0:
1641 return None
1642 else:
1643 assert len(rows) == 1
1644 results = rows[0];
mblighf8c624d2008-07-03 16:58:45 +00001645# print "current = %s" % results
jadmanski0afbb632008-06-06 21:10:57 +00001646 return HostQueueEntry(row=results)
mbligh36768f02008-02-22 18:28:33 +00001647
1648
jadmanski0afbb632008-06-06 21:10:57 +00001649 def yield_work(self):
1650 print "%s yielding work" % self.hostname
1651 if self.current_task():
1652 self.current_task().requeue()
1653
1654 def set_status(self,status):
1655 print '%s -> %s' % (self.hostname, status)
1656 self.update_field('status',status)
mbligh36768f02008-02-22 18:28:33 +00001657
1658
showard170873e2009-01-07 00:22:26 +00001659 def platform_and_labels(self):
showardd8e548a2008-09-09 03:04:57 +00001660 """
showard170873e2009-01-07 00:22:26 +00001661 Returns a tuple (platform_name, list_of_all_label_names).
showardd8e548a2008-09-09 03:04:57 +00001662 """
1663 rows = _db.execute("""
showard170873e2009-01-07 00:22:26 +00001664 SELECT labels.name, labels.platform
showardd8e548a2008-09-09 03:04:57 +00001665 FROM labels
1666 INNER JOIN hosts_labels ON labels.id = hosts_labels.label_id
showard170873e2009-01-07 00:22:26 +00001667 WHERE hosts_labels.host_id = %s
showardd8e548a2008-09-09 03:04:57 +00001668 ORDER BY labels.name
1669 """, (self.id,))
showard170873e2009-01-07 00:22:26 +00001670 platform = None
1671 all_labels = []
1672 for label_name, is_platform in rows:
1673 if is_platform:
1674 platform = label_name
1675 all_labels.append(label_name)
1676 return platform, all_labels
1677
1678
1679 def reverify_tasks(self):
1680 cleanup_task = CleanupTask(host=self)
1681 verify_task = VerifyTask(host=self)
1682 # just to make sure this host does not get taken away
1683 self.set_status('Cleaning')
1684 return [cleanup_task, verify_task]
showardd8e548a2008-09-09 03:04:57 +00001685
1686
mbligh36768f02008-02-22 18:28:33 +00001687class HostQueueEntry(DBObject):
jadmanski0afbb632008-06-06 21:10:57 +00001688 def __init__(self, id=None, row=None):
1689 assert id or row
1690 super(HostQueueEntry, self).__init__(id=id, row=row)
1691 self.job = Job(self.job_id)
mbligh36768f02008-02-22 18:28:33 +00001692
jadmanski0afbb632008-06-06 21:10:57 +00001693 if self.host_id:
1694 self.host = Host(self.host_id)
1695 else:
1696 self.host = None
mbligh36768f02008-02-22 18:28:33 +00001697
showard170873e2009-01-07 00:22:26 +00001698 self.queue_log_path = os.path.join(self.job.tag(),
jadmanski0afbb632008-06-06 21:10:57 +00001699 'queue.log.' + str(self.id))
mbligh36768f02008-02-22 18:28:33 +00001700
1701
jadmanski0afbb632008-06-06 21:10:57 +00001702 @classmethod
1703 def _get_table(cls):
1704 return 'host_queue_entries'
mblighe2586682008-02-29 22:45:46 +00001705
1706
jadmanski0afbb632008-06-06 21:10:57 +00001707 @classmethod
1708 def _fields(cls):
showard2bab8f42008-11-12 18:15:22 +00001709 return ['id', 'job_id', 'host_id', 'priority', 'status', 'meta_host',
1710 'active', 'complete', 'deleted', 'execution_subdir']
showard04c82c52008-05-29 19:38:12 +00001711
1712
showardc85c21b2008-11-24 22:17:37 +00001713 def _view_job_url(self):
1714 return "%s#tab_id=view_job&object_id=%s" % (_base_url, self.job.id)
1715
1716
jadmanski0afbb632008-06-06 21:10:57 +00001717 def set_host(self, host):
1718 if host:
1719 self.queue_log_record('Assigning host ' + host.hostname)
1720 self.update_field('host_id', host.id)
1721 self.update_field('active', True)
1722 self.block_host(host.id)
1723 else:
1724 self.queue_log_record('Releasing host')
1725 self.unblock_host(self.host.id)
1726 self.update_field('host_id', None)
mbligh36768f02008-02-22 18:28:33 +00001727
jadmanski0afbb632008-06-06 21:10:57 +00001728 self.host = host
mbligh36768f02008-02-22 18:28:33 +00001729
1730
jadmanski0afbb632008-06-06 21:10:57 +00001731 def get_host(self):
1732 return self.host
mbligh36768f02008-02-22 18:28:33 +00001733
1734
jadmanski0afbb632008-06-06 21:10:57 +00001735 def queue_log_record(self, log_line):
1736 now = str(datetime.datetime.now())
showard170873e2009-01-07 00:22:26 +00001737 _drone_manager.write_lines_to_file(self.queue_log_path,
1738 [now + ' ' + log_line])
mbligh36768f02008-02-22 18:28:33 +00001739
1740
jadmanski0afbb632008-06-06 21:10:57 +00001741 def block_host(self, host_id):
1742 print "creating block %s/%s" % (self.job.id, host_id)
1743 row = [0, self.job.id, host_id]
1744 block = IneligibleHostQueue(row=row, new_record=True)
1745 block.save()
mblighe2586682008-02-29 22:45:46 +00001746
1747
jadmanski0afbb632008-06-06 21:10:57 +00001748 def unblock_host(self, host_id):
1749 print "removing block %s/%s" % (self.job.id, host_id)
1750 blocks = IneligibleHostQueue.fetch(
1751 'job_id=%d and host_id=%d' % (self.job.id, host_id))
1752 for block in blocks:
1753 block.delete()
mblighe2586682008-02-29 22:45:46 +00001754
1755
showard2bab8f42008-11-12 18:15:22 +00001756 def set_execution_subdir(self, subdir=None):
1757 if subdir is None:
1758 assert self.get_host()
1759 subdir = self.get_host().hostname
1760 self.update_field('execution_subdir', subdir)
mbligh36768f02008-02-22 18:28:33 +00001761
1762
showard6355f6b2008-12-05 18:52:13 +00001763 def _get_hostname(self):
1764 if self.host:
1765 return self.host.hostname
1766 return 'no host'
1767
1768
showard170873e2009-01-07 00:22:26 +00001769 def __str__(self):
1770 return "%s/%d (%d)" % (self._get_hostname(), self.job.id, self.id)
1771
1772
jadmanski0afbb632008-06-06 21:10:57 +00001773 def set_status(self, status):
mblighf8c624d2008-07-03 16:58:45 +00001774 abort_statuses = ['Abort', 'Aborting', 'Aborted']
1775 if status not in abort_statuses:
1776 condition = ' AND '.join(['status <> "%s"' % x
1777 for x in abort_statuses])
1778 else:
1779 condition = ''
1780 self.update_field('status', status, condition=condition)
1781
showard170873e2009-01-07 00:22:26 +00001782 print "%s -> %s" % (self, self.status)
mblighf8c624d2008-07-03 16:58:45 +00001783
showardc85c21b2008-11-24 22:17:37 +00001784 if status in ['Queued', 'Parsing']:
jadmanski0afbb632008-06-06 21:10:57 +00001785 self.update_field('complete', False)
1786 self.update_field('active', False)
mbligh36768f02008-02-22 18:28:33 +00001787
jadmanski0afbb632008-06-06 21:10:57 +00001788 if status in ['Pending', 'Running', 'Verifying', 'Starting',
showarde58e3f82008-11-20 19:04:59 +00001789 'Aborting']:
jadmanski0afbb632008-06-06 21:10:57 +00001790 self.update_field('complete', False)
1791 self.update_field('active', True)
mbligh36768f02008-02-22 18:28:33 +00001792
showardc85c21b2008-11-24 22:17:37 +00001793 if status in ['Failed', 'Completed', 'Stopped', 'Aborted']:
jadmanski0afbb632008-06-06 21:10:57 +00001794 self.update_field('complete', True)
1795 self.update_field('active', False)
showardc85c21b2008-11-24 22:17:37 +00001796
1797 should_email_status = (status.lower() in _notify_email_statuses or
1798 'all' in _notify_email_statuses)
1799 if should_email_status:
1800 self._email_on_status(status)
1801
1802 self._email_on_job_complete()
1803
1804
1805 def _email_on_status(self, status):
showard6355f6b2008-12-05 18:52:13 +00001806 hostname = self._get_hostname()
showardc85c21b2008-11-24 22:17:37 +00001807
1808 subject = 'Autotest: Job ID: %s "%s" Host: %s %s' % (
1809 self.job.id, self.job.name, hostname, status)
1810 body = "Job ID: %s\nJob Name: %s\nHost: %s\nStatus: %s\n%s\n" % (
1811 self.job.id, self.job.name, hostname, status,
1812 self._view_job_url())
showard170873e2009-01-07 00:22:26 +00001813 email_manager.manager.send_email(self.job.email_list, subject, body)
showard542e8402008-09-19 20:16:18 +00001814
1815
1816 def _email_on_job_complete(self):
showardc85c21b2008-11-24 22:17:37 +00001817 if not self.job.is_finished():
1818 return
showard542e8402008-09-19 20:16:18 +00001819
showardc85c21b2008-11-24 22:17:37 +00001820 summary_text = []
showard6355f6b2008-12-05 18:52:13 +00001821 hosts_queue = HostQueueEntry.fetch('job_id = %s' % self.job.id)
showardc85c21b2008-11-24 22:17:37 +00001822 for queue_entry in hosts_queue:
1823 summary_text.append("Host: %s Status: %s" %
showard6355f6b2008-12-05 18:52:13 +00001824 (queue_entry._get_hostname(),
showardc85c21b2008-11-24 22:17:37 +00001825 queue_entry.status))
1826
1827 summary_text = "\n".join(summary_text)
1828 status_counts = models.Job.objects.get_status_counts(
1829 [self.job.id])[self.job.id]
1830 status = ', '.join('%d %s' % (count, status) for status, count
1831 in status_counts.iteritems())
1832
1833 subject = 'Autotest: Job ID: %s "%s" %s' % (
1834 self.job.id, self.job.name, status)
1835 body = "Job ID: %s\nJob Name: %s\nStatus: %s\n%s\nSummary:\n%s" % (
1836 self.job.id, self.job.name, status, self._view_job_url(),
1837 summary_text)
showard170873e2009-01-07 00:22:26 +00001838 email_manager.manager.send_email(self.job.email_list, subject, body)
mbligh36768f02008-02-22 18:28:33 +00001839
1840
jadmanski0afbb632008-06-06 21:10:57 +00001841 def run(self,assigned_host=None):
1842 if self.meta_host:
1843 assert assigned_host
1844 # ensure results dir exists for the queue log
jadmanski0afbb632008-06-06 21:10:57 +00001845 self.set_host(assigned_host)
mbligh36768f02008-02-22 18:28:33 +00001846
jadmanski0afbb632008-06-06 21:10:57 +00001847 print "%s/%s scheduled on %s, status=%s" % (self.job.name,
1848 self.meta_host, self.host.hostname, self.status)
mbligh36768f02008-02-22 18:28:33 +00001849
jadmanski0afbb632008-06-06 21:10:57 +00001850 return self.job.run(queue_entry=self)
mblighe2586682008-02-29 22:45:46 +00001851
jadmanski0afbb632008-06-06 21:10:57 +00001852 def requeue(self):
1853 self.set_status('Queued')
jadmanski0afbb632008-06-06 21:10:57 +00001854 if self.meta_host:
1855 self.set_host(None)
mbligh36768f02008-02-22 18:28:33 +00001856
1857
jadmanski0afbb632008-06-06 21:10:57 +00001858 def handle_host_failure(self):
1859 """\
1860 Called when this queue entry's host has failed verification and
1861 repair.
1862 """
1863 assert not self.meta_host
1864 self.set_status('Failed')
showard2bab8f42008-11-12 18:15:22 +00001865 self.job.stop_if_necessary()
mblighe2586682008-02-29 22:45:46 +00001866
1867
jadmanskif7fa2cc2008-10-01 14:13:23 +00001868 @property
1869 def aborted_by(self):
1870 self._load_abort_info()
1871 return self._aborted_by
1872
1873
1874 @property
1875 def aborted_on(self):
1876 self._load_abort_info()
1877 return self._aborted_on
1878
1879
1880 def _load_abort_info(self):
1881 """ Fetch info about who aborted the job. """
1882 if hasattr(self, "_aborted_by"):
1883 return
1884 rows = _db.execute("""
1885 SELECT users.login, aborted_host_queue_entries.aborted_on
1886 FROM aborted_host_queue_entries
1887 INNER JOIN users
1888 ON users.id = aborted_host_queue_entries.aborted_by_id
1889 WHERE aborted_host_queue_entries.queue_entry_id = %s
1890 """, (self.id,))
1891 if rows:
1892 self._aborted_by, self._aborted_on = rows[0]
1893 else:
1894 self._aborted_by = self._aborted_on = None
1895
1896
showardb2e2c322008-10-14 17:33:55 +00001897 def on_pending(self):
1898 """
1899 Called when an entry in a synchronous job has passed verify. If the
1900 job is ready to run, returns an agent to run the job. Returns None
1901 otherwise.
1902 """
1903 self.set_status('Pending')
showardcfd66a32008-10-15 20:31:48 +00001904 self.get_host().set_status('Pending')
showardb2e2c322008-10-14 17:33:55 +00001905 if self.job.is_ready():
1906 return self.job.run(self)
showard2bab8f42008-11-12 18:15:22 +00001907 self.job.stop_if_necessary()
showardb2e2c322008-10-14 17:33:55 +00001908 return None
1909
1910
showard170873e2009-01-07 00:22:26 +00001911 def abort(self, dispatcher, agents_to_abort=[]):
showard1be97432008-10-17 15:30:45 +00001912 host = self.get_host()
showard9d9ffd52008-11-09 23:14:35 +00001913 if self.active and host:
showard170873e2009-01-07 00:22:26 +00001914 dispatcher.add_agent(Agent(tasks=host.reverify_tasks()))
showard1be97432008-10-17 15:30:45 +00001915
showard170873e2009-01-07 00:22:26 +00001916 abort_task = AbortTask(self, agents_to_abort)
showard1be97432008-10-17 15:30:45 +00001917 self.set_status('Aborting')
showard170873e2009-01-07 00:22:26 +00001918 dispatcher.add_agent(Agent(tasks=[abort_task], num_processes=0))
1919
1920 def execution_tag(self):
1921 assert self.execution_subdir
1922 return "%s-%s/%s" % (self.job.id, self.job.owner, self.execution_subdir)
showard1be97432008-10-17 15:30:45 +00001923
1924
mbligh36768f02008-02-22 18:28:33 +00001925class Job(DBObject):
jadmanski0afbb632008-06-06 21:10:57 +00001926 def __init__(self, id=None, row=None):
1927 assert id or row
1928 super(Job, self).__init__(id=id, row=row)
mbligh36768f02008-02-22 18:28:33 +00001929
mblighe2586682008-02-29 22:45:46 +00001930
jadmanski0afbb632008-06-06 21:10:57 +00001931 @classmethod
1932 def _get_table(cls):
1933 return 'jobs'
mbligh36768f02008-02-22 18:28:33 +00001934
1935
jadmanski0afbb632008-06-06 21:10:57 +00001936 @classmethod
1937 def _fields(cls):
1938 return ['id', 'owner', 'name', 'priority', 'control_file',
showard2bab8f42008-11-12 18:15:22 +00001939 'control_type', 'created_on', 'synch_count', 'timeout',
showard21baa452008-10-21 00:08:39 +00001940 'run_verify', 'email_list', 'reboot_before', 'reboot_after']
showard04c82c52008-05-29 19:38:12 +00001941
1942
jadmanski0afbb632008-06-06 21:10:57 +00001943 def is_server_job(self):
1944 return self.control_type != 2
mbligh36768f02008-02-22 18:28:33 +00001945
1946
showard170873e2009-01-07 00:22:26 +00001947 def tag(self):
1948 return "%s-%s" % (self.id, self.owner)
1949
1950
jadmanski0afbb632008-06-06 21:10:57 +00001951 def get_host_queue_entries(self):
1952 rows = _db.execute("""
1953 SELECT * FROM host_queue_entries
1954 WHERE job_id= %s
1955 """, (self.id,))
1956 entries = [HostQueueEntry(row=i) for i in rows]
mbligh36768f02008-02-22 18:28:33 +00001957
jadmanski0afbb632008-06-06 21:10:57 +00001958 assert len(entries)>0
mbligh36768f02008-02-22 18:28:33 +00001959
jadmanski0afbb632008-06-06 21:10:57 +00001960 return entries
mbligh36768f02008-02-22 18:28:33 +00001961
1962
jadmanski0afbb632008-06-06 21:10:57 +00001963 def set_status(self, status, update_queues=False):
1964 self.update_field('status',status)
1965
1966 if update_queues:
1967 for queue_entry in self.get_host_queue_entries():
1968 queue_entry.set_status(status)
mbligh36768f02008-02-22 18:28:33 +00001969
1970
jadmanski0afbb632008-06-06 21:10:57 +00001971 def is_ready(self):
showard2bab8f42008-11-12 18:15:22 +00001972 pending_entries = models.HostQueueEntry.objects.filter(job=self.id,
1973 status='Pending')
1974 return (pending_entries.count() >= self.synch_count)
mbligh36768f02008-02-22 18:28:33 +00001975
1976
jadmanski0afbb632008-06-06 21:10:57 +00001977 def num_machines(self, clause = None):
1978 sql = "job_id=%s" % self.id
1979 if clause:
1980 sql += " AND (%s)" % clause
1981 return self.count(sql, table='host_queue_entries')
mbligh36768f02008-02-22 18:28:33 +00001982
1983
jadmanski0afbb632008-06-06 21:10:57 +00001984 def num_queued(self):
1985 return self.num_machines('not complete')
mbligh36768f02008-02-22 18:28:33 +00001986
1987
jadmanski0afbb632008-06-06 21:10:57 +00001988 def num_active(self):
1989 return self.num_machines('active')
mbligh36768f02008-02-22 18:28:33 +00001990
1991
jadmanski0afbb632008-06-06 21:10:57 +00001992 def num_complete(self):
1993 return self.num_machines('complete')
mbligh36768f02008-02-22 18:28:33 +00001994
1995
jadmanski0afbb632008-06-06 21:10:57 +00001996 def is_finished(self):
showardc85c21b2008-11-24 22:17:37 +00001997 return self.num_complete() == self.num_machines()
mbligh36768f02008-02-22 18:28:33 +00001998
mbligh36768f02008-02-22 18:28:33 +00001999
showard2bab8f42008-11-12 18:15:22 +00002000 def _stop_all_entries(self, entries_to_abort):
2001 """
2002 queue_entries: sequence of models.HostQueueEntry objects
2003 """
2004 for child_entry in entries_to_abort:
2005 assert not child_entry.complete
2006 if child_entry.status == models.HostQueueEntry.Status.PENDING:
2007 child_entry.host.status = models.Host.Status.READY
2008 child_entry.host.save()
2009 child_entry.status = models.HostQueueEntry.Status.STOPPED
2010 child_entry.save()
2011
2012
2013 def stop_if_necessary(self):
2014 not_yet_run = models.HostQueueEntry.objects.filter(
2015 job=self.id, status__in=(models.HostQueueEntry.Status.QUEUED,
2016 models.HostQueueEntry.Status.VERIFYING,
2017 models.HostQueueEntry.Status.PENDING))
2018 if not_yet_run.count() < self.synch_count:
2019 self._stop_all_entries(not_yet_run)
mblighe2586682008-02-29 22:45:46 +00002020
2021
jadmanski0afbb632008-06-06 21:10:57 +00002022 def write_to_machines_file(self, queue_entry):
2023 hostname = queue_entry.get_host().hostname
showard170873e2009-01-07 00:22:26 +00002024 file_path = os.path.join(self.tag(), '.machines')
2025 _drone_manager.write_lines_to_file(file_path, [hostname])
mbligh36768f02008-02-22 18:28:33 +00002026
2027
showard2bab8f42008-11-12 18:15:22 +00002028 def _next_group_name(self):
2029 query = models.HostQueueEntry.objects.filter(
2030 job=self.id).values('execution_subdir').distinct()
2031 subdirs = (entry['execution_subdir'] for entry in query)
2032 groups = (re.match(r'group(\d+)', subdir) for subdir in subdirs)
2033 ids = [int(match.group(1)) for match in groups if match]
2034 if ids:
2035 next_id = max(ids) + 1
2036 else:
2037 next_id = 0
2038 return "group%d" % next_id
2039
2040
showard170873e2009-01-07 00:22:26 +00002041 def _write_control_file(self, execution_tag):
2042 control_path = _drone_manager.attach_file_to_execution(
2043 execution_tag, self.control_file)
2044 return control_path
mbligh36768f02008-02-22 18:28:33 +00002045
showardb2e2c322008-10-14 17:33:55 +00002046
showard2bab8f42008-11-12 18:15:22 +00002047 def get_group_entries(self, queue_entry_from_group):
2048 execution_subdir = queue_entry_from_group.execution_subdir
showarde788ea62008-11-17 21:02:47 +00002049 return list(HostQueueEntry.fetch(
2050 where='job_id=%s AND execution_subdir=%s',
2051 params=(self.id, execution_subdir)))
showard2bab8f42008-11-12 18:15:22 +00002052
2053
showardb2e2c322008-10-14 17:33:55 +00002054 def _get_autoserv_params(self, queue_entries):
showard170873e2009-01-07 00:22:26 +00002055 assert queue_entries
2056 execution_tag = queue_entries[0].execution_tag()
2057 control_path = self._write_control_file(execution_tag)
jadmanski0afbb632008-06-06 21:10:57 +00002058 hostnames = ','.join([entry.get_host().hostname
2059 for entry in queue_entries])
mbligh36768f02008-02-22 18:28:33 +00002060
showard170873e2009-01-07 00:22:26 +00002061 params = [_autoserv_path, '-P', execution_tag, '-p', '-n',
2062 '-r', _drone_manager.absolute_path(execution_tag),
2063 '-u', self.owner, '-l', self.name, '-m', hostnames,
2064 _drone_manager.absolute_path(control_path)]
mbligh36768f02008-02-22 18:28:33 +00002065
jadmanski0afbb632008-06-06 21:10:57 +00002066 if not self.is_server_job():
2067 params.append('-c')
mbligh36768f02008-02-22 18:28:33 +00002068
showardb2e2c322008-10-14 17:33:55 +00002069 return params
mblighe2586682008-02-29 22:45:46 +00002070
mbligh36768f02008-02-22 18:28:33 +00002071
showard2bab8f42008-11-12 18:15:22 +00002072 def _get_pre_job_tasks(self, queue_entry):
showard21baa452008-10-21 00:08:39 +00002073 do_reboot = False
showard0fc38302008-10-23 00:44:07 +00002074 if self.reboot_before == models.RebootBefore.ALWAYS:
showard21baa452008-10-21 00:08:39 +00002075 do_reboot = True
showard0fc38302008-10-23 00:44:07 +00002076 elif self.reboot_before == models.RebootBefore.IF_DIRTY:
showard21baa452008-10-21 00:08:39 +00002077 do_reboot = queue_entry.get_host().dirty
2078
2079 tasks = []
2080 if do_reboot:
showard45ae8192008-11-05 19:32:53 +00002081 tasks.append(CleanupTask(queue_entry=queue_entry))
showard2bab8f42008-11-12 18:15:22 +00002082 tasks.append(VerifyTask(queue_entry=queue_entry))
showard21baa452008-10-21 00:08:39 +00002083 return tasks
2084
2085
showard2bab8f42008-11-12 18:15:22 +00002086 def _assign_new_group(self, queue_entries):
2087 if len(queue_entries) == 1:
2088 group_name = queue_entries[0].get_host().hostname
2089 else:
2090 group_name = self._next_group_name()
2091 print 'Running synchronous job %d hosts %s as %s' % (
2092 self.id, [entry.host.hostname for entry in queue_entries],
2093 group_name)
2094
2095 for queue_entry in queue_entries:
2096 queue_entry.set_execution_subdir(group_name)
2097
2098
2099 def _choose_group_to_run(self, include_queue_entry):
2100 chosen_entries = [include_queue_entry]
2101
2102 num_entries_needed = self.synch_count - 1
2103 if num_entries_needed > 0:
2104 pending_entries = HostQueueEntry.fetch(
2105 where='job_id = %s AND status = "Pending" AND id != %s',
2106 params=(self.id, include_queue_entry.id))
2107 chosen_entries += list(pending_entries)[:num_entries_needed]
2108
2109 self._assign_new_group(chosen_entries)
2110 return chosen_entries
2111
2112
2113 def run(self, queue_entry):
showardb2e2c322008-10-14 17:33:55 +00002114 if not self.is_ready():
showard9976ce92008-10-15 20:28:13 +00002115 if self.run_verify:
showarde58e3f82008-11-20 19:04:59 +00002116 queue_entry.set_status(models.HostQueueEntry.Status.VERIFYING)
showard170873e2009-01-07 00:22:26 +00002117 return Agent(self._get_pre_job_tasks(queue_entry))
showard9976ce92008-10-15 20:28:13 +00002118 else:
2119 return queue_entry.on_pending()
mbligh36768f02008-02-22 18:28:33 +00002120
showard2bab8f42008-11-12 18:15:22 +00002121 queue_entries = self._choose_group_to_run(queue_entry)
2122 return self._finish_run(queue_entries)
showardb2e2c322008-10-14 17:33:55 +00002123
2124
2125 def _finish_run(self, queue_entries, initial_tasks=[]):
showardb2ccdda2008-10-28 20:39:05 +00002126 for queue_entry in queue_entries:
2127 queue_entry.set_status('Starting')
showardb2e2c322008-10-14 17:33:55 +00002128 params = self._get_autoserv_params(queue_entries)
2129 queue_task = QueueTask(job=self, queue_entries=queue_entries,
2130 cmd=params)
2131 tasks = initial_tasks + [queue_task]
2132 entry_ids = [entry.id for entry in queue_entries]
2133
showard170873e2009-01-07 00:22:26 +00002134 return Agent(tasks, num_processes=len(queue_entries))
showardb2e2c322008-10-14 17:33:55 +00002135
2136
mbligh36768f02008-02-22 18:28:33 +00002137if __name__ == '__main__':
jadmanski0afbb632008-06-06 21:10:57 +00002138 main()