blob: 2d109e6f34070b6c6d6d7da6c00facb7e942fde4 [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
643 queue_host = queue_entry.get_host()
644 reboot_task = RebootTask(queue_host)
645 verify_task = VerifyTask(host = queue_host)
646 self.add_agent(Agent(tasks=[reboot_task,
647 verify_task],
648 queue_entry_ids=[queue_entry.id]))
649 queue_entry.set_status('Aborted')
650 # Secure the host from being picked up
651 queue_host.set_status('Rebooting')
652 rebooting_host_ids.add(queue_host.id)
653
654 # reverify hosts that were in the middle of verify, repair or
655 # reboot
656 self._reverify_hosts_where("""(status = 'Repairing' OR
657 status = 'Verifying' OR
658 status = 'Rebooting')""",
659 exclude_ids=rebooting_host_ids)
660
661 # finally, recover "Running" hosts with no active queue entries,
662 # although this should never happen
663 message = ('Recovering running host %s - this probably '
664 'indicates a scheduler bug')
665 self._reverify_hosts_where("""status = 'Running' AND
666 id NOT IN (SELECT host_id
667 FROM host_queue_entries
668 WHERE active)""",
669 print_message=message)
mblighbb421852008-03-11 22:36:16 +0000670
671
jadmanski0afbb632008-06-06 21:10:57 +0000672 def _reverify_hosts_where(self, where,
673 print_message='Reverifying host %s',
674 exclude_ids=set()):
675 rows = _db.execute('SELECT * FROM hosts WHERE locked = 0 AND '
676 'invalid = 0 AND ' + where)
677 hosts = [Host(row=i) for i in rows]
678 for host in hosts:
679 if host.id in exclude_ids:
680 continue
681 if print_message is not None:
682 print print_message % host.hostname
683 verify_task = VerifyTask(host = host)
684 self.add_agent(Agent(tasks = [verify_task]))
mbligh36768f02008-02-22 18:28:33 +0000685
686
jadmanski0afbb632008-06-06 21:10:57 +0000687 def _recover_hosts(self):
688 # recover "Repair Failed" hosts
689 message = 'Reverifying dead host %s'
690 self._reverify_hosts_where("status = 'Repair Failed'",
691 print_message=message)
mbligh62ba2ed2008-04-30 17:09:25 +0000692
693
showard3bb499f2008-07-03 19:42:20 +0000694 def _abort_timed_out_jobs(self):
695 """
696 Aborts all jobs that have timed out and not completed
697 """
698 update = """
699 UPDATE host_queue_entries INNER JOIN jobs
700 ON host_queue_entries.job_id = jobs.id"""
mbligh7e26d622008-07-29 21:04:42 +0000701 timed_out = ' AND jobs.created_on + INTERVAL jobs.timeout HOUR < NOW()'
showard3bb499f2008-07-03 19:42:20 +0000702
703 _db.execute(update + """
704 SET host_queue_entries.status = 'Abort'
showardb1e51872008-10-07 11:08:18 +0000705 WHERE host_queue_entries.active""" + timed_out)
showard3bb499f2008-07-03 19:42:20 +0000706
707 _db.execute(update + """
708 SET host_queue_entries.status = 'Aborted',
showardb1e51872008-10-07 11:08:18 +0000709 host_queue_entries.active = 0,
710 host_queue_entries.complete = 1
711 WHERE NOT host_queue_entries.active
712 AND NOT host_queue_entries.complete""" + timed_out)
showard3bb499f2008-07-03 19:42:20 +0000713
714
jadmanski0afbb632008-06-06 21:10:57 +0000715 def _clear_inactive_blocks(self):
716 """
717 Clear out blocks for all completed jobs.
718 """
719 # this would be simpler using NOT IN (subquery), but MySQL
720 # treats all IN subqueries as dependent, so this optimizes much
721 # better
722 _db.execute("""
723 DELETE ihq FROM ineligible_host_queues ihq
showard4eaaf522008-06-06 22:28:07 +0000724 LEFT JOIN (SELECT DISTINCT job_id FROM host_queue_entries
jadmanski0afbb632008-06-06 21:10:57 +0000725 WHERE NOT complete) hqe
726 USING (job_id) WHERE hqe.job_id IS NULL""")
showard04c82c52008-05-29 19:38:12 +0000727
728
showardb95b1bd2008-08-15 18:11:04 +0000729 def _get_pending_queue_entries(self):
showard63a34772008-08-18 19:32:50 +0000730 # prioritize by job priority, then non-metahost over metahost, then FIFO
731 return list(HostQueueEntry.fetch(
732 where='NOT complete AND NOT active',
733 order_by='priority DESC, meta_host, id'))
mbligh36768f02008-02-22 18:28:33 +0000734
735
jadmanski0afbb632008-06-06 21:10:57 +0000736 def _schedule_new_jobs(self):
737 print "finding work"
738
showard63a34772008-08-18 19:32:50 +0000739 queue_entries = self._get_pending_queue_entries()
740 if not queue_entries:
showardb95b1bd2008-08-15 18:11:04 +0000741 return
showardb95b1bd2008-08-15 18:11:04 +0000742
showard63a34772008-08-18 19:32:50 +0000743 self._host_scheduler.refresh(queue_entries)
showardb95b1bd2008-08-15 18:11:04 +0000744
showard63a34772008-08-18 19:32:50 +0000745 for queue_entry in queue_entries:
746 assigned_host = self._host_scheduler.find_eligible_host(queue_entry)
showardb95b1bd2008-08-15 18:11:04 +0000747 if not assigned_host:
jadmanski0afbb632008-06-06 21:10:57 +0000748 continue
showardb95b1bd2008-08-15 18:11:04 +0000749 self._run_queue_entry(queue_entry, assigned_host)
750
751
752 def _run_queue_entry(self, queue_entry, host):
753 agent = queue_entry.run(assigned_host=host)
showard9976ce92008-10-15 20:28:13 +0000754 # in some cases (synchronous jobs with run_verify=False), agent may be None
755 if agent:
756 self.add_agent(agent)
mblighd5c95802008-03-05 00:33:46 +0000757
758
jadmanski0afbb632008-06-06 21:10:57 +0000759 def _find_aborting(self):
760 num_aborted = 0
761 # Find jobs that are aborting
762 for entry in queue_entries_to_abort():
763 agents_to_abort = self.get_agents(entry)
764 entry_host = entry.get_host()
765 reboot_task = RebootTask(entry_host)
766 verify_task = VerifyTask(host = entry_host)
767 tasks = [reboot_task, verify_task]
768 if agents_to_abort:
769 abort_task = AbortTask(entry, agents_to_abort)
showard56193bb2008-08-13 20:07:41 +0000770 for agent in agents_to_abort:
771 self.remove_agent(agent)
jadmanski0afbb632008-06-06 21:10:57 +0000772 tasks.insert(0, abort_task)
773 else:
774 entry.set_status('Aborted')
775 # just to make sure this host does not get
776 # taken away
777 entry_host.set_status('Rebooting')
778 self.add_agent(Agent(tasks=tasks,
779 queue_entry_ids = [entry.id]))
780 num_aborted += 1
781 if num_aborted >= 50:
782 break
783
784
showard4c5374f2008-09-04 17:02:56 +0000785 def _can_start_agent(self, agent, num_running_processes,
786 num_started_this_cycle, have_reached_limit):
787 # always allow zero-process agents to run
788 if agent.num_processes == 0:
789 return True
790 # don't allow any nonzero-process agents to run after we've reached a
791 # limit (this avoids starvation of many-process agents)
792 if have_reached_limit:
793 return False
794 # total process throttling
795 if (num_running_processes + agent.num_processes >
796 self.max_running_processes):
797 return False
798 # if a single agent exceeds the per-cycle throttling, still allow it to
799 # run when it's the first agent in the cycle
800 if num_started_this_cycle == 0:
801 return True
802 # per-cycle throttling
803 if (num_started_this_cycle + agent.num_processes >
804 self.max_processes_started_per_cycle):
805 return False
806 return True
807
808
jadmanski0afbb632008-06-06 21:10:57 +0000809 def _handle_agents(self):
showard4c5374f2008-09-04 17:02:56 +0000810 num_running_processes = self.num_running_processes()
jadmanski0afbb632008-06-06 21:10:57 +0000811 num_started_this_cycle = 0
showard4c5374f2008-09-04 17:02:56 +0000812 have_reached_limit = False
813 # iterate over copy, so we can remove agents during iteration
814 for agent in list(self._agents):
815 if agent.is_done():
jadmanski0afbb632008-06-06 21:10:57 +0000816 print "agent finished"
showard4c5374f2008-09-04 17:02:56 +0000817 self._agents.remove(agent)
818 num_running_processes -= agent.num_processes
819 continue
820 if not agent.is_running():
821 if not self._can_start_agent(agent, num_running_processes,
822 num_started_this_cycle,
823 have_reached_limit):
824 have_reached_limit = True
825 continue
826 num_running_processes += agent.num_processes
827 num_started_this_cycle += agent.num_processes
828 agent.tick()
829 print num_running_processes, 'running processes'
mbligh36768f02008-02-22 18:28:33 +0000830
831
832class RunMonitor(object):
jadmanski0afbb632008-06-06 21:10:57 +0000833 def __init__(self, cmd, nice_level = None, log_file = None):
834 self.nice_level = nice_level
835 self.log_file = log_file
836 self.cmd = cmd
mbligh36768f02008-02-22 18:28:33 +0000837
jadmanski0afbb632008-06-06 21:10:57 +0000838 def run(self):
839 if self.nice_level:
840 nice_cmd = ['nice','-n', str(self.nice_level)]
841 nice_cmd.extend(self.cmd)
842 self.cmd = nice_cmd
mbligh36768f02008-02-22 18:28:33 +0000843
jadmanski0afbb632008-06-06 21:10:57 +0000844 out_file = None
845 if self.log_file:
846 try:
847 os.makedirs(os.path.dirname(self.log_file))
848 except OSError, exc:
849 if exc.errno != errno.EEXIST:
850 log_stacktrace(
851 'Unexpected error creating logfile '
852 'directory for %s' % self.log_file)
853 try:
854 out_file = open(self.log_file, 'a')
855 out_file.write("\n%s\n" % ('*'*80))
856 out_file.write("%s> %s\n" %
857 (time.strftime("%X %x"),
858 self.cmd))
859 out_file.write("%s\n" % ('*'*80))
860 except (OSError, IOError):
861 log_stacktrace('Error opening log file %s' %
862 self.log_file)
mblighcadb3532008-04-15 17:46:26 +0000863
jadmanski0afbb632008-06-06 21:10:57 +0000864 if not out_file:
865 out_file = open('/dev/null', 'w')
mblighcadb3532008-04-15 17:46:26 +0000866
jadmanski0afbb632008-06-06 21:10:57 +0000867 in_devnull = open('/dev/null', 'r')
868 print "cmd = %s" % self.cmd
869 print "path = %s" % os.getcwd()
mbligh36768f02008-02-22 18:28:33 +0000870
jadmanski0afbb632008-06-06 21:10:57 +0000871 self.proc = subprocess.Popen(self.cmd, stdout=out_file,
872 stderr=subprocess.STDOUT,
873 stdin=in_devnull)
874 out_file.close()
875 in_devnull.close()
mbligh36768f02008-02-22 18:28:33 +0000876
877
jadmanski0afbb632008-06-06 21:10:57 +0000878 def get_pid(self):
879 return self.proc.pid
mblighbb421852008-03-11 22:36:16 +0000880
881
jadmanski0afbb632008-06-06 21:10:57 +0000882 def kill(self):
883 kill_autoserv(self.get_pid(), self.exit_code)
mblighbb421852008-03-11 22:36:16 +0000884
mbligh36768f02008-02-22 18:28:33 +0000885
jadmanski0afbb632008-06-06 21:10:57 +0000886 def exit_code(self):
887 return self.proc.poll()
mbligh36768f02008-02-22 18:28:33 +0000888
889
mblighbb421852008-03-11 22:36:16 +0000890class PidfileException(Exception):
jadmanski0afbb632008-06-06 21:10:57 +0000891 """\
892 Raised when there's some unexpected behavior with the pid file.
893 """
mblighbb421852008-03-11 22:36:16 +0000894
895
896class PidfileRunMonitor(RunMonitor):
jadmanski0afbb632008-06-06 21:10:57 +0000897 def __init__(self, results_dir, cmd=None, nice_level=None,
898 log_file=None):
899 self.results_dir = os.path.abspath(results_dir)
900 self.pid_file = os.path.join(results_dir, AUTOSERV_PID_FILE)
901 self.lost_process = False
902 self.start_time = time.time()
showardb376bc52008-06-13 20:48:45 +0000903 super(PidfileRunMonitor, self).__init__(cmd, nice_level, log_file)
mblighbb421852008-03-11 22:36:16 +0000904
905
jadmanski0afbb632008-06-06 21:10:57 +0000906 def get_pid(self):
907 pid, exit_status = self.get_pidfile_info()
908 assert pid is not None
909 return pid
mblighbb421852008-03-11 22:36:16 +0000910
911
jadmanski0afbb632008-06-06 21:10:57 +0000912 def _check_command_line(self, command_line, spacer=' ',
913 print_error=False):
914 results_dir_arg = spacer.join(('', '-r', self.results_dir, ''))
915 match = results_dir_arg in command_line
916 if print_error and not match:
917 print '%s not found in %s' % (repr(results_dir_arg),
918 repr(command_line))
919 return match
mbligh90a549d2008-03-25 23:52:34 +0000920
921
jadmanski0afbb632008-06-06 21:10:57 +0000922 def _check_proc_fs(self, pid):
923 cmdline_path = os.path.join('/proc', str(pid), 'cmdline')
924 try:
925 cmdline_file = open(cmdline_path, 'r')
926 cmdline = cmdline_file.read().strip()
927 cmdline_file.close()
928 except IOError:
929 return False
930 # /proc/.../cmdline has \x00 separating args
931 return self._check_command_line(cmdline, spacer='\x00',
932 print_error=True)
mblighbb421852008-03-11 22:36:16 +0000933
934
jadmanski0afbb632008-06-06 21:10:57 +0000935 def read_pidfile(self):
936 if not os.path.exists(self.pid_file):
937 return None, None
938 file_obj = open(self.pid_file, 'r')
939 lines = file_obj.readlines()
940 file_obj.close()
941 assert 1 <= len(lines) <= 2
942 try:
943 pid = int(lines[0])
944 exit_status = None
945 if len(lines) == 2:
946 exit_status = int(lines[1])
947 except ValueError, exc:
948 raise PidfileException('Corrupt pid file: ' +
949 str(exc.args))
mblighbb421852008-03-11 22:36:16 +0000950
jadmanski0afbb632008-06-06 21:10:57 +0000951 return pid, exit_status
mblighbb421852008-03-11 22:36:16 +0000952
953
jadmanski0afbb632008-06-06 21:10:57 +0000954 def _find_autoserv_proc(self):
955 autoserv_procs = Dispatcher.find_autoservs()
956 for pid, args in autoserv_procs.iteritems():
957 if self._check_command_line(args):
958 return pid, args
959 return None, None
mbligh90a549d2008-03-25 23:52:34 +0000960
961
jadmanski0afbb632008-06-06 21:10:57 +0000962 def get_pidfile_info(self):
963 """\
964 Returns:
965 None, None if autoserv has not yet run
966 pid, None if autoserv is running
967 pid, exit_status if autoserv has completed
968 """
969 if self.lost_process:
970 return self.pid, self.exit_status
mblighbb421852008-03-11 22:36:16 +0000971
jadmanski0afbb632008-06-06 21:10:57 +0000972 pid, exit_status = self.read_pidfile()
mblighbb421852008-03-11 22:36:16 +0000973
jadmanski0afbb632008-06-06 21:10:57 +0000974 if pid is None:
975 return self._handle_no_pid()
mbligh90a549d2008-03-25 23:52:34 +0000976
jadmanski0afbb632008-06-06 21:10:57 +0000977 if exit_status is None:
978 # double check whether or not autoserv is running
979 proc_running = self._check_proc_fs(pid)
980 if proc_running:
981 return pid, exit_status
mbligh90a549d2008-03-25 23:52:34 +0000982
jadmanski0afbb632008-06-06 21:10:57 +0000983 # pid but no process - maybe process *just* exited
984 pid, exit_status = self.read_pidfile()
985 if exit_status is None:
986 # autoserv exited without writing an exit code
987 # to the pidfile
988 error = ('autoserv died without writing exit '
989 'code')
990 message = error + '\nPid: %s\nPidfile: %s' % (
991 pid, self.pid_file)
992 print message
993 email_manager.enqueue_notify_email(error,
994 message)
995 self.on_lost_process(pid)
996 return self.pid, self.exit_status
mblighbb421852008-03-11 22:36:16 +0000997
jadmanski0afbb632008-06-06 21:10:57 +0000998 return pid, exit_status
mblighbb421852008-03-11 22:36:16 +0000999
1000
jadmanski0afbb632008-06-06 21:10:57 +00001001 def _handle_no_pid(self):
1002 """\
1003 Called when no pidfile is found or no pid is in the pidfile.
1004 """
1005 # is autoserv running?
1006 pid, args = self._find_autoserv_proc()
1007 if pid is None:
1008 # no autoserv process running
1009 message = 'No pid found at ' + self.pid_file
1010 else:
1011 message = ("Process %d (%s) hasn't written pidfile %s" %
1012 (pid, args, self.pid_file))
mbligh90a549d2008-03-25 23:52:34 +00001013
jadmanski0afbb632008-06-06 21:10:57 +00001014 print message
1015 if time.time() - self.start_time > PIDFILE_TIMEOUT:
1016 email_manager.enqueue_notify_email(
1017 'Process has failed to write pidfile', message)
1018 if pid is not None:
1019 kill_autoserv(pid)
1020 else:
1021 pid = 0
1022 self.on_lost_process(pid)
1023 return self.pid, self.exit_status
mbligh90a549d2008-03-25 23:52:34 +00001024
jadmanski0afbb632008-06-06 21:10:57 +00001025 return None, None
mbligh90a549d2008-03-25 23:52:34 +00001026
1027
jadmanski0afbb632008-06-06 21:10:57 +00001028 def on_lost_process(self, pid):
1029 """\
1030 Called when autoserv has exited without writing an exit status,
1031 or we've timed out waiting for autoserv to write a pid to the
1032 pidfile. In either case, we just return failure and the caller
1033 should signal some kind of warning.
mbligh90a549d2008-03-25 23:52:34 +00001034
jadmanski0afbb632008-06-06 21:10:57 +00001035 pid is unimportant here, as it shouldn't be used by anyone.
1036 """
1037 self.lost_process = True
1038 self.pid = pid
1039 self.exit_status = 1
mbligh90a549d2008-03-25 23:52:34 +00001040
1041
jadmanski0afbb632008-06-06 21:10:57 +00001042 def exit_code(self):
1043 pid, exit_code = self.get_pidfile_info()
1044 return exit_code
mblighbb421852008-03-11 22:36:16 +00001045
1046
mbligh36768f02008-02-22 18:28:33 +00001047class Agent(object):
showard4c5374f2008-09-04 17:02:56 +00001048 def __init__(self, tasks, queue_entry_ids=[], num_processes=1):
jadmanski0afbb632008-06-06 21:10:57 +00001049 self.active_task = None
1050 self.queue = Queue.Queue(0)
1051 self.dispatcher = None
1052 self.queue_entry_ids = queue_entry_ids
showard4c5374f2008-09-04 17:02:56 +00001053 self.num_processes = num_processes
jadmanski0afbb632008-06-06 21:10:57 +00001054
1055 for task in tasks:
1056 self.add_task(task)
mbligh36768f02008-02-22 18:28:33 +00001057
1058
jadmanski0afbb632008-06-06 21:10:57 +00001059 def add_task(self, task):
1060 self.queue.put_nowait(task)
1061 task.agent = self
mbligh36768f02008-02-22 18:28:33 +00001062
1063
jadmanski0afbb632008-06-06 21:10:57 +00001064 def tick(self):
1065 print "agent tick"
1066 if self.active_task and not self.active_task.is_done():
1067 self.active_task.poll()
1068 else:
1069 self._next_task();
mbligh36768f02008-02-22 18:28:33 +00001070
1071
jadmanski0afbb632008-06-06 21:10:57 +00001072 def _next_task(self):
1073 print "agent picking task"
1074 if self.active_task:
1075 assert self.active_task.is_done()
mbligh36768f02008-02-22 18:28:33 +00001076
jadmanski0afbb632008-06-06 21:10:57 +00001077 if not self.active_task.success:
1078 self.on_task_failure()
mblighe2586682008-02-29 22:45:46 +00001079
jadmanski0afbb632008-06-06 21:10:57 +00001080 self.active_task = None
1081 if not self.is_done():
1082 self.active_task = self.queue.get_nowait()
1083 if self.active_task:
1084 self.active_task.start()
mbligh36768f02008-02-22 18:28:33 +00001085
1086
jadmanski0afbb632008-06-06 21:10:57 +00001087 def on_task_failure(self):
1088 self.queue = Queue.Queue(0)
1089 for task in self.active_task.failure_tasks:
1090 self.add_task(task)
mbligh16c722d2008-03-05 00:58:44 +00001091
mblighe2586682008-02-29 22:45:46 +00001092
showard4c5374f2008-09-04 17:02:56 +00001093 def is_running(self):
jadmanski0afbb632008-06-06 21:10:57 +00001094 return self.active_task is not None
showardec113162008-05-08 00:52:49 +00001095
1096
jadmanski0afbb632008-06-06 21:10:57 +00001097 def is_done(self):
1098 return self.active_task == None and self.queue.empty()
mbligh36768f02008-02-22 18:28:33 +00001099
1100
jadmanski0afbb632008-06-06 21:10:57 +00001101 def start(self):
1102 assert self.dispatcher
mbligh36768f02008-02-22 18:28:33 +00001103
jadmanski0afbb632008-06-06 21:10:57 +00001104 self._next_task()
mbligh36768f02008-02-22 18:28:33 +00001105
jadmanski0afbb632008-06-06 21:10:57 +00001106
mbligh36768f02008-02-22 18:28:33 +00001107class AgentTask(object):
jadmanski0afbb632008-06-06 21:10:57 +00001108 def __init__(self, cmd, failure_tasks = []):
1109 self.done = False
1110 self.failure_tasks = failure_tasks
1111 self.started = False
1112 self.cmd = cmd
1113 self.task = None
1114 self.agent = None
1115 self.monitor = None
1116 self.success = None
mbligh36768f02008-02-22 18:28:33 +00001117
1118
jadmanski0afbb632008-06-06 21:10:57 +00001119 def poll(self):
1120 print "poll"
1121 if self.monitor:
1122 self.tick(self.monitor.exit_code())
1123 else:
1124 self.finished(False)
mbligh36768f02008-02-22 18:28:33 +00001125
1126
jadmanski0afbb632008-06-06 21:10:57 +00001127 def tick(self, exit_code):
1128 if exit_code==None:
1129 return
1130# print "exit_code was %d" % exit_code
1131 if exit_code == 0:
1132 success = True
1133 else:
1134 success = False
mbligh36768f02008-02-22 18:28:33 +00001135
jadmanski0afbb632008-06-06 21:10:57 +00001136 self.finished(success)
mbligh36768f02008-02-22 18:28:33 +00001137
1138
jadmanski0afbb632008-06-06 21:10:57 +00001139 def is_done(self):
1140 return self.done
mbligh36768f02008-02-22 18:28:33 +00001141
1142
jadmanski0afbb632008-06-06 21:10:57 +00001143 def finished(self, success):
1144 self.done = True
1145 self.success = success
1146 self.epilog()
mbligh36768f02008-02-22 18:28:33 +00001147
1148
jadmanski0afbb632008-06-06 21:10:57 +00001149 def prolog(self):
1150 pass
mblighd64e5702008-04-04 21:39:28 +00001151
1152
jadmanski0afbb632008-06-06 21:10:57 +00001153 def create_temp_resultsdir(self, suffix=''):
1154 self.temp_results_dir = tempfile.mkdtemp(suffix=suffix)
mblighd64e5702008-04-04 21:39:28 +00001155
mbligh36768f02008-02-22 18:28:33 +00001156
jadmanski0afbb632008-06-06 21:10:57 +00001157 def cleanup(self):
1158 if (hasattr(self, 'temp_results_dir') and
1159 os.path.exists(self.temp_results_dir)):
1160 shutil.rmtree(self.temp_results_dir)
mbligh36768f02008-02-22 18:28:33 +00001161
1162
jadmanski0afbb632008-06-06 21:10:57 +00001163 def epilog(self):
1164 self.cleanup()
mbligh36768f02008-02-22 18:28:33 +00001165
1166
jadmanski0afbb632008-06-06 21:10:57 +00001167 def start(self):
1168 assert self.agent
1169
1170 if not self.started:
1171 self.prolog()
1172 self.run()
1173
1174 self.started = True
1175
1176
1177 def abort(self):
1178 if self.monitor:
1179 self.monitor.kill()
1180 self.done = True
1181 self.cleanup()
1182
1183
1184 def run(self):
1185 if self.cmd:
1186 print "agent starting monitor"
1187 log_file = None
1188 if hasattr(self, 'host'):
1189 log_file = os.path.join(RESULTS_DIR, 'hosts',
1190 self.host.hostname)
1191 self.monitor = RunMonitor(
1192 self.cmd, nice_level = AUTOSERV_NICE_LEVEL,
1193 log_file = log_file)
1194 self.monitor.run()
mbligh36768f02008-02-22 18:28:33 +00001195
1196
1197class RepairTask(AgentTask):
jadmanski0afbb632008-06-06 21:10:57 +00001198 def __init__(self, host, fail_queue_entry=None):
1199 """\
1200 fail_queue_entry: queue entry to mark failed if this repair
1201 fails.
1202 """
jadmanskifb7cfb12008-07-09 14:13:21 +00001203 protection = host_protections.Protection.get_string(host.protection)
jadmanski542537f2008-07-24 14:14:56 +00001204 # normalize the protection name
1205 protection = host_protections.Protection.get_attr_name(protection)
jadmanski0afbb632008-06-06 21:10:57 +00001206 self.create_temp_resultsdir('.repair')
1207 cmd = [_autoserv_path , '-R', '-m', host.hostname,
jadmanskifb7cfb12008-07-09 14:13:21 +00001208 '-r', self.temp_results_dir, '--host-protection', protection]
jadmanski0afbb632008-06-06 21:10:57 +00001209 self.host = host
1210 self.fail_queue_entry = fail_queue_entry
1211 super(RepairTask, self).__init__(cmd)
mblighe2586682008-02-29 22:45:46 +00001212
mbligh36768f02008-02-22 18:28:33 +00001213
jadmanski0afbb632008-06-06 21:10:57 +00001214 def prolog(self):
1215 print "repair_task starting"
1216 self.host.set_status('Repairing')
mbligh36768f02008-02-22 18:28:33 +00001217
1218
jadmanski0afbb632008-06-06 21:10:57 +00001219 def epilog(self):
1220 super(RepairTask, self).epilog()
1221 if self.success:
1222 self.host.set_status('Ready')
1223 else:
1224 self.host.set_status('Repair Failed')
1225 if self.fail_queue_entry:
1226 self.fail_queue_entry.handle_host_failure()
mbligh36768f02008-02-22 18:28:33 +00001227
1228
1229class VerifyTask(AgentTask):
showard9976ce92008-10-15 20:28:13 +00001230 def __init__(self, queue_entry=None, host=None):
jadmanski0afbb632008-06-06 21:10:57 +00001231 assert bool(queue_entry) != bool(host)
mbligh36768f02008-02-22 18:28:33 +00001232
jadmanski0afbb632008-06-06 21:10:57 +00001233 self.host = host or queue_entry.host
1234 self.queue_entry = queue_entry
mbligh36768f02008-02-22 18:28:33 +00001235
jadmanski0afbb632008-06-06 21:10:57 +00001236 self.create_temp_resultsdir('.verify')
showard3d9899a2008-07-31 02:11:58 +00001237
showard9976ce92008-10-15 20:28:13 +00001238 cmd = [_autoserv_path,'-v','-m',self.host.hostname, '-r', self.temp_results_dir]
mbligh36768f02008-02-22 18:28:33 +00001239
jadmanski0afbb632008-06-06 21:10:57 +00001240 fail_queue_entry = None
1241 if queue_entry and not queue_entry.meta_host:
1242 fail_queue_entry = queue_entry
1243 failure_tasks = [RepairTask(self.host, fail_queue_entry)]
mblighe2586682008-02-29 22:45:46 +00001244
jadmanski0afbb632008-06-06 21:10:57 +00001245 super(VerifyTask, self).__init__(cmd,
1246 failure_tasks=failure_tasks)
mblighe2586682008-02-29 22:45:46 +00001247
1248
jadmanski0afbb632008-06-06 21:10:57 +00001249 def prolog(self):
1250 print "starting verify on %s" % (self.host.hostname)
1251 if self.queue_entry:
1252 self.queue_entry.set_status('Verifying')
1253 self.queue_entry.clear_results_dir(
1254 self.queue_entry.verify_results_dir())
1255 self.host.set_status('Verifying')
mbligh36768f02008-02-22 18:28:33 +00001256
1257
jadmanski0afbb632008-06-06 21:10:57 +00001258 def cleanup(self):
1259 if not os.path.exists(self.temp_results_dir):
1260 return
1261 if self.queue_entry and (self.success or
1262 not self.queue_entry.meta_host):
1263 self.move_results()
1264 super(VerifyTask, self).cleanup()
mblighd64e5702008-04-04 21:39:28 +00001265
1266
jadmanski0afbb632008-06-06 21:10:57 +00001267 def epilog(self):
1268 super(VerifyTask, self).epilog()
mbligh36768f02008-02-22 18:28:33 +00001269
jadmanski0afbb632008-06-06 21:10:57 +00001270 if self.success:
1271 self.host.set_status('Ready')
1272 elif self.queue_entry:
1273 self.queue_entry.requeue()
mbligh36768f02008-02-22 18:28:33 +00001274
1275
jadmanski0afbb632008-06-06 21:10:57 +00001276 def move_results(self):
1277 assert self.queue_entry is not None
1278 target_dir = self.queue_entry.verify_results_dir()
1279 if not os.path.exists(target_dir):
1280 os.makedirs(target_dir)
1281 files = os.listdir(self.temp_results_dir)
1282 for filename in files:
1283 if filename == AUTOSERV_PID_FILE:
1284 continue
1285 self.force_move(os.path.join(self.temp_results_dir,
1286 filename),
1287 os.path.join(target_dir, filename))
mbligh36768f02008-02-22 18:28:33 +00001288
1289
jadmanski0afbb632008-06-06 21:10:57 +00001290 @staticmethod
1291 def force_move(source, dest):
1292 """\
1293 Replacement for shutil.move() that will delete the destination
1294 if it exists, even if it's a directory.
1295 """
1296 if os.path.exists(dest):
1297 print ('Warning: removing existing destination file ' +
1298 dest)
1299 remove_file_or_dir(dest)
1300 shutil.move(source, dest)
mblighe2586682008-02-29 22:45:46 +00001301
1302
mblighdffd6372008-02-29 22:47:33 +00001303class VerifySynchronousTask(VerifyTask):
jadmanski0afbb632008-06-06 21:10:57 +00001304 def epilog(self):
1305 super(VerifySynchronousTask, self).epilog()
1306 if self.success:
1307 if self.queue_entry.job.num_complete() > 0:
1308 # some other entry failed verify, and we've
1309 # already been marked as stopped
1310 return
mblighdffd6372008-02-29 22:47:33 +00001311
showardb2e2c322008-10-14 17:33:55 +00001312 agent = self.queue_entry.on_pending()
1313 if agent:
jadmanski0afbb632008-06-06 21:10:57 +00001314 self.agent.dispatcher.add_agent(agent)
mblighe2586682008-02-29 22:45:46 +00001315
showardb2e2c322008-10-14 17:33:55 +00001316
mbligh36768f02008-02-22 18:28:33 +00001317class QueueTask(AgentTask):
jadmanski0afbb632008-06-06 21:10:57 +00001318 def __init__(self, job, queue_entries, cmd):
1319 super(QueueTask, self).__init__(cmd)
1320 self.job = job
1321 self.queue_entries = queue_entries
mbligh36768f02008-02-22 18:28:33 +00001322
1323
jadmanski0afbb632008-06-06 21:10:57 +00001324 @staticmethod
showardd8e548a2008-09-09 03:04:57 +00001325 def _write_keyval(keyval_dir, field, value, keyval_filename='keyval'):
1326 key_path = os.path.join(keyval_dir, keyval_filename)
jadmanski0afbb632008-06-06 21:10:57 +00001327 keyval_file = open(key_path, 'a')
showardd8e548a2008-09-09 03:04:57 +00001328 print >> keyval_file, '%s=%s' % (field, str(value))
jadmanski0afbb632008-06-06 21:10:57 +00001329 keyval_file.close()
mbligh36768f02008-02-22 18:28:33 +00001330
1331
showardd8e548a2008-09-09 03:04:57 +00001332 def _host_keyval_dir(self):
1333 return os.path.join(self.results_dir(), 'host_keyvals')
1334
1335
1336 def _write_host_keyval(self, host):
1337 labels = ','.join(host.labels())
1338 self._write_keyval(self._host_keyval_dir(), 'labels', labels,
1339 keyval_filename=host.hostname)
1340
1341 def _create_host_keyval_dir(self):
1342 directory = self._host_keyval_dir()
1343 if not os.path.exists(directory):
1344 os.makedirs(directory)
1345
1346
jadmanski0afbb632008-06-06 21:10:57 +00001347 def results_dir(self):
1348 return self.queue_entries[0].results_dir()
mblighbb421852008-03-11 22:36:16 +00001349
1350
jadmanski0afbb632008-06-06 21:10:57 +00001351 def run(self):
1352 """\
1353 Override AgentTask.run() so we can use a PidfileRunMonitor.
1354 """
1355 self.monitor = PidfileRunMonitor(self.results_dir(),
1356 cmd=self.cmd,
1357 nice_level=AUTOSERV_NICE_LEVEL)
1358 self.monitor.run()
mblighbb421852008-03-11 22:36:16 +00001359
1360
jadmanski0afbb632008-06-06 21:10:57 +00001361 def prolog(self):
1362 # write some job timestamps into the job keyval file
1363 queued = time.mktime(self.job.created_on.timetuple())
1364 started = time.time()
showardd8e548a2008-09-09 03:04:57 +00001365 self._write_keyval(self.results_dir(), "job_queued", int(queued))
1366 self._write_keyval(self.results_dir(), "job_started", int(started))
1367 self._create_host_keyval_dir()
jadmanski0afbb632008-06-06 21:10:57 +00001368 for queue_entry in self.queue_entries:
showardd8e548a2008-09-09 03:04:57 +00001369 self._write_host_keyval(queue_entry.host)
jadmanski0afbb632008-06-06 21:10:57 +00001370 print "starting queue_task on %s/%s" % (queue_entry.host.hostname, queue_entry.id)
1371 queue_entry.set_status('Running')
1372 queue_entry.host.set_status('Running')
1373 if (not self.job.is_synchronous() and
1374 self.job.num_machines() > 1):
1375 assert len(self.queue_entries) == 1
1376 self.job.write_to_machines_file(self.queue_entries[0])
mbligh36768f02008-02-22 18:28:33 +00001377
1378
jadmanski0afbb632008-06-06 21:10:57 +00001379 def _finish_task(self):
1380 # write out the finished time into the results keyval
1381 finished = time.time()
jadmanskif7fa2cc2008-10-01 14:13:23 +00001382 self._write_keyval(self.results_dir(), "job_finished", int(finished))
jadmanskic2ac77f2008-05-16 21:44:04 +00001383
jadmanski0afbb632008-06-06 21:10:57 +00001384 # parse the results of the job
1385 if self.job.is_synchronous() or self.job.num_machines() == 1:
1386 parse_results(self.job.results_dir())
1387 else:
1388 for queue_entry in self.queue_entries:
jadmanskif7fa2cc2008-10-01 14:13:23 +00001389 parse_results(queue_entry.results_dir(), flags="-l 2")
1390
1391
1392 def _log_abort(self):
1393 # build up sets of all the aborted_by and aborted_on values
1394 aborted_by, aborted_on = set(), set()
1395 for queue_entry in self.queue_entries:
1396 if queue_entry.aborted_by:
1397 aborted_by.add(queue_entry.aborted_by)
1398 t = int(time.mktime(queue_entry.aborted_on.timetuple()))
1399 aborted_on.add(t)
1400
1401 # extract some actual, unique aborted by value and write it out
1402 assert len(aborted_by) <= 1
1403 if len(aborted_by) == 1:
1404 results_dir = self.results_dir()
1405 self._write_keyval(results_dir, "aborted_by", aborted_by.pop())
1406 self._write_keyval(results_dir, "aborted_on", max(aborted_on))
jadmanskic2ac77f2008-05-16 21:44:04 +00001407
1408
jadmanski0afbb632008-06-06 21:10:57 +00001409 def abort(self):
1410 super(QueueTask, self).abort()
jadmanskif7fa2cc2008-10-01 14:13:23 +00001411 self._log_abort()
jadmanski0afbb632008-06-06 21:10:57 +00001412 self._finish_task()
jadmanskic2ac77f2008-05-16 21:44:04 +00001413
1414
jadmanski0afbb632008-06-06 21:10:57 +00001415 def epilog(self):
1416 super(QueueTask, self).epilog()
1417 if self.success:
1418 status = 'Completed'
1419 else:
1420 status = 'Failed'
mbligh36768f02008-02-22 18:28:33 +00001421
jadmanski0afbb632008-06-06 21:10:57 +00001422 for queue_entry in self.queue_entries:
1423 queue_entry.set_status(status)
1424 queue_entry.host.set_status('Ready')
mbligh36768f02008-02-22 18:28:33 +00001425
jadmanski0afbb632008-06-06 21:10:57 +00001426 self._finish_task()
mblighbb421852008-03-11 22:36:16 +00001427
jadmanski0afbb632008-06-06 21:10:57 +00001428 print "queue_task finished with %s/%s" % (status, self.success)
mbligh36768f02008-02-22 18:28:33 +00001429
1430
mblighbb421852008-03-11 22:36:16 +00001431class RecoveryQueueTask(QueueTask):
jadmanski0afbb632008-06-06 21:10:57 +00001432 def __init__(self, job, queue_entries, run_monitor):
1433 super(RecoveryQueueTask, self).__init__(job,
1434 queue_entries, cmd=None)
1435 self.run_monitor = run_monitor
mblighbb421852008-03-11 22:36:16 +00001436
1437
jadmanski0afbb632008-06-06 21:10:57 +00001438 def run(self):
1439 self.monitor = self.run_monitor
mblighbb421852008-03-11 22:36:16 +00001440
1441
jadmanski0afbb632008-06-06 21:10:57 +00001442 def prolog(self):
1443 # recovering an existing process - don't do prolog
1444 pass
mblighbb421852008-03-11 22:36:16 +00001445
1446
mbligh36768f02008-02-22 18:28:33 +00001447class RebootTask(AgentTask):
jadmanski0afbb632008-06-06 21:10:57 +00001448 def __init__(self, host):
1449 global _autoserv_path
1450
1451 # Current implementation of autoserv requires control file
1452 # to be passed on reboot action request. TODO: remove when no
1453 # longer appropriate.
1454 self.create_temp_resultsdir('.reboot')
1455 self.cmd = [_autoserv_path, '-b', '-m', host.hostname,
1456 '-r', self.temp_results_dir, '/dev/null']
1457 self.host = host
1458 super(RebootTask, self).__init__(self.cmd,
1459 failure_tasks=[RepairTask(host)])
mbligh16c722d2008-03-05 00:58:44 +00001460
mblighd5c95802008-03-05 00:33:46 +00001461
jadmanski0afbb632008-06-06 21:10:57 +00001462 def prolog(self):
1463 print "starting reboot task for host: %s" % self.host.hostname
1464 self.host.set_status("Rebooting")
mblighd5c95802008-03-05 00:33:46 +00001465
mblighd5c95802008-03-05 00:33:46 +00001466
1467class AbortTask(AgentTask):
jadmanski0afbb632008-06-06 21:10:57 +00001468 def __init__(self, queue_entry, agents_to_abort):
1469 self.queue_entry = queue_entry
1470 self.agents_to_abort = agents_to_abort
jadmanski0afbb632008-06-06 21:10:57 +00001471 super(AbortTask, self).__init__('')
mbligh36768f02008-02-22 18:28:33 +00001472
1473
jadmanski0afbb632008-06-06 21:10:57 +00001474 def prolog(self):
1475 print "starting abort on host %s, job %s" % (
1476 self.queue_entry.host_id, self.queue_entry.job_id)
1477 self.queue_entry.set_status('Aborting')
mbligh36768f02008-02-22 18:28:33 +00001478
mblighd64e5702008-04-04 21:39:28 +00001479
jadmanski0afbb632008-06-06 21:10:57 +00001480 def epilog(self):
1481 super(AbortTask, self).epilog()
1482 self.queue_entry.set_status('Aborted')
1483 self.success = True
1484
1485
1486 def run(self):
1487 for agent in self.agents_to_abort:
1488 if (agent.active_task):
1489 agent.active_task.abort()
mbligh36768f02008-02-22 18:28:33 +00001490
1491
1492class DBObject(object):
jadmanski0afbb632008-06-06 21:10:57 +00001493 def __init__(self, id=None, row=None, new_record=False):
1494 assert (bool(id) != bool(row))
mbligh36768f02008-02-22 18:28:33 +00001495
jadmanski0afbb632008-06-06 21:10:57 +00001496 self.__table = self._get_table()
1497 fields = self._fields()
mbligh36768f02008-02-22 18:28:33 +00001498
jadmanski0afbb632008-06-06 21:10:57 +00001499 self.__new_record = new_record
mbligh36768f02008-02-22 18:28:33 +00001500
jadmanski0afbb632008-06-06 21:10:57 +00001501 if row is None:
1502 sql = 'SELECT * FROM %s WHERE ID=%%s' % self.__table
1503 rows = _db.execute(sql, (id,))
1504 if len(rows) == 0:
1505 raise "row not found (table=%s, id=%s)" % \
1506 (self.__table, id)
1507 row = rows[0]
mbligh36768f02008-02-22 18:28:33 +00001508
jadmanski0afbb632008-06-06 21:10:57 +00001509 assert len(row) == self.num_cols(), (
1510 "table = %s, row = %s/%d, fields = %s/%d" % (
1511 self.__table, row, len(row), fields, self.num_cols()))
mbligh36768f02008-02-22 18:28:33 +00001512
jadmanski0afbb632008-06-06 21:10:57 +00001513 self.__valid_fields = {}
1514 for i,value in enumerate(row):
1515 self.__dict__[fields[i]] = value
1516 self.__valid_fields[fields[i]] = True
mbligh36768f02008-02-22 18:28:33 +00001517
jadmanski0afbb632008-06-06 21:10:57 +00001518 del self.__valid_fields['id']
mbligh36768f02008-02-22 18:28:33 +00001519
mblighe2586682008-02-29 22:45:46 +00001520
jadmanski0afbb632008-06-06 21:10:57 +00001521 @classmethod
1522 def _get_table(cls):
1523 raise NotImplementedError('Subclasses must override this')
mblighe2586682008-02-29 22:45:46 +00001524
1525
jadmanski0afbb632008-06-06 21:10:57 +00001526 @classmethod
1527 def _fields(cls):
1528 raise NotImplementedError('Subclasses must override this')
showard04c82c52008-05-29 19:38:12 +00001529
1530
jadmanski0afbb632008-06-06 21:10:57 +00001531 @classmethod
1532 def num_cols(cls):
1533 return len(cls._fields())
showard04c82c52008-05-29 19:38:12 +00001534
1535
jadmanski0afbb632008-06-06 21:10:57 +00001536 def count(self, where, table = None):
1537 if not table:
1538 table = self.__table
mbligh36768f02008-02-22 18:28:33 +00001539
jadmanski0afbb632008-06-06 21:10:57 +00001540 rows = _db.execute("""
1541 SELECT count(*) FROM %s
1542 WHERE %s
1543 """ % (table, where))
mbligh6f8bab42008-02-29 22:45:14 +00001544
jadmanski0afbb632008-06-06 21:10:57 +00001545 assert len(rows) == 1
1546
1547 return int(rows[0][0])
mbligh36768f02008-02-22 18:28:33 +00001548
1549
mblighf8c624d2008-07-03 16:58:45 +00001550 def update_field(self, field, value, condition=''):
jadmanski0afbb632008-06-06 21:10:57 +00001551 assert self.__valid_fields[field]
mbligh36768f02008-02-22 18:28:33 +00001552
jadmanski0afbb632008-06-06 21:10:57 +00001553 if self.__dict__[field] == value:
1554 return
mbligh36768f02008-02-22 18:28:33 +00001555
mblighf8c624d2008-07-03 16:58:45 +00001556 query = "UPDATE %s SET %s = %%s WHERE id = %%s" % (self.__table, field)
1557 if condition:
1558 query += ' AND (%s)' % condition
jadmanski0afbb632008-06-06 21:10:57 +00001559 _db.execute(query, (value, self.id))
1560
1561 self.__dict__[field] = value
mbligh36768f02008-02-22 18:28:33 +00001562
1563
jadmanski0afbb632008-06-06 21:10:57 +00001564 def save(self):
1565 if self.__new_record:
1566 keys = self._fields()[1:] # avoid id
1567 columns = ','.join([str(key) for key in keys])
1568 values = ['"%s"' % self.__dict__[key] for key in keys]
1569 values = ','.join(values)
1570 query = """INSERT INTO %s (%s) VALUES (%s)""" % \
1571 (self.__table, columns, values)
1572 _db.execute(query)
mbligh36768f02008-02-22 18:28:33 +00001573
1574
jadmanski0afbb632008-06-06 21:10:57 +00001575 def delete(self):
1576 query = 'DELETE FROM %s WHERE id=%%s' % self.__table
1577 _db.execute(query, (self.id,))
mblighe2586682008-02-29 22:45:46 +00001578
1579
showard63a34772008-08-18 19:32:50 +00001580 @staticmethod
1581 def _prefix_with(string, prefix):
1582 if string:
1583 string = prefix + string
1584 return string
1585
1586
jadmanski0afbb632008-06-06 21:10:57 +00001587 @classmethod
showard989f25d2008-10-01 11:38:11 +00001588 def fetch(cls, where='', params=(), joins='', order_by=''):
showard63a34772008-08-18 19:32:50 +00001589 order_by = cls._prefix_with(order_by, 'ORDER BY ')
1590 where = cls._prefix_with(where, 'WHERE ')
1591 query = ('SELECT %(table)s.* FROM %(table)s %(joins)s '
1592 '%(where)s %(order_by)s' % {'table' : cls._get_table(),
1593 'joins' : joins,
1594 'where' : where,
1595 'order_by' : order_by})
1596 rows = _db.execute(query, params)
jadmanski0afbb632008-06-06 21:10:57 +00001597 for row in rows:
1598 yield cls(row=row)
mblighe2586682008-02-29 22:45:46 +00001599
mbligh36768f02008-02-22 18:28:33 +00001600
1601class IneligibleHostQueue(DBObject):
jadmanski0afbb632008-06-06 21:10:57 +00001602 def __init__(self, id=None, row=None, new_record=None):
1603 super(IneligibleHostQueue, self).__init__(id=id, row=row,
1604 new_record=new_record)
mblighe2586682008-02-29 22:45:46 +00001605
1606
jadmanski0afbb632008-06-06 21:10:57 +00001607 @classmethod
1608 def _get_table(cls):
1609 return 'ineligible_host_queues'
mbligh36768f02008-02-22 18:28:33 +00001610
1611
jadmanski0afbb632008-06-06 21:10:57 +00001612 @classmethod
1613 def _fields(cls):
1614 return ['id', 'job_id', 'host_id']
showard04c82c52008-05-29 19:38:12 +00001615
1616
showard989f25d2008-10-01 11:38:11 +00001617class Label(DBObject):
1618 @classmethod
1619 def _get_table(cls):
1620 return 'labels'
1621
1622
1623 @classmethod
1624 def _fields(cls):
1625 return ['id', 'name', 'kernel_config', 'platform', 'invalid',
1626 'only_if_needed']
1627
1628
mbligh36768f02008-02-22 18:28:33 +00001629class Host(DBObject):
jadmanski0afbb632008-06-06 21:10:57 +00001630 def __init__(self, id=None, row=None):
1631 super(Host, self).__init__(id=id, row=row)
mblighe2586682008-02-29 22:45:46 +00001632
1633
jadmanski0afbb632008-06-06 21:10:57 +00001634 @classmethod
1635 def _get_table(cls):
1636 return 'hosts'
mbligh36768f02008-02-22 18:28:33 +00001637
1638
jadmanski0afbb632008-06-06 21:10:57 +00001639 @classmethod
1640 def _fields(cls):
1641 return ['id', 'hostname', 'locked', 'synch_id','status',
showardfb2a7fa2008-07-17 17:04:12 +00001642 'invalid', 'protection', 'locked_by_id', 'lock_time']
showard04c82c52008-05-29 19:38:12 +00001643
1644
jadmanski0afbb632008-06-06 21:10:57 +00001645 def current_task(self):
1646 rows = _db.execute("""
1647 SELECT * FROM host_queue_entries WHERE host_id=%s AND NOT complete AND active
1648 """, (self.id,))
1649
1650 if len(rows) == 0:
1651 return None
1652 else:
1653 assert len(rows) == 1
1654 results = rows[0];
mblighf8c624d2008-07-03 16:58:45 +00001655# print "current = %s" % results
jadmanski0afbb632008-06-06 21:10:57 +00001656 return HostQueueEntry(row=results)
mbligh36768f02008-02-22 18:28:33 +00001657
1658
jadmanski0afbb632008-06-06 21:10:57 +00001659 def yield_work(self):
1660 print "%s yielding work" % self.hostname
1661 if self.current_task():
1662 self.current_task().requeue()
1663
1664 def set_status(self,status):
1665 print '%s -> %s' % (self.hostname, status)
1666 self.update_field('status',status)
mbligh36768f02008-02-22 18:28:33 +00001667
1668
showardd8e548a2008-09-09 03:04:57 +00001669 def labels(self):
1670 """
1671 Fetch a list of names of all non-platform labels associated with this
1672 host.
1673 """
1674 rows = _db.execute("""
1675 SELECT labels.name
1676 FROM labels
1677 INNER JOIN hosts_labels ON labels.id = hosts_labels.label_id
1678 WHERE NOT labels.platform AND hosts_labels.host_id = %s
1679 ORDER BY labels.name
1680 """, (self.id,))
1681 return [row[0] for row in rows]
1682
1683
mbligh36768f02008-02-22 18:28:33 +00001684class HostQueueEntry(DBObject):
jadmanski0afbb632008-06-06 21:10:57 +00001685 def __init__(self, id=None, row=None):
1686 assert id or row
1687 super(HostQueueEntry, self).__init__(id=id, row=row)
1688 self.job = Job(self.job_id)
mbligh36768f02008-02-22 18:28:33 +00001689
jadmanski0afbb632008-06-06 21:10:57 +00001690 if self.host_id:
1691 self.host = Host(self.host_id)
1692 else:
1693 self.host = None
mbligh36768f02008-02-22 18:28:33 +00001694
jadmanski0afbb632008-06-06 21:10:57 +00001695 self.queue_log_path = os.path.join(self.job.results_dir(),
1696 'queue.log.' + str(self.id))
mbligh36768f02008-02-22 18:28:33 +00001697
1698
jadmanski0afbb632008-06-06 21:10:57 +00001699 @classmethod
1700 def _get_table(cls):
1701 return 'host_queue_entries'
mblighe2586682008-02-29 22:45:46 +00001702
1703
jadmanski0afbb632008-06-06 21:10:57 +00001704 @classmethod
1705 def _fields(cls):
1706 return ['id', 'job_id', 'host_id', 'priority', 'status',
showardb8471e32008-07-03 19:51:08 +00001707 'meta_host', 'active', 'complete', 'deleted']
showard04c82c52008-05-29 19:38:12 +00001708
1709
jadmanski0afbb632008-06-06 21:10:57 +00001710 def set_host(self, host):
1711 if host:
1712 self.queue_log_record('Assigning host ' + host.hostname)
1713 self.update_field('host_id', host.id)
1714 self.update_field('active', True)
1715 self.block_host(host.id)
1716 else:
1717 self.queue_log_record('Releasing host')
1718 self.unblock_host(self.host.id)
1719 self.update_field('host_id', None)
mbligh36768f02008-02-22 18:28:33 +00001720
jadmanski0afbb632008-06-06 21:10:57 +00001721 self.host = host
mbligh36768f02008-02-22 18:28:33 +00001722
1723
jadmanski0afbb632008-06-06 21:10:57 +00001724 def get_host(self):
1725 return self.host
mbligh36768f02008-02-22 18:28:33 +00001726
1727
jadmanski0afbb632008-06-06 21:10:57 +00001728 def queue_log_record(self, log_line):
1729 now = str(datetime.datetime.now())
1730 queue_log = open(self.queue_log_path, 'a', 0)
1731 queue_log.write(now + ' ' + log_line + '\n')
1732 queue_log.close()
mbligh36768f02008-02-22 18:28:33 +00001733
1734
jadmanski0afbb632008-06-06 21:10:57 +00001735 def block_host(self, host_id):
1736 print "creating block %s/%s" % (self.job.id, host_id)
1737 row = [0, self.job.id, host_id]
1738 block = IneligibleHostQueue(row=row, new_record=True)
1739 block.save()
mblighe2586682008-02-29 22:45:46 +00001740
1741
jadmanski0afbb632008-06-06 21:10:57 +00001742 def unblock_host(self, host_id):
1743 print "removing block %s/%s" % (self.job.id, host_id)
1744 blocks = IneligibleHostQueue.fetch(
1745 'job_id=%d and host_id=%d' % (self.job.id, host_id))
1746 for block in blocks:
1747 block.delete()
mblighe2586682008-02-29 22:45:46 +00001748
1749
jadmanski0afbb632008-06-06 21:10:57 +00001750 def results_dir(self):
1751 if self.job.is_synchronous() or self.job.num_machines() == 1:
1752 return self.job.job_dir
1753 else:
1754 assert self.host
1755 return os.path.join(self.job.job_dir,
1756 self.host.hostname)
mbligh36768f02008-02-22 18:28:33 +00001757
mblighe2586682008-02-29 22:45:46 +00001758
jadmanski0afbb632008-06-06 21:10:57 +00001759 def verify_results_dir(self):
1760 if self.job.is_synchronous() or self.job.num_machines() > 1:
1761 assert self.host
1762 return os.path.join(self.job.job_dir,
1763 self.host.hostname)
1764 else:
1765 return self.job.job_dir
mbligh36768f02008-02-22 18:28:33 +00001766
1767
jadmanski0afbb632008-06-06 21:10:57 +00001768 def set_status(self, status):
mblighf8c624d2008-07-03 16:58:45 +00001769 abort_statuses = ['Abort', 'Aborting', 'Aborted']
1770 if status not in abort_statuses:
1771 condition = ' AND '.join(['status <> "%s"' % x
1772 for x in abort_statuses])
1773 else:
1774 condition = ''
1775 self.update_field('status', status, condition=condition)
1776
jadmanski0afbb632008-06-06 21:10:57 +00001777 if self.host:
1778 hostname = self.host.hostname
1779 else:
1780 hostname = 'no host'
1781 print "%s/%d status -> %s" % (hostname, self.id, self.status)
mblighf8c624d2008-07-03 16:58:45 +00001782
jadmanski0afbb632008-06-06 21:10:57 +00001783 if status in ['Queued']:
1784 self.update_field('complete', False)
1785 self.update_field('active', False)
mbligh36768f02008-02-22 18:28:33 +00001786
jadmanski0afbb632008-06-06 21:10:57 +00001787 if status in ['Pending', 'Running', 'Verifying', 'Starting',
1788 'Abort', 'Aborting']:
1789 self.update_field('complete', False)
1790 self.update_field('active', True)
mbligh36768f02008-02-22 18:28:33 +00001791
jadmanski0afbb632008-06-06 21:10:57 +00001792 if status in ['Failed', 'Completed', 'Stopped', 'Aborted']:
1793 self.update_field('complete', True)
1794 self.update_field('active', False)
showard542e8402008-09-19 20:16:18 +00001795 self._email_on_job_complete()
1796
1797
1798 def _email_on_job_complete(self):
1799 url = "%s#tab_id=view_job&object_id=%s" % (_base_url, self.job.id)
1800
1801 if self.job.is_finished():
1802 subject = "Autotest: Job ID: %s \"%s\" Completed" % (
1803 self.job.id, self.job.name)
1804 body = "Job ID: %s\nJob Name: %s\n%s\n" % (
1805 self.job.id, self.job.name, url)
1806 send_email(_email_from, self.job.email_list, subject, body)
mbligh36768f02008-02-22 18:28:33 +00001807
1808
jadmanski0afbb632008-06-06 21:10:57 +00001809 def run(self,assigned_host=None):
1810 if self.meta_host:
1811 assert assigned_host
1812 # ensure results dir exists for the queue log
1813 self.job.create_results_dir()
1814 self.set_host(assigned_host)
mbligh36768f02008-02-22 18:28:33 +00001815
jadmanski0afbb632008-06-06 21:10:57 +00001816 print "%s/%s scheduled on %s, status=%s" % (self.job.name,
1817 self.meta_host, self.host.hostname, self.status)
mbligh36768f02008-02-22 18:28:33 +00001818
jadmanski0afbb632008-06-06 21:10:57 +00001819 return self.job.run(queue_entry=self)
mblighe2586682008-02-29 22:45:46 +00001820
jadmanski0afbb632008-06-06 21:10:57 +00001821 def requeue(self):
1822 self.set_status('Queued')
mblighe2586682008-02-29 22:45:46 +00001823
jadmanski0afbb632008-06-06 21:10:57 +00001824 if self.meta_host:
1825 self.set_host(None)
mbligh36768f02008-02-22 18:28:33 +00001826
1827
jadmanski0afbb632008-06-06 21:10:57 +00001828 def handle_host_failure(self):
1829 """\
1830 Called when this queue entry's host has failed verification and
1831 repair.
1832 """
1833 assert not self.meta_host
1834 self.set_status('Failed')
1835 if self.job.is_synchronous():
1836 self.job.stop_all_entries()
mblighe2586682008-02-29 22:45:46 +00001837
1838
jadmanski0afbb632008-06-06 21:10:57 +00001839 def clear_results_dir(self, results_dir=None, dont_delete_files=False):
1840 results_dir = results_dir or self.results_dir()
1841 if not os.path.exists(results_dir):
1842 return
1843 if dont_delete_files:
1844 temp_dir = tempfile.mkdtemp(suffix='.clear_results')
1845 print 'Moving results from %s to %s' % (results_dir,
1846 temp_dir)
1847 for filename in os.listdir(results_dir):
1848 path = os.path.join(results_dir, filename)
1849 if dont_delete_files:
1850 shutil.move(path,
1851 os.path.join(temp_dir, filename))
1852 else:
1853 remove_file_or_dir(path)
mbligh36768f02008-02-22 18:28:33 +00001854
1855
jadmanskif7fa2cc2008-10-01 14:13:23 +00001856 @property
1857 def aborted_by(self):
1858 self._load_abort_info()
1859 return self._aborted_by
1860
1861
1862 @property
1863 def aborted_on(self):
1864 self._load_abort_info()
1865 return self._aborted_on
1866
1867
1868 def _load_abort_info(self):
1869 """ Fetch info about who aborted the job. """
1870 if hasattr(self, "_aborted_by"):
1871 return
1872 rows = _db.execute("""
1873 SELECT users.login, aborted_host_queue_entries.aborted_on
1874 FROM aborted_host_queue_entries
1875 INNER JOIN users
1876 ON users.id = aborted_host_queue_entries.aborted_by_id
1877 WHERE aborted_host_queue_entries.queue_entry_id = %s
1878 """, (self.id,))
1879 if rows:
1880 self._aborted_by, self._aborted_on = rows[0]
1881 else:
1882 self._aborted_by = self._aborted_on = None
1883
1884
showardb2e2c322008-10-14 17:33:55 +00001885 def on_pending(self):
1886 """
1887 Called when an entry in a synchronous job has passed verify. If the
1888 job is ready to run, returns an agent to run the job. Returns None
1889 otherwise.
1890 """
1891 self.set_status('Pending')
showardcfd66a32008-10-15 20:31:48 +00001892 self.get_host().set_status('Pending')
showardb2e2c322008-10-14 17:33:55 +00001893 if self.job.is_ready():
1894 return self.job.run(self)
1895 return None
1896
1897
mbligh36768f02008-02-22 18:28:33 +00001898class Job(DBObject):
jadmanski0afbb632008-06-06 21:10:57 +00001899 def __init__(self, id=None, row=None):
1900 assert id or row
1901 super(Job, self).__init__(id=id, row=row)
mbligh36768f02008-02-22 18:28:33 +00001902
jadmanski0afbb632008-06-06 21:10:57 +00001903 self.job_dir = os.path.join(RESULTS_DIR, "%s-%s" % (self.id,
1904 self.owner))
mblighe2586682008-02-29 22:45:46 +00001905
1906
jadmanski0afbb632008-06-06 21:10:57 +00001907 @classmethod
1908 def _get_table(cls):
1909 return 'jobs'
mbligh36768f02008-02-22 18:28:33 +00001910
1911
jadmanski0afbb632008-06-06 21:10:57 +00001912 @classmethod
1913 def _fields(cls):
1914 return ['id', 'owner', 'name', 'priority', 'control_file',
1915 'control_type', 'created_on', 'synch_type',
showard542e8402008-09-19 20:16:18 +00001916 'synch_count', 'synchronizing', 'timeout',
1917 'run_verify', 'email_list']
showard04c82c52008-05-29 19:38:12 +00001918
1919
jadmanski0afbb632008-06-06 21:10:57 +00001920 def is_server_job(self):
1921 return self.control_type != 2
mbligh36768f02008-02-22 18:28:33 +00001922
1923
jadmanski0afbb632008-06-06 21:10:57 +00001924 def get_host_queue_entries(self):
1925 rows = _db.execute("""
1926 SELECT * FROM host_queue_entries
1927 WHERE job_id= %s
1928 """, (self.id,))
1929 entries = [HostQueueEntry(row=i) for i in rows]
mbligh36768f02008-02-22 18:28:33 +00001930
jadmanski0afbb632008-06-06 21:10:57 +00001931 assert len(entries)>0
mbligh36768f02008-02-22 18:28:33 +00001932
jadmanski0afbb632008-06-06 21:10:57 +00001933 return entries
mbligh36768f02008-02-22 18:28:33 +00001934
1935
jadmanski0afbb632008-06-06 21:10:57 +00001936 def set_status(self, status, update_queues=False):
1937 self.update_field('status',status)
1938
1939 if update_queues:
1940 for queue_entry in self.get_host_queue_entries():
1941 queue_entry.set_status(status)
mbligh36768f02008-02-22 18:28:33 +00001942
1943
jadmanski0afbb632008-06-06 21:10:57 +00001944 def is_synchronous(self):
1945 return self.synch_type == 2
mbligh36768f02008-02-22 18:28:33 +00001946
1947
jadmanski0afbb632008-06-06 21:10:57 +00001948 def is_ready(self):
1949 if not self.is_synchronous():
1950 return True
1951 sql = "job_id=%s AND status='Pending'" % self.id
1952 count = self.count(sql, table='host_queue_entries')
showardb2e2c322008-10-14 17:33:55 +00001953 return (count == self.num_machines())
mbligh36768f02008-02-22 18:28:33 +00001954
1955
jadmanski0afbb632008-06-06 21:10:57 +00001956 def results_dir(self):
1957 return self.job_dir
mbligh36768f02008-02-22 18:28:33 +00001958
jadmanski0afbb632008-06-06 21:10:57 +00001959 def num_machines(self, clause = None):
1960 sql = "job_id=%s" % self.id
1961 if clause:
1962 sql += " AND (%s)" % clause
1963 return self.count(sql, table='host_queue_entries')
mbligh36768f02008-02-22 18:28:33 +00001964
1965
jadmanski0afbb632008-06-06 21:10:57 +00001966 def num_queued(self):
1967 return self.num_machines('not complete')
mbligh36768f02008-02-22 18:28:33 +00001968
1969
jadmanski0afbb632008-06-06 21:10:57 +00001970 def num_active(self):
1971 return self.num_machines('active')
mbligh36768f02008-02-22 18:28:33 +00001972
1973
jadmanski0afbb632008-06-06 21:10:57 +00001974 def num_complete(self):
1975 return self.num_machines('complete')
mbligh36768f02008-02-22 18:28:33 +00001976
1977
jadmanski0afbb632008-06-06 21:10:57 +00001978 def is_finished(self):
1979 left = self.num_queued()
1980 print "%s: %s machines left" % (self.name, left)
1981 return left==0
mbligh36768f02008-02-22 18:28:33 +00001982
mbligh36768f02008-02-22 18:28:33 +00001983
jadmanski0afbb632008-06-06 21:10:57 +00001984 def stop_all_entries(self):
1985 for child_entry in self.get_host_queue_entries():
1986 if not child_entry.complete:
1987 child_entry.set_status('Stopped')
mblighe2586682008-02-29 22:45:46 +00001988
1989
jadmanski0afbb632008-06-06 21:10:57 +00001990 def write_to_machines_file(self, queue_entry):
1991 hostname = queue_entry.get_host().hostname
1992 print "writing %s to job %s machines file" % (hostname, self.id)
1993 file_path = os.path.join(self.job_dir, '.machines')
1994 mf = open(file_path, 'a')
1995 mf.write("%s\n" % queue_entry.get_host().hostname)
1996 mf.close()
mbligh36768f02008-02-22 18:28:33 +00001997
1998
jadmanski0afbb632008-06-06 21:10:57 +00001999 def create_results_dir(self, queue_entry=None):
2000 print "create: active: %s complete %s" % (self.num_active(),
2001 self.num_complete())
mbligh36768f02008-02-22 18:28:33 +00002002
jadmanski0afbb632008-06-06 21:10:57 +00002003 if not os.path.exists(self.job_dir):
2004 os.makedirs(self.job_dir)
mbligh36768f02008-02-22 18:28:33 +00002005
jadmanski0afbb632008-06-06 21:10:57 +00002006 if queue_entry:
2007 return queue_entry.results_dir()
2008 return self.job_dir
mbligh36768f02008-02-22 18:28:33 +00002009
2010
showardb2e2c322008-10-14 17:33:55 +00002011 def _write_control_file(self):
2012 'Writes control file out to disk, returns a filename'
2013 control_fd, control_filename = tempfile.mkstemp(suffix='.control_file')
2014 control_file = os.fdopen(control_fd, 'w')
jadmanski0afbb632008-06-06 21:10:57 +00002015 if self.control_file:
showardb2e2c322008-10-14 17:33:55 +00002016 control_file.write(self.control_file)
2017 control_file.close()
2018 return control_filename
mbligh36768f02008-02-22 18:28:33 +00002019
showardb2e2c322008-10-14 17:33:55 +00002020
2021 def _get_job_tag(self, queue_entries):
2022 base_job_tag = "%s-%s" % (self.id, self.owner)
2023 if self.is_synchronous() or self.num_machines() == 1:
2024 return base_job_tag
jadmanski0afbb632008-06-06 21:10:57 +00002025 else:
showardb2e2c322008-10-14 17:33:55 +00002026 return base_job_tag + '/' + queue_entries[0].get_host().hostname
2027
2028
2029 def _get_autoserv_params(self, queue_entries):
2030 results_dir = self.create_results_dir(queue_entries[0])
2031 control_filename = self._write_control_file()
jadmanski0afbb632008-06-06 21:10:57 +00002032 hostnames = ','.join([entry.get_host().hostname
2033 for entry in queue_entries])
showardb2e2c322008-10-14 17:33:55 +00002034 job_tag = self._get_job_tag(queue_entries)
mbligh36768f02008-02-22 18:28:33 +00002035
showardb2e2c322008-10-14 17:33:55 +00002036 params = [_autoserv_path, '-P', job_tag, '-p', '-n',
jadmanski0afbb632008-06-06 21:10:57 +00002037 '-r', os.path.abspath(results_dir),
2038 '-b', '-u', self.owner, '-l', self.name,
showardb2e2c322008-10-14 17:33:55 +00002039 '-m', hostnames, control_filename]
mbligh36768f02008-02-22 18:28:33 +00002040
jadmanski0afbb632008-06-06 21:10:57 +00002041 if not self.is_server_job():
2042 params.append('-c')
mbligh36768f02008-02-22 18:28:33 +00002043
showardb2e2c322008-10-14 17:33:55 +00002044 return params
mblighe2586682008-02-29 22:45:46 +00002045
mbligh36768f02008-02-22 18:28:33 +00002046
showardb2e2c322008-10-14 17:33:55 +00002047 def _run_synchronous(self, queue_entry):
2048 if not self.is_ready():
showard9976ce92008-10-15 20:28:13 +00002049 if self.run_verify:
2050 return Agent([VerifySynchronousTask(queue_entry=queue_entry)], [queue_entry.id])
2051 else:
2052 return queue_entry.on_pending()
mbligh36768f02008-02-22 18:28:33 +00002053
showardb2e2c322008-10-14 17:33:55 +00002054 queue_entry.set_status('Starting')
jadmanski0afbb632008-06-06 21:10:57 +00002055
showardb2e2c322008-10-14 17:33:55 +00002056 return self._finish_run(self.get_host_queue_entries())
2057
2058
2059 def _run_asynchronous(self, queue_entry):
2060 # TODO(showard): this is of questionable necessity, but in the interest
2061 # of lowering risk, I'm leaving it in for now
2062 assert queue_entry
2063
showard9976ce92008-10-15 20:28:13 +00002064 initial_tasks = []
2065 if self.run_verify:
2066 initial_tasks = [VerifyTask(queue_entry)]
showardb2e2c322008-10-14 17:33:55 +00002067 return self._finish_run([queue_entry], initial_tasks)
2068
2069
2070 def _finish_run(self, queue_entries, initial_tasks=[]):
2071 params = self._get_autoserv_params(queue_entries)
2072 queue_task = QueueTask(job=self, queue_entries=queue_entries,
2073 cmd=params)
2074 tasks = initial_tasks + [queue_task]
2075 entry_ids = [entry.id for entry in queue_entries]
2076
2077 return Agent(tasks, entry_ids, num_processes=len(queue_entries))
2078
2079
2080 def run(self, queue_entry):
2081 if self.is_synchronous():
2082 return self._run_synchronous(queue_entry)
2083 return self._run_asynchronous(queue_entry)
mbligh36768f02008-02-22 18:28:33 +00002084
2085
2086if __name__ == '__main__':
jadmanski0afbb632008-06-06 21:10:57 +00002087 main()