blob: a1f217925b03384395f23db42419ed7e4671a5fd [file] [log] [blame]
mbligh36768f02008-02-22 18:28:33 +00001#!/usr/bin/python -u
2
3"""
4Autotest scheduler
5"""
showard909c7a62008-07-15 21:52:38 +00006
mbligh36768f02008-02-22 18:28:33 +00007
showard542e8402008-09-19 20:16:18 +00008import datetime, errno, MySQLdb, optparse, os, pwd, Queue, re, shutil, signal
9import smtplib, socket, stat, subprocess, sys, tempfile, time, traceback
mbligh70feeee2008-06-11 16:20:49 +000010import common
showard542e8402008-09-19 20:16:18 +000011from autotest_lib.client.common_lib import global_config
12from autotest_lib.client.common_lib import host_protections, utils
showardb1e51872008-10-07 11:08:18 +000013from autotest_lib.database import database_connection
mbligh70feeee2008-06-11 16:20:49 +000014
mblighb090f142008-02-27 21:33:46 +000015
mbligh36768f02008-02-22 18:28:33 +000016RESULTS_DIR = '.'
17AUTOSERV_NICE_LEVEL = 10
showardb1e51872008-10-07 11:08:18 +000018CONFIG_SECTION = 'AUTOTEST_WEB'
mbligh36768f02008-02-22 18:28:33 +000019
20AUTOTEST_PATH = os.path.join(os.path.dirname(__file__), '..')
21
22if os.environ.has_key('AUTOTEST_DIR'):
jadmanski0afbb632008-06-06 21:10:57 +000023 AUTOTEST_PATH = os.environ['AUTOTEST_DIR']
mbligh36768f02008-02-22 18:28:33 +000024AUTOTEST_SERVER_DIR = os.path.join(AUTOTEST_PATH, 'server')
25AUTOTEST_TKO_DIR = os.path.join(AUTOTEST_PATH, 'tko')
26
27if AUTOTEST_SERVER_DIR not in sys.path:
jadmanski0afbb632008-06-06 21:10:57 +000028 sys.path.insert(0, AUTOTEST_SERVER_DIR)
mbligh36768f02008-02-22 18:28:33 +000029
mblighbb421852008-03-11 22:36:16 +000030AUTOSERV_PID_FILE = '.autoserv_execute'
mbligh90a549d2008-03-25 23:52:34 +000031# how long to wait for autoserv to write a pidfile
32PIDFILE_TIMEOUT = 5 * 60 # 5 min
mblighbb421852008-03-11 22:36:16 +000033
mbligh6f8bab42008-02-29 22:45:14 +000034_db = None
mbligh36768f02008-02-22 18:28:33 +000035_shutdown = False
36_notify_email = None
mbligh4314a712008-02-29 22:44:30 +000037_autoserv_path = 'autoserv'
38_testing_mode = False
showardec113162008-05-08 00:52:49 +000039_global_config_section = 'SCHEDULER'
showard542e8402008-09-19 20:16:18 +000040_base_url = None
41# see os.getlogin() online docs
42_email_from = pwd.getpwuid(os.getuid())[0]
mbligh36768f02008-02-22 18:28:33 +000043
44
45def main():
jadmanski0afbb632008-06-06 21:10:57 +000046 usage = 'usage: %prog [options] results_dir'
mbligh36768f02008-02-22 18:28:33 +000047
jadmanski0afbb632008-06-06 21:10:57 +000048 parser = optparse.OptionParser(usage)
49 parser.add_option('--recover-hosts', help='Try to recover dead hosts',
50 action='store_true')
51 parser.add_option('--logfile', help='Set a log file that all stdout ' +
52 'should be redirected to. Stderr will go to this ' +
53 'file + ".err"')
54 parser.add_option('--test', help='Indicate that scheduler is under ' +
55 'test and should use dummy autoserv and no parsing',
56 action='store_true')
57 (options, args) = parser.parse_args()
58 if len(args) != 1:
59 parser.print_usage()
60 return
mbligh36768f02008-02-22 18:28:33 +000061
jadmanski0afbb632008-06-06 21:10:57 +000062 global RESULTS_DIR
63 RESULTS_DIR = args[0]
mbligh36768f02008-02-22 18:28:33 +000064
jadmanski0afbb632008-06-06 21:10:57 +000065 # read in notify_email from global_config
66 c = global_config.global_config
67 global _notify_email
68 val = c.get_config_value(_global_config_section, "notify_email")
69 if val != "":
70 _notify_email = val
mbligh36768f02008-02-22 18:28:33 +000071
showard3bb499f2008-07-03 19:42:20 +000072 tick_pause = c.get_config_value(
73 _global_config_section, 'tick_pause_sec', type=int)
74
jadmanski0afbb632008-06-06 21:10:57 +000075 if options.test:
76 global _autoserv_path
77 _autoserv_path = 'autoserv_dummy'
78 global _testing_mode
79 _testing_mode = True
mbligh36768f02008-02-22 18:28:33 +000080
showard542e8402008-09-19 20:16:18 +000081 # read in base url
82 global _base_url
showardb1e51872008-10-07 11:08:18 +000083 val = c.get_config_value(CONFIG_SECTION, "base_url")
showard542e8402008-09-19 20:16:18 +000084 if val:
85 _base_url = val
86 else:
87 _base_url = "http://your_autotest_server/afe/"
88
jadmanski0afbb632008-06-06 21:10:57 +000089 init(options.logfile)
90 dispatcher = Dispatcher()
91 dispatcher.do_initial_recovery(recover_hosts=options.recover_hosts)
92
93 try:
94 while not _shutdown:
95 dispatcher.tick()
showard3bb499f2008-07-03 19:42:20 +000096 time.sleep(tick_pause)
jadmanski0afbb632008-06-06 21:10:57 +000097 except:
98 log_stacktrace("Uncaught exception; terminating monitor_db")
99
100 email_manager.send_queued_emails()
101 _db.disconnect()
mbligh36768f02008-02-22 18:28:33 +0000102
103
104def handle_sigint(signum, frame):
jadmanski0afbb632008-06-06 21:10:57 +0000105 global _shutdown
106 _shutdown = True
107 print "Shutdown request received."
mbligh36768f02008-02-22 18:28:33 +0000108
109
110def init(logfile):
jadmanski0afbb632008-06-06 21:10:57 +0000111 if logfile:
112 enable_logging(logfile)
113 print "%s> dispatcher starting" % time.strftime("%X %x")
114 print "My PID is %d" % os.getpid()
mbligh36768f02008-02-22 18:28:33 +0000115
showardb1e51872008-10-07 11:08:18 +0000116 if _testing_mode:
117 global_config.global_config.override_config_value(
118 CONFIG_SECTION, 'database', 'stresstest_autotest_web')
119
jadmanski0afbb632008-06-06 21:10:57 +0000120 os.environ['PATH'] = AUTOTEST_SERVER_DIR + ':' + os.environ['PATH']
121 global _db
showardb1e51872008-10-07 11:08:18 +0000122 _db = database_connection.DatabaseConnection(CONFIG_SECTION)
jadmanski0afbb632008-06-06 21:10:57 +0000123 _db.connect()
mbligh36768f02008-02-22 18:28:33 +0000124
jadmanski0afbb632008-06-06 21:10:57 +0000125 print "Setting signal handler"
126 signal.signal(signal.SIGINT, handle_sigint)
127
128 print "Connected! Running..."
mbligh36768f02008-02-22 18:28:33 +0000129
130
131def enable_logging(logfile):
jadmanski0afbb632008-06-06 21:10:57 +0000132 out_file = logfile
133 err_file = "%s.err" % logfile
134 print "Enabling logging to %s (%s)" % (out_file, err_file)
135 out_fd = open(out_file, "a", buffering=0)
136 err_fd = open(err_file, "a", buffering=0)
mbligh36768f02008-02-22 18:28:33 +0000137
jadmanski0afbb632008-06-06 21:10:57 +0000138 os.dup2(out_fd.fileno(), sys.stdout.fileno())
139 os.dup2(err_fd.fileno(), sys.stderr.fileno())
mbligh36768f02008-02-22 18:28:33 +0000140
jadmanski0afbb632008-06-06 21:10:57 +0000141 sys.stdout = out_fd
142 sys.stderr = err_fd
mbligh36768f02008-02-22 18:28:33 +0000143
144
mblighd5c95802008-03-05 00:33:46 +0000145def queue_entries_to_abort():
jadmanski0afbb632008-06-06 21:10:57 +0000146 rows = _db.execute("""
147 SELECT * FROM host_queue_entries WHERE status='Abort';
148 """)
149 qe = [HostQueueEntry(row=i) for i in rows]
150 return qe
mbligh36768f02008-02-22 18:28:33 +0000151
mblighe2586682008-02-29 22:45:46 +0000152def remove_file_or_dir(path):
jadmanski0afbb632008-06-06 21:10:57 +0000153 if stat.S_ISDIR(os.stat(path).st_mode):
154 # directory
155 shutil.rmtree(path)
156 else:
157 # file
158 os.remove(path)
mblighe2586682008-02-29 22:45:46 +0000159
160
mblighdbdac6c2008-03-05 15:49:58 +0000161def generate_parse_command(results_dir, flags=""):
jadmanski0afbb632008-06-06 21:10:57 +0000162 parse = os.path.abspath(os.path.join(AUTOTEST_TKO_DIR, 'parse'))
163 output = os.path.abspath(os.path.join(results_dir, '.parse.log'))
164 cmd = "%s %s -r -o %s > %s 2>&1 &"
165 return cmd % (parse, flags, results_dir, output)
mblighdbdac6c2008-03-05 15:49:58 +0000166
167
showard970a6db2008-09-03 20:02:39 +0000168_parse_command_queue = []
mbligh36768f02008-02-22 18:28:33 +0000169def parse_results(results_dir, flags=""):
jadmanski0afbb632008-06-06 21:10:57 +0000170 if _testing_mode:
171 return
showard970a6db2008-09-03 20:02:39 +0000172 _parse_command_queue.append(generate_parse_command(results_dir, flags))
mbligh36768f02008-02-22 18:28:33 +0000173
174
mblighbb421852008-03-11 22:36:16 +0000175
176
mbligh36768f02008-02-22 18:28:33 +0000177def log_stacktrace(reason):
jadmanski0afbb632008-06-06 21:10:57 +0000178 (type, value, tb) = sys.exc_info()
179 str = "EXCEPTION: %s\n" % reason
180 str += ''.join(traceback.format_exception(type, value, tb))
mbligh36768f02008-02-22 18:28:33 +0000181
jadmanski0afbb632008-06-06 21:10:57 +0000182 sys.stderr.write("\n%s\n" % str)
183 email_manager.enqueue_notify_email("monitor_db exception", str)
mbligh36768f02008-02-22 18:28:33 +0000184
mblighbb421852008-03-11 22:36:16 +0000185
186def get_proc_poll_fn(pid):
jadmanski0afbb632008-06-06 21:10:57 +0000187 proc_path = os.path.join('/proc', str(pid))
188 def poll_fn():
189 if os.path.exists(proc_path):
190 return None
191 return 0 # we can't get a real exit code
192 return poll_fn
mblighbb421852008-03-11 22:36:16 +0000193
194
showard542e8402008-09-19 20:16:18 +0000195def send_email(from_addr, to_string, subject, body):
196 """Mails out emails to the addresses listed in to_string.
197
198 to_string is split into a list which can be delimited by any of:
199 ';', ',', ':' or any whitespace
200 """
201
202 # Create list from string removing empty strings from the list.
203 to_list = [x for x in re.split('\s|,|;|:', to_string) if x]
showard7d182aa2008-09-22 16:17:24 +0000204 if not to_list:
205 return
206
showard542e8402008-09-19 20:16:18 +0000207 msg = "From: %s\nTo: %s\nSubject: %s\n\n%s" % (
208 from_addr, ', '.join(to_list), subject, body)
showard7d182aa2008-09-22 16:17:24 +0000209 try:
210 mailer = smtplib.SMTP('localhost')
211 try:
212 mailer.sendmail(from_addr, to_list, msg)
213 finally:
214 mailer.quit()
215 except Exception, e:
216 print "Sending email failed. Reason: %s" % repr(e)
showard542e8402008-09-19 20:16:18 +0000217
218
mblighbb421852008-03-11 22:36:16 +0000219def kill_autoserv(pid, poll_fn=None):
jadmanski0afbb632008-06-06 21:10:57 +0000220 print 'killing', pid
221 if poll_fn is None:
222 poll_fn = get_proc_poll_fn(pid)
223 if poll_fn() == None:
224 os.kill(pid, signal.SIGCONT)
225 os.kill(pid, signal.SIGTERM)
mbligh36768f02008-02-22 18:28:33 +0000226
227
showard7cf9a9b2008-05-15 21:15:52 +0000228class EmailNotificationManager(object):
jadmanski0afbb632008-06-06 21:10:57 +0000229 def __init__(self):
230 self._emails = []
showard7cf9a9b2008-05-15 21:15:52 +0000231
jadmanski0afbb632008-06-06 21:10:57 +0000232 def enqueue_notify_email(self, subject, message):
233 if not _notify_email:
234 return
showard7cf9a9b2008-05-15 21:15:52 +0000235
jadmanski0afbb632008-06-06 21:10:57 +0000236 body = 'Subject: ' + subject + '\n'
237 body += "%s / %s / %s\n%s" % (socket.gethostname(),
238 os.getpid(),
239 time.strftime("%X %x"), message)
240 self._emails.append(body)
showard7cf9a9b2008-05-15 21:15:52 +0000241
242
jadmanski0afbb632008-06-06 21:10:57 +0000243 def send_queued_emails(self):
244 if not self._emails:
245 return
246 subject = 'Scheduler notifications from ' + socket.gethostname()
247 separator = '\n' + '-' * 40 + '\n'
248 body = separator.join(self._emails)
showard7cf9a9b2008-05-15 21:15:52 +0000249
showard542e8402008-09-19 20:16:18 +0000250 send_email(_email_from, _notify_email, subject, body)
jadmanski0afbb632008-06-06 21:10:57 +0000251 self._emails = []
showard7cf9a9b2008-05-15 21:15:52 +0000252
253email_manager = EmailNotificationManager()
254
255
showard63a34772008-08-18 19:32:50 +0000256class HostScheduler(object):
257 def _get_ready_hosts(self):
258 # avoid any host with a currently active queue entry against it
259 hosts = Host.fetch(
260 joins='LEFT JOIN host_queue_entries AS active_hqe '
261 'ON (hosts.id = active_hqe.host_id AND '
showardb1e51872008-10-07 11:08:18 +0000262 'active_hqe.active)',
showard63a34772008-08-18 19:32:50 +0000263 where="active_hqe.host_id IS NULL "
showardb1e51872008-10-07 11:08:18 +0000264 "AND NOT hosts.locked "
showard63a34772008-08-18 19:32:50 +0000265 "AND (hosts.status IS NULL OR hosts.status = 'Ready')")
266 return dict((host.id, host) for host in hosts)
267
268
269 @staticmethod
270 def _get_sql_id_list(id_list):
271 return ','.join(str(item_id) for item_id in id_list)
272
273
274 @classmethod
showard989f25d2008-10-01 11:38:11 +0000275 def _get_many2many_dict(cls, query, id_list, flip=False):
mbligh849a0f62008-08-28 20:12:19 +0000276 if not id_list:
277 return {}
showard63a34772008-08-18 19:32:50 +0000278 query %= cls._get_sql_id_list(id_list)
279 rows = _db.execute(query)
showard989f25d2008-10-01 11:38:11 +0000280 return cls._process_many2many_dict(rows, flip)
281
282
283 @staticmethod
284 def _process_many2many_dict(rows, flip=False):
showard63a34772008-08-18 19:32:50 +0000285 result = {}
286 for row in rows:
287 left_id, right_id = long(row[0]), long(row[1])
showard989f25d2008-10-01 11:38:11 +0000288 if flip:
289 left_id, right_id = right_id, left_id
showard63a34772008-08-18 19:32:50 +0000290 result.setdefault(left_id, set()).add(right_id)
291 return result
292
293
294 @classmethod
295 def _get_job_acl_groups(cls, job_ids):
296 query = """
297 SELECT jobs.id, acl_groups_users.acl_group_id
298 FROM jobs
299 INNER JOIN users ON users.login = jobs.owner
300 INNER JOIN acl_groups_users ON acl_groups_users.user_id = users.id
301 WHERE jobs.id IN (%s)
302 """
303 return cls._get_many2many_dict(query, job_ids)
304
305
306 @classmethod
307 def _get_job_ineligible_hosts(cls, job_ids):
308 query = """
309 SELECT job_id, host_id
310 FROM ineligible_host_queues
311 WHERE job_id IN (%s)
312 """
313 return cls._get_many2many_dict(query, job_ids)
314
315
316 @classmethod
showard989f25d2008-10-01 11:38:11 +0000317 def _get_job_dependencies(cls, job_ids):
318 query = """
319 SELECT job_id, label_id
320 FROM jobs_dependency_labels
321 WHERE job_id IN (%s)
322 """
323 return cls._get_many2many_dict(query, job_ids)
324
325
326 @classmethod
showard63a34772008-08-18 19:32:50 +0000327 def _get_host_acls(cls, host_ids):
328 query = """
329 SELECT host_id, acl_group_id
330 FROM acl_groups_hosts
331 WHERE host_id IN (%s)
332 """
333 return cls._get_many2many_dict(query, host_ids)
334
335
336 @classmethod
337 def _get_label_hosts(cls, host_ids):
338 query = """
339 SELECT label_id, host_id
340 FROM hosts_labels
341 WHERE host_id IN (%s)
showard989f25d2008-10-01 11:38:11 +0000342 """ % cls._get_sql_id_list(host_ids)
343 rows = _db.execute(query)
344 labels_to_hosts = cls._process_many2many_dict(rows)
345 hosts_to_labels = cls._process_many2many_dict(rows, flip=True)
346 return labels_to_hosts, hosts_to_labels
347
348
349 @classmethod
350 def _get_labels(cls):
351 return dict((label.id, label) for label in Label.fetch())
showard63a34772008-08-18 19:32:50 +0000352
353
354 def refresh(self, pending_queue_entries):
355 self._hosts_available = self._get_ready_hosts()
356
357 relevant_jobs = [queue_entry.job_id
358 for queue_entry in pending_queue_entries]
359 self._job_acls = self._get_job_acl_groups(relevant_jobs)
360 self._ineligible_hosts = self._get_job_ineligible_hosts(relevant_jobs)
showard989f25d2008-10-01 11:38:11 +0000361 self._job_dependencies = self._get_job_dependencies(relevant_jobs)
showard63a34772008-08-18 19:32:50 +0000362
363 host_ids = self._hosts_available.keys()
364 self._host_acls = self._get_host_acls(host_ids)
showard989f25d2008-10-01 11:38:11 +0000365 self._label_hosts, self._host_labels = self._get_label_hosts(host_ids)
366
367 self._labels = self._get_labels()
showard63a34772008-08-18 19:32:50 +0000368
369
370 def _is_acl_accessible(self, host_id, queue_entry):
371 job_acls = self._job_acls.get(queue_entry.job_id, set())
372 host_acls = self._host_acls.get(host_id, set())
373 return len(host_acls.intersection(job_acls)) > 0
374
375
showard989f25d2008-10-01 11:38:11 +0000376 def _check_job_dependencies(self, job_dependencies, host_labels):
377 missing = job_dependencies - host_labels
378 return len(job_dependencies - host_labels) == 0
379
380
381 def _check_only_if_needed_labels(self, job_dependencies, host_labels,
382 queue_entry):
383 for label_id in host_labels:
384 label = self._labels[label_id]
385 if not label.only_if_needed:
386 # we don't care about non-only_if_needed labels
387 continue
388 if queue_entry.meta_host == label_id:
389 # if the label was requested in a metahost it's OK
390 continue
391 if label_id not in job_dependencies:
392 return False
393 return True
394
395
396 def _is_host_eligible_for_job(self, host_id, queue_entry):
397 job_dependencies = self._job_dependencies.get(queue_entry.job_id, set())
398 host_labels = self._host_labels.get(host_id, set())
mblighc993bee2008-10-03 03:42:34 +0000399
400 acl = self._is_acl_accessible(host_id, queue_entry)
401 deps = self._check_job_dependencies(job_dependencies, host_labels)
402 only_if = self._check_only_if_needed_labels(job_dependencies,
403 host_labels, queue_entry)
404 return acl and deps and only_if
showard989f25d2008-10-01 11:38:11 +0000405
406
showard63a34772008-08-18 19:32:50 +0000407 def _schedule_non_metahost(self, queue_entry):
showard989f25d2008-10-01 11:38:11 +0000408 if not self._is_host_eligible_for_job(queue_entry.host_id, queue_entry):
showard63a34772008-08-18 19:32:50 +0000409 return None
410 return self._hosts_available.pop(queue_entry.host_id, None)
411
412
413 def _is_host_usable(self, host_id):
414 if host_id not in self._hosts_available:
415 # host was already used during this scheduling cycle
416 return False
417 if self._hosts_available[host_id].invalid:
418 # Invalid hosts cannot be used for metahosts. They're included in
419 # the original query because they can be used by non-metahosts.
420 return False
421 return True
422
423
424 def _schedule_metahost(self, queue_entry):
425 label_id = queue_entry.meta_host
426 hosts_in_label = self._label_hosts.get(label_id, set())
427 ineligible_host_ids = self._ineligible_hosts.get(queue_entry.job_id,
428 set())
429
430 # must iterate over a copy so we can mutate the original while iterating
431 for host_id in list(hosts_in_label):
432 if not self._is_host_usable(host_id):
433 hosts_in_label.remove(host_id)
434 continue
435 if host_id in ineligible_host_ids:
436 continue
showard989f25d2008-10-01 11:38:11 +0000437 if not self._is_host_eligible_for_job(host_id, queue_entry):
showard63a34772008-08-18 19:32:50 +0000438 continue
439
440 hosts_in_label.remove(host_id)
441 return self._hosts_available.pop(host_id)
442 return None
443
444
445 def find_eligible_host(self, queue_entry):
446 if not queue_entry.meta_host:
447 return self._schedule_non_metahost(queue_entry)
448 return self._schedule_metahost(queue_entry)
449
450
mbligh36768f02008-02-22 18:28:33 +0000451class Dispatcher:
jadmanski0afbb632008-06-06 21:10:57 +0000452 autoserv_procs_cache = None
showard4c5374f2008-09-04 17:02:56 +0000453 max_running_processes = global_config.global_config.get_config_value(
jadmanski0afbb632008-06-06 21:10:57 +0000454 _global_config_section, 'max_running_jobs', type=int)
showard4c5374f2008-09-04 17:02:56 +0000455 max_processes_started_per_cycle = (
jadmanski0afbb632008-06-06 21:10:57 +0000456 global_config.global_config.get_config_value(
457 _global_config_section, 'max_jobs_started_per_cycle', type=int))
showard3bb499f2008-07-03 19:42:20 +0000458 clean_interval = (
459 global_config.global_config.get_config_value(
460 _global_config_section, 'clean_interval_minutes', type=int))
showard970a6db2008-09-03 20:02:39 +0000461 max_parse_processes = (
462 global_config.global_config.get_config_value(
463 _global_config_section, 'max_parse_processes', type=int))
mbligh90a549d2008-03-25 23:52:34 +0000464
jadmanski0afbb632008-06-06 21:10:57 +0000465 def __init__(self):
466 self._agents = []
showard3bb499f2008-07-03 19:42:20 +0000467 self._last_clean_time = time.time()
showard63a34772008-08-18 19:32:50 +0000468 self._host_scheduler = HostScheduler()
mbligh36768f02008-02-22 18:28:33 +0000469
mbligh36768f02008-02-22 18:28:33 +0000470
jadmanski0afbb632008-06-06 21:10:57 +0000471 def do_initial_recovery(self, recover_hosts=True):
472 # always recover processes
473 self._recover_processes()
mblighbb421852008-03-11 22:36:16 +0000474
jadmanski0afbb632008-06-06 21:10:57 +0000475 if recover_hosts:
476 self._recover_hosts()
mbligh36768f02008-02-22 18:28:33 +0000477
478
jadmanski0afbb632008-06-06 21:10:57 +0000479 def tick(self):
480 Dispatcher.autoserv_procs_cache = None
showard3bb499f2008-07-03 19:42:20 +0000481 if self._last_clean_time + self.clean_interval * 60 < time.time():
482 self._abort_timed_out_jobs()
483 self._clear_inactive_blocks()
484 self._last_clean_time = time.time()
jadmanski0afbb632008-06-06 21:10:57 +0000485 self._find_aborting()
486 self._schedule_new_jobs()
487 self._handle_agents()
showard970a6db2008-09-03 20:02:39 +0000488 self._run_final_parses()
jadmanski0afbb632008-06-06 21:10:57 +0000489 email_manager.send_queued_emails()
mbligh36768f02008-02-22 18:28:33 +0000490
491
showard970a6db2008-09-03 20:02:39 +0000492 def _run_final_parses(self):
493 process_count = 0
494 try:
495 for line in utils.system_output('ps -e').splitlines():
496 if 'parse.py' in line:
497 process_count += 1
498 except Exception:
499 # We'll try again in a bit. This is a work-around for one time
500 # when the scheduler crashed due to a "Interrupted system call"
501 return
502
503 if process_count:
504 print "%d parses currently running" % process_count
505
506 while (process_count < self.max_parse_processes and
507 _parse_command_queue):
508 cmd = _parse_command_queue.pop(0)
509 print "Starting another final parse with cmd %s" % cmd
510 os.system(cmd)
511 process_count += 1
512
513 if _parse_command_queue:
514 print ("%d cmds still in final parse queue" %
515 len(_parse_command_queue))
516
517
jadmanski0afbb632008-06-06 21:10:57 +0000518 def add_agent(self, agent):
519 self._agents.append(agent)
520 agent.dispatcher = self
mblighd5c95802008-03-05 00:33:46 +0000521
jadmanski0afbb632008-06-06 21:10:57 +0000522 # Find agent corresponding to the specified queue_entry
523 def get_agents(self, queue_entry):
524 res_agents = []
525 for agent in self._agents:
526 if queue_entry.id in agent.queue_entry_ids:
527 res_agents.append(agent)
528 return res_agents
mbligh36768f02008-02-22 18:28:33 +0000529
530
jadmanski0afbb632008-06-06 21:10:57 +0000531 def remove_agent(self, agent):
532 self._agents.remove(agent)
showardec113162008-05-08 00:52:49 +0000533
534
showard4c5374f2008-09-04 17:02:56 +0000535 def num_running_processes(self):
536 return sum(agent.num_processes for agent in self._agents
537 if agent.is_running())
mblighbb421852008-03-11 22:36:16 +0000538
539
jadmanski0afbb632008-06-06 21:10:57 +0000540 @classmethod
541 def find_autoservs(cls, orphans_only=False):
542 """\
543 Returns a dict mapping pids to command lines for root autoserv
544 processes. If orphans_only=True, return only processes that
545 have been orphaned (i.e. parent pid = 1).
546 """
547 if cls.autoserv_procs_cache is not None:
548 return cls.autoserv_procs_cache
549
550 proc = subprocess.Popen(
551 ['/bin/ps', 'x', '-o', 'pid,pgid,ppid,comm,args'],
552 stdout=subprocess.PIPE)
553 # split each line into the four columns output by ps
554 procs = [line.split(None, 4) for line in
555 proc.communicate()[0].splitlines()]
556 autoserv_procs = {}
557 for proc in procs:
558 # check ppid == 1 for orphans
559 if orphans_only and proc[2] != 1:
560 continue
561 # only root autoserv processes have pgid == pid
562 if (proc[3] == 'autoserv' and # comm
563 proc[1] == proc[0]): # pgid == pid
564 # map pid to args
565 autoserv_procs[int(proc[0])] = proc[4]
566 cls.autoserv_procs_cache = autoserv_procs
567 return autoserv_procs
mblighbb421852008-03-11 22:36:16 +0000568
569
jadmanski0afbb632008-06-06 21:10:57 +0000570 def recover_queue_entry(self, queue_entry, run_monitor):
571 job = queue_entry.job
572 if job.is_synchronous():
573 all_queue_entries = job.get_host_queue_entries()
574 else:
575 all_queue_entries = [queue_entry]
576 all_queue_entry_ids = [queue_entry.id for queue_entry
577 in all_queue_entries]
578 queue_task = RecoveryQueueTask(
579 job=queue_entry.job,
580 queue_entries=all_queue_entries,
581 run_monitor=run_monitor)
582 self.add_agent(Agent(tasks=[queue_task],
583 queue_entry_ids=all_queue_entry_ids))
mblighbb421852008-03-11 22:36:16 +0000584
585
jadmanski0afbb632008-06-06 21:10:57 +0000586 def _recover_processes(self):
587 orphans = self.find_autoservs(orphans_only=True)
mblighbb421852008-03-11 22:36:16 +0000588
jadmanski0afbb632008-06-06 21:10:57 +0000589 # first, recover running queue entries
590 rows = _db.execute("""SELECT * FROM host_queue_entries
591 WHERE status = 'Running'""")
592 queue_entries = [HostQueueEntry(row=i) for i in rows]
593 requeue_entries = []
594 recovered_entry_ids = set()
595 for queue_entry in queue_entries:
596 run_monitor = PidfileRunMonitor(
597 queue_entry.results_dir())
jadmanski0afbb632008-06-06 21:10:57 +0000598 pid, exit_code = run_monitor.get_pidfile_info()
599 if pid is None:
600 # autoserv apparently never got run, so requeue
601 requeue_entries.append(queue_entry)
602 continue
603 if queue_entry.id in recovered_entry_ids:
604 # synchronous job we've already recovered
605 continue
606 print 'Recovering queue entry %d (pid %d)' % (
607 queue_entry.id, pid)
608 job = queue_entry.job
609 if job.is_synchronous():
610 for entry in job.get_host_queue_entries():
611 assert entry.active
612 recovered_entry_ids.add(entry.id)
613 self.recover_queue_entry(queue_entry,
614 run_monitor)
615 orphans.pop(pid, None)
mblighd5c95802008-03-05 00:33:46 +0000616
jadmanski0afbb632008-06-06 21:10:57 +0000617 # and requeue other active queue entries
618 rows = _db.execute("""SELECT * FROM host_queue_entries
619 WHERE active AND NOT complete
620 AND status != 'Running'
621 AND status != 'Pending'
622 AND status != 'Abort'
623 AND status != 'Aborting'""")
624 queue_entries = [HostQueueEntry(row=i) for i in rows]
625 for queue_entry in queue_entries + requeue_entries:
626 print 'Requeuing running QE %d' % queue_entry.id
627 queue_entry.clear_results_dir(dont_delete_files=True)
628 queue_entry.requeue()
mbligh90a549d2008-03-25 23:52:34 +0000629
630
jadmanski0afbb632008-06-06 21:10:57 +0000631 # now kill any remaining autoserv processes
632 for pid in orphans.keys():
633 print 'Killing orphan %d (%s)' % (pid, orphans[pid])
634 kill_autoserv(pid)
635
636 # recover aborting tasks
637 rebooting_host_ids = set()
638 rows = _db.execute("""SELECT * FROM host_queue_entries
639 WHERE status='Abort' or status='Aborting'""")
640 queue_entries = [HostQueueEntry(row=i) for i in rows]
641 for queue_entry in queue_entries:
642 print 'Recovering aborting QE %d' % queue_entry.id
showard1be97432008-10-17 15:30:45 +0000643 agent = queue_entry.abort()
644 self.add_agent(agent)
645 if queue_entry.get_host():
646 rebooting_host_ids.add(queue_entry.get_host().id)
jadmanski0afbb632008-06-06 21:10:57 +0000647
648 # reverify hosts that were in the middle of verify, repair or
649 # reboot
650 self._reverify_hosts_where("""(status = 'Repairing' OR
651 status = 'Verifying' OR
652 status = 'Rebooting')""",
653 exclude_ids=rebooting_host_ids)
654
655 # finally, recover "Running" hosts with no active queue entries,
656 # although this should never happen
657 message = ('Recovering running host %s - this probably '
658 'indicates a scheduler bug')
659 self._reverify_hosts_where("""status = 'Running' AND
660 id NOT IN (SELECT host_id
661 FROM host_queue_entries
662 WHERE active)""",
663 print_message=message)
mblighbb421852008-03-11 22:36:16 +0000664
665
jadmanski0afbb632008-06-06 21:10:57 +0000666 def _reverify_hosts_where(self, where,
667 print_message='Reverifying host %s',
668 exclude_ids=set()):
669 rows = _db.execute('SELECT * FROM hosts WHERE locked = 0 AND '
670 'invalid = 0 AND ' + where)
671 hosts = [Host(row=i) for i in rows]
672 for host in hosts:
673 if host.id in exclude_ids:
674 continue
675 if print_message is not None:
676 print print_message % host.hostname
677 verify_task = VerifyTask(host = host)
678 self.add_agent(Agent(tasks = [verify_task]))
mbligh36768f02008-02-22 18:28:33 +0000679
680
jadmanski0afbb632008-06-06 21:10:57 +0000681 def _recover_hosts(self):
682 # recover "Repair Failed" hosts
683 message = 'Reverifying dead host %s'
684 self._reverify_hosts_where("status = 'Repair Failed'",
685 print_message=message)
mbligh62ba2ed2008-04-30 17:09:25 +0000686
687
showard3bb499f2008-07-03 19:42:20 +0000688 def _abort_timed_out_jobs(self):
689 """
690 Aborts all jobs that have timed out and not completed
691 """
692 update = """
693 UPDATE host_queue_entries INNER JOIN jobs
694 ON host_queue_entries.job_id = jobs.id"""
mbligh7e26d622008-07-29 21:04:42 +0000695 timed_out = ' AND jobs.created_on + INTERVAL jobs.timeout HOUR < NOW()'
showard3bb499f2008-07-03 19:42:20 +0000696
697 _db.execute(update + """
698 SET host_queue_entries.status = 'Abort'
showardb1e51872008-10-07 11:08:18 +0000699 WHERE host_queue_entries.active""" + timed_out)
showard3bb499f2008-07-03 19:42:20 +0000700
701 _db.execute(update + """
702 SET host_queue_entries.status = 'Aborted',
showardb1e51872008-10-07 11:08:18 +0000703 host_queue_entries.active = 0,
704 host_queue_entries.complete = 1
705 WHERE NOT host_queue_entries.active
706 AND NOT host_queue_entries.complete""" + timed_out)
showard3bb499f2008-07-03 19:42:20 +0000707
708
jadmanski0afbb632008-06-06 21:10:57 +0000709 def _clear_inactive_blocks(self):
710 """
711 Clear out blocks for all completed jobs.
712 """
713 # this would be simpler using NOT IN (subquery), but MySQL
714 # treats all IN subqueries as dependent, so this optimizes much
715 # better
716 _db.execute("""
717 DELETE ihq FROM ineligible_host_queues ihq
showard4eaaf522008-06-06 22:28:07 +0000718 LEFT JOIN (SELECT DISTINCT job_id FROM host_queue_entries
jadmanski0afbb632008-06-06 21:10:57 +0000719 WHERE NOT complete) hqe
720 USING (job_id) WHERE hqe.job_id IS NULL""")
showard04c82c52008-05-29 19:38:12 +0000721
722
showardb95b1bd2008-08-15 18:11:04 +0000723 def _get_pending_queue_entries(self):
showard63a34772008-08-18 19:32:50 +0000724 # prioritize by job priority, then non-metahost over metahost, then FIFO
725 return list(HostQueueEntry.fetch(
726 where='NOT complete AND NOT active',
727 order_by='priority DESC, meta_host, id'))
mbligh36768f02008-02-22 18:28:33 +0000728
729
jadmanski0afbb632008-06-06 21:10:57 +0000730 def _schedule_new_jobs(self):
731 print "finding work"
732
showard63a34772008-08-18 19:32:50 +0000733 queue_entries = self._get_pending_queue_entries()
734 if not queue_entries:
showardb95b1bd2008-08-15 18:11:04 +0000735 return
showardb95b1bd2008-08-15 18:11:04 +0000736
showard63a34772008-08-18 19:32:50 +0000737 self._host_scheduler.refresh(queue_entries)
showardb95b1bd2008-08-15 18:11:04 +0000738
showard63a34772008-08-18 19:32:50 +0000739 for queue_entry in queue_entries:
740 assigned_host = self._host_scheduler.find_eligible_host(queue_entry)
showardb95b1bd2008-08-15 18:11:04 +0000741 if not assigned_host:
jadmanski0afbb632008-06-06 21:10:57 +0000742 continue
showardb95b1bd2008-08-15 18:11:04 +0000743 self._run_queue_entry(queue_entry, assigned_host)
744
745
746 def _run_queue_entry(self, queue_entry, host):
747 agent = queue_entry.run(assigned_host=host)
showard9976ce92008-10-15 20:28:13 +0000748 # in some cases (synchronous jobs with run_verify=False), agent may be None
749 if agent:
750 self.add_agent(agent)
mblighd5c95802008-03-05 00:33:46 +0000751
752
jadmanski0afbb632008-06-06 21:10:57 +0000753 def _find_aborting(self):
754 num_aborted = 0
755 # Find jobs that are aborting
756 for entry in queue_entries_to_abort():
757 agents_to_abort = self.get_agents(entry)
showard1be97432008-10-17 15:30:45 +0000758 for agent in agents_to_abort:
759 self.remove_agent(agent)
760
761 agent = entry.abort(agents_to_abort)
762 self.add_agent(agent)
jadmanski0afbb632008-06-06 21:10:57 +0000763 num_aborted += 1
764 if num_aborted >= 50:
765 break
766
767
showard4c5374f2008-09-04 17:02:56 +0000768 def _can_start_agent(self, agent, num_running_processes,
769 num_started_this_cycle, have_reached_limit):
770 # always allow zero-process agents to run
771 if agent.num_processes == 0:
772 return True
773 # don't allow any nonzero-process agents to run after we've reached a
774 # limit (this avoids starvation of many-process agents)
775 if have_reached_limit:
776 return False
777 # total process throttling
778 if (num_running_processes + agent.num_processes >
779 self.max_running_processes):
780 return False
781 # if a single agent exceeds the per-cycle throttling, still allow it to
782 # run when it's the first agent in the cycle
783 if num_started_this_cycle == 0:
784 return True
785 # per-cycle throttling
786 if (num_started_this_cycle + agent.num_processes >
787 self.max_processes_started_per_cycle):
788 return False
789 return True
790
791
jadmanski0afbb632008-06-06 21:10:57 +0000792 def _handle_agents(self):
showard4c5374f2008-09-04 17:02:56 +0000793 num_running_processes = self.num_running_processes()
jadmanski0afbb632008-06-06 21:10:57 +0000794 num_started_this_cycle = 0
showard4c5374f2008-09-04 17:02:56 +0000795 have_reached_limit = False
796 # iterate over copy, so we can remove agents during iteration
797 for agent in list(self._agents):
798 if agent.is_done():
jadmanski0afbb632008-06-06 21:10:57 +0000799 print "agent finished"
showard4c5374f2008-09-04 17:02:56 +0000800 self._agents.remove(agent)
801 num_running_processes -= agent.num_processes
802 continue
803 if not agent.is_running():
804 if not self._can_start_agent(agent, num_running_processes,
805 num_started_this_cycle,
806 have_reached_limit):
807 have_reached_limit = True
808 continue
809 num_running_processes += agent.num_processes
810 num_started_this_cycle += agent.num_processes
811 agent.tick()
812 print num_running_processes, 'running processes'
mbligh36768f02008-02-22 18:28:33 +0000813
814
815class RunMonitor(object):
jadmanski0afbb632008-06-06 21:10:57 +0000816 def __init__(self, cmd, nice_level = None, log_file = None):
817 self.nice_level = nice_level
818 self.log_file = log_file
819 self.cmd = cmd
mbligh36768f02008-02-22 18:28:33 +0000820
jadmanski0afbb632008-06-06 21:10:57 +0000821 def run(self):
822 if self.nice_level:
823 nice_cmd = ['nice','-n', str(self.nice_level)]
824 nice_cmd.extend(self.cmd)
825 self.cmd = nice_cmd
mbligh36768f02008-02-22 18:28:33 +0000826
jadmanski0afbb632008-06-06 21:10:57 +0000827 out_file = None
828 if self.log_file:
829 try:
830 os.makedirs(os.path.dirname(self.log_file))
831 except OSError, exc:
832 if exc.errno != errno.EEXIST:
833 log_stacktrace(
834 'Unexpected error creating logfile '
835 'directory for %s' % self.log_file)
836 try:
837 out_file = open(self.log_file, 'a')
838 out_file.write("\n%s\n" % ('*'*80))
839 out_file.write("%s> %s\n" %
840 (time.strftime("%X %x"),
841 self.cmd))
842 out_file.write("%s\n" % ('*'*80))
843 except (OSError, IOError):
844 log_stacktrace('Error opening log file %s' %
845 self.log_file)
mblighcadb3532008-04-15 17:46:26 +0000846
jadmanski0afbb632008-06-06 21:10:57 +0000847 if not out_file:
848 out_file = open('/dev/null', 'w')
mblighcadb3532008-04-15 17:46:26 +0000849
jadmanski0afbb632008-06-06 21:10:57 +0000850 in_devnull = open('/dev/null', 'r')
851 print "cmd = %s" % self.cmd
852 print "path = %s" % os.getcwd()
mbligh36768f02008-02-22 18:28:33 +0000853
jadmanski0afbb632008-06-06 21:10:57 +0000854 self.proc = subprocess.Popen(self.cmd, stdout=out_file,
855 stderr=subprocess.STDOUT,
856 stdin=in_devnull)
857 out_file.close()
858 in_devnull.close()
mbligh36768f02008-02-22 18:28:33 +0000859
860
jadmanski0afbb632008-06-06 21:10:57 +0000861 def get_pid(self):
862 return self.proc.pid
mblighbb421852008-03-11 22:36:16 +0000863
864
jadmanski0afbb632008-06-06 21:10:57 +0000865 def kill(self):
866 kill_autoserv(self.get_pid(), self.exit_code)
mblighbb421852008-03-11 22:36:16 +0000867
mbligh36768f02008-02-22 18:28:33 +0000868
jadmanski0afbb632008-06-06 21:10:57 +0000869 def exit_code(self):
870 return self.proc.poll()
mbligh36768f02008-02-22 18:28:33 +0000871
872
mblighbb421852008-03-11 22:36:16 +0000873class PidfileException(Exception):
jadmanski0afbb632008-06-06 21:10:57 +0000874 """\
875 Raised when there's some unexpected behavior with the pid file.
876 """
mblighbb421852008-03-11 22:36:16 +0000877
878
879class PidfileRunMonitor(RunMonitor):
jadmanski0afbb632008-06-06 21:10:57 +0000880 def __init__(self, results_dir, cmd=None, nice_level=None,
881 log_file=None):
882 self.results_dir = os.path.abspath(results_dir)
883 self.pid_file = os.path.join(results_dir, AUTOSERV_PID_FILE)
884 self.lost_process = False
885 self.start_time = time.time()
showardb376bc52008-06-13 20:48:45 +0000886 super(PidfileRunMonitor, self).__init__(cmd, nice_level, log_file)
mblighbb421852008-03-11 22:36:16 +0000887
888
jadmanski0afbb632008-06-06 21:10:57 +0000889 def get_pid(self):
890 pid, exit_status = self.get_pidfile_info()
891 assert pid is not None
892 return pid
mblighbb421852008-03-11 22:36:16 +0000893
894
jadmanski0afbb632008-06-06 21:10:57 +0000895 def _check_command_line(self, command_line, spacer=' ',
896 print_error=False):
897 results_dir_arg = spacer.join(('', '-r', self.results_dir, ''))
898 match = results_dir_arg in command_line
899 if print_error and not match:
900 print '%s not found in %s' % (repr(results_dir_arg),
901 repr(command_line))
902 return match
mbligh90a549d2008-03-25 23:52:34 +0000903
904
jadmanski0afbb632008-06-06 21:10:57 +0000905 def _check_proc_fs(self, pid):
906 cmdline_path = os.path.join('/proc', str(pid), 'cmdline')
907 try:
908 cmdline_file = open(cmdline_path, 'r')
909 cmdline = cmdline_file.read().strip()
910 cmdline_file.close()
911 except IOError:
912 return False
913 # /proc/.../cmdline has \x00 separating args
914 return self._check_command_line(cmdline, spacer='\x00',
915 print_error=True)
mblighbb421852008-03-11 22:36:16 +0000916
917
jadmanski0afbb632008-06-06 21:10:57 +0000918 def read_pidfile(self):
919 if not os.path.exists(self.pid_file):
920 return None, None
921 file_obj = open(self.pid_file, 'r')
922 lines = file_obj.readlines()
923 file_obj.close()
924 assert 1 <= len(lines) <= 2
925 try:
926 pid = int(lines[0])
927 exit_status = None
928 if len(lines) == 2:
929 exit_status = int(lines[1])
930 except ValueError, exc:
931 raise PidfileException('Corrupt pid file: ' +
932 str(exc.args))
mblighbb421852008-03-11 22:36:16 +0000933
jadmanski0afbb632008-06-06 21:10:57 +0000934 return pid, exit_status
mblighbb421852008-03-11 22:36:16 +0000935
936
jadmanski0afbb632008-06-06 21:10:57 +0000937 def _find_autoserv_proc(self):
938 autoserv_procs = Dispatcher.find_autoservs()
939 for pid, args in autoserv_procs.iteritems():
940 if self._check_command_line(args):
941 return pid, args
942 return None, None
mbligh90a549d2008-03-25 23:52:34 +0000943
944
jadmanski0afbb632008-06-06 21:10:57 +0000945 def get_pidfile_info(self):
946 """\
947 Returns:
948 None, None if autoserv has not yet run
949 pid, None if autoserv is running
950 pid, exit_status if autoserv has completed
951 """
952 if self.lost_process:
953 return self.pid, self.exit_status
mblighbb421852008-03-11 22:36:16 +0000954
jadmanski0afbb632008-06-06 21:10:57 +0000955 pid, exit_status = self.read_pidfile()
mblighbb421852008-03-11 22:36:16 +0000956
jadmanski0afbb632008-06-06 21:10:57 +0000957 if pid is None:
958 return self._handle_no_pid()
mbligh90a549d2008-03-25 23:52:34 +0000959
jadmanski0afbb632008-06-06 21:10:57 +0000960 if exit_status is None:
961 # double check whether or not autoserv is running
962 proc_running = self._check_proc_fs(pid)
963 if proc_running:
964 return pid, exit_status
mbligh90a549d2008-03-25 23:52:34 +0000965
jadmanski0afbb632008-06-06 21:10:57 +0000966 # pid but no process - maybe process *just* exited
967 pid, exit_status = self.read_pidfile()
968 if exit_status is None:
969 # autoserv exited without writing an exit code
970 # to the pidfile
971 error = ('autoserv died without writing exit '
972 'code')
973 message = error + '\nPid: %s\nPidfile: %s' % (
974 pid, self.pid_file)
975 print message
976 email_manager.enqueue_notify_email(error,
977 message)
978 self.on_lost_process(pid)
979 return self.pid, self.exit_status
mblighbb421852008-03-11 22:36:16 +0000980
jadmanski0afbb632008-06-06 21:10:57 +0000981 return pid, exit_status
mblighbb421852008-03-11 22:36:16 +0000982
983
jadmanski0afbb632008-06-06 21:10:57 +0000984 def _handle_no_pid(self):
985 """\
986 Called when no pidfile is found or no pid is in the pidfile.
987 """
988 # is autoserv running?
989 pid, args = self._find_autoserv_proc()
990 if pid is None:
991 # no autoserv process running
992 message = 'No pid found at ' + self.pid_file
993 else:
994 message = ("Process %d (%s) hasn't written pidfile %s" %
995 (pid, args, self.pid_file))
mbligh90a549d2008-03-25 23:52:34 +0000996
jadmanski0afbb632008-06-06 21:10:57 +0000997 print message
998 if time.time() - self.start_time > PIDFILE_TIMEOUT:
999 email_manager.enqueue_notify_email(
1000 'Process has failed to write pidfile', message)
1001 if pid is not None:
1002 kill_autoserv(pid)
1003 else:
1004 pid = 0
1005 self.on_lost_process(pid)
1006 return self.pid, self.exit_status
mbligh90a549d2008-03-25 23:52:34 +00001007
jadmanski0afbb632008-06-06 21:10:57 +00001008 return None, None
mbligh90a549d2008-03-25 23:52:34 +00001009
1010
jadmanski0afbb632008-06-06 21:10:57 +00001011 def on_lost_process(self, pid):
1012 """\
1013 Called when autoserv has exited without writing an exit status,
1014 or we've timed out waiting for autoserv to write a pid to the
1015 pidfile. In either case, we just return failure and the caller
1016 should signal some kind of warning.
mbligh90a549d2008-03-25 23:52:34 +00001017
jadmanski0afbb632008-06-06 21:10:57 +00001018 pid is unimportant here, as it shouldn't be used by anyone.
1019 """
1020 self.lost_process = True
1021 self.pid = pid
1022 self.exit_status = 1
mbligh90a549d2008-03-25 23:52:34 +00001023
1024
jadmanski0afbb632008-06-06 21:10:57 +00001025 def exit_code(self):
1026 pid, exit_code = self.get_pidfile_info()
1027 return exit_code
mblighbb421852008-03-11 22:36:16 +00001028
1029
mbligh36768f02008-02-22 18:28:33 +00001030class Agent(object):
showard4c5374f2008-09-04 17:02:56 +00001031 def __init__(self, tasks, queue_entry_ids=[], num_processes=1):
jadmanski0afbb632008-06-06 21:10:57 +00001032 self.active_task = None
1033 self.queue = Queue.Queue(0)
1034 self.dispatcher = None
1035 self.queue_entry_ids = queue_entry_ids
showard4c5374f2008-09-04 17:02:56 +00001036 self.num_processes = num_processes
jadmanski0afbb632008-06-06 21:10:57 +00001037
1038 for task in tasks:
1039 self.add_task(task)
mbligh36768f02008-02-22 18:28:33 +00001040
1041
jadmanski0afbb632008-06-06 21:10:57 +00001042 def add_task(self, task):
1043 self.queue.put_nowait(task)
1044 task.agent = self
mbligh36768f02008-02-22 18:28:33 +00001045
1046
jadmanski0afbb632008-06-06 21:10:57 +00001047 def tick(self):
1048 print "agent tick"
1049 if self.active_task and not self.active_task.is_done():
1050 self.active_task.poll()
1051 else:
1052 self._next_task();
mbligh36768f02008-02-22 18:28:33 +00001053
1054
jadmanski0afbb632008-06-06 21:10:57 +00001055 def _next_task(self):
1056 print "agent picking task"
1057 if self.active_task:
1058 assert self.active_task.is_done()
mbligh36768f02008-02-22 18:28:33 +00001059
jadmanski0afbb632008-06-06 21:10:57 +00001060 if not self.active_task.success:
1061 self.on_task_failure()
mblighe2586682008-02-29 22:45:46 +00001062
jadmanski0afbb632008-06-06 21:10:57 +00001063 self.active_task = None
1064 if not self.is_done():
1065 self.active_task = self.queue.get_nowait()
1066 if self.active_task:
1067 self.active_task.start()
mbligh36768f02008-02-22 18:28:33 +00001068
1069
jadmanski0afbb632008-06-06 21:10:57 +00001070 def on_task_failure(self):
1071 self.queue = Queue.Queue(0)
1072 for task in self.active_task.failure_tasks:
1073 self.add_task(task)
mbligh16c722d2008-03-05 00:58:44 +00001074
mblighe2586682008-02-29 22:45:46 +00001075
showard4c5374f2008-09-04 17:02:56 +00001076 def is_running(self):
jadmanski0afbb632008-06-06 21:10:57 +00001077 return self.active_task is not None
showardec113162008-05-08 00:52:49 +00001078
1079
jadmanski0afbb632008-06-06 21:10:57 +00001080 def is_done(self):
1081 return self.active_task == None and self.queue.empty()
mbligh36768f02008-02-22 18:28:33 +00001082
1083
jadmanski0afbb632008-06-06 21:10:57 +00001084 def start(self):
1085 assert self.dispatcher
mbligh36768f02008-02-22 18:28:33 +00001086
jadmanski0afbb632008-06-06 21:10:57 +00001087 self._next_task()
mbligh36768f02008-02-22 18:28:33 +00001088
jadmanski0afbb632008-06-06 21:10:57 +00001089
mbligh36768f02008-02-22 18:28:33 +00001090class AgentTask(object):
jadmanski0afbb632008-06-06 21:10:57 +00001091 def __init__(self, cmd, failure_tasks = []):
1092 self.done = False
1093 self.failure_tasks = failure_tasks
1094 self.started = False
1095 self.cmd = cmd
1096 self.task = None
1097 self.agent = None
1098 self.monitor = None
1099 self.success = None
mbligh36768f02008-02-22 18:28:33 +00001100
1101
jadmanski0afbb632008-06-06 21:10:57 +00001102 def poll(self):
1103 print "poll"
1104 if self.monitor:
1105 self.tick(self.monitor.exit_code())
1106 else:
1107 self.finished(False)
mbligh36768f02008-02-22 18:28:33 +00001108
1109
jadmanski0afbb632008-06-06 21:10:57 +00001110 def tick(self, exit_code):
1111 if exit_code==None:
1112 return
1113# print "exit_code was %d" % exit_code
1114 if exit_code == 0:
1115 success = True
1116 else:
1117 success = False
mbligh36768f02008-02-22 18:28:33 +00001118
jadmanski0afbb632008-06-06 21:10:57 +00001119 self.finished(success)
mbligh36768f02008-02-22 18:28:33 +00001120
1121
jadmanski0afbb632008-06-06 21:10:57 +00001122 def is_done(self):
1123 return self.done
mbligh36768f02008-02-22 18:28:33 +00001124
1125
jadmanski0afbb632008-06-06 21:10:57 +00001126 def finished(self, success):
1127 self.done = True
1128 self.success = success
1129 self.epilog()
mbligh36768f02008-02-22 18:28:33 +00001130
1131
jadmanski0afbb632008-06-06 21:10:57 +00001132 def prolog(self):
1133 pass
mblighd64e5702008-04-04 21:39:28 +00001134
1135
jadmanski0afbb632008-06-06 21:10:57 +00001136 def create_temp_resultsdir(self, suffix=''):
1137 self.temp_results_dir = tempfile.mkdtemp(suffix=suffix)
mblighd64e5702008-04-04 21:39:28 +00001138
mbligh36768f02008-02-22 18:28:33 +00001139
jadmanski0afbb632008-06-06 21:10:57 +00001140 def cleanup(self):
1141 if (hasattr(self, 'temp_results_dir') and
1142 os.path.exists(self.temp_results_dir)):
1143 shutil.rmtree(self.temp_results_dir)
mbligh36768f02008-02-22 18:28:33 +00001144
1145
jadmanski0afbb632008-06-06 21:10:57 +00001146 def epilog(self):
1147 self.cleanup()
mbligh36768f02008-02-22 18:28:33 +00001148
1149
jadmanski0afbb632008-06-06 21:10:57 +00001150 def start(self):
1151 assert self.agent
1152
1153 if not self.started:
1154 self.prolog()
1155 self.run()
1156
1157 self.started = True
1158
1159
1160 def abort(self):
1161 if self.monitor:
1162 self.monitor.kill()
1163 self.done = True
1164 self.cleanup()
1165
1166
1167 def run(self):
1168 if self.cmd:
1169 print "agent starting monitor"
1170 log_file = None
1171 if hasattr(self, 'host'):
1172 log_file = os.path.join(RESULTS_DIR, 'hosts',
1173 self.host.hostname)
1174 self.monitor = RunMonitor(
1175 self.cmd, nice_level = AUTOSERV_NICE_LEVEL,
1176 log_file = log_file)
1177 self.monitor.run()
mbligh36768f02008-02-22 18:28:33 +00001178
1179
1180class RepairTask(AgentTask):
jadmanski0afbb632008-06-06 21:10:57 +00001181 def __init__(self, host, fail_queue_entry=None):
1182 """\
1183 fail_queue_entry: queue entry to mark failed if this repair
1184 fails.
1185 """
jadmanskifb7cfb12008-07-09 14:13:21 +00001186 protection = host_protections.Protection.get_string(host.protection)
jadmanski542537f2008-07-24 14:14:56 +00001187 # normalize the protection name
1188 protection = host_protections.Protection.get_attr_name(protection)
jadmanski0afbb632008-06-06 21:10:57 +00001189 self.create_temp_resultsdir('.repair')
1190 cmd = [_autoserv_path , '-R', '-m', host.hostname,
jadmanskifb7cfb12008-07-09 14:13:21 +00001191 '-r', self.temp_results_dir, '--host-protection', protection]
jadmanski0afbb632008-06-06 21:10:57 +00001192 self.host = host
1193 self.fail_queue_entry = fail_queue_entry
1194 super(RepairTask, self).__init__(cmd)
mblighe2586682008-02-29 22:45:46 +00001195
mbligh36768f02008-02-22 18:28:33 +00001196
jadmanski0afbb632008-06-06 21:10:57 +00001197 def prolog(self):
1198 print "repair_task starting"
1199 self.host.set_status('Repairing')
mbligh36768f02008-02-22 18:28:33 +00001200
1201
jadmanski0afbb632008-06-06 21:10:57 +00001202 def epilog(self):
1203 super(RepairTask, self).epilog()
1204 if self.success:
1205 self.host.set_status('Ready')
1206 else:
1207 self.host.set_status('Repair Failed')
1208 if self.fail_queue_entry:
1209 self.fail_queue_entry.handle_host_failure()
mbligh36768f02008-02-22 18:28:33 +00001210
1211
1212class VerifyTask(AgentTask):
showard9976ce92008-10-15 20:28:13 +00001213 def __init__(self, queue_entry=None, host=None):
jadmanski0afbb632008-06-06 21:10:57 +00001214 assert bool(queue_entry) != bool(host)
mbligh36768f02008-02-22 18:28:33 +00001215
jadmanski0afbb632008-06-06 21:10:57 +00001216 self.host = host or queue_entry.host
1217 self.queue_entry = queue_entry
mbligh36768f02008-02-22 18:28:33 +00001218
jadmanski0afbb632008-06-06 21:10:57 +00001219 self.create_temp_resultsdir('.verify')
showard3d9899a2008-07-31 02:11:58 +00001220
showard9976ce92008-10-15 20:28:13 +00001221 cmd = [_autoserv_path,'-v','-m',self.host.hostname, '-r', self.temp_results_dir]
mbligh36768f02008-02-22 18:28:33 +00001222
jadmanski0afbb632008-06-06 21:10:57 +00001223 fail_queue_entry = None
1224 if queue_entry and not queue_entry.meta_host:
1225 fail_queue_entry = queue_entry
1226 failure_tasks = [RepairTask(self.host, fail_queue_entry)]
mblighe2586682008-02-29 22:45:46 +00001227
jadmanski0afbb632008-06-06 21:10:57 +00001228 super(VerifyTask, self).__init__(cmd,
1229 failure_tasks=failure_tasks)
mblighe2586682008-02-29 22:45:46 +00001230
1231
jadmanski0afbb632008-06-06 21:10:57 +00001232 def prolog(self):
1233 print "starting verify on %s" % (self.host.hostname)
1234 if self.queue_entry:
1235 self.queue_entry.set_status('Verifying')
1236 self.queue_entry.clear_results_dir(
1237 self.queue_entry.verify_results_dir())
1238 self.host.set_status('Verifying')
mbligh36768f02008-02-22 18:28:33 +00001239
1240
jadmanski0afbb632008-06-06 21:10:57 +00001241 def cleanup(self):
1242 if not os.path.exists(self.temp_results_dir):
1243 return
1244 if self.queue_entry and (self.success or
1245 not self.queue_entry.meta_host):
1246 self.move_results()
1247 super(VerifyTask, self).cleanup()
mblighd64e5702008-04-04 21:39:28 +00001248
1249
jadmanski0afbb632008-06-06 21:10:57 +00001250 def epilog(self):
1251 super(VerifyTask, self).epilog()
mbligh36768f02008-02-22 18:28:33 +00001252
jadmanski0afbb632008-06-06 21:10:57 +00001253 if self.success:
1254 self.host.set_status('Ready')
1255 elif self.queue_entry:
1256 self.queue_entry.requeue()
mbligh36768f02008-02-22 18:28:33 +00001257
1258
jadmanski0afbb632008-06-06 21:10:57 +00001259 def move_results(self):
1260 assert self.queue_entry is not None
1261 target_dir = self.queue_entry.verify_results_dir()
1262 if not os.path.exists(target_dir):
1263 os.makedirs(target_dir)
1264 files = os.listdir(self.temp_results_dir)
1265 for filename in files:
1266 if filename == AUTOSERV_PID_FILE:
1267 continue
1268 self.force_move(os.path.join(self.temp_results_dir,
1269 filename),
1270 os.path.join(target_dir, filename))
mbligh36768f02008-02-22 18:28:33 +00001271
1272
jadmanski0afbb632008-06-06 21:10:57 +00001273 @staticmethod
1274 def force_move(source, dest):
1275 """\
1276 Replacement for shutil.move() that will delete the destination
1277 if it exists, even if it's a directory.
1278 """
1279 if os.path.exists(dest):
1280 print ('Warning: removing existing destination file ' +
1281 dest)
1282 remove_file_or_dir(dest)
1283 shutil.move(source, dest)
mblighe2586682008-02-29 22:45:46 +00001284
1285
mblighdffd6372008-02-29 22:47:33 +00001286class VerifySynchronousTask(VerifyTask):
jadmanski0afbb632008-06-06 21:10:57 +00001287 def epilog(self):
1288 super(VerifySynchronousTask, self).epilog()
1289 if self.success:
1290 if self.queue_entry.job.num_complete() > 0:
1291 # some other entry failed verify, and we've
1292 # already been marked as stopped
1293 return
mblighdffd6372008-02-29 22:47:33 +00001294
showardb2e2c322008-10-14 17:33:55 +00001295 agent = self.queue_entry.on_pending()
1296 if agent:
jadmanski0afbb632008-06-06 21:10:57 +00001297 self.agent.dispatcher.add_agent(agent)
mblighe2586682008-02-29 22:45:46 +00001298
showardb2e2c322008-10-14 17:33:55 +00001299
mbligh36768f02008-02-22 18:28:33 +00001300class QueueTask(AgentTask):
jadmanski0afbb632008-06-06 21:10:57 +00001301 def __init__(self, job, queue_entries, cmd):
1302 super(QueueTask, self).__init__(cmd)
1303 self.job = job
1304 self.queue_entries = queue_entries
mbligh36768f02008-02-22 18:28:33 +00001305
1306
jadmanski0afbb632008-06-06 21:10:57 +00001307 @staticmethod
showardd8e548a2008-09-09 03:04:57 +00001308 def _write_keyval(keyval_dir, field, value, keyval_filename='keyval'):
1309 key_path = os.path.join(keyval_dir, keyval_filename)
jadmanski0afbb632008-06-06 21:10:57 +00001310 keyval_file = open(key_path, 'a')
showardd8e548a2008-09-09 03:04:57 +00001311 print >> keyval_file, '%s=%s' % (field, str(value))
jadmanski0afbb632008-06-06 21:10:57 +00001312 keyval_file.close()
mbligh36768f02008-02-22 18:28:33 +00001313
1314
showardd8e548a2008-09-09 03:04:57 +00001315 def _host_keyval_dir(self):
1316 return os.path.join(self.results_dir(), 'host_keyvals')
1317
1318
1319 def _write_host_keyval(self, host):
1320 labels = ','.join(host.labels())
1321 self._write_keyval(self._host_keyval_dir(), 'labels', labels,
1322 keyval_filename=host.hostname)
1323
1324 def _create_host_keyval_dir(self):
1325 directory = self._host_keyval_dir()
1326 if not os.path.exists(directory):
1327 os.makedirs(directory)
1328
1329
jadmanski0afbb632008-06-06 21:10:57 +00001330 def results_dir(self):
1331 return self.queue_entries[0].results_dir()
mblighbb421852008-03-11 22:36:16 +00001332
1333
jadmanski0afbb632008-06-06 21:10:57 +00001334 def run(self):
1335 """\
1336 Override AgentTask.run() so we can use a PidfileRunMonitor.
1337 """
1338 self.monitor = PidfileRunMonitor(self.results_dir(),
1339 cmd=self.cmd,
1340 nice_level=AUTOSERV_NICE_LEVEL)
1341 self.monitor.run()
mblighbb421852008-03-11 22:36:16 +00001342
1343
jadmanski0afbb632008-06-06 21:10:57 +00001344 def prolog(self):
1345 # write some job timestamps into the job keyval file
1346 queued = time.mktime(self.job.created_on.timetuple())
1347 started = time.time()
showardd8e548a2008-09-09 03:04:57 +00001348 self._write_keyval(self.results_dir(), "job_queued", int(queued))
1349 self._write_keyval(self.results_dir(), "job_started", int(started))
1350 self._create_host_keyval_dir()
jadmanski0afbb632008-06-06 21:10:57 +00001351 for queue_entry in self.queue_entries:
showardd8e548a2008-09-09 03:04:57 +00001352 self._write_host_keyval(queue_entry.host)
jadmanski0afbb632008-06-06 21:10:57 +00001353 print "starting queue_task on %s/%s" % (queue_entry.host.hostname, queue_entry.id)
1354 queue_entry.set_status('Running')
1355 queue_entry.host.set_status('Running')
1356 if (not self.job.is_synchronous() and
1357 self.job.num_machines() > 1):
1358 assert len(self.queue_entries) == 1
1359 self.job.write_to_machines_file(self.queue_entries[0])
mbligh36768f02008-02-22 18:28:33 +00001360
1361
jadmanski0afbb632008-06-06 21:10:57 +00001362 def _finish_task(self):
1363 # write out the finished time into the results keyval
1364 finished = time.time()
jadmanskif7fa2cc2008-10-01 14:13:23 +00001365 self._write_keyval(self.results_dir(), "job_finished", int(finished))
jadmanskic2ac77f2008-05-16 21:44:04 +00001366
jadmanski0afbb632008-06-06 21:10:57 +00001367 # parse the results of the job
1368 if self.job.is_synchronous() or self.job.num_machines() == 1:
1369 parse_results(self.job.results_dir())
1370 else:
1371 for queue_entry in self.queue_entries:
jadmanskif7fa2cc2008-10-01 14:13:23 +00001372 parse_results(queue_entry.results_dir(), flags="-l 2")
1373
1374
1375 def _log_abort(self):
1376 # build up sets of all the aborted_by and aborted_on values
1377 aborted_by, aborted_on = set(), set()
1378 for queue_entry in self.queue_entries:
1379 if queue_entry.aborted_by:
1380 aborted_by.add(queue_entry.aborted_by)
1381 t = int(time.mktime(queue_entry.aborted_on.timetuple()))
1382 aborted_on.add(t)
1383
1384 # extract some actual, unique aborted by value and write it out
1385 assert len(aborted_by) <= 1
1386 if len(aborted_by) == 1:
1387 results_dir = self.results_dir()
1388 self._write_keyval(results_dir, "aborted_by", aborted_by.pop())
1389 self._write_keyval(results_dir, "aborted_on", max(aborted_on))
jadmanskic2ac77f2008-05-16 21:44:04 +00001390
1391
jadmanski0afbb632008-06-06 21:10:57 +00001392 def abort(self):
1393 super(QueueTask, self).abort()
jadmanskif7fa2cc2008-10-01 14:13:23 +00001394 self._log_abort()
jadmanski0afbb632008-06-06 21:10:57 +00001395 self._finish_task()
jadmanskic2ac77f2008-05-16 21:44:04 +00001396
1397
jadmanski0afbb632008-06-06 21:10:57 +00001398 def epilog(self):
1399 super(QueueTask, self).epilog()
1400 if self.success:
1401 status = 'Completed'
1402 else:
1403 status = 'Failed'
mbligh36768f02008-02-22 18:28:33 +00001404
jadmanski0afbb632008-06-06 21:10:57 +00001405 for queue_entry in self.queue_entries:
1406 queue_entry.set_status(status)
1407 queue_entry.host.set_status('Ready')
mbligh36768f02008-02-22 18:28:33 +00001408
jadmanski0afbb632008-06-06 21:10:57 +00001409 self._finish_task()
mblighbb421852008-03-11 22:36:16 +00001410
jadmanski0afbb632008-06-06 21:10:57 +00001411 print "queue_task finished with %s/%s" % (status, self.success)
mbligh36768f02008-02-22 18:28:33 +00001412
1413
mblighbb421852008-03-11 22:36:16 +00001414class RecoveryQueueTask(QueueTask):
jadmanski0afbb632008-06-06 21:10:57 +00001415 def __init__(self, job, queue_entries, run_monitor):
1416 super(RecoveryQueueTask, self).__init__(job,
1417 queue_entries, cmd=None)
1418 self.run_monitor = run_monitor
mblighbb421852008-03-11 22:36:16 +00001419
1420
jadmanski0afbb632008-06-06 21:10:57 +00001421 def run(self):
1422 self.monitor = self.run_monitor
mblighbb421852008-03-11 22:36:16 +00001423
1424
jadmanski0afbb632008-06-06 21:10:57 +00001425 def prolog(self):
1426 # recovering an existing process - don't do prolog
1427 pass
mblighbb421852008-03-11 22:36:16 +00001428
1429
mbligh36768f02008-02-22 18:28:33 +00001430class RebootTask(AgentTask):
jadmanski0afbb632008-06-06 21:10:57 +00001431 def __init__(self, host):
1432 global _autoserv_path
1433
1434 # Current implementation of autoserv requires control file
1435 # to be passed on reboot action request. TODO: remove when no
1436 # longer appropriate.
1437 self.create_temp_resultsdir('.reboot')
1438 self.cmd = [_autoserv_path, '-b', '-m', host.hostname,
1439 '-r', self.temp_results_dir, '/dev/null']
1440 self.host = host
1441 super(RebootTask, self).__init__(self.cmd,
1442 failure_tasks=[RepairTask(host)])
mbligh16c722d2008-03-05 00:58:44 +00001443
mblighd5c95802008-03-05 00:33:46 +00001444
jadmanski0afbb632008-06-06 21:10:57 +00001445 def prolog(self):
1446 print "starting reboot task for host: %s" % self.host.hostname
1447 self.host.set_status("Rebooting")
mblighd5c95802008-03-05 00:33:46 +00001448
mblighd5c95802008-03-05 00:33:46 +00001449
1450class AbortTask(AgentTask):
jadmanski0afbb632008-06-06 21:10:57 +00001451 def __init__(self, queue_entry, agents_to_abort):
1452 self.queue_entry = queue_entry
1453 self.agents_to_abort = agents_to_abort
jadmanski0afbb632008-06-06 21:10:57 +00001454 super(AbortTask, self).__init__('')
mbligh36768f02008-02-22 18:28:33 +00001455
1456
jadmanski0afbb632008-06-06 21:10:57 +00001457 def prolog(self):
1458 print "starting abort on host %s, job %s" % (
1459 self.queue_entry.host_id, self.queue_entry.job_id)
mbligh36768f02008-02-22 18:28:33 +00001460
mblighd64e5702008-04-04 21:39:28 +00001461
jadmanski0afbb632008-06-06 21:10:57 +00001462 def epilog(self):
1463 super(AbortTask, self).epilog()
1464 self.queue_entry.set_status('Aborted')
1465 self.success = True
1466
1467
1468 def run(self):
1469 for agent in self.agents_to_abort:
1470 if (agent.active_task):
1471 agent.active_task.abort()
mbligh36768f02008-02-22 18:28:33 +00001472
1473
1474class DBObject(object):
jadmanski0afbb632008-06-06 21:10:57 +00001475 def __init__(self, id=None, row=None, new_record=False):
1476 assert (bool(id) != bool(row))
mbligh36768f02008-02-22 18:28:33 +00001477
jadmanski0afbb632008-06-06 21:10:57 +00001478 self.__table = self._get_table()
1479 fields = self._fields()
mbligh36768f02008-02-22 18:28:33 +00001480
jadmanski0afbb632008-06-06 21:10:57 +00001481 self.__new_record = new_record
mbligh36768f02008-02-22 18:28:33 +00001482
jadmanski0afbb632008-06-06 21:10:57 +00001483 if row is None:
1484 sql = 'SELECT * FROM %s WHERE ID=%%s' % self.__table
1485 rows = _db.execute(sql, (id,))
1486 if len(rows) == 0:
1487 raise "row not found (table=%s, id=%s)" % \
1488 (self.__table, id)
1489 row = rows[0]
mbligh36768f02008-02-22 18:28:33 +00001490
jadmanski0afbb632008-06-06 21:10:57 +00001491 assert len(row) == self.num_cols(), (
1492 "table = %s, row = %s/%d, fields = %s/%d" % (
1493 self.__table, row, len(row), fields, self.num_cols()))
mbligh36768f02008-02-22 18:28:33 +00001494
jadmanski0afbb632008-06-06 21:10:57 +00001495 self.__valid_fields = {}
1496 for i,value in enumerate(row):
1497 self.__dict__[fields[i]] = value
1498 self.__valid_fields[fields[i]] = True
mbligh36768f02008-02-22 18:28:33 +00001499
jadmanski0afbb632008-06-06 21:10:57 +00001500 del self.__valid_fields['id']
mbligh36768f02008-02-22 18:28:33 +00001501
mblighe2586682008-02-29 22:45:46 +00001502
jadmanski0afbb632008-06-06 21:10:57 +00001503 @classmethod
1504 def _get_table(cls):
1505 raise NotImplementedError('Subclasses must override this')
mblighe2586682008-02-29 22:45:46 +00001506
1507
jadmanski0afbb632008-06-06 21:10:57 +00001508 @classmethod
1509 def _fields(cls):
1510 raise NotImplementedError('Subclasses must override this')
showard04c82c52008-05-29 19:38:12 +00001511
1512
jadmanski0afbb632008-06-06 21:10:57 +00001513 @classmethod
1514 def num_cols(cls):
1515 return len(cls._fields())
showard04c82c52008-05-29 19:38:12 +00001516
1517
jadmanski0afbb632008-06-06 21:10:57 +00001518 def count(self, where, table = None):
1519 if not table:
1520 table = self.__table
mbligh36768f02008-02-22 18:28:33 +00001521
jadmanski0afbb632008-06-06 21:10:57 +00001522 rows = _db.execute("""
1523 SELECT count(*) FROM %s
1524 WHERE %s
1525 """ % (table, where))
mbligh6f8bab42008-02-29 22:45:14 +00001526
jadmanski0afbb632008-06-06 21:10:57 +00001527 assert len(rows) == 1
1528
1529 return int(rows[0][0])
mbligh36768f02008-02-22 18:28:33 +00001530
1531
mblighf8c624d2008-07-03 16:58:45 +00001532 def update_field(self, field, value, condition=''):
jadmanski0afbb632008-06-06 21:10:57 +00001533 assert self.__valid_fields[field]
mbligh36768f02008-02-22 18:28:33 +00001534
jadmanski0afbb632008-06-06 21:10:57 +00001535 if self.__dict__[field] == value:
1536 return
mbligh36768f02008-02-22 18:28:33 +00001537
mblighf8c624d2008-07-03 16:58:45 +00001538 query = "UPDATE %s SET %s = %%s WHERE id = %%s" % (self.__table, field)
1539 if condition:
1540 query += ' AND (%s)' % condition
jadmanski0afbb632008-06-06 21:10:57 +00001541 _db.execute(query, (value, self.id))
1542
1543 self.__dict__[field] = value
mbligh36768f02008-02-22 18:28:33 +00001544
1545
jadmanski0afbb632008-06-06 21:10:57 +00001546 def save(self):
1547 if self.__new_record:
1548 keys = self._fields()[1:] # avoid id
1549 columns = ','.join([str(key) for key in keys])
1550 values = ['"%s"' % self.__dict__[key] for key in keys]
1551 values = ','.join(values)
1552 query = """INSERT INTO %s (%s) VALUES (%s)""" % \
1553 (self.__table, columns, values)
1554 _db.execute(query)
mbligh36768f02008-02-22 18:28:33 +00001555
1556
jadmanski0afbb632008-06-06 21:10:57 +00001557 def delete(self):
1558 query = 'DELETE FROM %s WHERE id=%%s' % self.__table
1559 _db.execute(query, (self.id,))
mblighe2586682008-02-29 22:45:46 +00001560
1561
showard63a34772008-08-18 19:32:50 +00001562 @staticmethod
1563 def _prefix_with(string, prefix):
1564 if string:
1565 string = prefix + string
1566 return string
1567
1568
jadmanski0afbb632008-06-06 21:10:57 +00001569 @classmethod
showard989f25d2008-10-01 11:38:11 +00001570 def fetch(cls, where='', params=(), joins='', order_by=''):
showard63a34772008-08-18 19:32:50 +00001571 order_by = cls._prefix_with(order_by, 'ORDER BY ')
1572 where = cls._prefix_with(where, 'WHERE ')
1573 query = ('SELECT %(table)s.* FROM %(table)s %(joins)s '
1574 '%(where)s %(order_by)s' % {'table' : cls._get_table(),
1575 'joins' : joins,
1576 'where' : where,
1577 'order_by' : order_by})
1578 rows = _db.execute(query, params)
jadmanski0afbb632008-06-06 21:10:57 +00001579 for row in rows:
1580 yield cls(row=row)
mblighe2586682008-02-29 22:45:46 +00001581
mbligh36768f02008-02-22 18:28:33 +00001582
1583class IneligibleHostQueue(DBObject):
jadmanski0afbb632008-06-06 21:10:57 +00001584 def __init__(self, id=None, row=None, new_record=None):
1585 super(IneligibleHostQueue, self).__init__(id=id, row=row,
1586 new_record=new_record)
mblighe2586682008-02-29 22:45:46 +00001587
1588
jadmanski0afbb632008-06-06 21:10:57 +00001589 @classmethod
1590 def _get_table(cls):
1591 return 'ineligible_host_queues'
mbligh36768f02008-02-22 18:28:33 +00001592
1593
jadmanski0afbb632008-06-06 21:10:57 +00001594 @classmethod
1595 def _fields(cls):
1596 return ['id', 'job_id', 'host_id']
showard04c82c52008-05-29 19:38:12 +00001597
1598
showard989f25d2008-10-01 11:38:11 +00001599class Label(DBObject):
1600 @classmethod
1601 def _get_table(cls):
1602 return 'labels'
1603
1604
1605 @classmethod
1606 def _fields(cls):
1607 return ['id', 'name', 'kernel_config', 'platform', 'invalid',
1608 'only_if_needed']
1609
1610
mbligh36768f02008-02-22 18:28:33 +00001611class Host(DBObject):
jadmanski0afbb632008-06-06 21:10:57 +00001612 def __init__(self, id=None, row=None):
1613 super(Host, self).__init__(id=id, row=row)
mblighe2586682008-02-29 22:45:46 +00001614
1615
jadmanski0afbb632008-06-06 21:10:57 +00001616 @classmethod
1617 def _get_table(cls):
1618 return 'hosts'
mbligh36768f02008-02-22 18:28:33 +00001619
1620
jadmanski0afbb632008-06-06 21:10:57 +00001621 @classmethod
1622 def _fields(cls):
1623 return ['id', 'hostname', 'locked', 'synch_id','status',
showardfb2a7fa2008-07-17 17:04:12 +00001624 'invalid', 'protection', 'locked_by_id', 'lock_time']
showard04c82c52008-05-29 19:38:12 +00001625
1626
jadmanski0afbb632008-06-06 21:10:57 +00001627 def current_task(self):
1628 rows = _db.execute("""
1629 SELECT * FROM host_queue_entries WHERE host_id=%s AND NOT complete AND active
1630 """, (self.id,))
1631
1632 if len(rows) == 0:
1633 return None
1634 else:
1635 assert len(rows) == 1
1636 results = rows[0];
mblighf8c624d2008-07-03 16:58:45 +00001637# print "current = %s" % results
jadmanski0afbb632008-06-06 21:10:57 +00001638 return HostQueueEntry(row=results)
mbligh36768f02008-02-22 18:28:33 +00001639
1640
jadmanski0afbb632008-06-06 21:10:57 +00001641 def yield_work(self):
1642 print "%s yielding work" % self.hostname
1643 if self.current_task():
1644 self.current_task().requeue()
1645
1646 def set_status(self,status):
1647 print '%s -> %s' % (self.hostname, status)
1648 self.update_field('status',status)
mbligh36768f02008-02-22 18:28:33 +00001649
1650
showardd8e548a2008-09-09 03:04:57 +00001651 def labels(self):
1652 """
1653 Fetch a list of names of all non-platform labels associated with this
1654 host.
1655 """
1656 rows = _db.execute("""
1657 SELECT labels.name
1658 FROM labels
1659 INNER JOIN hosts_labels ON labels.id = hosts_labels.label_id
1660 WHERE NOT labels.platform AND hosts_labels.host_id = %s
1661 ORDER BY labels.name
1662 """, (self.id,))
1663 return [row[0] for row in rows]
1664
1665
mbligh36768f02008-02-22 18:28:33 +00001666class HostQueueEntry(DBObject):
jadmanski0afbb632008-06-06 21:10:57 +00001667 def __init__(self, id=None, row=None):
1668 assert id or row
1669 super(HostQueueEntry, self).__init__(id=id, row=row)
1670 self.job = Job(self.job_id)
mbligh36768f02008-02-22 18:28:33 +00001671
jadmanski0afbb632008-06-06 21:10:57 +00001672 if self.host_id:
1673 self.host = Host(self.host_id)
1674 else:
1675 self.host = None
mbligh36768f02008-02-22 18:28:33 +00001676
jadmanski0afbb632008-06-06 21:10:57 +00001677 self.queue_log_path = os.path.join(self.job.results_dir(),
1678 'queue.log.' + str(self.id))
mbligh36768f02008-02-22 18:28:33 +00001679
1680
jadmanski0afbb632008-06-06 21:10:57 +00001681 @classmethod
1682 def _get_table(cls):
1683 return 'host_queue_entries'
mblighe2586682008-02-29 22:45:46 +00001684
1685
jadmanski0afbb632008-06-06 21:10:57 +00001686 @classmethod
1687 def _fields(cls):
1688 return ['id', 'job_id', 'host_id', 'priority', 'status',
showardb8471e32008-07-03 19:51:08 +00001689 'meta_host', 'active', 'complete', 'deleted']
showard04c82c52008-05-29 19:38:12 +00001690
1691
jadmanski0afbb632008-06-06 21:10:57 +00001692 def set_host(self, host):
1693 if host:
1694 self.queue_log_record('Assigning host ' + host.hostname)
1695 self.update_field('host_id', host.id)
1696 self.update_field('active', True)
1697 self.block_host(host.id)
1698 else:
1699 self.queue_log_record('Releasing host')
1700 self.unblock_host(self.host.id)
1701 self.update_field('host_id', None)
mbligh36768f02008-02-22 18:28:33 +00001702
jadmanski0afbb632008-06-06 21:10:57 +00001703 self.host = host
mbligh36768f02008-02-22 18:28:33 +00001704
1705
jadmanski0afbb632008-06-06 21:10:57 +00001706 def get_host(self):
1707 return self.host
mbligh36768f02008-02-22 18:28:33 +00001708
1709
jadmanski0afbb632008-06-06 21:10:57 +00001710 def queue_log_record(self, log_line):
1711 now = str(datetime.datetime.now())
1712 queue_log = open(self.queue_log_path, 'a', 0)
1713 queue_log.write(now + ' ' + log_line + '\n')
1714 queue_log.close()
mbligh36768f02008-02-22 18:28:33 +00001715
1716
jadmanski0afbb632008-06-06 21:10:57 +00001717 def block_host(self, host_id):
1718 print "creating block %s/%s" % (self.job.id, host_id)
1719 row = [0, self.job.id, host_id]
1720 block = IneligibleHostQueue(row=row, new_record=True)
1721 block.save()
mblighe2586682008-02-29 22:45:46 +00001722
1723
jadmanski0afbb632008-06-06 21:10:57 +00001724 def unblock_host(self, host_id):
1725 print "removing block %s/%s" % (self.job.id, host_id)
1726 blocks = IneligibleHostQueue.fetch(
1727 'job_id=%d and host_id=%d' % (self.job.id, host_id))
1728 for block in blocks:
1729 block.delete()
mblighe2586682008-02-29 22:45:46 +00001730
1731
jadmanski0afbb632008-06-06 21:10:57 +00001732 def results_dir(self):
1733 if self.job.is_synchronous() or self.job.num_machines() == 1:
1734 return self.job.job_dir
1735 else:
1736 assert self.host
1737 return os.path.join(self.job.job_dir,
1738 self.host.hostname)
mbligh36768f02008-02-22 18:28:33 +00001739
mblighe2586682008-02-29 22:45:46 +00001740
jadmanski0afbb632008-06-06 21:10:57 +00001741 def verify_results_dir(self):
1742 if self.job.is_synchronous() or self.job.num_machines() > 1:
1743 assert self.host
1744 return os.path.join(self.job.job_dir,
1745 self.host.hostname)
1746 else:
1747 return self.job.job_dir
mbligh36768f02008-02-22 18:28:33 +00001748
1749
jadmanski0afbb632008-06-06 21:10:57 +00001750 def set_status(self, status):
mblighf8c624d2008-07-03 16:58:45 +00001751 abort_statuses = ['Abort', 'Aborting', 'Aborted']
1752 if status not in abort_statuses:
1753 condition = ' AND '.join(['status <> "%s"' % x
1754 for x in abort_statuses])
1755 else:
1756 condition = ''
1757 self.update_field('status', status, condition=condition)
1758
jadmanski0afbb632008-06-06 21:10:57 +00001759 if self.host:
1760 hostname = self.host.hostname
1761 else:
1762 hostname = 'no host'
1763 print "%s/%d status -> %s" % (hostname, self.id, self.status)
mblighf8c624d2008-07-03 16:58:45 +00001764
jadmanski0afbb632008-06-06 21:10:57 +00001765 if status in ['Queued']:
1766 self.update_field('complete', False)
1767 self.update_field('active', False)
mbligh36768f02008-02-22 18:28:33 +00001768
jadmanski0afbb632008-06-06 21:10:57 +00001769 if status in ['Pending', 'Running', 'Verifying', 'Starting',
1770 'Abort', 'Aborting']:
1771 self.update_field('complete', False)
1772 self.update_field('active', True)
mbligh36768f02008-02-22 18:28:33 +00001773
jadmanski0afbb632008-06-06 21:10:57 +00001774 if status in ['Failed', 'Completed', 'Stopped', 'Aborted']:
1775 self.update_field('complete', True)
1776 self.update_field('active', False)
showard542e8402008-09-19 20:16:18 +00001777 self._email_on_job_complete()
1778
1779
1780 def _email_on_job_complete(self):
1781 url = "%s#tab_id=view_job&object_id=%s" % (_base_url, self.job.id)
1782
1783 if self.job.is_finished():
1784 subject = "Autotest: Job ID: %s \"%s\" Completed" % (
1785 self.job.id, self.job.name)
1786 body = "Job ID: %s\nJob Name: %s\n%s\n" % (
1787 self.job.id, self.job.name, url)
1788 send_email(_email_from, self.job.email_list, subject, body)
mbligh36768f02008-02-22 18:28:33 +00001789
1790
jadmanski0afbb632008-06-06 21:10:57 +00001791 def run(self,assigned_host=None):
1792 if self.meta_host:
1793 assert assigned_host
1794 # ensure results dir exists for the queue log
1795 self.job.create_results_dir()
1796 self.set_host(assigned_host)
mbligh36768f02008-02-22 18:28:33 +00001797
jadmanski0afbb632008-06-06 21:10:57 +00001798 print "%s/%s scheduled on %s, status=%s" % (self.job.name,
1799 self.meta_host, self.host.hostname, self.status)
mbligh36768f02008-02-22 18:28:33 +00001800
jadmanski0afbb632008-06-06 21:10:57 +00001801 return self.job.run(queue_entry=self)
mblighe2586682008-02-29 22:45:46 +00001802
jadmanski0afbb632008-06-06 21:10:57 +00001803 def requeue(self):
1804 self.set_status('Queued')
mblighe2586682008-02-29 22:45:46 +00001805
jadmanski0afbb632008-06-06 21:10:57 +00001806 if self.meta_host:
1807 self.set_host(None)
mbligh36768f02008-02-22 18:28:33 +00001808
1809
jadmanski0afbb632008-06-06 21:10:57 +00001810 def handle_host_failure(self):
1811 """\
1812 Called when this queue entry's host has failed verification and
1813 repair.
1814 """
1815 assert not self.meta_host
1816 self.set_status('Failed')
1817 if self.job.is_synchronous():
1818 self.job.stop_all_entries()
mblighe2586682008-02-29 22:45:46 +00001819
1820
jadmanski0afbb632008-06-06 21:10:57 +00001821 def clear_results_dir(self, results_dir=None, dont_delete_files=False):
1822 results_dir = results_dir or self.results_dir()
1823 if not os.path.exists(results_dir):
1824 return
1825 if dont_delete_files:
1826 temp_dir = tempfile.mkdtemp(suffix='.clear_results')
1827 print 'Moving results from %s to %s' % (results_dir,
1828 temp_dir)
1829 for filename in os.listdir(results_dir):
1830 path = os.path.join(results_dir, filename)
1831 if dont_delete_files:
1832 shutil.move(path,
1833 os.path.join(temp_dir, filename))
1834 else:
1835 remove_file_or_dir(path)
mbligh36768f02008-02-22 18:28:33 +00001836
1837
jadmanskif7fa2cc2008-10-01 14:13:23 +00001838 @property
1839 def aborted_by(self):
1840 self._load_abort_info()
1841 return self._aborted_by
1842
1843
1844 @property
1845 def aborted_on(self):
1846 self._load_abort_info()
1847 return self._aborted_on
1848
1849
1850 def _load_abort_info(self):
1851 """ Fetch info about who aborted the job. """
1852 if hasattr(self, "_aborted_by"):
1853 return
1854 rows = _db.execute("""
1855 SELECT users.login, aborted_host_queue_entries.aborted_on
1856 FROM aborted_host_queue_entries
1857 INNER JOIN users
1858 ON users.id = aborted_host_queue_entries.aborted_by_id
1859 WHERE aborted_host_queue_entries.queue_entry_id = %s
1860 """, (self.id,))
1861 if rows:
1862 self._aborted_by, self._aborted_on = rows[0]
1863 else:
1864 self._aborted_by = self._aborted_on = None
1865
1866
showardb2e2c322008-10-14 17:33:55 +00001867 def on_pending(self):
1868 """
1869 Called when an entry in a synchronous job has passed verify. If the
1870 job is ready to run, returns an agent to run the job. Returns None
1871 otherwise.
1872 """
1873 self.set_status('Pending')
showardcfd66a32008-10-15 20:31:48 +00001874 self.get_host().set_status('Pending')
showardb2e2c322008-10-14 17:33:55 +00001875 if self.job.is_ready():
1876 return self.job.run(self)
1877 return None
1878
1879
showard1be97432008-10-17 15:30:45 +00001880 def abort(self, agents_to_abort=[]):
1881 abort_task = AbortTask(self, agents_to_abort)
1882 tasks = [abort_task]
1883
1884 host = self.get_host()
1885 if host:
1886 reboot_task = RebootTask(host)
1887 verify_task = VerifyTask(host=host)
1888 # just to make sure this host does not get taken away
1889 host.set_status('Rebooting')
1890 tasks += [reboot_task, verify_task]
1891
1892 self.set_status('Aborting')
1893 return Agent(tasks=tasks, queue_entry_ids=[self.id])
1894
1895
mbligh36768f02008-02-22 18:28:33 +00001896class Job(DBObject):
jadmanski0afbb632008-06-06 21:10:57 +00001897 def __init__(self, id=None, row=None):
1898 assert id or row
1899 super(Job, self).__init__(id=id, row=row)
mbligh36768f02008-02-22 18:28:33 +00001900
jadmanski0afbb632008-06-06 21:10:57 +00001901 self.job_dir = os.path.join(RESULTS_DIR, "%s-%s" % (self.id,
1902 self.owner))
mblighe2586682008-02-29 22:45:46 +00001903
1904
jadmanski0afbb632008-06-06 21:10:57 +00001905 @classmethod
1906 def _get_table(cls):
1907 return 'jobs'
mbligh36768f02008-02-22 18:28:33 +00001908
1909
jadmanski0afbb632008-06-06 21:10:57 +00001910 @classmethod
1911 def _fields(cls):
1912 return ['id', 'owner', 'name', 'priority', 'control_file',
1913 'control_type', 'created_on', 'synch_type',
showard542e8402008-09-19 20:16:18 +00001914 'synch_count', 'synchronizing', 'timeout',
1915 'run_verify', 'email_list']
showard04c82c52008-05-29 19:38:12 +00001916
1917
jadmanski0afbb632008-06-06 21:10:57 +00001918 def is_server_job(self):
1919 return self.control_type != 2
mbligh36768f02008-02-22 18:28:33 +00001920
1921
jadmanski0afbb632008-06-06 21:10:57 +00001922 def get_host_queue_entries(self):
1923 rows = _db.execute("""
1924 SELECT * FROM host_queue_entries
1925 WHERE job_id= %s
1926 """, (self.id,))
1927 entries = [HostQueueEntry(row=i) for i in rows]
mbligh36768f02008-02-22 18:28:33 +00001928
jadmanski0afbb632008-06-06 21:10:57 +00001929 assert len(entries)>0
mbligh36768f02008-02-22 18:28:33 +00001930
jadmanski0afbb632008-06-06 21:10:57 +00001931 return entries
mbligh36768f02008-02-22 18:28:33 +00001932
1933
jadmanski0afbb632008-06-06 21:10:57 +00001934 def set_status(self, status, update_queues=False):
1935 self.update_field('status',status)
1936
1937 if update_queues:
1938 for queue_entry in self.get_host_queue_entries():
1939 queue_entry.set_status(status)
mbligh36768f02008-02-22 18:28:33 +00001940
1941
jadmanski0afbb632008-06-06 21:10:57 +00001942 def is_synchronous(self):
1943 return self.synch_type == 2
mbligh36768f02008-02-22 18:28:33 +00001944
1945
jadmanski0afbb632008-06-06 21:10:57 +00001946 def is_ready(self):
1947 if not self.is_synchronous():
1948 return True
1949 sql = "job_id=%s AND status='Pending'" % self.id
1950 count = self.count(sql, table='host_queue_entries')
showardb2e2c322008-10-14 17:33:55 +00001951 return (count == self.num_machines())
mbligh36768f02008-02-22 18:28:33 +00001952
1953
jadmanski0afbb632008-06-06 21:10:57 +00001954 def results_dir(self):
1955 return self.job_dir
mbligh36768f02008-02-22 18:28:33 +00001956
jadmanski0afbb632008-06-06 21:10:57 +00001957 def num_machines(self, clause = None):
1958 sql = "job_id=%s" % self.id
1959 if clause:
1960 sql += " AND (%s)" % clause
1961 return self.count(sql, table='host_queue_entries')
mbligh36768f02008-02-22 18:28:33 +00001962
1963
jadmanski0afbb632008-06-06 21:10:57 +00001964 def num_queued(self):
1965 return self.num_machines('not complete')
mbligh36768f02008-02-22 18:28:33 +00001966
1967
jadmanski0afbb632008-06-06 21:10:57 +00001968 def num_active(self):
1969 return self.num_machines('active')
mbligh36768f02008-02-22 18:28:33 +00001970
1971
jadmanski0afbb632008-06-06 21:10:57 +00001972 def num_complete(self):
1973 return self.num_machines('complete')
mbligh36768f02008-02-22 18:28:33 +00001974
1975
jadmanski0afbb632008-06-06 21:10:57 +00001976 def is_finished(self):
1977 left = self.num_queued()
1978 print "%s: %s machines left" % (self.name, left)
1979 return left==0
mbligh36768f02008-02-22 18:28:33 +00001980
mbligh36768f02008-02-22 18:28:33 +00001981
jadmanski0afbb632008-06-06 21:10:57 +00001982 def stop_all_entries(self):
1983 for child_entry in self.get_host_queue_entries():
1984 if not child_entry.complete:
1985 child_entry.set_status('Stopped')
mblighe2586682008-02-29 22:45:46 +00001986
1987
jadmanski0afbb632008-06-06 21:10:57 +00001988 def write_to_machines_file(self, queue_entry):
1989 hostname = queue_entry.get_host().hostname
1990 print "writing %s to job %s machines file" % (hostname, self.id)
1991 file_path = os.path.join(self.job_dir, '.machines')
1992 mf = open(file_path, 'a')
1993 mf.write("%s\n" % queue_entry.get_host().hostname)
1994 mf.close()
mbligh36768f02008-02-22 18:28:33 +00001995
1996
jadmanski0afbb632008-06-06 21:10:57 +00001997 def create_results_dir(self, queue_entry=None):
1998 print "create: active: %s complete %s" % (self.num_active(),
1999 self.num_complete())
mbligh36768f02008-02-22 18:28:33 +00002000
jadmanski0afbb632008-06-06 21:10:57 +00002001 if not os.path.exists(self.job_dir):
2002 os.makedirs(self.job_dir)
mbligh36768f02008-02-22 18:28:33 +00002003
jadmanski0afbb632008-06-06 21:10:57 +00002004 if queue_entry:
2005 return queue_entry.results_dir()
2006 return self.job_dir
mbligh36768f02008-02-22 18:28:33 +00002007
2008
showardb2e2c322008-10-14 17:33:55 +00002009 def _write_control_file(self):
2010 'Writes control file out to disk, returns a filename'
2011 control_fd, control_filename = tempfile.mkstemp(suffix='.control_file')
2012 control_file = os.fdopen(control_fd, 'w')
jadmanski0afbb632008-06-06 21:10:57 +00002013 if self.control_file:
showardb2e2c322008-10-14 17:33:55 +00002014 control_file.write(self.control_file)
2015 control_file.close()
2016 return control_filename
mbligh36768f02008-02-22 18:28:33 +00002017
showardb2e2c322008-10-14 17:33:55 +00002018
2019 def _get_job_tag(self, queue_entries):
2020 base_job_tag = "%s-%s" % (self.id, self.owner)
2021 if self.is_synchronous() or self.num_machines() == 1:
2022 return base_job_tag
jadmanski0afbb632008-06-06 21:10:57 +00002023 else:
showardb2e2c322008-10-14 17:33:55 +00002024 return base_job_tag + '/' + queue_entries[0].get_host().hostname
2025
2026
2027 def _get_autoserv_params(self, queue_entries):
2028 results_dir = self.create_results_dir(queue_entries[0])
2029 control_filename = self._write_control_file()
jadmanski0afbb632008-06-06 21:10:57 +00002030 hostnames = ','.join([entry.get_host().hostname
2031 for entry in queue_entries])
showardb2e2c322008-10-14 17:33:55 +00002032 job_tag = self._get_job_tag(queue_entries)
mbligh36768f02008-02-22 18:28:33 +00002033
showardb2e2c322008-10-14 17:33:55 +00002034 params = [_autoserv_path, '-P', job_tag, '-p', '-n',
jadmanski0afbb632008-06-06 21:10:57 +00002035 '-r', os.path.abspath(results_dir),
2036 '-b', '-u', self.owner, '-l', self.name,
showardb2e2c322008-10-14 17:33:55 +00002037 '-m', hostnames, control_filename]
mbligh36768f02008-02-22 18:28:33 +00002038
jadmanski0afbb632008-06-06 21:10:57 +00002039 if not self.is_server_job():
2040 params.append('-c')
mbligh36768f02008-02-22 18:28:33 +00002041
showardb2e2c322008-10-14 17:33:55 +00002042 return params
mblighe2586682008-02-29 22:45:46 +00002043
mbligh36768f02008-02-22 18:28:33 +00002044
showardb2e2c322008-10-14 17:33:55 +00002045 def _run_synchronous(self, queue_entry):
2046 if not self.is_ready():
showard9976ce92008-10-15 20:28:13 +00002047 if self.run_verify:
2048 return Agent([VerifySynchronousTask(queue_entry=queue_entry)], [queue_entry.id])
2049 else:
2050 return queue_entry.on_pending()
mbligh36768f02008-02-22 18:28:33 +00002051
showardb2e2c322008-10-14 17:33:55 +00002052 queue_entry.set_status('Starting')
jadmanski0afbb632008-06-06 21:10:57 +00002053
showardb2e2c322008-10-14 17:33:55 +00002054 return self._finish_run(self.get_host_queue_entries())
2055
2056
2057 def _run_asynchronous(self, queue_entry):
2058 # TODO(showard): this is of questionable necessity, but in the interest
2059 # of lowering risk, I'm leaving it in for now
2060 assert queue_entry
2061
showard9976ce92008-10-15 20:28:13 +00002062 initial_tasks = []
2063 if self.run_verify:
2064 initial_tasks = [VerifyTask(queue_entry)]
showardb2e2c322008-10-14 17:33:55 +00002065 return self._finish_run([queue_entry], initial_tasks)
2066
2067
2068 def _finish_run(self, queue_entries, initial_tasks=[]):
2069 params = self._get_autoserv_params(queue_entries)
2070 queue_task = QueueTask(job=self, queue_entries=queue_entries,
2071 cmd=params)
2072 tasks = initial_tasks + [queue_task]
2073 entry_ids = [entry.id for entry in queue_entries]
2074
2075 return Agent(tasks, entry_ids, num_processes=len(queue_entries))
2076
2077
2078 def run(self, queue_entry):
2079 if self.is_synchronous():
2080 return self._run_synchronous(queue_entry)
2081 return self._run_asynchronous(queue_entry)
mbligh36768f02008-02-22 18:28:33 +00002082
2083
2084if __name__ == '__main__':
jadmanski0afbb632008-06-06 21:10:57 +00002085 main()