blob: 5bf9c040602786d4e4628f640ef29e2856ba9fd9 [file] [log] [blame]
mbligh36768f02008-02-22 18:28:33 +00001#!/usr/bin/python -u
2
3"""
4Autotest scheduler
5"""
showard909c7a62008-07-15 21:52:38 +00006
mbligh36768f02008-02-22 18:28:33 +00007
mbligh8bcd23a2009-02-03 19:14:06 +00008import datetime, errno, optparse, os, pwd, Queue, re, shutil, signal
showard542e8402008-09-19 20:16:18 +00009import smtplib, socket, stat, subprocess, sys, tempfile, time, traceback
showard170873e2009-01-07 00:22:26 +000010import itertools, logging
mbligh70feeee2008-06-11 16:20:49 +000011import common
mbligh8bcd23a2009-02-03 19:14:06 +000012import MySQLdb
showard21baa452008-10-21 00:08:39 +000013from autotest_lib.frontend import setup_django_environment
showard542e8402008-09-19 20:16:18 +000014from autotest_lib.client.common_lib import global_config
showard2bab8f42008-11-12 18:15:22 +000015from autotest_lib.client.common_lib import host_protections, utils, debug
showardb1e51872008-10-07 11:08:18 +000016from autotest_lib.database import database_connection
showard21baa452008-10-21 00:08:39 +000017from autotest_lib.frontend.afe import models
showard170873e2009-01-07 00:22:26 +000018from autotest_lib.scheduler import drone_manager, drones, email_manager
showardd1ee1dd2009-01-07 21:33:08 +000019from autotest_lib.scheduler import status_server, scheduler_config
mbligh70feeee2008-06-11 16:20:49 +000020
mblighb090f142008-02-27 21:33:46 +000021
mbligh36768f02008-02-22 18:28:33 +000022RESULTS_DIR = '.'
23AUTOSERV_NICE_LEVEL = 10
showard170873e2009-01-07 00:22:26 +000024DB_CONFIG_SECTION = 'AUTOTEST_WEB'
mbligh36768f02008-02-22 18:28:33 +000025
26AUTOTEST_PATH = os.path.join(os.path.dirname(__file__), '..')
27
28if os.environ.has_key('AUTOTEST_DIR'):
jadmanski0afbb632008-06-06 21:10:57 +000029 AUTOTEST_PATH = os.environ['AUTOTEST_DIR']
mbligh36768f02008-02-22 18:28:33 +000030AUTOTEST_SERVER_DIR = os.path.join(AUTOTEST_PATH, 'server')
31AUTOTEST_TKO_DIR = os.path.join(AUTOTEST_PATH, 'tko')
32
33if AUTOTEST_SERVER_DIR not in sys.path:
jadmanski0afbb632008-06-06 21:10:57 +000034 sys.path.insert(0, AUTOTEST_SERVER_DIR)
mbligh36768f02008-02-22 18:28:33 +000035
mbligh90a549d2008-03-25 23:52:34 +000036# how long to wait for autoserv to write a pidfile
37PIDFILE_TIMEOUT = 5 * 60 # 5 min
mblighbb421852008-03-11 22:36:16 +000038
mbligh6f8bab42008-02-29 22:45:14 +000039_db = None
mbligh36768f02008-02-22 18:28:33 +000040_shutdown = False
showard170873e2009-01-07 00:22:26 +000041_autoserv_path = os.path.join(drones.AUTOTEST_INSTALL_DIR, 'server', 'autoserv')
42_parser_path = os.path.join(drones.AUTOTEST_INSTALL_DIR, 'tko', 'parse')
mbligh4314a712008-02-29 22:44:30 +000043_testing_mode = False
showard542e8402008-09-19 20:16:18 +000044_base_url = None
showardc85c21b2008-11-24 22:17:37 +000045_notify_email_statuses = []
showard170873e2009-01-07 00:22:26 +000046_drone_manager = drone_manager.DroneManager()
mbligh36768f02008-02-22 18:28:33 +000047
48
49def main():
jadmanski0afbb632008-06-06 21:10:57 +000050 usage = 'usage: %prog [options] results_dir'
mbligh36768f02008-02-22 18:28:33 +000051
jadmanski0afbb632008-06-06 21:10:57 +000052 parser = optparse.OptionParser(usage)
53 parser.add_option('--recover-hosts', help='Try to recover dead hosts',
54 action='store_true')
55 parser.add_option('--logfile', help='Set a log file that all stdout ' +
56 'should be redirected to. Stderr will go to this ' +
57 'file + ".err"')
58 parser.add_option('--test', help='Indicate that scheduler is under ' +
59 'test and should use dummy autoserv and no parsing',
60 action='store_true')
61 (options, args) = parser.parse_args()
62 if len(args) != 1:
63 parser.print_usage()
64 return
mbligh36768f02008-02-22 18:28:33 +000065
jadmanski0afbb632008-06-06 21:10:57 +000066 global RESULTS_DIR
67 RESULTS_DIR = args[0]
mbligh36768f02008-02-22 18:28:33 +000068
jadmanski0afbb632008-06-06 21:10:57 +000069 c = global_config.global_config
showardd1ee1dd2009-01-07 21:33:08 +000070 notify_statuses_list = c.get_config_value(scheduler_config.CONFIG_SECTION,
71 "notify_email_statuses",
72 default='')
showardc85c21b2008-11-24 22:17:37 +000073 global _notify_email_statuses
showard170873e2009-01-07 00:22:26 +000074 _notify_email_statuses = [status for status in
75 re.split(r'[\s,;:]', notify_statuses_list.lower())
76 if status]
showardc85c21b2008-11-24 22:17:37 +000077
jadmanski0afbb632008-06-06 21:10:57 +000078 if options.test:
79 global _autoserv_path
80 _autoserv_path = 'autoserv_dummy'
81 global _testing_mode
82 _testing_mode = True
mbligh36768f02008-02-22 18:28:33 +000083
mbligh37eceaa2008-12-15 22:56:37 +000084 # AUTOTEST_WEB.base_url is still a supported config option as some people
85 # may wish to override the entire url.
showard542e8402008-09-19 20:16:18 +000086 global _base_url
showard170873e2009-01-07 00:22:26 +000087 config_base_url = c.get_config_value(DB_CONFIG_SECTION, 'base_url',
88 default='')
mbligh37eceaa2008-12-15 22:56:37 +000089 if config_base_url:
90 _base_url = config_base_url
showard542e8402008-09-19 20:16:18 +000091 else:
mbligh37eceaa2008-12-15 22:56:37 +000092 # For the common case of everything running on a single server you
93 # can just set the hostname in a single place in the config file.
94 server_name = c.get_config_value('SERVER', 'hostname')
95 if not server_name:
96 print 'Error: [SERVER] hostname missing from the config file.'
97 sys.exit(1)
98 _base_url = 'http://%s/afe/' % server_name
showard542e8402008-09-19 20:16:18 +000099
showardc5afc462009-01-13 00:09:39 +0000100 server = status_server.StatusServer(_drone_manager)
showardd1ee1dd2009-01-07 21:33:08 +0000101 server.start()
102
jadmanski0afbb632008-06-06 21:10:57 +0000103 try:
showardc5afc462009-01-13 00:09:39 +0000104 init(options.logfile)
105 dispatcher = Dispatcher()
106 dispatcher.do_initial_recovery(recover_hosts=options.recover_hosts)
107
jadmanski0afbb632008-06-06 21:10:57 +0000108 while not _shutdown:
109 dispatcher.tick()
showardd1ee1dd2009-01-07 21:33:08 +0000110 time.sleep(scheduler_config.config.tick_pause_sec)
jadmanski0afbb632008-06-06 21:10:57 +0000111 except:
showard170873e2009-01-07 00:22:26 +0000112 email_manager.manager.log_stacktrace(
113 "Uncaught exception; terminating monitor_db")
jadmanski0afbb632008-06-06 21:10:57 +0000114
showard170873e2009-01-07 00:22:26 +0000115 email_manager.manager.send_queued_emails()
showard55b4b542009-01-08 23:30:30 +0000116 server.shutdown()
showard170873e2009-01-07 00:22:26 +0000117 _drone_manager.shutdown()
jadmanski0afbb632008-06-06 21:10:57 +0000118 _db.disconnect()
mbligh36768f02008-02-22 18:28:33 +0000119
120
121def handle_sigint(signum, frame):
jadmanski0afbb632008-06-06 21:10:57 +0000122 global _shutdown
123 _shutdown = True
124 print "Shutdown request received."
mbligh36768f02008-02-22 18:28:33 +0000125
126
127def init(logfile):
jadmanski0afbb632008-06-06 21:10:57 +0000128 if logfile:
129 enable_logging(logfile)
130 print "%s> dispatcher starting" % time.strftime("%X %x")
131 print "My PID is %d" % os.getpid()
mbligh36768f02008-02-22 18:28:33 +0000132
showardb1e51872008-10-07 11:08:18 +0000133 if _testing_mode:
134 global_config.global_config.override_config_value(
showard170873e2009-01-07 00:22:26 +0000135 DB_CONFIG_SECTION, 'database', 'stresstest_autotest_web')
showardb1e51872008-10-07 11:08:18 +0000136
jadmanski0afbb632008-06-06 21:10:57 +0000137 os.environ['PATH'] = AUTOTEST_SERVER_DIR + ':' + os.environ['PATH']
138 global _db
showard170873e2009-01-07 00:22:26 +0000139 _db = database_connection.DatabaseConnection(DB_CONFIG_SECTION)
jadmanski0afbb632008-06-06 21:10:57 +0000140 _db.connect()
mbligh36768f02008-02-22 18:28:33 +0000141
showardfa8629c2008-11-04 16:51:23 +0000142 # ensure Django connection is in autocommit
143 setup_django_environment.enable_autocommit()
144
showard2bab8f42008-11-12 18:15:22 +0000145 debug.configure('scheduler', format_string='%(message)s')
showard67831ae2009-01-16 03:07:38 +0000146 debug.get_logger().setLevel(logging.INFO)
showard2bab8f42008-11-12 18:15:22 +0000147
jadmanski0afbb632008-06-06 21:10:57 +0000148 print "Setting signal handler"
149 signal.signal(signal.SIGINT, handle_sigint)
150
showardd1ee1dd2009-01-07 21:33:08 +0000151 drones = global_config.global_config.get_config_value(
152 scheduler_config.CONFIG_SECTION, 'drones', default='localhost')
153 drone_list = [hostname.strip() for hostname in drones.split(',')]
showard170873e2009-01-07 00:22:26 +0000154 results_host = global_config.global_config.get_config_value(
showardd1ee1dd2009-01-07 21:33:08 +0000155 scheduler_config.CONFIG_SECTION, 'results_host', default='localhost')
showard170873e2009-01-07 00:22:26 +0000156 _drone_manager.initialize(RESULTS_DIR, drone_list, results_host)
157
jadmanski0afbb632008-06-06 21:10:57 +0000158 print "Connected! Running..."
mbligh36768f02008-02-22 18:28:33 +0000159
160
161def enable_logging(logfile):
jadmanski0afbb632008-06-06 21:10:57 +0000162 out_file = logfile
163 err_file = "%s.err" % logfile
164 print "Enabling logging to %s (%s)" % (out_file, err_file)
165 out_fd = open(out_file, "a", buffering=0)
166 err_fd = open(err_file, "a", buffering=0)
mbligh36768f02008-02-22 18:28:33 +0000167
jadmanski0afbb632008-06-06 21:10:57 +0000168 os.dup2(out_fd.fileno(), sys.stdout.fileno())
169 os.dup2(err_fd.fileno(), sys.stderr.fileno())
mbligh36768f02008-02-22 18:28:33 +0000170
jadmanski0afbb632008-06-06 21:10:57 +0000171 sys.stdout = out_fd
172 sys.stderr = err_fd
mbligh36768f02008-02-22 18:28:33 +0000173
174
mblighd5c95802008-03-05 00:33:46 +0000175def queue_entries_to_abort():
jadmanski0afbb632008-06-06 21:10:57 +0000176 rows = _db.execute("""
177 SELECT * FROM host_queue_entries WHERE status='Abort';
178 """)
showard2bab8f42008-11-12 18:15:22 +0000179
jadmanski0afbb632008-06-06 21:10:57 +0000180 qe = [HostQueueEntry(row=i) for i in rows]
181 return qe
mbligh36768f02008-02-22 18:28:33 +0000182
showard7cf9a9b2008-05-15 21:15:52 +0000183
showard63a34772008-08-18 19:32:50 +0000184class HostScheduler(object):
185 def _get_ready_hosts(self):
186 # avoid any host with a currently active queue entry against it
187 hosts = Host.fetch(
188 joins='LEFT JOIN host_queue_entries AS active_hqe '
189 'ON (hosts.id = active_hqe.host_id AND '
showardb1e51872008-10-07 11:08:18 +0000190 'active_hqe.active)',
showard63a34772008-08-18 19:32:50 +0000191 where="active_hqe.host_id IS NULL "
showardb1e51872008-10-07 11:08:18 +0000192 "AND NOT hosts.locked "
showard63a34772008-08-18 19:32:50 +0000193 "AND (hosts.status IS NULL OR hosts.status = 'Ready')")
194 return dict((host.id, host) for host in hosts)
195
196
197 @staticmethod
198 def _get_sql_id_list(id_list):
199 return ','.join(str(item_id) for item_id in id_list)
200
201
202 @classmethod
showard989f25d2008-10-01 11:38:11 +0000203 def _get_many2many_dict(cls, query, id_list, flip=False):
mbligh849a0f62008-08-28 20:12:19 +0000204 if not id_list:
205 return {}
showard63a34772008-08-18 19:32:50 +0000206 query %= cls._get_sql_id_list(id_list)
207 rows = _db.execute(query)
showard989f25d2008-10-01 11:38:11 +0000208 return cls._process_many2many_dict(rows, flip)
209
210
211 @staticmethod
212 def _process_many2many_dict(rows, flip=False):
showard63a34772008-08-18 19:32:50 +0000213 result = {}
214 for row in rows:
215 left_id, right_id = long(row[0]), long(row[1])
showard989f25d2008-10-01 11:38:11 +0000216 if flip:
217 left_id, right_id = right_id, left_id
showard63a34772008-08-18 19:32:50 +0000218 result.setdefault(left_id, set()).add(right_id)
219 return result
220
221
222 @classmethod
223 def _get_job_acl_groups(cls, job_ids):
224 query = """
showardd9ac4452009-02-07 02:04:37 +0000225 SELECT jobs.id, acl_groups_users.aclgroup_id
showard63a34772008-08-18 19:32:50 +0000226 FROM jobs
227 INNER JOIN users ON users.login = jobs.owner
228 INNER JOIN acl_groups_users ON acl_groups_users.user_id = users.id
229 WHERE jobs.id IN (%s)
230 """
231 return cls._get_many2many_dict(query, job_ids)
232
233
234 @classmethod
235 def _get_job_ineligible_hosts(cls, job_ids):
236 query = """
237 SELECT job_id, host_id
238 FROM ineligible_host_queues
239 WHERE job_id IN (%s)
240 """
241 return cls._get_many2many_dict(query, job_ids)
242
243
244 @classmethod
showard989f25d2008-10-01 11:38:11 +0000245 def _get_job_dependencies(cls, job_ids):
246 query = """
247 SELECT job_id, label_id
248 FROM jobs_dependency_labels
249 WHERE job_id IN (%s)
250 """
251 return cls._get_many2many_dict(query, job_ids)
252
253
254 @classmethod
showard63a34772008-08-18 19:32:50 +0000255 def _get_host_acls(cls, host_ids):
256 query = """
showardd9ac4452009-02-07 02:04:37 +0000257 SELECT host_id, aclgroup_id
showard63a34772008-08-18 19:32:50 +0000258 FROM acl_groups_hosts
259 WHERE host_id IN (%s)
260 """
261 return cls._get_many2many_dict(query, host_ids)
262
263
264 @classmethod
265 def _get_label_hosts(cls, host_ids):
showardfa8629c2008-11-04 16:51:23 +0000266 if not host_ids:
267 return {}, {}
showard63a34772008-08-18 19:32:50 +0000268 query = """
269 SELECT label_id, host_id
270 FROM hosts_labels
271 WHERE host_id IN (%s)
showard989f25d2008-10-01 11:38:11 +0000272 """ % cls._get_sql_id_list(host_ids)
273 rows = _db.execute(query)
274 labels_to_hosts = cls._process_many2many_dict(rows)
275 hosts_to_labels = cls._process_many2many_dict(rows, flip=True)
276 return labels_to_hosts, hosts_to_labels
277
278
279 @classmethod
280 def _get_labels(cls):
281 return dict((label.id, label) for label in Label.fetch())
showard63a34772008-08-18 19:32:50 +0000282
283
284 def refresh(self, pending_queue_entries):
285 self._hosts_available = self._get_ready_hosts()
286
287 relevant_jobs = [queue_entry.job_id
288 for queue_entry in pending_queue_entries]
289 self._job_acls = self._get_job_acl_groups(relevant_jobs)
290 self._ineligible_hosts = self._get_job_ineligible_hosts(relevant_jobs)
showard989f25d2008-10-01 11:38:11 +0000291 self._job_dependencies = self._get_job_dependencies(relevant_jobs)
showard63a34772008-08-18 19:32:50 +0000292
293 host_ids = self._hosts_available.keys()
294 self._host_acls = self._get_host_acls(host_ids)
showard989f25d2008-10-01 11:38:11 +0000295 self._label_hosts, self._host_labels = self._get_label_hosts(host_ids)
296
297 self._labels = self._get_labels()
showard63a34772008-08-18 19:32:50 +0000298
299
300 def _is_acl_accessible(self, host_id, queue_entry):
301 job_acls = self._job_acls.get(queue_entry.job_id, set())
302 host_acls = self._host_acls.get(host_id, set())
303 return len(host_acls.intersection(job_acls)) > 0
304
305
showard989f25d2008-10-01 11:38:11 +0000306 def _check_job_dependencies(self, job_dependencies, host_labels):
307 missing = job_dependencies - host_labels
308 return len(job_dependencies - host_labels) == 0
309
310
311 def _check_only_if_needed_labels(self, job_dependencies, host_labels,
312 queue_entry):
showardade14e22009-01-26 22:38:32 +0000313 if not queue_entry.meta_host:
314 # bypass only_if_needed labels when a specific host is selected
315 return True
316
showard989f25d2008-10-01 11:38:11 +0000317 for label_id in host_labels:
318 label = self._labels[label_id]
319 if not label.only_if_needed:
320 # we don't care about non-only_if_needed labels
321 continue
322 if queue_entry.meta_host == label_id:
323 # if the label was requested in a metahost it's OK
324 continue
325 if label_id not in job_dependencies:
326 return False
327 return True
328
329
330 def _is_host_eligible_for_job(self, host_id, queue_entry):
331 job_dependencies = self._job_dependencies.get(queue_entry.job_id, set())
332 host_labels = self._host_labels.get(host_id, set())
mblighc993bee2008-10-03 03:42:34 +0000333
334 acl = self._is_acl_accessible(host_id, queue_entry)
335 deps = self._check_job_dependencies(job_dependencies, host_labels)
336 only_if = self._check_only_if_needed_labels(job_dependencies,
337 host_labels, queue_entry)
338 return acl and deps and only_if
showard989f25d2008-10-01 11:38:11 +0000339
340
showard63a34772008-08-18 19:32:50 +0000341 def _schedule_non_metahost(self, queue_entry):
showard989f25d2008-10-01 11:38:11 +0000342 if not self._is_host_eligible_for_job(queue_entry.host_id, queue_entry):
showard63a34772008-08-18 19:32:50 +0000343 return None
344 return self._hosts_available.pop(queue_entry.host_id, None)
345
346
347 def _is_host_usable(self, host_id):
348 if host_id not in self._hosts_available:
349 # host was already used during this scheduling cycle
350 return False
351 if self._hosts_available[host_id].invalid:
352 # Invalid hosts cannot be used for metahosts. They're included in
353 # the original query because they can be used by non-metahosts.
354 return False
355 return True
356
357
358 def _schedule_metahost(self, queue_entry):
359 label_id = queue_entry.meta_host
360 hosts_in_label = self._label_hosts.get(label_id, set())
361 ineligible_host_ids = self._ineligible_hosts.get(queue_entry.job_id,
362 set())
363
364 # must iterate over a copy so we can mutate the original while iterating
365 for host_id in list(hosts_in_label):
366 if not self._is_host_usable(host_id):
367 hosts_in_label.remove(host_id)
368 continue
369 if host_id in ineligible_host_ids:
370 continue
showard989f25d2008-10-01 11:38:11 +0000371 if not self._is_host_eligible_for_job(host_id, queue_entry):
showard63a34772008-08-18 19:32:50 +0000372 continue
373
374 hosts_in_label.remove(host_id)
375 return self._hosts_available.pop(host_id)
376 return None
377
378
379 def find_eligible_host(self, queue_entry):
380 if not queue_entry.meta_host:
381 return self._schedule_non_metahost(queue_entry)
382 return self._schedule_metahost(queue_entry)
383
384
showard170873e2009-01-07 00:22:26 +0000385class Dispatcher(object):
jadmanski0afbb632008-06-06 21:10:57 +0000386 def __init__(self):
387 self._agents = []
showard3bb499f2008-07-03 19:42:20 +0000388 self._last_clean_time = time.time()
showard63a34772008-08-18 19:32:50 +0000389 self._host_scheduler = HostScheduler()
showard170873e2009-01-07 00:22:26 +0000390 self._host_agents = {}
391 self._queue_entry_agents = {}
mbligh36768f02008-02-22 18:28:33 +0000392
mbligh36768f02008-02-22 18:28:33 +0000393
jadmanski0afbb632008-06-06 21:10:57 +0000394 def do_initial_recovery(self, recover_hosts=True):
395 # always recover processes
396 self._recover_processes()
mblighbb421852008-03-11 22:36:16 +0000397
jadmanski0afbb632008-06-06 21:10:57 +0000398 if recover_hosts:
399 self._recover_hosts()
mbligh36768f02008-02-22 18:28:33 +0000400
401
jadmanski0afbb632008-06-06 21:10:57 +0000402 def tick(self):
showard170873e2009-01-07 00:22:26 +0000403 _drone_manager.refresh()
showarda3ab0d52008-11-03 19:03:47 +0000404 self._run_cleanup_maybe()
jadmanski0afbb632008-06-06 21:10:57 +0000405 self._find_aborting()
406 self._schedule_new_jobs()
407 self._handle_agents()
showard170873e2009-01-07 00:22:26 +0000408 _drone_manager.execute_actions()
409 email_manager.manager.send_queued_emails()
mbligh36768f02008-02-22 18:28:33 +0000410
showard97aed502008-11-04 02:01:24 +0000411
showarda3ab0d52008-11-03 19:03:47 +0000412 def _run_cleanup_maybe(self):
showardd1ee1dd2009-01-07 21:33:08 +0000413 should_cleanup = (self._last_clean_time +
414 scheduler_config.config.clean_interval * 60 <
415 time.time())
416 if should_cleanup:
showarda3ab0d52008-11-03 19:03:47 +0000417 print 'Running cleanup'
418 self._abort_timed_out_jobs()
419 self._abort_jobs_past_synch_start_timeout()
420 self._clear_inactive_blocks()
showardfa8629c2008-11-04 16:51:23 +0000421 self._check_for_db_inconsistencies()
showarda3ab0d52008-11-03 19:03:47 +0000422 self._last_clean_time = time.time()
423
mbligh36768f02008-02-22 18:28:33 +0000424
showard170873e2009-01-07 00:22:26 +0000425 def _register_agent_for_ids(self, agent_dict, object_ids, agent):
426 for object_id in object_ids:
427 agent_dict.setdefault(object_id, set()).add(agent)
428
429
430 def _unregister_agent_for_ids(self, agent_dict, object_ids, agent):
431 for object_id in object_ids:
432 assert object_id in agent_dict
433 agent_dict[object_id].remove(agent)
434
435
jadmanski0afbb632008-06-06 21:10:57 +0000436 def add_agent(self, agent):
437 self._agents.append(agent)
438 agent.dispatcher = self
showard170873e2009-01-07 00:22:26 +0000439 self._register_agent_for_ids(self._host_agents, agent.host_ids, agent)
440 self._register_agent_for_ids(self._queue_entry_agents,
441 agent.queue_entry_ids, agent)
mblighd5c95802008-03-05 00:33:46 +0000442
showard170873e2009-01-07 00:22:26 +0000443
444 def get_agents_for_entry(self, queue_entry):
445 """
446 Find agents corresponding to the specified queue_entry.
447 """
448 return self._queue_entry_agents.get(queue_entry.id, set())
449
450
451 def host_has_agent(self, host):
452 """
453 Determine if there is currently an Agent present using this host.
454 """
455 return bool(self._host_agents.get(host.id, None))
mbligh36768f02008-02-22 18:28:33 +0000456
457
jadmanski0afbb632008-06-06 21:10:57 +0000458 def remove_agent(self, agent):
459 self._agents.remove(agent)
showard170873e2009-01-07 00:22:26 +0000460 self._unregister_agent_for_ids(self._host_agents, agent.host_ids,
461 agent)
462 self._unregister_agent_for_ids(self._queue_entry_agents,
463 agent.queue_entry_ids, agent)
showardec113162008-05-08 00:52:49 +0000464
465
showard4c5374f2008-09-04 17:02:56 +0000466 def num_running_processes(self):
467 return sum(agent.num_processes for agent in self._agents
468 if agent.is_running())
mblighbb421852008-03-11 22:36:16 +0000469
470
showard170873e2009-01-07 00:22:26 +0000471 def _extract_execution_tag(self, command_line):
472 match = re.match(r'.* -P (\S+) ', command_line)
473 if not match:
474 return None
475 return match.group(1)
mblighbb421852008-03-11 22:36:16 +0000476
477
showard2bab8f42008-11-12 18:15:22 +0000478 def _recover_queue_entries(self, queue_entries, run_monitor):
479 assert len(queue_entries) > 0
showard2bab8f42008-11-12 18:15:22 +0000480 queue_task = RecoveryQueueTask(job=queue_entries[0].job,
481 queue_entries=queue_entries,
482 run_monitor=run_monitor)
jadmanski0afbb632008-06-06 21:10:57 +0000483 self.add_agent(Agent(tasks=[queue_task],
showard170873e2009-01-07 00:22:26 +0000484 num_processes=len(queue_entries)))
mblighbb421852008-03-11 22:36:16 +0000485
486
jadmanski0afbb632008-06-06 21:10:57 +0000487 def _recover_processes(self):
showard170873e2009-01-07 00:22:26 +0000488 self._register_pidfiles()
489 _drone_manager.refresh()
490 self._recover_running_entries()
491 self._recover_aborting_entries()
492 self._requeue_other_active_entries()
493 self._recover_parsing_entries()
494 self._reverify_remaining_hosts()
495 # reinitialize drones after killing orphaned processes, since they can
496 # leave around files when they die
497 _drone_manager.execute_actions()
498 _drone_manager.reinitialize_drones()
mblighbb421852008-03-11 22:36:16 +0000499
showard170873e2009-01-07 00:22:26 +0000500
501 def _register_pidfiles(self):
502 # during recovery we may need to read pidfiles for both running and
503 # parsing entries
504 queue_entries = HostQueueEntry.fetch(
505 where="status IN ('Running', 'Parsing')")
jadmanski0afbb632008-06-06 21:10:57 +0000506 for queue_entry in queue_entries:
showard170873e2009-01-07 00:22:26 +0000507 pidfile_id = _drone_manager.get_pidfile_id_from(
508 queue_entry.execution_tag())
509 _drone_manager.register_pidfile(pidfile_id)
510
511
512 def _recover_running_entries(self):
513 orphans = _drone_manager.get_orphaned_autoserv_processes()
514
515 queue_entries = HostQueueEntry.fetch(where="status = 'Running'")
516 requeue_entries = []
517 for queue_entry in queue_entries:
518 if self.get_agents_for_entry(queue_entry):
jadmanski0afbb632008-06-06 21:10:57 +0000519 # synchronous job we've already recovered
520 continue
showard170873e2009-01-07 00:22:26 +0000521 execution_tag = queue_entry.execution_tag()
522 run_monitor = PidfileRunMonitor()
523 run_monitor.attach_to_existing_process(execution_tag)
524 if not run_monitor.has_process():
525 # autoserv apparently never got run, so let it get requeued
526 continue
showarde788ea62008-11-17 21:02:47 +0000527 queue_entries = queue_entry.job.get_group_entries(queue_entry)
showard170873e2009-01-07 00:22:26 +0000528 print 'Recovering %s (process %s)' % (
529 ', '.join(str(entry) for entry in queue_entries),
530 run_monitor.get_process())
showard2bab8f42008-11-12 18:15:22 +0000531 self._recover_queue_entries(queue_entries, run_monitor)
showard170873e2009-01-07 00:22:26 +0000532 orphans.pop(execution_tag, None)
mbligh90a549d2008-03-25 23:52:34 +0000533
jadmanski0afbb632008-06-06 21:10:57 +0000534 # now kill any remaining autoserv processes
showard170873e2009-01-07 00:22:26 +0000535 for process in orphans.itervalues():
536 print 'Killing orphan %s' % process
537 _drone_manager.kill_process(process)
jadmanski0afbb632008-06-06 21:10:57 +0000538
showard170873e2009-01-07 00:22:26 +0000539
540 def _recover_aborting_entries(self):
541 queue_entries = HostQueueEntry.fetch(
542 where='status IN ("Abort", "Aborting")')
jadmanski0afbb632008-06-06 21:10:57 +0000543 for queue_entry in queue_entries:
showard170873e2009-01-07 00:22:26 +0000544 print 'Recovering aborting QE %s' % queue_entry
545 agent = queue_entry.abort(self)
jadmanski0afbb632008-06-06 21:10:57 +0000546
showard97aed502008-11-04 02:01:24 +0000547
showard170873e2009-01-07 00:22:26 +0000548 def _requeue_other_active_entries(self):
549 queue_entries = HostQueueEntry.fetch(
550 where='active AND NOT complete AND status != "Pending"')
551 for queue_entry in queue_entries:
552 if self.get_agents_for_entry(queue_entry):
553 # entry has already been recovered
554 continue
555 print 'Requeuing active QE %s (status=%s)' % (queue_entry,
556 queue_entry.status)
557 if queue_entry.host:
558 tasks = queue_entry.host.reverify_tasks()
559 self.add_agent(Agent(tasks))
560 agent = queue_entry.requeue()
561
562
563 def _reverify_remaining_hosts(self):
showard45ae8192008-11-05 19:32:53 +0000564 # reverify hosts that were in the middle of verify, repair or cleanup
jadmanski0afbb632008-06-06 21:10:57 +0000565 self._reverify_hosts_where("""(status = 'Repairing' OR
566 status = 'Verifying' OR
showard170873e2009-01-07 00:22:26 +0000567 status = 'Cleaning')""")
jadmanski0afbb632008-06-06 21:10:57 +0000568
showard170873e2009-01-07 00:22:26 +0000569 # recover "Running" hosts with no active queue entries, although this
570 # should never happen
571 message = ('Recovering running host %s - this probably indicates a '
572 'scheduler bug')
jadmanski0afbb632008-06-06 21:10:57 +0000573 self._reverify_hosts_where("""status = 'Running' AND
574 id NOT IN (SELECT host_id
575 FROM host_queue_entries
576 WHERE active)""",
577 print_message=message)
mblighbb421852008-03-11 22:36:16 +0000578
579
jadmanski0afbb632008-06-06 21:10:57 +0000580 def _reverify_hosts_where(self, where,
showard170873e2009-01-07 00:22:26 +0000581 print_message='Reverifying host %s'):
582 full_where='locked = 0 AND invalid = 0 AND ' + where
583 for host in Host.fetch(where=full_where):
584 if self.host_has_agent(host):
585 # host has already been recovered in some way
jadmanski0afbb632008-06-06 21:10:57 +0000586 continue
showard170873e2009-01-07 00:22:26 +0000587 if print_message:
jadmanski0afbb632008-06-06 21:10:57 +0000588 print print_message % host.hostname
showard170873e2009-01-07 00:22:26 +0000589 tasks = host.reverify_tasks()
590 self.add_agent(Agent(tasks))
mbligh36768f02008-02-22 18:28:33 +0000591
592
showard97aed502008-11-04 02:01:24 +0000593 def _recover_parsing_entries(self):
showard2bab8f42008-11-12 18:15:22 +0000594 recovered_entry_ids = set()
showard97aed502008-11-04 02:01:24 +0000595 for entry in HostQueueEntry.fetch(where='status = "Parsing"'):
showard2bab8f42008-11-12 18:15:22 +0000596 if entry.id in recovered_entry_ids:
597 continue
598 queue_entries = entry.job.get_group_entries(entry)
showard170873e2009-01-07 00:22:26 +0000599 recovered_entry_ids = recovered_entry_ids.union(
600 entry.id for entry in queue_entries)
601 print 'Recovering parsing entries %s' % (
602 ', '.join(str(entry) for entry in queue_entries))
showard97aed502008-11-04 02:01:24 +0000603
604 reparse_task = FinalReparseTask(queue_entries)
showard170873e2009-01-07 00:22:26 +0000605 self.add_agent(Agent([reparse_task], num_processes=0))
showard97aed502008-11-04 02:01:24 +0000606
607
jadmanski0afbb632008-06-06 21:10:57 +0000608 def _recover_hosts(self):
609 # recover "Repair Failed" hosts
610 message = 'Reverifying dead host %s'
611 self._reverify_hosts_where("status = 'Repair Failed'",
612 print_message=message)
mbligh62ba2ed2008-04-30 17:09:25 +0000613
614
showard3bb499f2008-07-03 19:42:20 +0000615 def _abort_timed_out_jobs(self):
616 """
617 Aborts all jobs that have timed out and not completed
618 """
showarda3ab0d52008-11-03 19:03:47 +0000619 query = models.Job.objects.filter(hostqueueentry__complete=False).extra(
620 where=['created_on + INTERVAL timeout HOUR < NOW()'])
621 for job in query.distinct():
622 print 'Aborting job %d due to job timeout' % job.id
623 job.abort(None)
showard3bb499f2008-07-03 19:42:20 +0000624
625
showard98863972008-10-29 21:14:56 +0000626 def _abort_jobs_past_synch_start_timeout(self):
627 """
628 Abort synchronous jobs that are past the start timeout (from global
629 config) and are holding a machine that's in everyone.
630 """
631 timeout_delta = datetime.timedelta(
showardd1ee1dd2009-01-07 21:33:08 +0000632 minutes=scheduler_config.config.synch_job_start_timeout_minutes)
showard98863972008-10-29 21:14:56 +0000633 timeout_start = datetime.datetime.now() - timeout_delta
634 query = models.Job.objects.filter(
showard98863972008-10-29 21:14:56 +0000635 created_on__lt=timeout_start,
636 hostqueueentry__status='Pending',
showardd9ac4452009-02-07 02:04:37 +0000637 hostqueueentry__host__aclgroup__name='Everyone')
showard98863972008-10-29 21:14:56 +0000638 for job in query.distinct():
639 print 'Aborting job %d due to start timeout' % job.id
showardff059d72008-12-03 18:18:53 +0000640 entries_to_abort = job.hostqueueentry_set.exclude(
641 status=models.HostQueueEntry.Status.RUNNING)
642 for queue_entry in entries_to_abort:
643 queue_entry.abort(None)
showard98863972008-10-29 21:14:56 +0000644
645
jadmanski0afbb632008-06-06 21:10:57 +0000646 def _clear_inactive_blocks(self):
647 """
648 Clear out blocks for all completed jobs.
649 """
650 # this would be simpler using NOT IN (subquery), but MySQL
651 # treats all IN subqueries as dependent, so this optimizes much
652 # better
653 _db.execute("""
654 DELETE ihq FROM ineligible_host_queues ihq
showard4eaaf522008-06-06 22:28:07 +0000655 LEFT JOIN (SELECT DISTINCT job_id FROM host_queue_entries
jadmanski0afbb632008-06-06 21:10:57 +0000656 WHERE NOT complete) hqe
657 USING (job_id) WHERE hqe.job_id IS NULL""")
showard04c82c52008-05-29 19:38:12 +0000658
659
showardb95b1bd2008-08-15 18:11:04 +0000660 def _get_pending_queue_entries(self):
showard63a34772008-08-18 19:32:50 +0000661 # prioritize by job priority, then non-metahost over metahost, then FIFO
662 return list(HostQueueEntry.fetch(
showard25cbdbd2009-02-17 20:57:21 +0000663 joins='INNER JOIN jobs ON (job_id=jobs.id)',
showardac9ce222008-12-03 18:19:44 +0000664 where='NOT complete AND NOT active AND status="Queued"',
showard25cbdbd2009-02-17 20:57:21 +0000665 order_by='jobs.priority DESC, meta_host, job_id'))
mbligh36768f02008-02-22 18:28:33 +0000666
667
jadmanski0afbb632008-06-06 21:10:57 +0000668 def _schedule_new_jobs(self):
showard63a34772008-08-18 19:32:50 +0000669 queue_entries = self._get_pending_queue_entries()
670 if not queue_entries:
showardb95b1bd2008-08-15 18:11:04 +0000671 return
showardb95b1bd2008-08-15 18:11:04 +0000672
showard63a34772008-08-18 19:32:50 +0000673 self._host_scheduler.refresh(queue_entries)
showardb95b1bd2008-08-15 18:11:04 +0000674
showard63a34772008-08-18 19:32:50 +0000675 for queue_entry in queue_entries:
676 assigned_host = self._host_scheduler.find_eligible_host(queue_entry)
showardb95b1bd2008-08-15 18:11:04 +0000677 if not assigned_host:
jadmanski0afbb632008-06-06 21:10:57 +0000678 continue
showardb95b1bd2008-08-15 18:11:04 +0000679 self._run_queue_entry(queue_entry, assigned_host)
680
681
682 def _run_queue_entry(self, queue_entry, host):
683 agent = queue_entry.run(assigned_host=host)
showard170873e2009-01-07 00:22:26 +0000684 # in some cases (synchronous jobs with run_verify=False), agent may be
685 # None
showard9976ce92008-10-15 20:28:13 +0000686 if agent:
687 self.add_agent(agent)
mblighd5c95802008-03-05 00:33:46 +0000688
689
jadmanski0afbb632008-06-06 21:10:57 +0000690 def _find_aborting(self):
jadmanski0afbb632008-06-06 21:10:57 +0000691 for entry in queue_entries_to_abort():
showard170873e2009-01-07 00:22:26 +0000692 agents_to_abort = list(self.get_agents_for_entry(entry))
showard1be97432008-10-17 15:30:45 +0000693 for agent in agents_to_abort:
694 self.remove_agent(agent)
695
showard170873e2009-01-07 00:22:26 +0000696 entry.abort(self, agents_to_abort)
jadmanski0afbb632008-06-06 21:10:57 +0000697
698
showard324bf812009-01-20 23:23:38 +0000699 def _can_start_agent(self, agent, num_started_this_cycle,
700 have_reached_limit):
showard4c5374f2008-09-04 17:02:56 +0000701 # always allow zero-process agents to run
702 if agent.num_processes == 0:
703 return True
704 # don't allow any nonzero-process agents to run after we've reached a
705 # limit (this avoids starvation of many-process agents)
706 if have_reached_limit:
707 return False
708 # total process throttling
showard324bf812009-01-20 23:23:38 +0000709 if agent.num_processes > _drone_manager.max_runnable_processes():
showard4c5374f2008-09-04 17:02:56 +0000710 return False
711 # if a single agent exceeds the per-cycle throttling, still allow it to
712 # run when it's the first agent in the cycle
713 if num_started_this_cycle == 0:
714 return True
715 # per-cycle throttling
716 if (num_started_this_cycle + agent.num_processes >
showardd1ee1dd2009-01-07 21:33:08 +0000717 scheduler_config.config.max_processes_started_per_cycle):
showard4c5374f2008-09-04 17:02:56 +0000718 return False
719 return True
720
721
jadmanski0afbb632008-06-06 21:10:57 +0000722 def _handle_agents(self):
jadmanski0afbb632008-06-06 21:10:57 +0000723 num_started_this_cycle = 0
showard4c5374f2008-09-04 17:02:56 +0000724 have_reached_limit = False
725 # iterate over copy, so we can remove agents during iteration
726 for agent in list(self._agents):
727 if agent.is_done():
jadmanski0afbb632008-06-06 21:10:57 +0000728 print "agent finished"
showard170873e2009-01-07 00:22:26 +0000729 self.remove_agent(agent)
showard4c5374f2008-09-04 17:02:56 +0000730 continue
731 if not agent.is_running():
showard324bf812009-01-20 23:23:38 +0000732 if not self._can_start_agent(agent, num_started_this_cycle,
showard4c5374f2008-09-04 17:02:56 +0000733 have_reached_limit):
734 have_reached_limit = True
735 continue
showard4c5374f2008-09-04 17:02:56 +0000736 num_started_this_cycle += agent.num_processes
737 agent.tick()
showard324bf812009-01-20 23:23:38 +0000738 print _drone_manager.total_running_processes(), 'running processes'
mbligh36768f02008-02-22 18:28:33 +0000739
740
showardfa8629c2008-11-04 16:51:23 +0000741 def _check_for_db_inconsistencies(self):
742 query = models.HostQueueEntry.objects.filter(active=True, complete=True)
743 if query.count() != 0:
744 subject = ('%d queue entries found with active=complete=1'
745 % query.count())
746 message = '\n'.join(str(entry.get_object_dict())
747 for entry in query[:50])
748 if len(query) > 50:
749 message += '\n(truncated)\n'
750
751 print subject
showard170873e2009-01-07 00:22:26 +0000752 email_manager.manager.enqueue_notify_email(subject, message)
showardfa8629c2008-11-04 16:51:23 +0000753
754
showard170873e2009-01-07 00:22:26 +0000755class PidfileRunMonitor(object):
756 """
757 Client must call either run() to start a new process or
758 attach_to_existing_process().
759 """
mbligh36768f02008-02-22 18:28:33 +0000760
showard170873e2009-01-07 00:22:26 +0000761 class _PidfileException(Exception):
762 """
763 Raised when there's some unexpected behavior with the pid file, but only
764 used internally (never allowed to escape this class).
765 """
mbligh36768f02008-02-22 18:28:33 +0000766
767
showard170873e2009-01-07 00:22:26 +0000768 def __init__(self):
769 self._lost_process = False
770 self._start_time = None
771 self.pidfile_id = None
772 self._state = drone_manager.PidfileContents()
showard2bab8f42008-11-12 18:15:22 +0000773
774
showard170873e2009-01-07 00:22:26 +0000775 def _add_nice_command(self, command, nice_level):
776 if not nice_level:
777 return command
778 return ['nice', '-n', str(nice_level)] + command
779
780
781 def _set_start_time(self):
782 self._start_time = time.time()
783
784
785 def run(self, command, working_directory, nice_level=None, log_file=None,
786 pidfile_name=None, paired_with_pidfile=None):
787 assert command is not None
788 if nice_level is not None:
789 command = ['nice', '-n', str(nice_level)] + command
790 self._set_start_time()
791 self.pidfile_id = _drone_manager.execute_command(
792 command, working_directory, log_file=log_file,
793 pidfile_name=pidfile_name, paired_with_pidfile=paired_with_pidfile)
794
795
796 def attach_to_existing_process(self, execution_tag):
797 self._set_start_time()
798 self.pidfile_id = _drone_manager.get_pidfile_id_from(execution_tag)
799 _drone_manager.register_pidfile(self.pidfile_id)
mblighbb421852008-03-11 22:36:16 +0000800
801
jadmanski0afbb632008-06-06 21:10:57 +0000802 def kill(self):
showard170873e2009-01-07 00:22:26 +0000803 if self.has_process():
804 _drone_manager.kill_process(self.get_process())
mblighbb421852008-03-11 22:36:16 +0000805
mbligh36768f02008-02-22 18:28:33 +0000806
showard170873e2009-01-07 00:22:26 +0000807 def has_process(self):
showard21baa452008-10-21 00:08:39 +0000808 self._get_pidfile_info()
showard170873e2009-01-07 00:22:26 +0000809 return self._state.process is not None
showard21baa452008-10-21 00:08:39 +0000810
811
showard170873e2009-01-07 00:22:26 +0000812 def get_process(self):
showard21baa452008-10-21 00:08:39 +0000813 self._get_pidfile_info()
showard170873e2009-01-07 00:22:26 +0000814 assert self.has_process()
815 return self._state.process
mblighbb421852008-03-11 22:36:16 +0000816
817
showard170873e2009-01-07 00:22:26 +0000818 def _read_pidfile(self, use_second_read=False):
819 assert self.pidfile_id is not None, (
820 'You must call run() or attach_to_existing_process()')
821 contents = _drone_manager.get_pidfile_contents(
822 self.pidfile_id, use_second_read=use_second_read)
823 if contents.is_invalid():
824 self._state = drone_manager.PidfileContents()
825 raise self._PidfileException(contents)
826 self._state = contents
mbligh90a549d2008-03-25 23:52:34 +0000827
828
showard21baa452008-10-21 00:08:39 +0000829 def _handle_pidfile_error(self, error, message=''):
showard170873e2009-01-07 00:22:26 +0000830 message = error + '\nProcess: %s\nPidfile: %s\n%s' % (
831 self._state.process, self.pidfile_id, message)
showard21baa452008-10-21 00:08:39 +0000832 print message
showard170873e2009-01-07 00:22:26 +0000833 email_manager.manager.enqueue_notify_email(error, message)
834 if self._state.process is not None:
835 process = self._state.process
showard21baa452008-10-21 00:08:39 +0000836 else:
showard170873e2009-01-07 00:22:26 +0000837 process = _drone_manager.get_dummy_process()
838 self.on_lost_process(process)
showard21baa452008-10-21 00:08:39 +0000839
840
841 def _get_pidfile_info_helper(self):
showard170873e2009-01-07 00:22:26 +0000842 if self._lost_process:
showard21baa452008-10-21 00:08:39 +0000843 return
mblighbb421852008-03-11 22:36:16 +0000844
showard21baa452008-10-21 00:08:39 +0000845 self._read_pidfile()
mblighbb421852008-03-11 22:36:16 +0000846
showard170873e2009-01-07 00:22:26 +0000847 if self._state.process is None:
848 self._handle_no_process()
showard21baa452008-10-21 00:08:39 +0000849 return
mbligh90a549d2008-03-25 23:52:34 +0000850
showard21baa452008-10-21 00:08:39 +0000851 if self._state.exit_status is None:
jadmanski0afbb632008-06-06 21:10:57 +0000852 # double check whether or not autoserv is running
showard170873e2009-01-07 00:22:26 +0000853 if _drone_manager.is_process_running(self._state.process):
showard21baa452008-10-21 00:08:39 +0000854 return
mbligh90a549d2008-03-25 23:52:34 +0000855
showard170873e2009-01-07 00:22:26 +0000856 # pid but no running process - maybe process *just* exited
857 self._read_pidfile(use_second_read=True)
showard21baa452008-10-21 00:08:39 +0000858 if self._state.exit_status is None:
jadmanski0afbb632008-06-06 21:10:57 +0000859 # autoserv exited without writing an exit code
860 # to the pidfile
showard21baa452008-10-21 00:08:39 +0000861 self._handle_pidfile_error(
862 'autoserv died without writing exit code')
mblighbb421852008-03-11 22:36:16 +0000863
showard21baa452008-10-21 00:08:39 +0000864
865 def _get_pidfile_info(self):
866 """\
867 After completion, self._state will contain:
868 pid=None, exit_status=None if autoserv has not yet run
869 pid!=None, exit_status=None if autoserv is running
870 pid!=None, exit_status!=None if autoserv has completed
871 """
872 try:
873 self._get_pidfile_info_helper()
showard170873e2009-01-07 00:22:26 +0000874 except self._PidfileException, exc:
showard21baa452008-10-21 00:08:39 +0000875 self._handle_pidfile_error('Pidfile error', traceback.format_exc())
mblighbb421852008-03-11 22:36:16 +0000876
877
showard170873e2009-01-07 00:22:26 +0000878 def _handle_no_process(self):
jadmanski0afbb632008-06-06 21:10:57 +0000879 """\
880 Called when no pidfile is found or no pid is in the pidfile.
881 """
showard170873e2009-01-07 00:22:26 +0000882 message = 'No pid found at %s' % self.pidfile_id
jadmanski0afbb632008-06-06 21:10:57 +0000883 print message
showard170873e2009-01-07 00:22:26 +0000884 if time.time() - self._start_time > PIDFILE_TIMEOUT:
885 email_manager.manager.enqueue_notify_email(
jadmanski0afbb632008-06-06 21:10:57 +0000886 'Process has failed to write pidfile', message)
showard170873e2009-01-07 00:22:26 +0000887 self.on_lost_process(_drone_manager.get_dummy_process())
mbligh90a549d2008-03-25 23:52:34 +0000888
889
showard170873e2009-01-07 00:22:26 +0000890 def on_lost_process(self, process):
jadmanski0afbb632008-06-06 21:10:57 +0000891 """\
892 Called when autoserv has exited without writing an exit status,
893 or we've timed out waiting for autoserv to write a pid to the
894 pidfile. In either case, we just return failure and the caller
895 should signal some kind of warning.
mbligh90a549d2008-03-25 23:52:34 +0000896
showard170873e2009-01-07 00:22:26 +0000897 process is unimportant here, as it shouldn't be used by anyone.
jadmanski0afbb632008-06-06 21:10:57 +0000898 """
899 self.lost_process = True
showard170873e2009-01-07 00:22:26 +0000900 self._state.process = process
showard21baa452008-10-21 00:08:39 +0000901 self._state.exit_status = 1
902 self._state.num_tests_failed = 0
mbligh90a549d2008-03-25 23:52:34 +0000903
904
jadmanski0afbb632008-06-06 21:10:57 +0000905 def exit_code(self):
showard21baa452008-10-21 00:08:39 +0000906 self._get_pidfile_info()
907 return self._state.exit_status
908
909
910 def num_tests_failed(self):
911 self._get_pidfile_info()
912 assert self._state.num_tests_failed is not None
913 return self._state.num_tests_failed
mblighbb421852008-03-11 22:36:16 +0000914
915
mbligh36768f02008-02-22 18:28:33 +0000916class Agent(object):
showard170873e2009-01-07 00:22:26 +0000917 def __init__(self, tasks, num_processes=1):
jadmanski0afbb632008-06-06 21:10:57 +0000918 self.active_task = None
919 self.queue = Queue.Queue(0)
920 self.dispatcher = None
showard4c5374f2008-09-04 17:02:56 +0000921 self.num_processes = num_processes
jadmanski0afbb632008-06-06 21:10:57 +0000922
showard170873e2009-01-07 00:22:26 +0000923 self.queue_entry_ids = self._union_ids(task.queue_entry_ids
924 for task in tasks)
925 self.host_ids = self._union_ids(task.host_ids for task in tasks)
926
jadmanski0afbb632008-06-06 21:10:57 +0000927 for task in tasks:
928 self.add_task(task)
mbligh36768f02008-02-22 18:28:33 +0000929
930
showard170873e2009-01-07 00:22:26 +0000931 def _union_ids(self, id_lists):
932 return set(itertools.chain(*id_lists))
933
934
jadmanski0afbb632008-06-06 21:10:57 +0000935 def add_task(self, task):
936 self.queue.put_nowait(task)
937 task.agent = self
mbligh36768f02008-02-22 18:28:33 +0000938
939
jadmanski0afbb632008-06-06 21:10:57 +0000940 def tick(self):
showard21baa452008-10-21 00:08:39 +0000941 while not self.is_done():
942 if self.active_task and not self.active_task.is_done():
943 self.active_task.poll()
944 if not self.active_task.is_done():
945 return
946 self._next_task()
mbligh36768f02008-02-22 18:28:33 +0000947
948
jadmanski0afbb632008-06-06 21:10:57 +0000949 def _next_task(self):
950 print "agent picking task"
951 if self.active_task:
952 assert self.active_task.is_done()
mbligh36768f02008-02-22 18:28:33 +0000953
jadmanski0afbb632008-06-06 21:10:57 +0000954 if not self.active_task.success:
955 self.on_task_failure()
mblighe2586682008-02-29 22:45:46 +0000956
jadmanski0afbb632008-06-06 21:10:57 +0000957 self.active_task = None
958 if not self.is_done():
959 self.active_task = self.queue.get_nowait()
960 if self.active_task:
961 self.active_task.start()
mbligh36768f02008-02-22 18:28:33 +0000962
963
jadmanski0afbb632008-06-06 21:10:57 +0000964 def on_task_failure(self):
965 self.queue = Queue.Queue(0)
966 for task in self.active_task.failure_tasks:
967 self.add_task(task)
mbligh16c722d2008-03-05 00:58:44 +0000968
mblighe2586682008-02-29 22:45:46 +0000969
showard4c5374f2008-09-04 17:02:56 +0000970 def is_running(self):
jadmanski0afbb632008-06-06 21:10:57 +0000971 return self.active_task is not None
showardec113162008-05-08 00:52:49 +0000972
973
jadmanski0afbb632008-06-06 21:10:57 +0000974 def is_done(self):
mblighd876f452008-12-03 15:09:17 +0000975 return self.active_task is None and self.queue.empty()
mbligh36768f02008-02-22 18:28:33 +0000976
977
jadmanski0afbb632008-06-06 21:10:57 +0000978 def start(self):
979 assert self.dispatcher
mbligh36768f02008-02-22 18:28:33 +0000980
jadmanski0afbb632008-06-06 21:10:57 +0000981 self._next_task()
mbligh36768f02008-02-22 18:28:33 +0000982
jadmanski0afbb632008-06-06 21:10:57 +0000983
mbligh36768f02008-02-22 18:28:33 +0000984class AgentTask(object):
showard170873e2009-01-07 00:22:26 +0000985 def __init__(self, cmd, working_directory=None, failure_tasks=[]):
jadmanski0afbb632008-06-06 21:10:57 +0000986 self.done = False
987 self.failure_tasks = failure_tasks
988 self.started = False
989 self.cmd = cmd
showard170873e2009-01-07 00:22:26 +0000990 self._working_directory = working_directory
jadmanski0afbb632008-06-06 21:10:57 +0000991 self.task = None
992 self.agent = None
993 self.monitor = None
994 self.success = None
showard170873e2009-01-07 00:22:26 +0000995 self.queue_entry_ids = []
996 self.host_ids = []
997 self.log_file = None
998
999
1000 def _set_ids(self, host=None, queue_entries=None):
1001 if queue_entries and queue_entries != [None]:
1002 self.host_ids = [entry.host.id for entry in queue_entries]
1003 self.queue_entry_ids = [entry.id for entry in queue_entries]
1004 else:
1005 assert host
1006 self.host_ids = [host.id]
mbligh36768f02008-02-22 18:28:33 +00001007
1008
jadmanski0afbb632008-06-06 21:10:57 +00001009 def poll(self):
jadmanski0afbb632008-06-06 21:10:57 +00001010 if self.monitor:
1011 self.tick(self.monitor.exit_code())
1012 else:
1013 self.finished(False)
mbligh36768f02008-02-22 18:28:33 +00001014
1015
jadmanski0afbb632008-06-06 21:10:57 +00001016 def tick(self, exit_code):
showard170873e2009-01-07 00:22:26 +00001017 if exit_code is None:
jadmanski0afbb632008-06-06 21:10:57 +00001018 return
jadmanski0afbb632008-06-06 21:10:57 +00001019 if exit_code == 0:
1020 success = True
1021 else:
1022 success = False
mbligh36768f02008-02-22 18:28:33 +00001023
jadmanski0afbb632008-06-06 21:10:57 +00001024 self.finished(success)
mbligh36768f02008-02-22 18:28:33 +00001025
1026
jadmanski0afbb632008-06-06 21:10:57 +00001027 def is_done(self):
1028 return self.done
mbligh36768f02008-02-22 18:28:33 +00001029
1030
jadmanski0afbb632008-06-06 21:10:57 +00001031 def finished(self, success):
1032 self.done = True
1033 self.success = success
1034 self.epilog()
mbligh36768f02008-02-22 18:28:33 +00001035
1036
jadmanski0afbb632008-06-06 21:10:57 +00001037 def prolog(self):
1038 pass
mblighd64e5702008-04-04 21:39:28 +00001039
1040
jadmanski0afbb632008-06-06 21:10:57 +00001041 def create_temp_resultsdir(self, suffix=''):
showard170873e2009-01-07 00:22:26 +00001042 self.temp_results_dir = _drone_manager.get_temporary_path('agent_task')
mblighd64e5702008-04-04 21:39:28 +00001043
mbligh36768f02008-02-22 18:28:33 +00001044
jadmanski0afbb632008-06-06 21:10:57 +00001045 def cleanup(self):
showard170873e2009-01-07 00:22:26 +00001046 if self.monitor and self.log_file:
1047 _drone_manager.copy_to_results_repository(
1048 self.monitor.get_process(), self.log_file)
mbligh36768f02008-02-22 18:28:33 +00001049
1050
jadmanski0afbb632008-06-06 21:10:57 +00001051 def epilog(self):
1052 self.cleanup()
mbligh36768f02008-02-22 18:28:33 +00001053
1054
jadmanski0afbb632008-06-06 21:10:57 +00001055 def start(self):
1056 assert self.agent
1057
1058 if not self.started:
1059 self.prolog()
1060 self.run()
1061
1062 self.started = True
1063
1064
1065 def abort(self):
1066 if self.monitor:
1067 self.monitor.kill()
1068 self.done = True
1069 self.cleanup()
1070
1071
showard170873e2009-01-07 00:22:26 +00001072 def set_host_log_file(self, base_name, host):
1073 filename = '%s.%s' % (time.time(), base_name)
1074 self.log_file = os.path.join('hosts', host.hostname, filename)
1075
1076
showardde634ee2009-01-30 01:44:24 +00001077 def _get_consistent_execution_tag(self, queue_entries):
1078 first_execution_tag = queue_entries[0].execution_tag()
1079 for queue_entry in queue_entries[1:]:
1080 assert queue_entry.execution_tag() == first_execution_tag, (
1081 '%s (%s) != %s (%s)' % (queue_entry.execution_tag(),
1082 queue_entry,
1083 first_execution_tag,
1084 queue_entries[0]))
1085 return first_execution_tag
1086
1087
showard678df4f2009-02-04 21:36:39 +00001088 def _copy_and_parse_results(self, queue_entries):
showardde634ee2009-01-30 01:44:24 +00001089 assert len(queue_entries) > 0
1090 assert self.monitor
1091 execution_tag = self._get_consistent_execution_tag(queue_entries)
showard678df4f2009-02-04 21:36:39 +00001092 results_path = execution_tag + '/'
1093 _drone_manager.copy_to_results_repository(self.monitor.get_process(),
1094 results_path)
showardde634ee2009-01-30 01:44:24 +00001095
1096 reparse_task = FinalReparseTask(queue_entries)
1097 self.agent.dispatcher.add_agent(Agent([reparse_task], num_processes=0))
1098
1099
jadmanski0afbb632008-06-06 21:10:57 +00001100 def run(self):
1101 if self.cmd:
showard170873e2009-01-07 00:22:26 +00001102 self.monitor = PidfileRunMonitor()
1103 self.monitor.run(self.cmd, self._working_directory,
1104 nice_level=AUTOSERV_NICE_LEVEL,
1105 log_file=self.log_file)
mbligh36768f02008-02-22 18:28:33 +00001106
1107
1108class RepairTask(AgentTask):
showarde788ea62008-11-17 21:02:47 +00001109 def __init__(self, host, queue_entry=None):
jadmanski0afbb632008-06-06 21:10:57 +00001110 """\
showard170873e2009-01-07 00:22:26 +00001111 queue_entry: queue entry to mark failed if this repair fails.
jadmanski0afbb632008-06-06 21:10:57 +00001112 """
jadmanskifb7cfb12008-07-09 14:13:21 +00001113 protection = host_protections.Protection.get_string(host.protection)
jadmanski542537f2008-07-24 14:14:56 +00001114 # normalize the protection name
1115 protection = host_protections.Protection.get_attr_name(protection)
showard170873e2009-01-07 00:22:26 +00001116
jadmanski0afbb632008-06-06 21:10:57 +00001117 self.host = host
showarde788ea62008-11-17 21:02:47 +00001118 self.queue_entry = queue_entry
showard170873e2009-01-07 00:22:26 +00001119 self._set_ids(host=host, queue_entries=[queue_entry])
1120
1121 self.create_temp_resultsdir('.repair')
1122 cmd = [_autoserv_path , '-p', '-R', '-m', host.hostname,
1123 '-r', _drone_manager.absolute_path(self.temp_results_dir),
1124 '--host-protection', protection]
1125 super(RepairTask, self).__init__(cmd, self.temp_results_dir)
1126
1127 self._set_ids(host=host, queue_entries=[queue_entry])
1128 self.set_host_log_file('repair', self.host)
mblighe2586682008-02-29 22:45:46 +00001129
mbligh36768f02008-02-22 18:28:33 +00001130
jadmanski0afbb632008-06-06 21:10:57 +00001131 def prolog(self):
1132 print "repair_task starting"
1133 self.host.set_status('Repairing')
showarde788ea62008-11-17 21:02:47 +00001134 if self.queue_entry:
1135 self.queue_entry.requeue()
mbligh36768f02008-02-22 18:28:33 +00001136
1137
showardde634ee2009-01-30 01:44:24 +00001138 def _fail_queue_entry(self):
1139 assert self.queue_entry
1140 self.queue_entry.set_execution_subdir()
showard678df4f2009-02-04 21:36:39 +00001141 # copy results logs into the normal place for job results
1142 _drone_manager.copy_results_on_drone(
1143 self.monitor.get_process(),
1144 source_path=self.temp_results_dir + '/',
1145 destination_path=self.queue_entry.execution_tag() + '/')
1146
1147 self._copy_and_parse_results([self.queue_entry])
showardde634ee2009-01-30 01:44:24 +00001148 self.queue_entry.handle_host_failure()
1149
1150
jadmanski0afbb632008-06-06 21:10:57 +00001151 def epilog(self):
1152 super(RepairTask, self).epilog()
1153 if self.success:
1154 self.host.set_status('Ready')
1155 else:
1156 self.host.set_status('Repair Failed')
showarde788ea62008-11-17 21:02:47 +00001157 if self.queue_entry and not self.queue_entry.meta_host:
showardde634ee2009-01-30 01:44:24 +00001158 self._fail_queue_entry()
mbligh36768f02008-02-22 18:28:33 +00001159
1160
showard8fe93b52008-11-18 17:53:22 +00001161class PreJobTask(AgentTask):
showard170873e2009-01-07 00:22:26 +00001162 def epilog(self):
1163 super(PreJobTask, self).epilog()
showard8fe93b52008-11-18 17:53:22 +00001164 should_copy_results = (self.queue_entry and not self.success
1165 and not self.queue_entry.meta_host)
1166 if should_copy_results:
1167 self.queue_entry.set_execution_subdir()
showard170873e2009-01-07 00:22:26 +00001168 destination = os.path.join(self.queue_entry.execution_tag(),
1169 os.path.basename(self.log_file))
1170 _drone_manager.copy_to_results_repository(
1171 self.monitor.get_process(), self.log_file,
1172 destination_path=destination)
showard8fe93b52008-11-18 17:53:22 +00001173
1174
1175class VerifyTask(PreJobTask):
showard9976ce92008-10-15 20:28:13 +00001176 def __init__(self, queue_entry=None, host=None):
jadmanski0afbb632008-06-06 21:10:57 +00001177 assert bool(queue_entry) != bool(host)
jadmanski0afbb632008-06-06 21:10:57 +00001178 self.host = host or queue_entry.host
1179 self.queue_entry = queue_entry
mbligh36768f02008-02-22 18:28:33 +00001180
jadmanski0afbb632008-06-06 21:10:57 +00001181 self.create_temp_resultsdir('.verify')
showard170873e2009-01-07 00:22:26 +00001182 cmd = [_autoserv_path, '-p', '-v', '-m', self.host.hostname, '-r',
1183 _drone_manager.absolute_path(self.temp_results_dir)]
showarde788ea62008-11-17 21:02:47 +00001184 failure_tasks = [RepairTask(self.host, queue_entry=queue_entry)]
showard170873e2009-01-07 00:22:26 +00001185 super(VerifyTask, self).__init__(cmd, self.temp_results_dir,
1186 failure_tasks=failure_tasks)
mblighe2586682008-02-29 22:45:46 +00001187
showard170873e2009-01-07 00:22:26 +00001188 self.set_host_log_file('verify', self.host)
1189 self._set_ids(host=host, queue_entries=[queue_entry])
mblighe2586682008-02-29 22:45:46 +00001190
1191
jadmanski0afbb632008-06-06 21:10:57 +00001192 def prolog(self):
showard8fe93b52008-11-18 17:53:22 +00001193 super(VerifyTask, self).prolog()
jadmanski0afbb632008-06-06 21:10:57 +00001194 print "starting verify on %s" % (self.host.hostname)
1195 if self.queue_entry:
1196 self.queue_entry.set_status('Verifying')
jadmanski0afbb632008-06-06 21:10:57 +00001197 self.host.set_status('Verifying')
mbligh36768f02008-02-22 18:28:33 +00001198
1199
jadmanski0afbb632008-06-06 21:10:57 +00001200 def epilog(self):
1201 super(VerifyTask, self).epilog()
mbligh36768f02008-02-22 18:28:33 +00001202
jadmanski0afbb632008-06-06 21:10:57 +00001203 if self.success:
1204 self.host.set_status('Ready')
mbligh36768f02008-02-22 18:28:33 +00001205
1206
mbligh36768f02008-02-22 18:28:33 +00001207class QueueTask(AgentTask):
jadmanski0afbb632008-06-06 21:10:57 +00001208 def __init__(self, job, queue_entries, cmd):
jadmanski0afbb632008-06-06 21:10:57 +00001209 self.job = job
1210 self.queue_entries = queue_entries
showard170873e2009-01-07 00:22:26 +00001211 super(QueueTask, self).__init__(cmd, self._execution_tag())
1212 self._set_ids(queue_entries=queue_entries)
mbligh36768f02008-02-22 18:28:33 +00001213
1214
showard170873e2009-01-07 00:22:26 +00001215 def _format_keyval(self, key, value):
1216 return '%s=%s' % (key, value)
mbligh36768f02008-02-22 18:28:33 +00001217
1218
showard73ec0442009-02-07 02:05:20 +00001219 def _keyval_path(self):
1220 return os.path.join(self._execution_tag(), 'keyval')
1221
1222
1223 def _write_keyvals_before_job_helper(self, keyval_dict, keyval_path):
1224 keyval_contents = '\n'.join(self._format_keyval(key, value)
1225 for key, value in keyval_dict.iteritems())
1226 # always end with a newline to allow additional keyvals to be written
1227 keyval_contents += '\n'
1228 _drone_manager.attach_file_to_execution(self._execution_tag(),
1229 keyval_contents,
1230 file_path=keyval_path)
1231
1232
1233 def _write_keyvals_before_job(self, keyval_dict):
1234 self._write_keyvals_before_job_helper(keyval_dict, self._keyval_path())
1235
1236
1237 def _write_keyval_after_job(self, field, value):
showard170873e2009-01-07 00:22:26 +00001238 assert self.monitor and self.monitor.has_process()
1239 paired_with_pidfile = self.monitor.pidfile_id
1240 _drone_manager.write_lines_to_file(
showard73ec0442009-02-07 02:05:20 +00001241 self._keyval_path(), [self._format_keyval(field, value)],
showard170873e2009-01-07 00:22:26 +00001242 paired_with_pidfile=paired_with_pidfile)
showardd8e548a2008-09-09 03:04:57 +00001243
1244
showard170873e2009-01-07 00:22:26 +00001245 def _write_host_keyvals(self, host):
1246 keyval_path = os.path.join(self._execution_tag(), 'host_keyvals',
1247 host.hostname)
1248 platform, all_labels = host.platform_and_labels()
showard73ec0442009-02-07 02:05:20 +00001249 keyval_dict = dict(platform=platform, labels=','.join(all_labels))
1250 self._write_keyvals_before_job_helper(keyval_dict, keyval_path)
showardd8e548a2008-09-09 03:04:57 +00001251
1252
showard170873e2009-01-07 00:22:26 +00001253 def _execution_tag(self):
1254 return self.queue_entries[0].execution_tag()
mblighbb421852008-03-11 22:36:16 +00001255
1256
jadmanski0afbb632008-06-06 21:10:57 +00001257 def prolog(self):
showard73ec0442009-02-07 02:05:20 +00001258 queued = int(time.mktime(self.job.created_on.timetuple()))
1259 self._write_keyvals_before_job({'job_queued': queued})
jadmanski0afbb632008-06-06 21:10:57 +00001260 for queue_entry in self.queue_entries:
showard170873e2009-01-07 00:22:26 +00001261 self._write_host_keyvals(queue_entry.host)
jadmanski0afbb632008-06-06 21:10:57 +00001262 queue_entry.set_status('Running')
1263 queue_entry.host.set_status('Running')
showard21baa452008-10-21 00:08:39 +00001264 queue_entry.host.update_field('dirty', 1)
showard2bab8f42008-11-12 18:15:22 +00001265 if self.job.synch_count == 1:
jadmanski0afbb632008-06-06 21:10:57 +00001266 assert len(self.queue_entries) == 1
1267 self.job.write_to_machines_file(self.queue_entries[0])
mbligh36768f02008-02-22 18:28:33 +00001268
1269
showard97aed502008-11-04 02:01:24 +00001270 def _finish_task(self, success):
showard73ec0442009-02-07 02:05:20 +00001271 finished = int(time.time())
1272 self._write_keyval_after_job("job_finished", finished)
showard678df4f2009-02-04 21:36:39 +00001273 self._copy_and_parse_results(self.queue_entries)
jadmanskif7fa2cc2008-10-01 14:13:23 +00001274
1275
showardcbd74612008-11-19 21:42:02 +00001276 def _write_status_comment(self, comment):
showard170873e2009-01-07 00:22:26 +00001277 _drone_manager.write_lines_to_file(
1278 os.path.join(self._execution_tag(), 'status.log'),
1279 ['INFO\t----\t----\t' + comment],
1280 paired_with_pidfile=self.monitor.pidfile_id)
showardcbd74612008-11-19 21:42:02 +00001281
1282
jadmanskif7fa2cc2008-10-01 14:13:23 +00001283 def _log_abort(self):
showard170873e2009-01-07 00:22:26 +00001284 if not self.monitor or not self.monitor.has_process():
1285 return
1286
jadmanskif7fa2cc2008-10-01 14:13:23 +00001287 # build up sets of all the aborted_by and aborted_on values
1288 aborted_by, aborted_on = set(), set()
1289 for queue_entry in self.queue_entries:
1290 if queue_entry.aborted_by:
1291 aborted_by.add(queue_entry.aborted_by)
1292 t = int(time.mktime(queue_entry.aborted_on.timetuple()))
1293 aborted_on.add(t)
1294
1295 # extract some actual, unique aborted by value and write it out
1296 assert len(aborted_by) <= 1
1297 if len(aborted_by) == 1:
showardcbd74612008-11-19 21:42:02 +00001298 aborted_by_value = aborted_by.pop()
1299 aborted_on_value = max(aborted_on)
1300 else:
1301 aborted_by_value = 'autotest_system'
1302 aborted_on_value = int(time.time())
showard170873e2009-01-07 00:22:26 +00001303
showarda0382352009-02-11 23:36:43 +00001304 self._write_keyval_after_job("aborted_by", aborted_by_value)
1305 self._write_keyval_after_job("aborted_on", aborted_on_value)
showard170873e2009-01-07 00:22:26 +00001306
showardcbd74612008-11-19 21:42:02 +00001307 aborted_on_string = str(datetime.datetime.fromtimestamp(
1308 aborted_on_value))
1309 self._write_status_comment('Job aborted by %s on %s' %
1310 (aborted_by_value, aborted_on_string))
jadmanskic2ac77f2008-05-16 21:44:04 +00001311
1312
jadmanski0afbb632008-06-06 21:10:57 +00001313 def abort(self):
1314 super(QueueTask, self).abort()
jadmanskif7fa2cc2008-10-01 14:13:23 +00001315 self._log_abort()
showard97aed502008-11-04 02:01:24 +00001316 self._finish_task(False)
jadmanskic2ac77f2008-05-16 21:44:04 +00001317
1318
showard21baa452008-10-21 00:08:39 +00001319 def _reboot_hosts(self):
1320 reboot_after = self.job.reboot_after
1321 do_reboot = False
showard0fc38302008-10-23 00:44:07 +00001322 if reboot_after == models.RebootAfter.ALWAYS:
showard21baa452008-10-21 00:08:39 +00001323 do_reboot = True
showard0fc38302008-10-23 00:44:07 +00001324 elif reboot_after == models.RebootAfter.IF_ALL_TESTS_PASSED:
showard21baa452008-10-21 00:08:39 +00001325 num_tests_failed = self.monitor.num_tests_failed()
1326 do_reboot = (self.success and num_tests_failed == 0)
1327
showard8ebca792008-11-04 21:54:22 +00001328 for queue_entry in self.queue_entries:
1329 if do_reboot:
showard45ae8192008-11-05 19:32:53 +00001330 # don't pass the queue entry to the CleanupTask. if the cleanup
showardfa8629c2008-11-04 16:51:23 +00001331 # fails, the job doesn't care -- it's over.
showard45ae8192008-11-05 19:32:53 +00001332 cleanup_task = CleanupTask(host=queue_entry.get_host())
1333 self.agent.dispatcher.add_agent(Agent([cleanup_task]))
showard8ebca792008-11-04 21:54:22 +00001334 else:
1335 queue_entry.host.set_status('Ready')
showard21baa452008-10-21 00:08:39 +00001336
1337
jadmanski0afbb632008-06-06 21:10:57 +00001338 def epilog(self):
1339 super(QueueTask, self).epilog()
showard97aed502008-11-04 02:01:24 +00001340 self._finish_task(self.success)
showard21baa452008-10-21 00:08:39 +00001341 self._reboot_hosts()
mblighbb421852008-03-11 22:36:16 +00001342
showard97aed502008-11-04 02:01:24 +00001343 print "queue_task finished with succes=%s" % self.success
mbligh36768f02008-02-22 18:28:33 +00001344
1345
mblighbb421852008-03-11 22:36:16 +00001346class RecoveryQueueTask(QueueTask):
jadmanski0afbb632008-06-06 21:10:57 +00001347 def __init__(self, job, queue_entries, run_monitor):
showard170873e2009-01-07 00:22:26 +00001348 super(RecoveryQueueTask, self).__init__(job, queue_entries, cmd=None)
jadmanski0afbb632008-06-06 21:10:57 +00001349 self.run_monitor = run_monitor
mblighbb421852008-03-11 22:36:16 +00001350
1351
jadmanski0afbb632008-06-06 21:10:57 +00001352 def run(self):
1353 self.monitor = self.run_monitor
mblighbb421852008-03-11 22:36:16 +00001354
1355
jadmanski0afbb632008-06-06 21:10:57 +00001356 def prolog(self):
1357 # recovering an existing process - don't do prolog
1358 pass
mblighbb421852008-03-11 22:36:16 +00001359
1360
showard8fe93b52008-11-18 17:53:22 +00001361class CleanupTask(PreJobTask):
showardfa8629c2008-11-04 16:51:23 +00001362 def __init__(self, host=None, queue_entry=None):
1363 assert bool(host) ^ bool(queue_entry)
1364 if queue_entry:
1365 host = queue_entry.get_host()
showardfa8629c2008-11-04 16:51:23 +00001366 self.queue_entry = queue_entry
jadmanski0afbb632008-06-06 21:10:57 +00001367 self.host = host
showard170873e2009-01-07 00:22:26 +00001368
1369 self.create_temp_resultsdir('.cleanup')
1370 self.cmd = [_autoserv_path, '-p', '--cleanup', '-m', host.hostname,
1371 '-r', _drone_manager.absolute_path(self.temp_results_dir)]
showarde788ea62008-11-17 21:02:47 +00001372 repair_task = RepairTask(host, queue_entry=queue_entry)
showard170873e2009-01-07 00:22:26 +00001373 super(CleanupTask, self).__init__(self.cmd, self.temp_results_dir,
1374 failure_tasks=[repair_task])
1375
1376 self._set_ids(host=host, queue_entries=[queue_entry])
1377 self.set_host_log_file('cleanup', self.host)
mbligh16c722d2008-03-05 00:58:44 +00001378
mblighd5c95802008-03-05 00:33:46 +00001379
jadmanski0afbb632008-06-06 21:10:57 +00001380 def prolog(self):
showard8fe93b52008-11-18 17:53:22 +00001381 super(CleanupTask, self).prolog()
showard45ae8192008-11-05 19:32:53 +00001382 print "starting cleanup task for host: %s" % self.host.hostname
1383 self.host.set_status("Cleaning")
mblighd5c95802008-03-05 00:33:46 +00001384
mblighd5c95802008-03-05 00:33:46 +00001385
showard21baa452008-10-21 00:08:39 +00001386 def epilog(self):
showard45ae8192008-11-05 19:32:53 +00001387 super(CleanupTask, self).epilog()
showard21baa452008-10-21 00:08:39 +00001388 if self.success:
showardfa8629c2008-11-04 16:51:23 +00001389 self.host.set_status('Ready')
showard21baa452008-10-21 00:08:39 +00001390 self.host.update_field('dirty', 0)
1391
1392
mblighd5c95802008-03-05 00:33:46 +00001393class AbortTask(AgentTask):
jadmanski0afbb632008-06-06 21:10:57 +00001394 def __init__(self, queue_entry, agents_to_abort):
jadmanski0afbb632008-06-06 21:10:57 +00001395 super(AbortTask, self).__init__('')
showard170873e2009-01-07 00:22:26 +00001396 self.queue_entry = queue_entry
1397 # don't use _set_ids, since we don't want to set the host_ids
1398 self.queue_entry_ids = [queue_entry.id]
1399 self.agents_to_abort = agents_to_abort
mbligh36768f02008-02-22 18:28:33 +00001400
1401
jadmanski0afbb632008-06-06 21:10:57 +00001402 def prolog(self):
1403 print "starting abort on host %s, job %s" % (
1404 self.queue_entry.host_id, self.queue_entry.job_id)
mbligh36768f02008-02-22 18:28:33 +00001405
mblighd64e5702008-04-04 21:39:28 +00001406
jadmanski0afbb632008-06-06 21:10:57 +00001407 def epilog(self):
1408 super(AbortTask, self).epilog()
1409 self.queue_entry.set_status('Aborted')
1410 self.success = True
1411
1412
1413 def run(self):
1414 for agent in self.agents_to_abort:
1415 if (agent.active_task):
1416 agent.active_task.abort()
mbligh36768f02008-02-22 18:28:33 +00001417
1418
showard97aed502008-11-04 02:01:24 +00001419class FinalReparseTask(AgentTask):
showard97aed502008-11-04 02:01:24 +00001420 _num_running_parses = 0
1421
1422 def __init__(self, queue_entries):
1423 self._queue_entries = queue_entries
showard170873e2009-01-07 00:22:26 +00001424 # don't use _set_ids, since we don't want to set the host_ids
1425 self.queue_entry_ids = [entry.id for entry in queue_entries]
showard97aed502008-11-04 02:01:24 +00001426 self._parse_started = False
1427
1428 assert len(queue_entries) > 0
1429 queue_entry = queue_entries[0]
showard97aed502008-11-04 02:01:24 +00001430
showard170873e2009-01-07 00:22:26 +00001431 self._execution_tag = queue_entry.execution_tag()
1432 self._results_dir = _drone_manager.absolute_path(self._execution_tag)
1433 self._autoserv_monitor = PidfileRunMonitor()
1434 self._autoserv_monitor.attach_to_existing_process(self._execution_tag)
1435 self._final_status = self._determine_final_status()
1436
showard97aed502008-11-04 02:01:24 +00001437 if _testing_mode:
1438 self.cmd = 'true'
showard170873e2009-01-07 00:22:26 +00001439 else:
1440 super(FinalReparseTask, self).__init__(
1441 cmd=self._generate_parse_command(),
1442 working_directory=self._execution_tag)
showard97aed502008-11-04 02:01:24 +00001443
showard170873e2009-01-07 00:22:26 +00001444 self.log_file = os.path.join(self._execution_tag, '.parse.log')
showard97aed502008-11-04 02:01:24 +00001445
1446
1447 @classmethod
1448 def _increment_running_parses(cls):
1449 cls._num_running_parses += 1
1450
1451
1452 @classmethod
1453 def _decrement_running_parses(cls):
1454 cls._num_running_parses -= 1
1455
1456
1457 @classmethod
1458 def _can_run_new_parse(cls):
showardd1ee1dd2009-01-07 21:33:08 +00001459 return (cls._num_running_parses <
1460 scheduler_config.config.max_parse_processes)
showard97aed502008-11-04 02:01:24 +00001461
1462
showard170873e2009-01-07 00:22:26 +00001463 def _determine_final_status(self):
1464 # we'll use a PidfileRunMonitor to read the autoserv exit status
1465 if self._autoserv_monitor.exit_code() == 0:
1466 return models.HostQueueEntry.Status.COMPLETED
1467 return models.HostQueueEntry.Status.FAILED
1468
1469
showard97aed502008-11-04 02:01:24 +00001470 def prolog(self):
1471 super(FinalReparseTask, self).prolog()
1472 for queue_entry in self._queue_entries:
1473 queue_entry.set_status(models.HostQueueEntry.Status.PARSING)
1474
1475
1476 def epilog(self):
1477 super(FinalReparseTask, self).epilog()
showard97aed502008-11-04 02:01:24 +00001478 for queue_entry in self._queue_entries:
showard170873e2009-01-07 00:22:26 +00001479 queue_entry.set_status(self._final_status)
showard97aed502008-11-04 02:01:24 +00001480
1481
showard2bab8f42008-11-12 18:15:22 +00001482 def _generate_parse_command(self):
showard170873e2009-01-07 00:22:26 +00001483 return [_parser_path, '--write-pidfile', '-l', '2', '-r', '-o',
1484 self._results_dir]
showard97aed502008-11-04 02:01:24 +00001485
1486
1487 def poll(self):
1488 # override poll to keep trying to start until the parse count goes down
1489 # and we can, at which point we revert to default behavior
1490 if self._parse_started:
1491 super(FinalReparseTask, self).poll()
1492 else:
1493 self._try_starting_parse()
1494
1495
1496 def run(self):
1497 # override run() to not actually run unless we can
1498 self._try_starting_parse()
1499
1500
1501 def _try_starting_parse(self):
1502 if not self._can_run_new_parse():
1503 return
showard170873e2009-01-07 00:22:26 +00001504
showard678df4f2009-02-04 21:36:39 +00001505 # make sure we actually have results to parse
1506 if not self._autoserv_monitor.has_process():
1507 email_manager.manager.enqueue_notify_email(
1508 'No results to parse',
1509 'No results to parse at %s' % self._autoserv_monitor.pidfile_id)
1510 self.finished(False)
1511 return
1512
showard97aed502008-11-04 02:01:24 +00001513 # actually run the parse command
showard170873e2009-01-07 00:22:26 +00001514 self.monitor = PidfileRunMonitor()
1515 self.monitor.run(self.cmd, self._working_directory,
1516 log_file=self.log_file,
1517 pidfile_name='.parser_execute',
1518 paired_with_pidfile=self._autoserv_monitor.pidfile_id)
1519
showard97aed502008-11-04 02:01:24 +00001520 self._increment_running_parses()
1521 self._parse_started = True
1522
1523
1524 def finished(self, success):
1525 super(FinalReparseTask, self).finished(success)
showard678df4f2009-02-04 21:36:39 +00001526 if self._parse_started:
1527 self._decrement_running_parses()
showard97aed502008-11-04 02:01:24 +00001528
1529
showardc9ae1782009-01-30 01:42:37 +00001530class SetEntryPendingTask(AgentTask):
1531 def __init__(self, queue_entry):
1532 super(SetEntryPendingTask, self).__init__(cmd='')
1533 self._queue_entry = queue_entry
1534 self._set_ids(queue_entries=[queue_entry])
1535
1536
1537 def run(self):
1538 agent = self._queue_entry.on_pending()
1539 if agent:
1540 self.agent.dispatcher.add_agent(agent)
1541 self.finished(True)
1542
1543
mbligh36768f02008-02-22 18:28:33 +00001544class DBObject(object):
showard6ae5ea92009-02-25 00:11:51 +00001545
1546 # Subclasses MUST override these:
1547 _table_name = ''
1548 _fields = ()
1549
1550
jadmanski0afbb632008-06-06 21:10:57 +00001551 def __init__(self, id=None, row=None, new_record=False):
1552 assert (bool(id) != bool(row))
showard6ae5ea92009-02-25 00:11:51 +00001553 assert self._table_name, '_table_name must be defined in your class'
1554 assert self._fields, '_fields must be defined in your class'
mbligh36768f02008-02-22 18:28:33 +00001555
showard6ae5ea92009-02-25 00:11:51 +00001556 self.__table = self._table_name
mbligh36768f02008-02-22 18:28:33 +00001557
jadmanski0afbb632008-06-06 21:10:57 +00001558 self.__new_record = new_record
mbligh36768f02008-02-22 18:28:33 +00001559
jadmanski0afbb632008-06-06 21:10:57 +00001560 if row is None:
1561 sql = 'SELECT * FROM %s WHERE ID=%%s' % self.__table
1562 rows = _db.execute(sql, (id,))
1563 if len(rows) == 0:
1564 raise "row not found (table=%s, id=%s)" % \
1565 (self.__table, id)
1566 row = rows[0]
mbligh36768f02008-02-22 18:28:33 +00001567
showard2bab8f42008-11-12 18:15:22 +00001568 self._update_fields_from_row(row)
1569
1570
1571 def _update_fields_from_row(self, row):
jadmanski0afbb632008-06-06 21:10:57 +00001572 assert len(row) == self.num_cols(), (
1573 "table = %s, row = %s/%d, fields = %s/%d" % (
showard6ae5ea92009-02-25 00:11:51 +00001574 self.__table, row, len(row), self._fields, self.num_cols()))
mbligh36768f02008-02-22 18:28:33 +00001575
showard2bab8f42008-11-12 18:15:22 +00001576 self._valid_fields = set()
showard6ae5ea92009-02-25 00:11:51 +00001577 for field, value in zip(self._fields, row):
showard2bab8f42008-11-12 18:15:22 +00001578 setattr(self, field, value)
1579 self._valid_fields.add(field)
mbligh36768f02008-02-22 18:28:33 +00001580
showard2bab8f42008-11-12 18:15:22 +00001581 self._valid_fields.remove('id')
mbligh36768f02008-02-22 18:28:33 +00001582
mblighe2586682008-02-29 22:45:46 +00001583
jadmanski0afbb632008-06-06 21:10:57 +00001584 @classmethod
jadmanski0afbb632008-06-06 21:10:57 +00001585 def num_cols(cls):
showard6ae5ea92009-02-25 00:11:51 +00001586 return len(cls._fields)
showard04c82c52008-05-29 19:38:12 +00001587
1588
jadmanski0afbb632008-06-06 21:10:57 +00001589 def count(self, where, table = None):
1590 if not table:
1591 table = self.__table
mbligh36768f02008-02-22 18:28:33 +00001592
jadmanski0afbb632008-06-06 21:10:57 +00001593 rows = _db.execute("""
1594 SELECT count(*) FROM %s
1595 WHERE %s
1596 """ % (table, where))
mbligh6f8bab42008-02-29 22:45:14 +00001597
jadmanski0afbb632008-06-06 21:10:57 +00001598 assert len(rows) == 1
1599
1600 return int(rows[0][0])
mbligh36768f02008-02-22 18:28:33 +00001601
1602
mblighf8c624d2008-07-03 16:58:45 +00001603 def update_field(self, field, value, condition=''):
showard2bab8f42008-11-12 18:15:22 +00001604 assert field in self._valid_fields
mbligh36768f02008-02-22 18:28:33 +00001605
showard2bab8f42008-11-12 18:15:22 +00001606 if getattr(self, field) == value:
jadmanski0afbb632008-06-06 21:10:57 +00001607 return
mbligh36768f02008-02-22 18:28:33 +00001608
mblighf8c624d2008-07-03 16:58:45 +00001609 query = "UPDATE %s SET %s = %%s WHERE id = %%s" % (self.__table, field)
1610 if condition:
1611 query += ' AND (%s)' % condition
jadmanski0afbb632008-06-06 21:10:57 +00001612 _db.execute(query, (value, self.id))
1613
showard2bab8f42008-11-12 18:15:22 +00001614 setattr(self, field, value)
mbligh36768f02008-02-22 18:28:33 +00001615
1616
jadmanski0afbb632008-06-06 21:10:57 +00001617 def save(self):
1618 if self.__new_record:
showard6ae5ea92009-02-25 00:11:51 +00001619 keys = self._fields[1:] # avoid id
jadmanski0afbb632008-06-06 21:10:57 +00001620 columns = ','.join([str(key) for key in keys])
1621 values = ['"%s"' % self.__dict__[key] for key in keys]
1622 values = ','.join(values)
1623 query = """INSERT INTO %s (%s) VALUES (%s)""" % \
1624 (self.__table, columns, values)
1625 _db.execute(query)
mbligh36768f02008-02-22 18:28:33 +00001626
1627
jadmanski0afbb632008-06-06 21:10:57 +00001628 def delete(self):
1629 query = 'DELETE FROM %s WHERE id=%%s' % self.__table
1630 _db.execute(query, (self.id,))
mblighe2586682008-02-29 22:45:46 +00001631
1632
showard63a34772008-08-18 19:32:50 +00001633 @staticmethod
1634 def _prefix_with(string, prefix):
1635 if string:
1636 string = prefix + string
1637 return string
1638
1639
jadmanski0afbb632008-06-06 21:10:57 +00001640 @classmethod
showard989f25d2008-10-01 11:38:11 +00001641 def fetch(cls, where='', params=(), joins='', order_by=''):
showard63a34772008-08-18 19:32:50 +00001642 order_by = cls._prefix_with(order_by, 'ORDER BY ')
1643 where = cls._prefix_with(where, 'WHERE ')
1644 query = ('SELECT %(table)s.* FROM %(table)s %(joins)s '
showard6ae5ea92009-02-25 00:11:51 +00001645 '%(where)s %(order_by)s' % {'table' : cls._table_name,
showard63a34772008-08-18 19:32:50 +00001646 'joins' : joins,
1647 'where' : where,
1648 'order_by' : order_by})
1649 rows = _db.execute(query, params)
jadmanski0afbb632008-06-06 21:10:57 +00001650 for row in rows:
1651 yield cls(row=row)
mblighe2586682008-02-29 22:45:46 +00001652
mbligh36768f02008-02-22 18:28:33 +00001653
1654class IneligibleHostQueue(DBObject):
showard6ae5ea92009-02-25 00:11:51 +00001655 _table_name = 'ineligible_host_queues'
1656 _fields = ('id', 'job_id', 'host_id')
showard04c82c52008-05-29 19:38:12 +00001657
1658
showard989f25d2008-10-01 11:38:11 +00001659class Label(DBObject):
showard6ae5ea92009-02-25 00:11:51 +00001660 _table_name = 'labels'
1661 _fields = ('id', 'name', 'kernel_config', 'platform', 'invalid',
1662 'only_if_needed')
showard989f25d2008-10-01 11:38:11 +00001663
1664
mbligh36768f02008-02-22 18:28:33 +00001665class Host(DBObject):
showard6ae5ea92009-02-25 00:11:51 +00001666 _table_name = 'hosts'
1667 _fields = ('id', 'hostname', 'locked', 'synch_id', 'status',
1668 'invalid', 'protection', 'locked_by_id', 'lock_time', 'dirty')
1669
1670
jadmanski0afbb632008-06-06 21:10:57 +00001671 def __init__(self, id=None, row=None):
1672 super(Host, self).__init__(id=id, row=row)
mblighe2586682008-02-29 22:45:46 +00001673
1674
jadmanski0afbb632008-06-06 21:10:57 +00001675 def current_task(self):
1676 rows = _db.execute("""
1677 SELECT * FROM host_queue_entries WHERE host_id=%s AND NOT complete AND active
1678 """, (self.id,))
1679
1680 if len(rows) == 0:
1681 return None
1682 else:
1683 assert len(rows) == 1
1684 results = rows[0];
jadmanski0afbb632008-06-06 21:10:57 +00001685 return HostQueueEntry(row=results)
mbligh36768f02008-02-22 18:28:33 +00001686
1687
jadmanski0afbb632008-06-06 21:10:57 +00001688 def yield_work(self):
1689 print "%s yielding work" % self.hostname
1690 if self.current_task():
1691 self.current_task().requeue()
1692
showard6ae5ea92009-02-25 00:11:51 +00001693
jadmanski0afbb632008-06-06 21:10:57 +00001694 def set_status(self,status):
1695 print '%s -> %s' % (self.hostname, status)
1696 self.update_field('status',status)
mbligh36768f02008-02-22 18:28:33 +00001697
1698
showard170873e2009-01-07 00:22:26 +00001699 def platform_and_labels(self):
showardd8e548a2008-09-09 03:04:57 +00001700 """
showard170873e2009-01-07 00:22:26 +00001701 Returns a tuple (platform_name, list_of_all_label_names).
showardd8e548a2008-09-09 03:04:57 +00001702 """
1703 rows = _db.execute("""
showard170873e2009-01-07 00:22:26 +00001704 SELECT labels.name, labels.platform
showardd8e548a2008-09-09 03:04:57 +00001705 FROM labels
1706 INNER JOIN hosts_labels ON labels.id = hosts_labels.label_id
showard170873e2009-01-07 00:22:26 +00001707 WHERE hosts_labels.host_id = %s
showardd8e548a2008-09-09 03:04:57 +00001708 ORDER BY labels.name
1709 """, (self.id,))
showard170873e2009-01-07 00:22:26 +00001710 platform = None
1711 all_labels = []
1712 for label_name, is_platform in rows:
1713 if is_platform:
1714 platform = label_name
1715 all_labels.append(label_name)
1716 return platform, all_labels
1717
1718
1719 def reverify_tasks(self):
1720 cleanup_task = CleanupTask(host=self)
1721 verify_task = VerifyTask(host=self)
1722 # just to make sure this host does not get taken away
1723 self.set_status('Cleaning')
1724 return [cleanup_task, verify_task]
showardd8e548a2008-09-09 03:04:57 +00001725
1726
mbligh36768f02008-02-22 18:28:33 +00001727class HostQueueEntry(DBObject):
showard6ae5ea92009-02-25 00:11:51 +00001728 _table_name = 'host_queue_entries'
1729 _fields = ('id', 'job_id', 'host_id', 'status', 'meta_host',
1730 'active', 'complete', 'deleted', 'execution_subdir')
1731
1732
jadmanski0afbb632008-06-06 21:10:57 +00001733 def __init__(self, id=None, row=None):
1734 assert id or row
1735 super(HostQueueEntry, self).__init__(id=id, row=row)
1736 self.job = Job(self.job_id)
mbligh36768f02008-02-22 18:28:33 +00001737
jadmanski0afbb632008-06-06 21:10:57 +00001738 if self.host_id:
1739 self.host = Host(self.host_id)
1740 else:
1741 self.host = None
mbligh36768f02008-02-22 18:28:33 +00001742
showard170873e2009-01-07 00:22:26 +00001743 self.queue_log_path = os.path.join(self.job.tag(),
jadmanski0afbb632008-06-06 21:10:57 +00001744 'queue.log.' + str(self.id))
mbligh36768f02008-02-22 18:28:33 +00001745
1746
showardc85c21b2008-11-24 22:17:37 +00001747 def _view_job_url(self):
1748 return "%s#tab_id=view_job&object_id=%s" % (_base_url, self.job.id)
1749
1750
jadmanski0afbb632008-06-06 21:10:57 +00001751 def set_host(self, host):
1752 if host:
1753 self.queue_log_record('Assigning host ' + host.hostname)
1754 self.update_field('host_id', host.id)
1755 self.update_field('active', True)
1756 self.block_host(host.id)
1757 else:
1758 self.queue_log_record('Releasing host')
1759 self.unblock_host(self.host.id)
1760 self.update_field('host_id', None)
mbligh36768f02008-02-22 18:28:33 +00001761
jadmanski0afbb632008-06-06 21:10:57 +00001762 self.host = host
mbligh36768f02008-02-22 18:28:33 +00001763
1764
jadmanski0afbb632008-06-06 21:10:57 +00001765 def get_host(self):
1766 return self.host
mbligh36768f02008-02-22 18:28:33 +00001767
1768
jadmanski0afbb632008-06-06 21:10:57 +00001769 def queue_log_record(self, log_line):
1770 now = str(datetime.datetime.now())
showard170873e2009-01-07 00:22:26 +00001771 _drone_manager.write_lines_to_file(self.queue_log_path,
1772 [now + ' ' + log_line])
mbligh36768f02008-02-22 18:28:33 +00001773
1774
jadmanski0afbb632008-06-06 21:10:57 +00001775 def block_host(self, host_id):
1776 print "creating block %s/%s" % (self.job.id, host_id)
1777 row = [0, self.job.id, host_id]
1778 block = IneligibleHostQueue(row=row, new_record=True)
1779 block.save()
mblighe2586682008-02-29 22:45:46 +00001780
1781
jadmanski0afbb632008-06-06 21:10:57 +00001782 def unblock_host(self, host_id):
1783 print "removing block %s/%s" % (self.job.id, host_id)
1784 blocks = IneligibleHostQueue.fetch(
1785 'job_id=%d and host_id=%d' % (self.job.id, host_id))
1786 for block in blocks:
1787 block.delete()
mblighe2586682008-02-29 22:45:46 +00001788
1789
showard2bab8f42008-11-12 18:15:22 +00001790 def set_execution_subdir(self, subdir=None):
1791 if subdir is None:
1792 assert self.get_host()
1793 subdir = self.get_host().hostname
1794 self.update_field('execution_subdir', subdir)
mbligh36768f02008-02-22 18:28:33 +00001795
1796
showard6355f6b2008-12-05 18:52:13 +00001797 def _get_hostname(self):
1798 if self.host:
1799 return self.host.hostname
1800 return 'no host'
1801
1802
showard170873e2009-01-07 00:22:26 +00001803 def __str__(self):
1804 return "%s/%d (%d)" % (self._get_hostname(), self.job.id, self.id)
1805
1806
jadmanski0afbb632008-06-06 21:10:57 +00001807 def set_status(self, status):
mblighf8c624d2008-07-03 16:58:45 +00001808 abort_statuses = ['Abort', 'Aborting', 'Aborted']
1809 if status not in abort_statuses:
1810 condition = ' AND '.join(['status <> "%s"' % x
1811 for x in abort_statuses])
1812 else:
1813 condition = ''
1814 self.update_field('status', status, condition=condition)
1815
showard170873e2009-01-07 00:22:26 +00001816 print "%s -> %s" % (self, self.status)
mblighf8c624d2008-07-03 16:58:45 +00001817
showardc85c21b2008-11-24 22:17:37 +00001818 if status in ['Queued', 'Parsing']:
jadmanski0afbb632008-06-06 21:10:57 +00001819 self.update_field('complete', False)
1820 self.update_field('active', False)
mbligh36768f02008-02-22 18:28:33 +00001821
jadmanski0afbb632008-06-06 21:10:57 +00001822 if status in ['Pending', 'Running', 'Verifying', 'Starting',
showarde58e3f82008-11-20 19:04:59 +00001823 'Aborting']:
jadmanski0afbb632008-06-06 21:10:57 +00001824 self.update_field('complete', False)
1825 self.update_field('active', True)
mbligh36768f02008-02-22 18:28:33 +00001826
showardc85c21b2008-11-24 22:17:37 +00001827 if status in ['Failed', 'Completed', 'Stopped', 'Aborted']:
jadmanski0afbb632008-06-06 21:10:57 +00001828 self.update_field('complete', True)
1829 self.update_field('active', False)
showardc85c21b2008-11-24 22:17:37 +00001830
1831 should_email_status = (status.lower() in _notify_email_statuses or
1832 'all' in _notify_email_statuses)
1833 if should_email_status:
1834 self._email_on_status(status)
1835
1836 self._email_on_job_complete()
1837
1838
1839 def _email_on_status(self, status):
showard6355f6b2008-12-05 18:52:13 +00001840 hostname = self._get_hostname()
showardc85c21b2008-11-24 22:17:37 +00001841
1842 subject = 'Autotest: Job ID: %s "%s" Host: %s %s' % (
1843 self.job.id, self.job.name, hostname, status)
1844 body = "Job ID: %s\nJob Name: %s\nHost: %s\nStatus: %s\n%s\n" % (
1845 self.job.id, self.job.name, hostname, status,
1846 self._view_job_url())
showard170873e2009-01-07 00:22:26 +00001847 email_manager.manager.send_email(self.job.email_list, subject, body)
showard542e8402008-09-19 20:16:18 +00001848
1849
1850 def _email_on_job_complete(self):
showardc85c21b2008-11-24 22:17:37 +00001851 if not self.job.is_finished():
1852 return
showard542e8402008-09-19 20:16:18 +00001853
showardc85c21b2008-11-24 22:17:37 +00001854 summary_text = []
showard6355f6b2008-12-05 18:52:13 +00001855 hosts_queue = HostQueueEntry.fetch('job_id = %s' % self.job.id)
showardc85c21b2008-11-24 22:17:37 +00001856 for queue_entry in hosts_queue:
1857 summary_text.append("Host: %s Status: %s" %
showard6355f6b2008-12-05 18:52:13 +00001858 (queue_entry._get_hostname(),
showardc85c21b2008-11-24 22:17:37 +00001859 queue_entry.status))
1860
1861 summary_text = "\n".join(summary_text)
1862 status_counts = models.Job.objects.get_status_counts(
1863 [self.job.id])[self.job.id]
1864 status = ', '.join('%d %s' % (count, status) for status, count
1865 in status_counts.iteritems())
1866
1867 subject = 'Autotest: Job ID: %s "%s" %s' % (
1868 self.job.id, self.job.name, status)
1869 body = "Job ID: %s\nJob Name: %s\nStatus: %s\n%s\nSummary:\n%s" % (
1870 self.job.id, self.job.name, status, self._view_job_url(),
1871 summary_text)
showard170873e2009-01-07 00:22:26 +00001872 email_manager.manager.send_email(self.job.email_list, subject, body)
mbligh36768f02008-02-22 18:28:33 +00001873
1874
jadmanski0afbb632008-06-06 21:10:57 +00001875 def run(self,assigned_host=None):
1876 if self.meta_host:
1877 assert assigned_host
1878 # ensure results dir exists for the queue log
jadmanski0afbb632008-06-06 21:10:57 +00001879 self.set_host(assigned_host)
mbligh36768f02008-02-22 18:28:33 +00001880
jadmanski0afbb632008-06-06 21:10:57 +00001881 print "%s/%s scheduled on %s, status=%s" % (self.job.name,
1882 self.meta_host, self.host.hostname, self.status)
mbligh36768f02008-02-22 18:28:33 +00001883
jadmanski0afbb632008-06-06 21:10:57 +00001884 return self.job.run(queue_entry=self)
mblighe2586682008-02-29 22:45:46 +00001885
showard6ae5ea92009-02-25 00:11:51 +00001886
jadmanski0afbb632008-06-06 21:10:57 +00001887 def requeue(self):
1888 self.set_status('Queued')
showardde634ee2009-01-30 01:44:24 +00001889 # verify/cleanup failure sets the execution subdir, so reset it here
1890 self.set_execution_subdir('')
jadmanski0afbb632008-06-06 21:10:57 +00001891 if self.meta_host:
1892 self.set_host(None)
mbligh36768f02008-02-22 18:28:33 +00001893
1894
jadmanski0afbb632008-06-06 21:10:57 +00001895 def handle_host_failure(self):
1896 """\
1897 Called when this queue entry's host has failed verification and
1898 repair.
1899 """
1900 assert not self.meta_host
1901 self.set_status('Failed')
showard2bab8f42008-11-12 18:15:22 +00001902 self.job.stop_if_necessary()
mblighe2586682008-02-29 22:45:46 +00001903
1904
jadmanskif7fa2cc2008-10-01 14:13:23 +00001905 @property
1906 def aborted_by(self):
1907 self._load_abort_info()
1908 return self._aborted_by
1909
1910
1911 @property
1912 def aborted_on(self):
1913 self._load_abort_info()
1914 return self._aborted_on
1915
1916
1917 def _load_abort_info(self):
1918 """ Fetch info about who aborted the job. """
1919 if hasattr(self, "_aborted_by"):
1920 return
1921 rows = _db.execute("""
1922 SELECT users.login, aborted_host_queue_entries.aborted_on
1923 FROM aborted_host_queue_entries
1924 INNER JOIN users
1925 ON users.id = aborted_host_queue_entries.aborted_by_id
1926 WHERE aborted_host_queue_entries.queue_entry_id = %s
1927 """, (self.id,))
1928 if rows:
1929 self._aborted_by, self._aborted_on = rows[0]
1930 else:
1931 self._aborted_by = self._aborted_on = None
1932
1933
showardb2e2c322008-10-14 17:33:55 +00001934 def on_pending(self):
1935 """
1936 Called when an entry in a synchronous job has passed verify. If the
1937 job is ready to run, returns an agent to run the job. Returns None
1938 otherwise.
1939 """
1940 self.set_status('Pending')
showardcfd66a32008-10-15 20:31:48 +00001941 self.get_host().set_status('Pending')
showardb2e2c322008-10-14 17:33:55 +00001942 if self.job.is_ready():
1943 return self.job.run(self)
showard2bab8f42008-11-12 18:15:22 +00001944 self.job.stop_if_necessary()
showardb2e2c322008-10-14 17:33:55 +00001945 return None
1946
1947
showard170873e2009-01-07 00:22:26 +00001948 def abort(self, dispatcher, agents_to_abort=[]):
showard1be97432008-10-17 15:30:45 +00001949 host = self.get_host()
showard9d9ffd52008-11-09 23:14:35 +00001950 if self.active and host:
showard170873e2009-01-07 00:22:26 +00001951 dispatcher.add_agent(Agent(tasks=host.reverify_tasks()))
showard1be97432008-10-17 15:30:45 +00001952
showard170873e2009-01-07 00:22:26 +00001953 abort_task = AbortTask(self, agents_to_abort)
showard1be97432008-10-17 15:30:45 +00001954 self.set_status('Aborting')
showard170873e2009-01-07 00:22:26 +00001955 dispatcher.add_agent(Agent(tasks=[abort_task], num_processes=0))
1956
1957 def execution_tag(self):
1958 assert self.execution_subdir
1959 return "%s-%s/%s" % (self.job.id, self.job.owner, self.execution_subdir)
showard1be97432008-10-17 15:30:45 +00001960
1961
mbligh36768f02008-02-22 18:28:33 +00001962class Job(DBObject):
showard6ae5ea92009-02-25 00:11:51 +00001963 _table_name = 'jobs'
1964 _fields = ('id', 'owner', 'name', 'priority', 'control_file',
1965 'control_type', 'created_on', 'synch_count', 'timeout',
1966 'run_verify', 'email_list', 'reboot_before', 'reboot_after')
1967
1968
jadmanski0afbb632008-06-06 21:10:57 +00001969 def __init__(self, id=None, row=None):
1970 assert id or row
1971 super(Job, self).__init__(id=id, row=row)
mbligh36768f02008-02-22 18:28:33 +00001972
mblighe2586682008-02-29 22:45:46 +00001973
jadmanski0afbb632008-06-06 21:10:57 +00001974 def is_server_job(self):
1975 return self.control_type != 2
mbligh36768f02008-02-22 18:28:33 +00001976
1977
showard170873e2009-01-07 00:22:26 +00001978 def tag(self):
1979 return "%s-%s" % (self.id, self.owner)
1980
1981
jadmanski0afbb632008-06-06 21:10:57 +00001982 def get_host_queue_entries(self):
1983 rows = _db.execute("""
1984 SELECT * FROM host_queue_entries
1985 WHERE job_id= %s
1986 """, (self.id,))
1987 entries = [HostQueueEntry(row=i) for i in rows]
mbligh36768f02008-02-22 18:28:33 +00001988
jadmanski0afbb632008-06-06 21:10:57 +00001989 assert len(entries)>0
mbligh36768f02008-02-22 18:28:33 +00001990
jadmanski0afbb632008-06-06 21:10:57 +00001991 return entries
mbligh36768f02008-02-22 18:28:33 +00001992
1993
jadmanski0afbb632008-06-06 21:10:57 +00001994 def set_status(self, status, update_queues=False):
1995 self.update_field('status',status)
1996
1997 if update_queues:
1998 for queue_entry in self.get_host_queue_entries():
1999 queue_entry.set_status(status)
mbligh36768f02008-02-22 18:28:33 +00002000
2001
jadmanski0afbb632008-06-06 21:10:57 +00002002 def is_ready(self):
showard2bab8f42008-11-12 18:15:22 +00002003 pending_entries = models.HostQueueEntry.objects.filter(job=self.id,
2004 status='Pending')
2005 return (pending_entries.count() >= self.synch_count)
mbligh36768f02008-02-22 18:28:33 +00002006
2007
jadmanski0afbb632008-06-06 21:10:57 +00002008 def num_machines(self, clause = None):
2009 sql = "job_id=%s" % self.id
2010 if clause:
2011 sql += " AND (%s)" % clause
2012 return self.count(sql, table='host_queue_entries')
mbligh36768f02008-02-22 18:28:33 +00002013
2014
jadmanski0afbb632008-06-06 21:10:57 +00002015 def num_queued(self):
2016 return self.num_machines('not complete')
mbligh36768f02008-02-22 18:28:33 +00002017
2018
jadmanski0afbb632008-06-06 21:10:57 +00002019 def num_active(self):
2020 return self.num_machines('active')
mbligh36768f02008-02-22 18:28:33 +00002021
2022
jadmanski0afbb632008-06-06 21:10:57 +00002023 def num_complete(self):
2024 return self.num_machines('complete')
mbligh36768f02008-02-22 18:28:33 +00002025
2026
jadmanski0afbb632008-06-06 21:10:57 +00002027 def is_finished(self):
showardc85c21b2008-11-24 22:17:37 +00002028 return self.num_complete() == self.num_machines()
mbligh36768f02008-02-22 18:28:33 +00002029
mbligh36768f02008-02-22 18:28:33 +00002030
showard6bb7c292009-01-30 01:44:51 +00002031 def _not_yet_run_entries(self, include_verifying=True):
2032 statuses = [models.HostQueueEntry.Status.QUEUED,
2033 models.HostQueueEntry.Status.PENDING]
2034 if include_verifying:
2035 statuses.append(models.HostQueueEntry.Status.VERIFYING)
2036 return models.HostQueueEntry.objects.filter(job=self.id,
2037 status__in=statuses)
2038
2039
2040 def _stop_all_entries(self):
2041 entries_to_stop = self._not_yet_run_entries(
2042 include_verifying=False)
2043 for child_entry in entries_to_stop:
showard4f9e5372009-01-07 21:33:38 +00002044 assert not child_entry.complete, (
2045 '%s status=%s, active=%s, complete=%s' %
2046 (child_entry.id, child_entry.status, child_entry.active,
2047 child_entry.complete))
showard2bab8f42008-11-12 18:15:22 +00002048 if child_entry.status == models.HostQueueEntry.Status.PENDING:
2049 child_entry.host.status = models.Host.Status.READY
2050 child_entry.host.save()
2051 child_entry.status = models.HostQueueEntry.Status.STOPPED
2052 child_entry.save()
2053
showard2bab8f42008-11-12 18:15:22 +00002054 def stop_if_necessary(self):
showard6bb7c292009-01-30 01:44:51 +00002055 not_yet_run = self._not_yet_run_entries()
showard2bab8f42008-11-12 18:15:22 +00002056 if not_yet_run.count() < self.synch_count:
showard6bb7c292009-01-30 01:44:51 +00002057 self._stop_all_entries()
mblighe2586682008-02-29 22:45:46 +00002058
2059
jadmanski0afbb632008-06-06 21:10:57 +00002060 def write_to_machines_file(self, queue_entry):
2061 hostname = queue_entry.get_host().hostname
showard170873e2009-01-07 00:22:26 +00002062 file_path = os.path.join(self.tag(), '.machines')
2063 _drone_manager.write_lines_to_file(file_path, [hostname])
mbligh36768f02008-02-22 18:28:33 +00002064
2065
showard2bab8f42008-11-12 18:15:22 +00002066 def _next_group_name(self):
2067 query = models.HostQueueEntry.objects.filter(
2068 job=self.id).values('execution_subdir').distinct()
2069 subdirs = (entry['execution_subdir'] for entry in query)
2070 groups = (re.match(r'group(\d+)', subdir) for subdir in subdirs)
2071 ids = [int(match.group(1)) for match in groups if match]
2072 if ids:
2073 next_id = max(ids) + 1
2074 else:
2075 next_id = 0
2076 return "group%d" % next_id
2077
2078
showard170873e2009-01-07 00:22:26 +00002079 def _write_control_file(self, execution_tag):
2080 control_path = _drone_manager.attach_file_to_execution(
2081 execution_tag, self.control_file)
2082 return control_path
mbligh36768f02008-02-22 18:28:33 +00002083
showardb2e2c322008-10-14 17:33:55 +00002084
showard2bab8f42008-11-12 18:15:22 +00002085 def get_group_entries(self, queue_entry_from_group):
2086 execution_subdir = queue_entry_from_group.execution_subdir
showarde788ea62008-11-17 21:02:47 +00002087 return list(HostQueueEntry.fetch(
2088 where='job_id=%s AND execution_subdir=%s',
2089 params=(self.id, execution_subdir)))
showard2bab8f42008-11-12 18:15:22 +00002090
2091
showardb2e2c322008-10-14 17:33:55 +00002092 def _get_autoserv_params(self, queue_entries):
showard170873e2009-01-07 00:22:26 +00002093 assert queue_entries
2094 execution_tag = queue_entries[0].execution_tag()
2095 control_path = self._write_control_file(execution_tag)
jadmanski0afbb632008-06-06 21:10:57 +00002096 hostnames = ','.join([entry.get_host().hostname
2097 for entry in queue_entries])
mbligh36768f02008-02-22 18:28:33 +00002098
showard170873e2009-01-07 00:22:26 +00002099 params = [_autoserv_path, '-P', execution_tag, '-p', '-n',
2100 '-r', _drone_manager.absolute_path(execution_tag),
2101 '-u', self.owner, '-l', self.name, '-m', hostnames,
2102 _drone_manager.absolute_path(control_path)]
mbligh36768f02008-02-22 18:28:33 +00002103
jadmanski0afbb632008-06-06 21:10:57 +00002104 if not self.is_server_job():
2105 params.append('-c')
mbligh36768f02008-02-22 18:28:33 +00002106
showardb2e2c322008-10-14 17:33:55 +00002107 return params
mblighe2586682008-02-29 22:45:46 +00002108
mbligh36768f02008-02-22 18:28:33 +00002109
showardc9ae1782009-01-30 01:42:37 +00002110 def _should_run_cleanup(self, queue_entry):
showard0fc38302008-10-23 00:44:07 +00002111 if self.reboot_before == models.RebootBefore.ALWAYS:
showardc9ae1782009-01-30 01:42:37 +00002112 return True
showard0fc38302008-10-23 00:44:07 +00002113 elif self.reboot_before == models.RebootBefore.IF_DIRTY:
showardc9ae1782009-01-30 01:42:37 +00002114 return queue_entry.get_host().dirty
2115 return False
showard21baa452008-10-21 00:08:39 +00002116
showardc9ae1782009-01-30 01:42:37 +00002117
2118 def _should_run_verify(self, queue_entry):
2119 do_not_verify = (queue_entry.host.protection ==
2120 host_protections.Protection.DO_NOT_VERIFY)
2121 if do_not_verify:
2122 return False
2123 return self.run_verify
2124
2125
2126 def _get_pre_job_tasks(self, queue_entry):
showard21baa452008-10-21 00:08:39 +00002127 tasks = []
showardc9ae1782009-01-30 01:42:37 +00002128 if self._should_run_cleanup(queue_entry):
showard45ae8192008-11-05 19:32:53 +00002129 tasks.append(CleanupTask(queue_entry=queue_entry))
showardc9ae1782009-01-30 01:42:37 +00002130 if self._should_run_verify(queue_entry):
2131 tasks.append(VerifyTask(queue_entry=queue_entry))
2132 tasks.append(SetEntryPendingTask(queue_entry))
showard21baa452008-10-21 00:08:39 +00002133 return tasks
2134
2135
showard2bab8f42008-11-12 18:15:22 +00002136 def _assign_new_group(self, queue_entries):
2137 if len(queue_entries) == 1:
2138 group_name = queue_entries[0].get_host().hostname
2139 else:
2140 group_name = self._next_group_name()
2141 print 'Running synchronous job %d hosts %s as %s' % (
2142 self.id, [entry.host.hostname for entry in queue_entries],
2143 group_name)
2144
2145 for queue_entry in queue_entries:
2146 queue_entry.set_execution_subdir(group_name)
2147
2148
2149 def _choose_group_to_run(self, include_queue_entry):
2150 chosen_entries = [include_queue_entry]
2151
2152 num_entries_needed = self.synch_count - 1
2153 if num_entries_needed > 0:
2154 pending_entries = HostQueueEntry.fetch(
2155 where='job_id = %s AND status = "Pending" AND id != %s',
2156 params=(self.id, include_queue_entry.id))
2157 chosen_entries += list(pending_entries)[:num_entries_needed]
2158
2159 self._assign_new_group(chosen_entries)
2160 return chosen_entries
2161
2162
2163 def run(self, queue_entry):
showardb2e2c322008-10-14 17:33:55 +00002164 if not self.is_ready():
showardc9ae1782009-01-30 01:42:37 +00002165 queue_entry.set_status(models.HostQueueEntry.Status.VERIFYING)
2166 return Agent(self._get_pre_job_tasks(queue_entry))
mbligh36768f02008-02-22 18:28:33 +00002167
showard2bab8f42008-11-12 18:15:22 +00002168 queue_entries = self._choose_group_to_run(queue_entry)
2169 return self._finish_run(queue_entries)
showardb2e2c322008-10-14 17:33:55 +00002170
2171
2172 def _finish_run(self, queue_entries, initial_tasks=[]):
showardb2ccdda2008-10-28 20:39:05 +00002173 for queue_entry in queue_entries:
2174 queue_entry.set_status('Starting')
showardb2e2c322008-10-14 17:33:55 +00002175 params = self._get_autoserv_params(queue_entries)
2176 queue_task = QueueTask(job=self, queue_entries=queue_entries,
2177 cmd=params)
2178 tasks = initial_tasks + [queue_task]
2179 entry_ids = [entry.id for entry in queue_entries]
2180
showard170873e2009-01-07 00:22:26 +00002181 return Agent(tasks, num_processes=len(queue_entries))
showardb2e2c322008-10-14 17:33:55 +00002182
2183
mbligh36768f02008-02-22 18:28:33 +00002184if __name__ == '__main__':
jadmanski0afbb632008-06-06 21:10:57 +00002185 main()