blob: f5aea075975796b4bf11d7d91a0841162a323ec2 [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
showard402934a2009-12-21 22:20:47 +00008import common
showardef519212009-05-08 02:29:53 +00009import datetime, errno, optparse, os, pwd, Queue, re, shutil, signal
Eric Li6f27d4f2010-09-29 10:55:17 -070010import smtplib, socket, stat, subprocess, sys, tempfile, time, traceback, urllib
showardf13a9e22009-12-18 22:54:09 +000011import itertools, logging, weakref, gc
showard402934a2009-12-21 22:20:47 +000012
mbligh8bcd23a2009-02-03 19:14:06 +000013import MySQLdb
showard402934a2009-12-21 22:20:47 +000014
showard043c62a2009-06-10 19:48:57 +000015from autotest_lib.scheduler import scheduler_logging_config
showard21baa452008-10-21 00:08:39 +000016from autotest_lib.frontend import setup_django_environment
showard402934a2009-12-21 22:20:47 +000017
18import django.db
19
showard136e6dc2009-06-10 19:38:49 +000020from autotest_lib.client.common_lib import global_config, logging_manager
showardb18134f2009-03-20 20:52:18 +000021from autotest_lib.client.common_lib import host_protections, utils
showardb1e51872008-10-07 11:08:18 +000022from autotest_lib.database import database_connection
showard844960a2009-05-29 18:41:18 +000023from autotest_lib.frontend.afe import models, rpc_utils, readonly_connection
jamesrendd855242010-03-02 22:23:44 +000024from autotest_lib.frontend.afe import model_attributes
showard170873e2009-01-07 00:22:26 +000025from autotest_lib.scheduler import drone_manager, drones, email_manager
Dale Curtisaa513362011-03-01 17:27:44 -080026from autotest_lib.scheduler import gc_stats, host_scheduler, monitor_db_cleanup
showardd1ee1dd2009-01-07 21:33:08 +000027from autotest_lib.scheduler import status_server, scheduler_config
jamesrenc44ae992010-02-19 00:12:54 +000028from autotest_lib.scheduler import scheduler_models
showard549afad2009-08-20 23:33:36 +000029BABYSITTER_PID_FILE_PREFIX = 'monitor_db_babysitter'
30PID_FILE_PREFIX = 'monitor_db'
mblighb090f142008-02-27 21:33:46 +000031
mbligh36768f02008-02-22 18:28:33 +000032RESULTS_DIR = '.'
33AUTOSERV_NICE_LEVEL = 10
showard170873e2009-01-07 00:22:26 +000034DB_CONFIG_SECTION = 'AUTOTEST_WEB'
mbligh36768f02008-02-22 18:28:33 +000035AUTOTEST_PATH = os.path.join(os.path.dirname(__file__), '..')
36
37if os.environ.has_key('AUTOTEST_DIR'):
jadmanski0afbb632008-06-06 21:10:57 +000038 AUTOTEST_PATH = os.environ['AUTOTEST_DIR']
mbligh36768f02008-02-22 18:28:33 +000039AUTOTEST_SERVER_DIR = os.path.join(AUTOTEST_PATH, 'server')
40AUTOTEST_TKO_DIR = os.path.join(AUTOTEST_PATH, 'tko')
41
42if AUTOTEST_SERVER_DIR not in sys.path:
jadmanski0afbb632008-06-06 21:10:57 +000043 sys.path.insert(0, AUTOTEST_SERVER_DIR)
mbligh36768f02008-02-22 18:28:33 +000044
showard35162b02009-03-03 02:17:30 +000045# error message to leave in results dir when an autoserv process disappears
46# mysteriously
47_LOST_PROCESS_ERROR = """\
48Autoserv failed abnormally during execution for this job, probably due to a
49system error on the Autotest server. Full results may not be available. Sorry.
50"""
51
mbligh6f8bab42008-02-29 22:45:14 +000052_db = None
mbligh36768f02008-02-22 18:28:33 +000053_shutdown = False
showard170873e2009-01-07 00:22:26 +000054_autoserv_path = os.path.join(drones.AUTOTEST_INSTALL_DIR, 'server', 'autoserv')
mbligh4314a712008-02-29 22:44:30 +000055_testing_mode = False
jamesrenc44ae992010-02-19 00:12:54 +000056_drone_manager = None
mbligh36768f02008-02-22 18:28:33 +000057
Eric Lie0493a42010-11-15 13:05:43 -080058def _parser_path_default(install_dir):
59 return os.path.join(install_dir, 'tko', 'parse')
60_parser_path_func = utils.import_site_function(
61 __file__, 'autotest_lib.scheduler.site_monitor_db',
62 'parser_path', _parser_path_default)
63_parser_path = _parser_path_func(drones.AUTOTEST_INSTALL_DIR)
64
mbligh36768f02008-02-22 18:28:33 +000065
showardec6a3b92009-09-25 20:29:13 +000066def _get_pidfile_timeout_secs():
67 """@returns How long to wait for autoserv to write pidfile."""
68 pidfile_timeout_mins = global_config.global_config.get_config_value(
69 scheduler_config.CONFIG_SECTION, 'pidfile_timeout_mins', type=int)
70 return pidfile_timeout_mins * 60
71
72
mbligh83c1e9e2009-05-01 23:10:41 +000073def _site_init_monitor_db_dummy():
74 return {}
75
76
jamesren76fcf192010-04-21 20:39:50 +000077def _verify_default_drone_set_exists():
78 if (models.DroneSet.drone_sets_enabled() and
79 not models.DroneSet.default_drone_set_name()):
Dale Curtisaa513362011-03-01 17:27:44 -080080 raise host_scheduler.SchedulerError(
81 'Drone sets are enabled, but no default is set')
jamesren76fcf192010-04-21 20:39:50 +000082
83
84def _sanity_check():
85 """Make sure the configs are consistent before starting the scheduler"""
86 _verify_default_drone_set_exists()
87
88
mbligh36768f02008-02-22 18:28:33 +000089def main():
showard27f33872009-04-07 18:20:53 +000090 try:
showard549afad2009-08-20 23:33:36 +000091 try:
92 main_without_exception_handling()
93 except SystemExit:
94 raise
95 except:
96 logging.exception('Exception escaping in monitor_db')
97 raise
98 finally:
99 utils.delete_pid_file_if_exists(PID_FILE_PREFIX)
showard27f33872009-04-07 18:20:53 +0000100
101
102def main_without_exception_handling():
showard136e6dc2009-06-10 19:38:49 +0000103 setup_logging()
mbligh36768f02008-02-22 18:28:33 +0000104
showard136e6dc2009-06-10 19:38:49 +0000105 usage = 'usage: %prog [options] results_dir'
jadmanski0afbb632008-06-06 21:10:57 +0000106 parser = optparse.OptionParser(usage)
107 parser.add_option('--recover-hosts', help='Try to recover dead hosts',
108 action='store_true')
jadmanski0afbb632008-06-06 21:10:57 +0000109 parser.add_option('--test', help='Indicate that scheduler is under ' +
110 'test and should use dummy autoserv and no parsing',
111 action='store_true')
112 (options, args) = parser.parse_args()
113 if len(args) != 1:
114 parser.print_usage()
115 return
mbligh36768f02008-02-22 18:28:33 +0000116
showard5613c662009-06-08 23:30:33 +0000117 scheduler_enabled = global_config.global_config.get_config_value(
118 scheduler_config.CONFIG_SECTION, 'enable_scheduler', type=bool)
119
120 if not scheduler_enabled:
121 msg = ("Scheduler not enabled, set enable_scheduler to true in the "
122 "global_config's SCHEDULER section to enabled it. Exiting.")
mbligh6fbdb802009-08-03 16:42:55 +0000123 logging.error(msg)
showard5613c662009-06-08 23:30:33 +0000124 sys.exit(1)
125
jadmanski0afbb632008-06-06 21:10:57 +0000126 global RESULTS_DIR
127 RESULTS_DIR = args[0]
mbligh36768f02008-02-22 18:28:33 +0000128
mbligh83c1e9e2009-05-01 23:10:41 +0000129 site_init = utils.import_site_function(__file__,
130 "autotest_lib.scheduler.site_monitor_db", "site_init_monitor_db",
131 _site_init_monitor_db_dummy)
132 site_init()
133
showardcca334f2009-03-12 20:38:34 +0000134 # Change the cwd while running to avoid issues incase we were launched from
135 # somewhere odd (such as a random NFS home directory of the person running
136 # sudo to launch us as the appropriate user).
137 os.chdir(RESULTS_DIR)
138
jamesrenc7d387e2010-08-10 21:48:30 +0000139 # This is helpful for debugging why stuff a scheduler launches is
140 # misbehaving.
141 logging.info('os.environ: %s', os.environ)
showardc85c21b2008-11-24 22:17:37 +0000142
jadmanski0afbb632008-06-06 21:10:57 +0000143 if options.test:
144 global _autoserv_path
145 _autoserv_path = 'autoserv_dummy'
146 global _testing_mode
147 _testing_mode = True
mbligh36768f02008-02-22 18:28:33 +0000148
jamesrenc44ae992010-02-19 00:12:54 +0000149 server = status_server.StatusServer()
showardd1ee1dd2009-01-07 21:33:08 +0000150 server.start()
151
jadmanski0afbb632008-06-06 21:10:57 +0000152 try:
jamesrenc44ae992010-02-19 00:12:54 +0000153 initialize()
showardc5afc462009-01-13 00:09:39 +0000154 dispatcher = Dispatcher()
showard915958d2009-04-22 21:00:58 +0000155 dispatcher.initialize(recover_hosts=options.recover_hosts)
showardc5afc462009-01-13 00:09:39 +0000156
Eric Lia82dc352011-02-23 13:15:52 -0800157 while not _shutdown and not server._shutdown_scheduler:
jadmanski0afbb632008-06-06 21:10:57 +0000158 dispatcher.tick()
showardd1ee1dd2009-01-07 21:33:08 +0000159 time.sleep(scheduler_config.config.tick_pause_sec)
jadmanski0afbb632008-06-06 21:10:57 +0000160 except:
showard170873e2009-01-07 00:22:26 +0000161 email_manager.manager.log_stacktrace(
162 "Uncaught exception; terminating monitor_db")
jadmanski0afbb632008-06-06 21:10:57 +0000163
showard170873e2009-01-07 00:22:26 +0000164 email_manager.manager.send_queued_emails()
showard55b4b542009-01-08 23:30:30 +0000165 server.shutdown()
showard170873e2009-01-07 00:22:26 +0000166 _drone_manager.shutdown()
jadmanski0afbb632008-06-06 21:10:57 +0000167 _db.disconnect()
mbligh36768f02008-02-22 18:28:33 +0000168
169
showard136e6dc2009-06-10 19:38:49 +0000170def setup_logging():
171 log_dir = os.environ.get('AUTOTEST_SCHEDULER_LOG_DIR', None)
172 log_name = os.environ.get('AUTOTEST_SCHEDULER_LOG_NAME', None)
173 logging_manager.configure_logging(
174 scheduler_logging_config.SchedulerLoggingConfig(), log_dir=log_dir,
175 logfile_name=log_name)
176
177
mbligh36768f02008-02-22 18:28:33 +0000178def handle_sigint(signum, frame):
jadmanski0afbb632008-06-06 21:10:57 +0000179 global _shutdown
180 _shutdown = True
showardb18134f2009-03-20 20:52:18 +0000181 logging.info("Shutdown request received.")
mbligh36768f02008-02-22 18:28:33 +0000182
183
jamesrenc44ae992010-02-19 00:12:54 +0000184def initialize():
showardb18134f2009-03-20 20:52:18 +0000185 logging.info("%s> dispatcher starting", time.strftime("%X %x"))
186 logging.info("My PID is %d", os.getpid())
mbligh36768f02008-02-22 18:28:33 +0000187
showard8de37132009-08-31 18:33:08 +0000188 if utils.program_is_alive(PID_FILE_PREFIX):
showard549afad2009-08-20 23:33:36 +0000189 logging.critical("monitor_db already running, aborting!")
190 sys.exit(1)
191 utils.write_pid(PID_FILE_PREFIX)
mblighfb676032009-04-01 18:25:38 +0000192
showardb1e51872008-10-07 11:08:18 +0000193 if _testing_mode:
194 global_config.global_config.override_config_value(
showard170873e2009-01-07 00:22:26 +0000195 DB_CONFIG_SECTION, 'database', 'stresstest_autotest_web')
showardb1e51872008-10-07 11:08:18 +0000196
jadmanski0afbb632008-06-06 21:10:57 +0000197 os.environ['PATH'] = AUTOTEST_SERVER_DIR + ':' + os.environ['PATH']
198 global _db
showard170873e2009-01-07 00:22:26 +0000199 _db = database_connection.DatabaseConnection(DB_CONFIG_SECTION)
showardb21b8c82009-12-07 19:39:39 +0000200 _db.connect(db_type='django')
mbligh36768f02008-02-22 18:28:33 +0000201
showardfa8629c2008-11-04 16:51:23 +0000202 # ensure Django connection is in autocommit
203 setup_django_environment.enable_autocommit()
showard844960a2009-05-29 18:41:18 +0000204 # bypass the readonly connection
205 readonly_connection.ReadOnlyConnection.set_globally_disabled(True)
showardfa8629c2008-11-04 16:51:23 +0000206
showardb18134f2009-03-20 20:52:18 +0000207 logging.info("Setting signal handler")
jadmanski0afbb632008-06-06 21:10:57 +0000208 signal.signal(signal.SIGINT, handle_sigint)
209
jamesrenc44ae992010-02-19 00:12:54 +0000210 initialize_globals()
211 scheduler_models.initialize()
212
showardd1ee1dd2009-01-07 21:33:08 +0000213 drones = global_config.global_config.get_config_value(
214 scheduler_config.CONFIG_SECTION, 'drones', default='localhost')
215 drone_list = [hostname.strip() for hostname in drones.split(',')]
showard170873e2009-01-07 00:22:26 +0000216 results_host = global_config.global_config.get_config_value(
showardd1ee1dd2009-01-07 21:33:08 +0000217 scheduler_config.CONFIG_SECTION, 'results_host', default='localhost')
showard170873e2009-01-07 00:22:26 +0000218 _drone_manager.initialize(RESULTS_DIR, drone_list, results_host)
219
showardb18134f2009-03-20 20:52:18 +0000220 logging.info("Connected! Running...")
mbligh36768f02008-02-22 18:28:33 +0000221
222
jamesrenc44ae992010-02-19 00:12:54 +0000223def initialize_globals():
224 global _drone_manager
225 _drone_manager = drone_manager.instance()
226
227
showarded2afea2009-07-07 20:54:07 +0000228def _autoserv_command_line(machines, extra_args, job=None, queue_entry=None,
229 verbose=True):
showardf1ae3542009-05-11 19:26:02 +0000230 """
231 @returns The autoserv command line as a list of executable + parameters.
232
233 @param machines - string - A machine or comma separated list of machines
234 for the (-m) flag.
showardf1ae3542009-05-11 19:26:02 +0000235 @param extra_args - list - Additional arguments to pass to autoserv.
236 @param job - Job object - If supplied, -u owner and -l name parameters
237 will be added.
238 @param queue_entry - A HostQueueEntry object - If supplied and no Job
239 object was supplied, this will be used to lookup the Job object.
240 """
showarda9545c02009-12-18 22:44:26 +0000241 autoserv_argv = [_autoserv_path, '-p',
showarded2afea2009-07-07 20:54:07 +0000242 '-r', drone_manager.WORKING_DIRECTORY]
showarda9545c02009-12-18 22:44:26 +0000243 if machines:
244 autoserv_argv += ['-m', machines]
showard87ba02a2009-04-20 19:37:32 +0000245 if job or queue_entry:
246 if not job:
247 job = queue_entry.job
248 autoserv_argv += ['-u', job.owner, '-l', job.name]
showarde9c69362009-06-30 01:58:03 +0000249 if verbose:
250 autoserv_argv.append('--verbose')
showard87ba02a2009-04-20 19:37:32 +0000251 return autoserv_argv + extra_args
252
253
showard170873e2009-01-07 00:22:26 +0000254class Dispatcher(object):
jadmanski0afbb632008-06-06 21:10:57 +0000255 def __init__(self):
256 self._agents = []
showard3bb499f2008-07-03 19:42:20 +0000257 self._last_clean_time = time.time()
Dale Curtisaa513362011-03-01 17:27:44 -0800258 self._host_scheduler = host_scheduler.HostScheduler(_db)
mblighf3294cc2009-04-08 21:17:38 +0000259 user_cleanup_time = scheduler_config.config.clean_interval
260 self._periodic_cleanup = monitor_db_cleanup.UserCleanup(
261 _db, user_cleanup_time)
262 self._24hr_upkeep = monitor_db_cleanup.TwentyFourHourUpkeep(_db)
showard170873e2009-01-07 00:22:26 +0000263 self._host_agents = {}
264 self._queue_entry_agents = {}
showardf13a9e22009-12-18 22:54:09 +0000265 self._tick_count = 0
266 self._last_garbage_stats_time = time.time()
267 self._seconds_between_garbage_stats = 60 * (
268 global_config.global_config.get_config_value(
269 scheduler_config.CONFIG_SECTION,
Dale Curtis456d3c12011-07-19 11:42:51 -0700270 'gc_stats_interval_mins', type=int, default=6*60))
mbligh36768f02008-02-22 18:28:33 +0000271
mbligh36768f02008-02-22 18:28:33 +0000272
showard915958d2009-04-22 21:00:58 +0000273 def initialize(self, recover_hosts=True):
274 self._periodic_cleanup.initialize()
275 self._24hr_upkeep.initialize()
276
jadmanski0afbb632008-06-06 21:10:57 +0000277 # always recover processes
278 self._recover_processes()
mblighbb421852008-03-11 22:36:16 +0000279
jadmanski0afbb632008-06-06 21:10:57 +0000280 if recover_hosts:
281 self._recover_hosts()
mbligh36768f02008-02-22 18:28:33 +0000282
jamesrenc44ae992010-02-19 00:12:54 +0000283 self._host_scheduler.recovery_on_startup()
284
mbligh36768f02008-02-22 18:28:33 +0000285
jadmanski0afbb632008-06-06 21:10:57 +0000286 def tick(self):
showardf13a9e22009-12-18 22:54:09 +0000287 self._garbage_collection()
showard170873e2009-01-07 00:22:26 +0000288 _drone_manager.refresh()
mblighf3294cc2009-04-08 21:17:38 +0000289 self._run_cleanup()
jadmanski0afbb632008-06-06 21:10:57 +0000290 self._find_aborting()
showard29f7cd22009-04-29 21:16:24 +0000291 self._process_recurring_runs()
showard8cc058f2009-09-08 16:26:33 +0000292 self._schedule_delay_tasks()
showard8cc058f2009-09-08 16:26:33 +0000293 self._schedule_running_host_queue_entries()
294 self._schedule_special_tasks()
showard65db3932009-10-28 19:54:35 +0000295 self._schedule_new_jobs()
jadmanski0afbb632008-06-06 21:10:57 +0000296 self._handle_agents()
jamesrene21bf412010-02-26 02:30:07 +0000297 self._host_scheduler.tick()
showard170873e2009-01-07 00:22:26 +0000298 _drone_manager.execute_actions()
299 email_manager.manager.send_queued_emails()
showard402934a2009-12-21 22:20:47 +0000300 django.db.reset_queries()
showardf13a9e22009-12-18 22:54:09 +0000301 self._tick_count += 1
mbligh36768f02008-02-22 18:28:33 +0000302
showard97aed502008-11-04 02:01:24 +0000303
mblighf3294cc2009-04-08 21:17:38 +0000304 def _run_cleanup(self):
305 self._periodic_cleanup.run_cleanup_maybe()
306 self._24hr_upkeep.run_cleanup_maybe()
showarda3ab0d52008-11-03 19:03:47 +0000307
mbligh36768f02008-02-22 18:28:33 +0000308
showardf13a9e22009-12-18 22:54:09 +0000309 def _garbage_collection(self):
310 threshold_time = time.time() - self._seconds_between_garbage_stats
311 if threshold_time < self._last_garbage_stats_time:
312 # Don't generate these reports very often.
313 return
314
315 self._last_garbage_stats_time = time.time()
316 # Force a full level 0 collection (because we can, it doesn't hurt
317 # at this interval).
318 gc.collect()
319 logging.info('Logging garbage collector stats on tick %d.',
320 self._tick_count)
321 gc_stats._log_garbage_collector_stats()
322
323
showard170873e2009-01-07 00:22:26 +0000324 def _register_agent_for_ids(self, agent_dict, object_ids, agent):
325 for object_id in object_ids:
326 agent_dict.setdefault(object_id, set()).add(agent)
327
328
329 def _unregister_agent_for_ids(self, agent_dict, object_ids, agent):
330 for object_id in object_ids:
331 assert object_id in agent_dict
332 agent_dict[object_id].remove(agent)
333
334
showardd1195652009-12-08 22:21:02 +0000335 def add_agent_task(self, agent_task):
336 agent = Agent(agent_task)
jadmanski0afbb632008-06-06 21:10:57 +0000337 self._agents.append(agent)
338 agent.dispatcher = self
showard170873e2009-01-07 00:22:26 +0000339 self._register_agent_for_ids(self._host_agents, agent.host_ids, agent)
340 self._register_agent_for_ids(self._queue_entry_agents,
341 agent.queue_entry_ids, agent)
mblighd5c95802008-03-05 00:33:46 +0000342
showard170873e2009-01-07 00:22:26 +0000343
344 def get_agents_for_entry(self, queue_entry):
345 """
346 Find agents corresponding to the specified queue_entry.
347 """
showardd3dc1992009-04-22 21:01:40 +0000348 return list(self._queue_entry_agents.get(queue_entry.id, set()))
showard170873e2009-01-07 00:22:26 +0000349
350
351 def host_has_agent(self, host):
352 """
353 Determine if there is currently an Agent present using this host.
354 """
355 return bool(self._host_agents.get(host.id, None))
mbligh36768f02008-02-22 18:28:33 +0000356
357
jadmanski0afbb632008-06-06 21:10:57 +0000358 def remove_agent(self, agent):
359 self._agents.remove(agent)
showard170873e2009-01-07 00:22:26 +0000360 self._unregister_agent_for_ids(self._host_agents, agent.host_ids,
361 agent)
362 self._unregister_agent_for_ids(self._queue_entry_agents,
363 agent.queue_entry_ids, agent)
showardec113162008-05-08 00:52:49 +0000364
365
showard8cc058f2009-09-08 16:26:33 +0000366 def _host_has_scheduled_special_task(self, host):
367 return bool(models.SpecialTask.objects.filter(host__id=host.id,
368 is_active=False,
369 is_complete=False))
370
371
jadmanski0afbb632008-06-06 21:10:57 +0000372 def _recover_processes(self):
showardd1195652009-12-08 22:21:02 +0000373 agent_tasks = self._create_recovery_agent_tasks()
374 self._register_pidfiles(agent_tasks)
showard170873e2009-01-07 00:22:26 +0000375 _drone_manager.refresh()
showardd1195652009-12-08 22:21:02 +0000376 self._recover_tasks(agent_tasks)
showard8cc058f2009-09-08 16:26:33 +0000377 self._recover_pending_entries()
showardb8900452009-10-12 20:31:01 +0000378 self._check_for_unrecovered_verifying_entries()
showard170873e2009-01-07 00:22:26 +0000379 self._reverify_remaining_hosts()
380 # reinitialize drones after killing orphaned processes, since they can
381 # leave around files when they die
382 _drone_manager.execute_actions()
383 _drone_manager.reinitialize_drones()
mblighbb421852008-03-11 22:36:16 +0000384
showard170873e2009-01-07 00:22:26 +0000385
showardd1195652009-12-08 22:21:02 +0000386 def _create_recovery_agent_tasks(self):
387 return (self._get_queue_entry_agent_tasks()
388 + self._get_special_task_agent_tasks(is_active=True))
389
390
391 def _get_queue_entry_agent_tasks(self):
392 # host queue entry statuses handled directly by AgentTasks (Verifying is
393 # handled through SpecialTasks, so is not listed here)
394 statuses = (models.HostQueueEntry.Status.STARTING,
395 models.HostQueueEntry.Status.RUNNING,
396 models.HostQueueEntry.Status.GATHERING,
mbligh4608b002010-01-05 18:22:35 +0000397 models.HostQueueEntry.Status.PARSING,
398 models.HostQueueEntry.Status.ARCHIVING)
showardd1195652009-12-08 22:21:02 +0000399 status_list = ','.join("'%s'" % status for status in statuses)
jamesrenc44ae992010-02-19 00:12:54 +0000400 queue_entries = scheduler_models.HostQueueEntry.fetch(
showardd1195652009-12-08 22:21:02 +0000401 where='status IN (%s)' % status_list)
402
403 agent_tasks = []
404 used_queue_entries = set()
405 for entry in queue_entries:
406 if self.get_agents_for_entry(entry):
407 # already being handled
408 continue
409 if entry in used_queue_entries:
410 # already picked up by a synchronous job
411 continue
412 agent_task = self._get_agent_task_for_queue_entry(entry)
413 agent_tasks.append(agent_task)
414 used_queue_entries.update(agent_task.queue_entries)
415 return agent_tasks
showard170873e2009-01-07 00:22:26 +0000416
417
showardd1195652009-12-08 22:21:02 +0000418 def _get_special_task_agent_tasks(self, is_active=False):
419 special_tasks = models.SpecialTask.objects.filter(
420 is_active=is_active, is_complete=False)
421 return [self._get_agent_task_for_special_task(task)
422 for task in special_tasks]
423
424
425 def _get_agent_task_for_queue_entry(self, queue_entry):
426 """
427 Construct an AgentTask instance for the given active HostQueueEntry,
428 if one can currently run it.
429 @param queue_entry: a HostQueueEntry
430 @returns an AgentTask to run the queue entry
431 """
432 task_entries = queue_entry.job.get_group_entries(queue_entry)
433 self._check_for_duplicate_host_entries(task_entries)
434
435 if queue_entry.status in (models.HostQueueEntry.Status.STARTING,
436 models.HostQueueEntry.Status.RUNNING):
showarda9545c02009-12-18 22:44:26 +0000437 if queue_entry.is_hostless():
438 return HostlessQueueTask(queue_entry=queue_entry)
showardd1195652009-12-08 22:21:02 +0000439 return QueueTask(queue_entries=task_entries)
440 if queue_entry.status == models.HostQueueEntry.Status.GATHERING:
441 return GatherLogsTask(queue_entries=task_entries)
442 if queue_entry.status == models.HostQueueEntry.Status.PARSING:
443 return FinalReparseTask(queue_entries=task_entries)
mbligh4608b002010-01-05 18:22:35 +0000444 if queue_entry.status == models.HostQueueEntry.Status.ARCHIVING:
445 return ArchiveResultsTask(queue_entries=task_entries)
showardd1195652009-12-08 22:21:02 +0000446
Dale Curtisaa513362011-03-01 17:27:44 -0800447 raise host_scheduler.SchedulerError(
448 '_get_agent_task_for_queue_entry got entry with '
449 'invalid status %s: %s' % (queue_entry.status, queue_entry))
showardd1195652009-12-08 22:21:02 +0000450
451
452 def _check_for_duplicate_host_entries(self, task_entries):
mbligh4608b002010-01-05 18:22:35 +0000453 non_host_statuses = (models.HostQueueEntry.Status.PARSING,
454 models.HostQueueEntry.Status.ARCHIVING)
showardd1195652009-12-08 22:21:02 +0000455 for task_entry in task_entries:
showarda9545c02009-12-18 22:44:26 +0000456 using_host = (task_entry.host is not None
mbligh4608b002010-01-05 18:22:35 +0000457 and task_entry.status not in non_host_statuses)
showarda9545c02009-12-18 22:44:26 +0000458 if using_host:
showardd1195652009-12-08 22:21:02 +0000459 self._assert_host_has_no_agent(task_entry)
460
461
462 def _assert_host_has_no_agent(self, entry):
463 """
464 @param entry: a HostQueueEntry or a SpecialTask
465 """
466 if self.host_has_agent(entry.host):
467 agent = tuple(self._host_agents.get(entry.host.id))[0]
Dale Curtisaa513362011-03-01 17:27:44 -0800468 raise host_scheduler.SchedulerError(
showardd1195652009-12-08 22:21:02 +0000469 'While scheduling %s, host %s already has a host agent %s'
470 % (entry, entry.host, agent.task))
471
472
473 def _get_agent_task_for_special_task(self, special_task):
474 """
475 Construct an AgentTask class to run the given SpecialTask and add it
476 to this dispatcher.
477 @param special_task: a models.SpecialTask instance
478 @returns an AgentTask to run this SpecialTask
479 """
480 self._assert_host_has_no_agent(special_task)
481
482 special_agent_task_classes = (CleanupTask, VerifyTask, RepairTask)
483 for agent_task_class in special_agent_task_classes:
484 if agent_task_class.TASK_TYPE == special_task.task:
485 return agent_task_class(task=special_task)
486
Dale Curtisaa513362011-03-01 17:27:44 -0800487 raise host_scheduler.SchedulerError(
488 'No AgentTask class for task', str(special_task))
showardd1195652009-12-08 22:21:02 +0000489
490
491 def _register_pidfiles(self, agent_tasks):
492 for agent_task in agent_tasks:
493 agent_task.register_necessary_pidfiles()
494
495
496 def _recover_tasks(self, agent_tasks):
497 orphans = _drone_manager.get_orphaned_autoserv_processes()
498
499 for agent_task in agent_tasks:
500 agent_task.recover()
501 if agent_task.monitor and agent_task.monitor.has_process():
502 orphans.discard(agent_task.monitor.get_process())
503 self.add_agent_task(agent_task)
504
505 self._check_for_remaining_orphan_processes(orphans)
showarded2afea2009-07-07 20:54:07 +0000506
507
showard8cc058f2009-09-08 16:26:33 +0000508 def _get_unassigned_entries(self, status):
jamesrenc44ae992010-02-19 00:12:54 +0000509 for entry in scheduler_models.HostQueueEntry.fetch(where="status = '%s'"
510 % status):
showard0db3d432009-10-12 20:29:15 +0000511 if entry.status == status and not self.get_agents_for_entry(entry):
512 # The status can change during iteration, e.g., if job.run()
513 # sets a group of queue entries to Starting
showard8cc058f2009-09-08 16:26:33 +0000514 yield entry
515
516
showard6878e8b2009-07-20 22:37:45 +0000517 def _check_for_remaining_orphan_processes(self, orphans):
518 if not orphans:
519 return
520 subject = 'Unrecovered orphan autoserv processes remain'
521 message = '\n'.join(str(process) for process in orphans)
522 email_manager.manager.enqueue_notify_email(subject, message)
mbligh5fa9e112009-08-03 16:46:06 +0000523
524 die_on_orphans = global_config.global_config.get_config_value(
525 scheduler_config.CONFIG_SECTION, 'die_on_orphans', type=bool)
526
527 if die_on_orphans:
528 raise RuntimeError(subject + '\n' + message)
jadmanski0afbb632008-06-06 21:10:57 +0000529
showard170873e2009-01-07 00:22:26 +0000530
showard8cc058f2009-09-08 16:26:33 +0000531 def _recover_pending_entries(self):
532 for entry in self._get_unassigned_entries(
533 models.HostQueueEntry.Status.PENDING):
showard56824072009-10-12 20:30:21 +0000534 logging.info('Recovering Pending entry %s', entry)
showard8cc058f2009-09-08 16:26:33 +0000535 entry.on_pending()
536
537
showardb8900452009-10-12 20:31:01 +0000538 def _check_for_unrecovered_verifying_entries(self):
jamesrenc44ae992010-02-19 00:12:54 +0000539 queue_entries = scheduler_models.HostQueueEntry.fetch(
showardb8900452009-10-12 20:31:01 +0000540 where='status = "%s"' % models.HostQueueEntry.Status.VERIFYING)
541 unrecovered_hqes = []
542 for queue_entry in queue_entries:
543 special_tasks = models.SpecialTask.objects.filter(
544 task__in=(models.SpecialTask.Task.CLEANUP,
545 models.SpecialTask.Task.VERIFY),
546 queue_entry__id=queue_entry.id,
547 is_complete=False)
548 if special_tasks.count() == 0:
549 unrecovered_hqes.append(queue_entry)
showardd3dc1992009-04-22 21:01:40 +0000550
showardb8900452009-10-12 20:31:01 +0000551 if unrecovered_hqes:
552 message = '\n'.join(str(hqe) for hqe in unrecovered_hqes)
Dale Curtisaa513362011-03-01 17:27:44 -0800553 raise host_scheduler.SchedulerError(
showard37757f32009-10-19 18:34:24 +0000554 '%d unrecovered verifying host queue entries:\n%s' %
showardb8900452009-10-12 20:31:01 +0000555 (len(unrecovered_hqes), message))
showard170873e2009-01-07 00:22:26 +0000556
557
showard65db3932009-10-28 19:54:35 +0000558 def _get_prioritized_special_tasks(self):
559 """
560 Returns all queued SpecialTasks prioritized for repair first, then
561 cleanup, then verify.
562 """
563 queued_tasks = models.SpecialTask.objects.filter(is_active=False,
564 is_complete=False,
565 host__locked=False)
566 # exclude hosts with active queue entries unless the SpecialTask is for
567 # that queue entry
showard7e67b432010-01-20 01:13:04 +0000568 queued_tasks = models.SpecialTask.objects.add_join(
showardeab66ce2009-12-23 00:03:56 +0000569 queued_tasks, 'afe_host_queue_entries', 'host_id',
570 join_condition='afe_host_queue_entries.active',
showard7e67b432010-01-20 01:13:04 +0000571 join_from_key='host_id', force_left_join=True)
showard65db3932009-10-28 19:54:35 +0000572 queued_tasks = queued_tasks.extra(
showardeab66ce2009-12-23 00:03:56 +0000573 where=['(afe_host_queue_entries.id IS NULL OR '
574 'afe_host_queue_entries.id = '
575 'afe_special_tasks.queue_entry_id)'])
showard6d7b2ff2009-06-10 00:16:47 +0000576
showard65db3932009-10-28 19:54:35 +0000577 # reorder tasks by priority
578 task_priority_order = [models.SpecialTask.Task.REPAIR,
579 models.SpecialTask.Task.CLEANUP,
580 models.SpecialTask.Task.VERIFY]
581 def task_priority_key(task):
582 return task_priority_order.index(task.task)
583 return sorted(queued_tasks, key=task_priority_key)
584
585
showard65db3932009-10-28 19:54:35 +0000586 def _schedule_special_tasks(self):
587 """
588 Execute queued SpecialTasks that are ready to run on idle hosts.
589 """
590 for task in self._get_prioritized_special_tasks():
showard8cc058f2009-09-08 16:26:33 +0000591 if self.host_has_agent(task.host):
showard2fe3f1d2009-07-06 20:19:11 +0000592 continue
showardd1195652009-12-08 22:21:02 +0000593 self.add_agent_task(self._get_agent_task_for_special_task(task))
showard1ff7b2e2009-05-15 23:17:18 +0000594
595
showard170873e2009-01-07 00:22:26 +0000596 def _reverify_remaining_hosts(self):
showarded2afea2009-07-07 20:54:07 +0000597 # recover active hosts that have not yet been recovered, although this
showard170873e2009-01-07 00:22:26 +0000598 # should never happen
showarded2afea2009-07-07 20:54:07 +0000599 message = ('Recovering active host %s - this probably indicates a '
showard170873e2009-01-07 00:22:26 +0000600 'scheduler bug')
showarded2afea2009-07-07 20:54:07 +0000601 self._reverify_hosts_where(
showard8cc058f2009-09-08 16:26:33 +0000602 "status IN ('Repairing', 'Verifying', 'Cleaning')",
showarded2afea2009-07-07 20:54:07 +0000603 print_message=message)
mblighbb421852008-03-11 22:36:16 +0000604
605
jadmanski0afbb632008-06-06 21:10:57 +0000606 def _reverify_hosts_where(self, where,
showard2fe3f1d2009-07-06 20:19:11 +0000607 print_message='Reverifying host %s'):
Dale Curtis456d3c12011-07-19 11:42:51 -0700608 full_where='locked = 0 AND invalid = 0 AND ' + where
jamesrenc44ae992010-02-19 00:12:54 +0000609 for host in scheduler_models.Host.fetch(where=full_where):
showard170873e2009-01-07 00:22:26 +0000610 if self.host_has_agent(host):
611 # host has already been recovered in some way
jadmanski0afbb632008-06-06 21:10:57 +0000612 continue
showard8cc058f2009-09-08 16:26:33 +0000613 if self._host_has_scheduled_special_task(host):
614 # host will have a special task scheduled on the next cycle
615 continue
showard170873e2009-01-07 00:22:26 +0000616 if print_message:
showardb18134f2009-03-20 20:52:18 +0000617 logging.info(print_message, host.hostname)
showard8cc058f2009-09-08 16:26:33 +0000618 models.SpecialTask.objects.create(
619 task=models.SpecialTask.Task.CLEANUP,
showard9bb960b2009-11-19 01:02:11 +0000620 host=models.Host.objects.get(id=host.id))
mbligh36768f02008-02-22 18:28:33 +0000621
622
jadmanski0afbb632008-06-06 21:10:57 +0000623 def _recover_hosts(self):
624 # recover "Repair Failed" hosts
625 message = 'Reverifying dead host %s'
626 self._reverify_hosts_where("status = 'Repair Failed'",
627 print_message=message)
mbligh62ba2ed2008-04-30 17:09:25 +0000628
629
showard04c82c52008-05-29 19:38:12 +0000630
showardb95b1bd2008-08-15 18:11:04 +0000631 def _get_pending_queue_entries(self):
showard63a34772008-08-18 19:32:50 +0000632 # prioritize by job priority, then non-metahost over metahost, then FIFO
jamesrenc44ae992010-02-19 00:12:54 +0000633 return list(scheduler_models.HostQueueEntry.fetch(
showardeab66ce2009-12-23 00:03:56 +0000634 joins='INNER JOIN afe_jobs ON (job_id=afe_jobs.id)',
showardac9ce222008-12-03 18:19:44 +0000635 where='NOT complete AND NOT active AND status="Queued"',
showardeab66ce2009-12-23 00:03:56 +0000636 order_by='afe_jobs.priority DESC, meta_host, job_id'))
mbligh36768f02008-02-22 18:28:33 +0000637
638
showard89f84db2009-03-12 20:39:13 +0000639 def _refresh_pending_queue_entries(self):
640 """
641 Lookup the pending HostQueueEntries and call our HostScheduler
642 refresh() method given that list. Return the list.
643
644 @returns A list of pending HostQueueEntries sorted in priority order.
645 """
showard63a34772008-08-18 19:32:50 +0000646 queue_entries = self._get_pending_queue_entries()
647 if not queue_entries:
showard89f84db2009-03-12 20:39:13 +0000648 return []
showardb95b1bd2008-08-15 18:11:04 +0000649
showard63a34772008-08-18 19:32:50 +0000650 self._host_scheduler.refresh(queue_entries)
showardb95b1bd2008-08-15 18:11:04 +0000651
showard89f84db2009-03-12 20:39:13 +0000652 return queue_entries
653
654
655 def _schedule_atomic_group(self, queue_entry):
656 """
657 Schedule the given queue_entry on an atomic group of hosts.
658
659 Returns immediately if there are insufficient available hosts.
660
661 Creates new HostQueueEntries based off of queue_entry for the
662 scheduled hosts and starts them all running.
663 """
664 # This is a virtual host queue entry representing an entire
665 # atomic group, find a group and schedule their hosts.
666 group_hosts = self._host_scheduler.find_eligible_atomic_group(
667 queue_entry)
668 if not group_hosts:
669 return
showardcbe6f942009-06-17 19:33:49 +0000670
671 logging.info('Expanding atomic group entry %s with hosts %s',
672 queue_entry,
673 ', '.join(host.hostname for host in group_hosts))
jamesren883492a2010-02-12 00:45:18 +0000674
showard89f84db2009-03-12 20:39:13 +0000675 for assigned_host in group_hosts[1:]:
676 # Create a new HQE for every additional assigned_host.
jamesrenc44ae992010-02-19 00:12:54 +0000677 new_hqe = scheduler_models.HostQueueEntry.clone(queue_entry)
showard89f84db2009-03-12 20:39:13 +0000678 new_hqe.save()
jamesren883492a2010-02-12 00:45:18 +0000679 new_hqe.set_host(assigned_host)
680 self._run_queue_entry(new_hqe)
681
682 # The first assigned host uses the original HostQueueEntry
683 queue_entry.set_host(group_hosts[0])
684 self._run_queue_entry(queue_entry)
showard89f84db2009-03-12 20:39:13 +0000685
686
showarda9545c02009-12-18 22:44:26 +0000687 def _schedule_hostless_job(self, queue_entry):
688 self.add_agent_task(HostlessQueueTask(queue_entry))
jamesren47bd7372010-03-13 00:58:17 +0000689 queue_entry.set_status(models.HostQueueEntry.Status.STARTING)
showarda9545c02009-12-18 22:44:26 +0000690
691
showard89f84db2009-03-12 20:39:13 +0000692 def _schedule_new_jobs(self):
693 queue_entries = self._refresh_pending_queue_entries()
694 if not queue_entries:
695 return
696
showard63a34772008-08-18 19:32:50 +0000697 for queue_entry in queue_entries:
showarde55955f2009-10-07 20:48:58 +0000698 is_unassigned_atomic_group = (
699 queue_entry.atomic_group_id is not None
700 and queue_entry.host_id is None)
jamesren883492a2010-02-12 00:45:18 +0000701
702 if queue_entry.is_hostless():
showarda9545c02009-12-18 22:44:26 +0000703 self._schedule_hostless_job(queue_entry)
jamesren883492a2010-02-12 00:45:18 +0000704 elif is_unassigned_atomic_group:
705 self._schedule_atomic_group(queue_entry)
showarde55955f2009-10-07 20:48:58 +0000706 else:
jamesren883492a2010-02-12 00:45:18 +0000707 assigned_host = self._host_scheduler.schedule_entry(queue_entry)
showard65db3932009-10-28 19:54:35 +0000708 if assigned_host and not self.host_has_agent(assigned_host):
jamesren883492a2010-02-12 00:45:18 +0000709 assert assigned_host.id == queue_entry.host_id
710 self._run_queue_entry(queue_entry)
showardb95b1bd2008-08-15 18:11:04 +0000711
712
showard8cc058f2009-09-08 16:26:33 +0000713 def _schedule_running_host_queue_entries(self):
showardd1195652009-12-08 22:21:02 +0000714 for agent_task in self._get_queue_entry_agent_tasks():
715 self.add_agent_task(agent_task)
showard8cc058f2009-09-08 16:26:33 +0000716
717
718 def _schedule_delay_tasks(self):
jamesrenc44ae992010-02-19 00:12:54 +0000719 for entry in scheduler_models.HostQueueEntry.fetch(
720 where='status = "%s"' % models.HostQueueEntry.Status.WAITING):
showard8cc058f2009-09-08 16:26:33 +0000721 task = entry.job.schedule_delayed_callback_task(entry)
722 if task:
showardd1195652009-12-08 22:21:02 +0000723 self.add_agent_task(task)
showard8cc058f2009-09-08 16:26:33 +0000724
725
jamesren883492a2010-02-12 00:45:18 +0000726 def _run_queue_entry(self, queue_entry):
727 queue_entry.schedule_pre_job_tasks()
mblighd5c95802008-03-05 00:33:46 +0000728
729
jadmanski0afbb632008-06-06 21:10:57 +0000730 def _find_aborting(self):
jamesrene7c65cb2010-06-08 20:38:10 +0000731 jobs_to_stop = set()
jamesrenc44ae992010-02-19 00:12:54 +0000732 for entry in scheduler_models.HostQueueEntry.fetch(
733 where='aborted and not complete'):
showardf4a2e502009-07-28 20:06:39 +0000734 logging.info('Aborting %s', entry)
showardd3dc1992009-04-22 21:01:40 +0000735 for agent in self.get_agents_for_entry(entry):
736 agent.abort()
737 entry.abort(self)
jamesrene7c65cb2010-06-08 20:38:10 +0000738 jobs_to_stop.add(entry.job)
739 for job in jobs_to_stop:
740 job.stop_if_necessary()
jadmanski0afbb632008-06-06 21:10:57 +0000741
742
showard324bf812009-01-20 23:23:38 +0000743 def _can_start_agent(self, agent, num_started_this_cycle,
744 have_reached_limit):
showard4c5374f2008-09-04 17:02:56 +0000745 # always allow zero-process agents to run
showardd1195652009-12-08 22:21:02 +0000746 if agent.task.num_processes == 0:
showard4c5374f2008-09-04 17:02:56 +0000747 return True
748 # don't allow any nonzero-process agents to run after we've reached a
749 # limit (this avoids starvation of many-process agents)
750 if have_reached_limit:
751 return False
752 # total process throttling
showard9bb960b2009-11-19 01:02:11 +0000753 max_runnable_processes = _drone_manager.max_runnable_processes(
jamesren76fcf192010-04-21 20:39:50 +0000754 agent.task.owner_username,
755 agent.task.get_drone_hostnames_allowed())
showardd1195652009-12-08 22:21:02 +0000756 if agent.task.num_processes > max_runnable_processes:
showard4c5374f2008-09-04 17:02:56 +0000757 return False
758 # if a single agent exceeds the per-cycle throttling, still allow it to
759 # run when it's the first agent in the cycle
760 if num_started_this_cycle == 0:
761 return True
762 # per-cycle throttling
showardd1195652009-12-08 22:21:02 +0000763 if (num_started_this_cycle + agent.task.num_processes >
764 scheduler_config.config.max_processes_started_per_cycle):
showard4c5374f2008-09-04 17:02:56 +0000765 return False
766 return True
767
768
jadmanski0afbb632008-06-06 21:10:57 +0000769 def _handle_agents(self):
jadmanski0afbb632008-06-06 21:10:57 +0000770 num_started_this_cycle = 0
showard4c5374f2008-09-04 17:02:56 +0000771 have_reached_limit = False
772 # iterate over copy, so we can remove agents during iteration
773 for agent in list(self._agents):
showard8cc058f2009-09-08 16:26:33 +0000774 if not agent.started:
showard324bf812009-01-20 23:23:38 +0000775 if not self._can_start_agent(agent, num_started_this_cycle,
showard4c5374f2008-09-04 17:02:56 +0000776 have_reached_limit):
777 have_reached_limit = True
778 continue
showardd1195652009-12-08 22:21:02 +0000779 num_started_this_cycle += agent.task.num_processes
showard4c5374f2008-09-04 17:02:56 +0000780 agent.tick()
showard8cc058f2009-09-08 16:26:33 +0000781 if agent.is_done():
782 logging.info("agent finished")
783 self.remove_agent(agent)
showarda9435c02009-05-13 21:28:17 +0000784 logging.info('%d running processes',
showardb18134f2009-03-20 20:52:18 +0000785 _drone_manager.total_running_processes())
mbligh36768f02008-02-22 18:28:33 +0000786
787
showard29f7cd22009-04-29 21:16:24 +0000788 def _process_recurring_runs(self):
789 recurring_runs = models.RecurringRun.objects.filter(
790 start_date__lte=datetime.datetime.now())
791 for rrun in recurring_runs:
792 # Create job from template
793 job = rrun.job
794 info = rpc_utils.get_job_info(job)
showarda9435c02009-05-13 21:28:17 +0000795 options = job.get_object_dict()
showard29f7cd22009-04-29 21:16:24 +0000796
797 host_objects = info['hosts']
798 one_time_hosts = info['one_time_hosts']
799 metahost_objects = info['meta_hosts']
800 dependencies = info['dependencies']
801 atomic_group = info['atomic_group']
802
803 for host in one_time_hosts or []:
804 this_host = models.Host.create_one_time_host(host.hostname)
805 host_objects.append(this_host)
806
807 try:
808 rpc_utils.create_new_job(owner=rrun.owner.login,
showarda9435c02009-05-13 21:28:17 +0000809 options=options,
showard29f7cd22009-04-29 21:16:24 +0000810 host_objects=host_objects,
811 metahost_objects=metahost_objects,
showard29f7cd22009-04-29 21:16:24 +0000812 atomic_group=atomic_group)
813
814 except Exception, ex:
815 logging.exception(ex)
816 #TODO send email
817
818 if rrun.loop_count == 1:
819 rrun.delete()
820 else:
821 if rrun.loop_count != 0: # if not infinite loop
822 # calculate new start_date
823 difference = datetime.timedelta(seconds=rrun.loop_period)
824 rrun.start_date = rrun.start_date + difference
825 rrun.loop_count -= 1
826 rrun.save()
827
828
showard170873e2009-01-07 00:22:26 +0000829class PidfileRunMonitor(object):
830 """
831 Client must call either run() to start a new process or
832 attach_to_existing_process().
833 """
mbligh36768f02008-02-22 18:28:33 +0000834
showard170873e2009-01-07 00:22:26 +0000835 class _PidfileException(Exception):
836 """
837 Raised when there's some unexpected behavior with the pid file, but only
838 used internally (never allowed to escape this class).
839 """
mbligh36768f02008-02-22 18:28:33 +0000840
841
showard170873e2009-01-07 00:22:26 +0000842 def __init__(self):
showard35162b02009-03-03 02:17:30 +0000843 self.lost_process = False
showard170873e2009-01-07 00:22:26 +0000844 self._start_time = None
845 self.pidfile_id = None
846 self._state = drone_manager.PidfileContents()
showard2bab8f42008-11-12 18:15:22 +0000847
848
showard170873e2009-01-07 00:22:26 +0000849 def _add_nice_command(self, command, nice_level):
850 if not nice_level:
851 return command
852 return ['nice', '-n', str(nice_level)] + command
853
854
855 def _set_start_time(self):
856 self._start_time = time.time()
857
858
showard418785b2009-11-23 20:19:59 +0000859 def run(self, command, working_directory, num_processes, nice_level=None,
860 log_file=None, pidfile_name=None, paired_with_pidfile=None,
jamesren76fcf192010-04-21 20:39:50 +0000861 username=None, drone_hostnames_allowed=None):
showard170873e2009-01-07 00:22:26 +0000862 assert command is not None
863 if nice_level is not None:
864 command = ['nice', '-n', str(nice_level)] + command
865 self._set_start_time()
866 self.pidfile_id = _drone_manager.execute_command(
showardd3dc1992009-04-22 21:01:40 +0000867 command, working_directory, pidfile_name=pidfile_name,
showard418785b2009-11-23 20:19:59 +0000868 num_processes=num_processes, log_file=log_file,
jamesren76fcf192010-04-21 20:39:50 +0000869 paired_with_pidfile=paired_with_pidfile, username=username,
870 drone_hostnames_allowed=drone_hostnames_allowed)
showard170873e2009-01-07 00:22:26 +0000871
872
showarded2afea2009-07-07 20:54:07 +0000873 def attach_to_existing_process(self, execution_path,
jamesrenc44ae992010-02-19 00:12:54 +0000874 pidfile_name=drone_manager.AUTOSERV_PID_FILE,
showardd1195652009-12-08 22:21:02 +0000875 num_processes=None):
showard170873e2009-01-07 00:22:26 +0000876 self._set_start_time()
showardd3dc1992009-04-22 21:01:40 +0000877 self.pidfile_id = _drone_manager.get_pidfile_id_from(
showarded2afea2009-07-07 20:54:07 +0000878 execution_path, pidfile_name=pidfile_name)
showardd1195652009-12-08 22:21:02 +0000879 if num_processes is not None:
880 _drone_manager.declare_process_count(self.pidfile_id, num_processes)
mblighbb421852008-03-11 22:36:16 +0000881
882
jadmanski0afbb632008-06-06 21:10:57 +0000883 def kill(self):
showard170873e2009-01-07 00:22:26 +0000884 if self.has_process():
885 _drone_manager.kill_process(self.get_process())
mblighbb421852008-03-11 22:36:16 +0000886
mbligh36768f02008-02-22 18:28:33 +0000887
showard170873e2009-01-07 00:22:26 +0000888 def has_process(self):
showard21baa452008-10-21 00:08:39 +0000889 self._get_pidfile_info()
showard170873e2009-01-07 00:22:26 +0000890 return self._state.process is not None
showard21baa452008-10-21 00:08:39 +0000891
892
showard170873e2009-01-07 00:22:26 +0000893 def get_process(self):
showard21baa452008-10-21 00:08:39 +0000894 self._get_pidfile_info()
showard35162b02009-03-03 02:17:30 +0000895 assert self._state.process is not None
showard170873e2009-01-07 00:22:26 +0000896 return self._state.process
mblighbb421852008-03-11 22:36:16 +0000897
898
showard170873e2009-01-07 00:22:26 +0000899 def _read_pidfile(self, use_second_read=False):
900 assert self.pidfile_id is not None, (
901 'You must call run() or attach_to_existing_process()')
902 contents = _drone_manager.get_pidfile_contents(
903 self.pidfile_id, use_second_read=use_second_read)
904 if contents.is_invalid():
905 self._state = drone_manager.PidfileContents()
906 raise self._PidfileException(contents)
907 self._state = contents
mbligh90a549d2008-03-25 23:52:34 +0000908
909
showard21baa452008-10-21 00:08:39 +0000910 def _handle_pidfile_error(self, error, message=''):
showard170873e2009-01-07 00:22:26 +0000911 message = error + '\nProcess: %s\nPidfile: %s\n%s' % (
912 self._state.process, self.pidfile_id, message)
showard170873e2009-01-07 00:22:26 +0000913 email_manager.manager.enqueue_notify_email(error, message)
showard35162b02009-03-03 02:17:30 +0000914 self.on_lost_process(self._state.process)
showard21baa452008-10-21 00:08:39 +0000915
916
917 def _get_pidfile_info_helper(self):
showard35162b02009-03-03 02:17:30 +0000918 if self.lost_process:
showard21baa452008-10-21 00:08:39 +0000919 return
mblighbb421852008-03-11 22:36:16 +0000920
showard21baa452008-10-21 00:08:39 +0000921 self._read_pidfile()
mblighbb421852008-03-11 22:36:16 +0000922
showard170873e2009-01-07 00:22:26 +0000923 if self._state.process is None:
924 self._handle_no_process()
showard21baa452008-10-21 00:08:39 +0000925 return
mbligh90a549d2008-03-25 23:52:34 +0000926
showard21baa452008-10-21 00:08:39 +0000927 if self._state.exit_status is None:
jadmanski0afbb632008-06-06 21:10:57 +0000928 # double check whether or not autoserv is running
showard170873e2009-01-07 00:22:26 +0000929 if _drone_manager.is_process_running(self._state.process):
showard21baa452008-10-21 00:08:39 +0000930 return
mbligh90a549d2008-03-25 23:52:34 +0000931
showard170873e2009-01-07 00:22:26 +0000932 # pid but no running process - maybe process *just* exited
933 self._read_pidfile(use_second_read=True)
showard21baa452008-10-21 00:08:39 +0000934 if self._state.exit_status is None:
jadmanski0afbb632008-06-06 21:10:57 +0000935 # autoserv exited without writing an exit code
936 # to the pidfile
showard21baa452008-10-21 00:08:39 +0000937 self._handle_pidfile_error(
938 'autoserv died without writing exit code')
mblighbb421852008-03-11 22:36:16 +0000939
showard21baa452008-10-21 00:08:39 +0000940
941 def _get_pidfile_info(self):
942 """\
943 After completion, self._state will contain:
944 pid=None, exit_status=None if autoserv has not yet run
945 pid!=None, exit_status=None if autoserv is running
946 pid!=None, exit_status!=None if autoserv has completed
947 """
948 try:
949 self._get_pidfile_info_helper()
showard170873e2009-01-07 00:22:26 +0000950 except self._PidfileException, exc:
showard21baa452008-10-21 00:08:39 +0000951 self._handle_pidfile_error('Pidfile error', traceback.format_exc())
mblighbb421852008-03-11 22:36:16 +0000952
953
showard170873e2009-01-07 00:22:26 +0000954 def _handle_no_process(self):
jadmanski0afbb632008-06-06 21:10:57 +0000955 """\
956 Called when no pidfile is found or no pid is in the pidfile.
957 """
showard170873e2009-01-07 00:22:26 +0000958 message = 'No pid found at %s' % self.pidfile_id
showardec6a3b92009-09-25 20:29:13 +0000959 if time.time() - self._start_time > _get_pidfile_timeout_secs():
showard170873e2009-01-07 00:22:26 +0000960 email_manager.manager.enqueue_notify_email(
jadmanski0afbb632008-06-06 21:10:57 +0000961 'Process has failed to write pidfile', message)
showard35162b02009-03-03 02:17:30 +0000962 self.on_lost_process()
mbligh90a549d2008-03-25 23:52:34 +0000963
964
showard35162b02009-03-03 02:17:30 +0000965 def on_lost_process(self, process=None):
jadmanski0afbb632008-06-06 21:10:57 +0000966 """\
967 Called when autoserv has exited without writing an exit status,
968 or we've timed out waiting for autoserv to write a pid to the
969 pidfile. In either case, we just return failure and the caller
970 should signal some kind of warning.
mbligh90a549d2008-03-25 23:52:34 +0000971
showard170873e2009-01-07 00:22:26 +0000972 process is unimportant here, as it shouldn't be used by anyone.
jadmanski0afbb632008-06-06 21:10:57 +0000973 """
974 self.lost_process = True
showard170873e2009-01-07 00:22:26 +0000975 self._state.process = process
showard21baa452008-10-21 00:08:39 +0000976 self._state.exit_status = 1
977 self._state.num_tests_failed = 0
mbligh90a549d2008-03-25 23:52:34 +0000978
979
jadmanski0afbb632008-06-06 21:10:57 +0000980 def exit_code(self):
showard21baa452008-10-21 00:08:39 +0000981 self._get_pidfile_info()
982 return self._state.exit_status
983
984
985 def num_tests_failed(self):
showard6bba3d12009-08-20 23:31:41 +0000986 """@returns The number of tests that failed or -1 if unknown."""
showard21baa452008-10-21 00:08:39 +0000987 self._get_pidfile_info()
showard6bba3d12009-08-20 23:31:41 +0000988 if self._state.num_tests_failed is None:
989 return -1
showard21baa452008-10-21 00:08:39 +0000990 return self._state.num_tests_failed
mblighbb421852008-03-11 22:36:16 +0000991
992
showardcdaeae82009-08-31 18:32:48 +0000993 def try_copy_results_on_drone(self, **kwargs):
994 if self.has_process():
995 # copy results logs into the normal place for job results
996 _drone_manager.copy_results_on_drone(self.get_process(), **kwargs)
997
998
999 def try_copy_to_results_repository(self, source, **kwargs):
1000 if self.has_process():
1001 _drone_manager.copy_to_results_repository(self.get_process(),
1002 source, **kwargs)
1003
1004
mbligh36768f02008-02-22 18:28:33 +00001005class Agent(object):
showard77182562009-06-10 00:16:05 +00001006 """
showard8cc058f2009-09-08 16:26:33 +00001007 An agent for use by the Dispatcher class to perform a task.
showard77182562009-06-10 00:16:05 +00001008
1009 The following methods are required on all task objects:
1010 poll() - Called periodically to let the task check its status and
1011 update its internal state. If the task succeeded.
1012 is_done() - Returns True if the task is finished.
1013 abort() - Called when an abort has been requested. The task must
1014 set its aborted attribute to True if it actually aborted.
1015
1016 The following attributes are required on all task objects:
1017 aborted - bool, True if this task was aborted.
showard77182562009-06-10 00:16:05 +00001018 success - bool, True if this task succeeded.
1019 queue_entry_ids - A sequence of HostQueueEntry ids this task handles.
1020 host_ids - A sequence of Host ids this task represents.
showard77182562009-06-10 00:16:05 +00001021 """
1022
1023
showard418785b2009-11-23 20:19:59 +00001024 def __init__(self, task):
showard77182562009-06-10 00:16:05 +00001025 """
showard8cc058f2009-09-08 16:26:33 +00001026 @param task: A task as described in the class docstring.
showard77182562009-06-10 00:16:05 +00001027 """
showard8cc058f2009-09-08 16:26:33 +00001028 self.task = task
showard8cc058f2009-09-08 16:26:33 +00001029
showard77182562009-06-10 00:16:05 +00001030 # This is filled in by Dispatcher.add_agent()
jadmanski0afbb632008-06-06 21:10:57 +00001031 self.dispatcher = None
jadmanski0afbb632008-06-06 21:10:57 +00001032
showard8cc058f2009-09-08 16:26:33 +00001033 self.queue_entry_ids = task.queue_entry_ids
1034 self.host_ids = task.host_ids
showard170873e2009-01-07 00:22:26 +00001035
showard8cc058f2009-09-08 16:26:33 +00001036 self.started = False
showard9bb960b2009-11-19 01:02:11 +00001037 self.finished = False
mbligh36768f02008-02-22 18:28:33 +00001038
1039
jadmanski0afbb632008-06-06 21:10:57 +00001040 def tick(self):
showard8cc058f2009-09-08 16:26:33 +00001041 self.started = True
showard9bb960b2009-11-19 01:02:11 +00001042 if not self.finished:
showard8cc058f2009-09-08 16:26:33 +00001043 self.task.poll()
1044 if self.task.is_done():
showard9bb960b2009-11-19 01:02:11 +00001045 self.finished = True
showardec113162008-05-08 00:52:49 +00001046
1047
jadmanski0afbb632008-06-06 21:10:57 +00001048 def is_done(self):
showard9bb960b2009-11-19 01:02:11 +00001049 return self.finished
mbligh36768f02008-02-22 18:28:33 +00001050
1051
showardd3dc1992009-04-22 21:01:40 +00001052 def abort(self):
showard8cc058f2009-09-08 16:26:33 +00001053 if self.task:
1054 self.task.abort()
1055 if self.task.aborted:
showard08a36412009-05-05 01:01:13 +00001056 # tasks can choose to ignore aborts
showard9bb960b2009-11-19 01:02:11 +00001057 self.finished = True
showard20f9bdd2009-04-29 19:48:33 +00001058
showardd3dc1992009-04-22 21:01:40 +00001059
mbligh36768f02008-02-22 18:28:33 +00001060class AgentTask(object):
showardd1195652009-12-08 22:21:02 +00001061 class _NullMonitor(object):
1062 pidfile_id = None
1063
1064 def has_process(self):
1065 return True
1066
1067
1068 def __init__(self, log_file_name=None):
showard9bb960b2009-11-19 01:02:11 +00001069 """
showardd1195652009-12-08 22:21:02 +00001070 @param log_file_name: (optional) name of file to log command output to
showard9bb960b2009-11-19 01:02:11 +00001071 """
jadmanski0afbb632008-06-06 21:10:57 +00001072 self.done = False
showardd1195652009-12-08 22:21:02 +00001073 self.started = False
jadmanski0afbb632008-06-06 21:10:57 +00001074 self.success = None
showardd3dc1992009-04-22 21:01:40 +00001075 self.aborted = False
showardd1195652009-12-08 22:21:02 +00001076 self.monitor = None
showard170873e2009-01-07 00:22:26 +00001077 self.queue_entry_ids = []
1078 self.host_ids = []
showardd1195652009-12-08 22:21:02 +00001079 self._log_file_name = log_file_name
showard170873e2009-01-07 00:22:26 +00001080
1081
1082 def _set_ids(self, host=None, queue_entries=None):
1083 if queue_entries and queue_entries != [None]:
1084 self.host_ids = [entry.host.id for entry in queue_entries]
1085 self.queue_entry_ids = [entry.id for entry in queue_entries]
1086 else:
1087 assert host
1088 self.host_ids = [host.id]
mbligh36768f02008-02-22 18:28:33 +00001089
1090
jadmanski0afbb632008-06-06 21:10:57 +00001091 def poll(self):
showard08a36412009-05-05 01:01:13 +00001092 if not self.started:
1093 self.start()
showardd1195652009-12-08 22:21:02 +00001094 if not self.done:
1095 self.tick()
showard08a36412009-05-05 01:01:13 +00001096
1097
1098 def tick(self):
showardd1195652009-12-08 22:21:02 +00001099 assert self.monitor
1100 exit_code = self.monitor.exit_code()
1101 if exit_code is None:
1102 return
mbligh36768f02008-02-22 18:28:33 +00001103
showardd1195652009-12-08 22:21:02 +00001104 success = (exit_code == 0)
jadmanski0afbb632008-06-06 21:10:57 +00001105 self.finished(success)
mbligh36768f02008-02-22 18:28:33 +00001106
1107
jadmanski0afbb632008-06-06 21:10:57 +00001108 def is_done(self):
1109 return self.done
mbligh36768f02008-02-22 18:28:33 +00001110
1111
jadmanski0afbb632008-06-06 21:10:57 +00001112 def finished(self, success):
showard08a36412009-05-05 01:01:13 +00001113 if self.done:
showardd1195652009-12-08 22:21:02 +00001114 assert self.started
showard08a36412009-05-05 01:01:13 +00001115 return
showardd1195652009-12-08 22:21:02 +00001116 self.started = True
jadmanski0afbb632008-06-06 21:10:57 +00001117 self.done = True
1118 self.success = success
1119 self.epilog()
mbligh36768f02008-02-22 18:28:33 +00001120
1121
jadmanski0afbb632008-06-06 21:10:57 +00001122 def prolog(self):
showardd1195652009-12-08 22:21:02 +00001123 """
1124 To be overridden.
1125 """
showarded2afea2009-07-07 20:54:07 +00001126 assert not self.monitor
showardd1195652009-12-08 22:21:02 +00001127 self.register_necessary_pidfiles()
1128
1129
1130 def _log_file(self):
1131 if not self._log_file_name:
1132 return None
1133 return os.path.join(self._working_directory(), self._log_file_name)
mblighd64e5702008-04-04 21:39:28 +00001134
mbligh36768f02008-02-22 18:28:33 +00001135
jadmanski0afbb632008-06-06 21:10:57 +00001136 def cleanup(self):
showardd1195652009-12-08 22:21:02 +00001137 log_file = self._log_file()
1138 if self.monitor and log_file:
1139 self.monitor.try_copy_to_results_repository(log_file)
mbligh36768f02008-02-22 18:28:33 +00001140
1141
jadmanski0afbb632008-06-06 21:10:57 +00001142 def epilog(self):
showardd1195652009-12-08 22:21:02 +00001143 """
1144 To be overridden.
1145 """
jadmanski0afbb632008-06-06 21:10:57 +00001146 self.cleanup()
showarda9545c02009-12-18 22:44:26 +00001147 logging.info("%s finished with success=%s", type(self).__name__,
1148 self.success)
1149
mbligh36768f02008-02-22 18:28:33 +00001150
1151
jadmanski0afbb632008-06-06 21:10:57 +00001152 def start(self):
jadmanski0afbb632008-06-06 21:10:57 +00001153 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
showardd3dc1992009-04-22 21:01:40 +00001164 self.aborted = True
jadmanski0afbb632008-06-06 21:10:57 +00001165 self.cleanup()
1166
1167
showarded2afea2009-07-07 20:54:07 +00001168 def _get_consistent_execution_path(self, execution_entries):
1169 first_execution_path = execution_entries[0].execution_path()
1170 for execution_entry in execution_entries[1:]:
1171 assert execution_entry.execution_path() == first_execution_path, (
1172 '%s (%s) != %s (%s)' % (execution_entry.execution_path(),
1173 execution_entry,
1174 first_execution_path,
1175 execution_entries[0]))
1176 return first_execution_path
showard170873e2009-01-07 00:22:26 +00001177
1178
showarded2afea2009-07-07 20:54:07 +00001179 def _copy_results(self, execution_entries, use_monitor=None):
1180 """
1181 @param execution_entries: list of objects with execution_path() method
1182 """
showard6d1c1432009-08-20 23:30:39 +00001183 if use_monitor is not None and not use_monitor.has_process():
1184 return
1185
showarded2afea2009-07-07 20:54:07 +00001186 assert len(execution_entries) > 0
showard6b733412009-04-27 20:09:18 +00001187 if use_monitor is None:
1188 assert self.monitor
1189 use_monitor = self.monitor
1190 assert use_monitor.has_process()
showarded2afea2009-07-07 20:54:07 +00001191 execution_path = self._get_consistent_execution_path(execution_entries)
1192 results_path = execution_path + '/'
showardcdaeae82009-08-31 18:32:48 +00001193 use_monitor.try_copy_to_results_repository(results_path)
showardde634ee2009-01-30 01:44:24 +00001194
showarda1e74b32009-05-12 17:32:04 +00001195
1196 def _parse_results(self, queue_entries):
showard8cc058f2009-09-08 16:26:33 +00001197 for queue_entry in queue_entries:
1198 queue_entry.set_status(models.HostQueueEntry.Status.PARSING)
showardde634ee2009-01-30 01:44:24 +00001199
1200
mbligh4608b002010-01-05 18:22:35 +00001201 def _archive_results(self, queue_entries):
1202 for queue_entry in queue_entries:
1203 queue_entry.set_status(models.HostQueueEntry.Status.ARCHIVING)
showarda1e74b32009-05-12 17:32:04 +00001204
1205
showardd1195652009-12-08 22:21:02 +00001206 def _command_line(self):
1207 """
1208 Return the command line to run. Must be overridden.
1209 """
1210 raise NotImplementedError
1211
1212
1213 @property
1214 def num_processes(self):
1215 """
1216 Return the number of processes forked by this AgentTask's process. It
1217 may only be approximate. To be overridden if necessary.
1218 """
1219 return 1
1220
1221
1222 def _paired_with_monitor(self):
1223 """
1224 If this AgentTask's process must run on the same machine as some
1225 previous process, this method should be overridden to return a
1226 PidfileRunMonitor for that process.
1227 """
1228 return self._NullMonitor()
1229
1230
1231 @property
1232 def owner_username(self):
1233 """
1234 Return login of user responsible for this task. May be None. Must be
1235 overridden.
1236 """
1237 raise NotImplementedError
1238
1239
1240 def _working_directory(self):
1241 """
1242 Return the directory where this AgentTask's process executes. Must be
1243 overridden.
1244 """
1245 raise NotImplementedError
1246
1247
1248 def _pidfile_name(self):
1249 """
1250 Return the name of the pidfile this AgentTask's process uses. To be
1251 overridden if necessary.
1252 """
jamesrenc44ae992010-02-19 00:12:54 +00001253 return drone_manager.AUTOSERV_PID_FILE
showardd1195652009-12-08 22:21:02 +00001254
1255
1256 def _check_paired_results_exist(self):
1257 if not self._paired_with_monitor().has_process():
1258 email_manager.manager.enqueue_notify_email(
1259 'No paired results in task',
1260 'No paired results in task %s at %s'
1261 % (self, self._paired_with_monitor().pidfile_id))
1262 self.finished(False)
1263 return False
1264 return True
1265
1266
1267 def _create_monitor(self):
showarded2afea2009-07-07 20:54:07 +00001268 assert not self.monitor
showardd1195652009-12-08 22:21:02 +00001269 self.monitor = PidfileRunMonitor()
1270
1271
1272 def run(self):
1273 if not self._check_paired_results_exist():
1274 return
1275
1276 self._create_monitor()
1277 self.monitor.run(
1278 self._command_line(), self._working_directory(),
1279 num_processes=self.num_processes,
1280 nice_level=AUTOSERV_NICE_LEVEL, log_file=self._log_file(),
1281 pidfile_name=self._pidfile_name(),
1282 paired_with_pidfile=self._paired_with_monitor().pidfile_id,
jamesren76fcf192010-04-21 20:39:50 +00001283 username=self.owner_username,
1284 drone_hostnames_allowed=self.get_drone_hostnames_allowed())
1285
1286
1287 def get_drone_hostnames_allowed(self):
1288 if not models.DroneSet.drone_sets_enabled():
1289 return None
1290
1291 hqes = models.HostQueueEntry.objects.filter(id__in=self.queue_entry_ids)
1292 if not hqes:
1293 # Only special tasks could be missing host queue entries
1294 assert isinstance(self, SpecialAgentTask)
1295 return self._user_or_global_default_drone_set(
1296 self.task, self.task.requested_by)
1297
1298 job_ids = hqes.values_list('job', flat=True).distinct()
1299 assert job_ids.count() == 1, ("AgentTask's queue entries "
1300 "span multiple jobs")
1301
1302 job = models.Job.objects.get(id=job_ids[0])
1303 drone_set = job.drone_set
1304 if not drone_set:
jamesrendd77e012010-04-28 18:07:30 +00001305 return self._user_or_global_default_drone_set(job, job.user())
jamesren76fcf192010-04-21 20:39:50 +00001306
1307 return drone_set.get_drone_hostnames()
1308
1309
1310 def _user_or_global_default_drone_set(self, obj_with_owner, user):
1311 """
1312 Returns the user's default drone set, if present.
1313
1314 Otherwise, returns the global default drone set.
1315 """
1316 default_hostnames = models.DroneSet.get_default().get_drone_hostnames()
1317 if not user:
1318 logging.warn('%s had no owner; using default drone set',
1319 obj_with_owner)
1320 return default_hostnames
1321 if not user.drone_set:
1322 logging.warn('User %s has no default drone set, using global '
1323 'default', user.login)
1324 return default_hostnames
1325 return user.drone_set.get_drone_hostnames()
showardd1195652009-12-08 22:21:02 +00001326
1327
1328 def register_necessary_pidfiles(self):
1329 pidfile_id = _drone_manager.get_pidfile_id_from(
1330 self._working_directory(), self._pidfile_name())
1331 _drone_manager.register_pidfile(pidfile_id)
1332
1333 paired_pidfile_id = self._paired_with_monitor().pidfile_id
1334 if paired_pidfile_id:
1335 _drone_manager.register_pidfile(paired_pidfile_id)
1336
1337
1338 def recover(self):
1339 if not self._check_paired_results_exist():
1340 return
1341
1342 self._create_monitor()
1343 self.monitor.attach_to_existing_process(
1344 self._working_directory(), pidfile_name=self._pidfile_name(),
1345 num_processes=self.num_processes)
1346 if not self.monitor.has_process():
1347 # no process to recover; wait to be started normally
1348 self.monitor = None
1349 return
1350
1351 self.started = True
1352 logging.info('Recovering process %s for %s at %s'
1353 % (self.monitor.get_process(), type(self).__name__,
1354 self._working_directory()))
mbligh36768f02008-02-22 18:28:33 +00001355
1356
mbligh4608b002010-01-05 18:22:35 +00001357 def _check_queue_entry_statuses(self, queue_entries, allowed_hqe_statuses,
1358 allowed_host_statuses=None):
jamesrenb8f3f352010-06-10 00:44:06 +00001359 class_name = self.__class__.__name__
mbligh4608b002010-01-05 18:22:35 +00001360 for entry in queue_entries:
1361 if entry.status not in allowed_hqe_statuses:
Dale Curtisaa513362011-03-01 17:27:44 -08001362 raise host_scheduler.SchedulerError(
1363 '%s attempting to start entry with invalid status %s: '
1364 '%s' % (class_name, entry.status, entry))
mbligh4608b002010-01-05 18:22:35 +00001365 invalid_host_status = (
1366 allowed_host_statuses is not None
1367 and entry.host.status not in allowed_host_statuses)
1368 if invalid_host_status:
Dale Curtisaa513362011-03-01 17:27:44 -08001369 raise host_scheduler.SchedulerError(
1370 '%s attempting to start on queue entry with invalid '
1371 'host status %s: %s'
1372 % (class_name, entry.host.status, entry))
mbligh4608b002010-01-05 18:22:35 +00001373
1374
showardd9205182009-04-27 20:09:55 +00001375class TaskWithJobKeyvals(object):
1376 """AgentTask mixin providing functionality to help with job keyval files."""
1377 _KEYVAL_FILE = 'keyval'
1378 def _format_keyval(self, key, value):
1379 return '%s=%s' % (key, value)
1380
1381
1382 def _keyval_path(self):
1383 """Subclasses must override this"""
lmrb7c5d272010-04-16 06:34:04 +00001384 raise NotImplementedError
showardd9205182009-04-27 20:09:55 +00001385
1386
1387 def _write_keyval_after_job(self, field, value):
1388 assert self.monitor
1389 if not self.monitor.has_process():
1390 return
1391 _drone_manager.write_lines_to_file(
1392 self._keyval_path(), [self._format_keyval(field, value)],
1393 paired_with_process=self.monitor.get_process())
1394
1395
1396 def _job_queued_keyval(self, job):
1397 return 'job_queued', int(time.mktime(job.created_on.timetuple()))
1398
1399
1400 def _write_job_finished(self):
1401 self._write_keyval_after_job("job_finished", int(time.time()))
1402
1403
showarddb502762009-09-09 15:31:20 +00001404 def _write_keyvals_before_job_helper(self, keyval_dict, keyval_path):
1405 keyval_contents = '\n'.join(self._format_keyval(key, value)
1406 for key, value in keyval_dict.iteritems())
1407 # always end with a newline to allow additional keyvals to be written
1408 keyval_contents += '\n'
showard493beaa2009-12-18 22:44:45 +00001409 _drone_manager.attach_file_to_execution(self._working_directory(),
showarddb502762009-09-09 15:31:20 +00001410 keyval_contents,
1411 file_path=keyval_path)
1412
1413
1414 def _write_keyvals_before_job(self, keyval_dict):
1415 self._write_keyvals_before_job_helper(keyval_dict, self._keyval_path())
1416
1417
1418 def _write_host_keyvals(self, host):
showardd1195652009-12-08 22:21:02 +00001419 keyval_path = os.path.join(self._working_directory(), 'host_keyvals',
showarddb502762009-09-09 15:31:20 +00001420 host.hostname)
1421 platform, all_labels = host.platform_and_labels()
Eric Li6f27d4f2010-09-29 10:55:17 -07001422 all_labels = [ urllib.quote(label) for label in all_labels ]
showarddb502762009-09-09 15:31:20 +00001423 keyval_dict = dict(platform=platform, labels=','.join(all_labels))
1424 self._write_keyvals_before_job_helper(keyval_dict, keyval_path)
1425
1426
showard8cc058f2009-09-08 16:26:33 +00001427class SpecialAgentTask(AgentTask, TaskWithJobKeyvals):
showarded2afea2009-07-07 20:54:07 +00001428 """
1429 Subclass for AgentTasks that correspond to a SpecialTask entry in the DB.
1430 """
1431
1432 TASK_TYPE = None
1433 host = None
1434 queue_entry = None
1435
showardd1195652009-12-08 22:21:02 +00001436 def __init__(self, task, extra_command_args):
1437 super(SpecialAgentTask, self).__init__()
1438
lmrb7c5d272010-04-16 06:34:04 +00001439 assert self.TASK_TYPE is not None, 'self.TASK_TYPE must be overridden'
showard8cc058f2009-09-08 16:26:33 +00001440
jamesrenc44ae992010-02-19 00:12:54 +00001441 self.host = scheduler_models.Host(id=task.host.id)
showard8cc058f2009-09-08 16:26:33 +00001442 self.queue_entry = None
1443 if task.queue_entry:
jamesrenc44ae992010-02-19 00:12:54 +00001444 self.queue_entry = scheduler_models.HostQueueEntry(
1445 id=task.queue_entry.id)
showard8cc058f2009-09-08 16:26:33 +00001446
showarded2afea2009-07-07 20:54:07 +00001447 self.task = task
1448 self._extra_command_args = extra_command_args
showarded2afea2009-07-07 20:54:07 +00001449
1450
showard8cc058f2009-09-08 16:26:33 +00001451 def _keyval_path(self):
showardd1195652009-12-08 22:21:02 +00001452 return os.path.join(self._working_directory(), self._KEYVAL_FILE)
1453
1454
1455 def _command_line(self):
1456 return _autoserv_command_line(self.host.hostname,
1457 self._extra_command_args,
1458 queue_entry=self.queue_entry)
1459
1460
1461 def _working_directory(self):
1462 return self.task.execution_path()
1463
1464
1465 @property
1466 def owner_username(self):
1467 if self.task.requested_by:
1468 return self.task.requested_by.login
1469 return None
showard8cc058f2009-09-08 16:26:33 +00001470
1471
showarded2afea2009-07-07 20:54:07 +00001472 def prolog(self):
1473 super(SpecialAgentTask, self).prolog()
showarded2afea2009-07-07 20:54:07 +00001474 self.task.activate()
showarddb502762009-09-09 15:31:20 +00001475 self._write_host_keyvals(self.host)
showarded2afea2009-07-07 20:54:07 +00001476
1477
showardde634ee2009-01-30 01:44:24 +00001478 def _fail_queue_entry(self):
showard2fe3f1d2009-07-06 20:19:11 +00001479 assert self.queue_entry
showardccbd6c52009-03-21 00:10:21 +00001480
showard2fe3f1d2009-07-06 20:19:11 +00001481 if self.queue_entry.meta_host:
showardccbd6c52009-03-21 00:10:21 +00001482 return # don't fail metahost entries, they'll be reassigned
1483
showard2fe3f1d2009-07-06 20:19:11 +00001484 self.queue_entry.update_from_database()
showard8cc058f2009-09-08 16:26:33 +00001485 if self.queue_entry.status != models.HostQueueEntry.Status.QUEUED:
showardccbd6c52009-03-21 00:10:21 +00001486 return # entry has been aborted
1487
showard2fe3f1d2009-07-06 20:19:11 +00001488 self.queue_entry.set_execution_subdir()
showardd9205182009-04-27 20:09:55 +00001489 queued_key, queued_time = self._job_queued_keyval(
showard2fe3f1d2009-07-06 20:19:11 +00001490 self.queue_entry.job)
showardd9205182009-04-27 20:09:55 +00001491 self._write_keyval_after_job(queued_key, queued_time)
1492 self._write_job_finished()
showardcdaeae82009-08-31 18:32:48 +00001493
showard8cc058f2009-09-08 16:26:33 +00001494 # copy results logs into the normal place for job results
showardcdaeae82009-08-31 18:32:48 +00001495 self.monitor.try_copy_results_on_drone(
showardd1195652009-12-08 22:21:02 +00001496 source_path=self._working_directory() + '/',
showardcdaeae82009-08-31 18:32:48 +00001497 destination_path=self.queue_entry.execution_path() + '/')
showard678df4f2009-02-04 21:36:39 +00001498
showard8cc058f2009-09-08 16:26:33 +00001499 pidfile_id = _drone_manager.get_pidfile_id_from(
1500 self.queue_entry.execution_path(),
jamesrenc44ae992010-02-19 00:12:54 +00001501 pidfile_name=drone_manager.AUTOSERV_PID_FILE)
showard8cc058f2009-09-08 16:26:33 +00001502 _drone_manager.register_pidfile(pidfile_id)
mbligh4608b002010-01-05 18:22:35 +00001503
1504 if self.queue_entry.job.parse_failed_repair:
1505 self._parse_results([self.queue_entry])
1506 else:
1507 self._archive_results([self.queue_entry])
showard8cc058f2009-09-08 16:26:33 +00001508
1509
1510 def cleanup(self):
1511 super(SpecialAgentTask, self).cleanup()
showarde60e44e2009-11-13 20:45:38 +00001512
1513 # We will consider an aborted task to be "Failed"
1514 self.task.finish(bool(self.success))
1515
showardf85a0b72009-10-07 20:48:45 +00001516 if self.monitor:
1517 if self.monitor.has_process():
1518 self._copy_results([self.task])
1519 if self.monitor.pidfile_id is not None:
1520 _drone_manager.unregister_pidfile(self.monitor.pidfile_id)
showard8cc058f2009-09-08 16:26:33 +00001521
1522
1523class RepairTask(SpecialAgentTask):
1524 TASK_TYPE = models.SpecialTask.Task.REPAIR
1525
1526
showardd1195652009-12-08 22:21:02 +00001527 def __init__(self, task):
showard8cc058f2009-09-08 16:26:33 +00001528 """\
1529 queue_entry: queue entry to mark failed if this repair fails.
1530 """
1531 protection = host_protections.Protection.get_string(
1532 task.host.protection)
1533 # normalize the protection name
1534 protection = host_protections.Protection.get_attr_name(protection)
1535
1536 super(RepairTask, self).__init__(
showardd1195652009-12-08 22:21:02 +00001537 task, ['-R', '--host-protection', protection])
showard8cc058f2009-09-08 16:26:33 +00001538
1539 # *don't* include the queue entry in IDs -- if the queue entry is
1540 # aborted, we want to leave the repair task running
1541 self._set_ids(host=self.host)
1542
1543
1544 def prolog(self):
1545 super(RepairTask, self).prolog()
1546 logging.info("repair_task starting")
1547 self.host.set_status(models.Host.Status.REPAIRING)
showardde634ee2009-01-30 01:44:24 +00001548
1549
jadmanski0afbb632008-06-06 21:10:57 +00001550 def epilog(self):
1551 super(RepairTask, self).epilog()
showard6d7b2ff2009-06-10 00:16:47 +00001552
jadmanski0afbb632008-06-06 21:10:57 +00001553 if self.success:
showard8cc058f2009-09-08 16:26:33 +00001554 self.host.set_status(models.Host.Status.READY)
jadmanski0afbb632008-06-06 21:10:57 +00001555 else:
showard8cc058f2009-09-08 16:26:33 +00001556 self.host.set_status(models.Host.Status.REPAIR_FAILED)
showard2fe3f1d2009-07-06 20:19:11 +00001557 if self.queue_entry:
showardde634ee2009-01-30 01:44:24 +00001558 self._fail_queue_entry()
mbligh36768f02008-02-22 18:28:33 +00001559
1560
showarded2afea2009-07-07 20:54:07 +00001561class PreJobTask(SpecialAgentTask):
showard775300b2009-09-09 15:30:50 +00001562 def _copy_to_results_repository(self):
1563 if not self.queue_entry or self.queue_entry.meta_host:
1564 return
1565
1566 self.queue_entry.set_execution_subdir()
1567 log_name = os.path.basename(self.task.execution_path())
1568 source = os.path.join(self.task.execution_path(), 'debug',
1569 'autoserv.DEBUG')
1570 destination = os.path.join(
1571 self.queue_entry.execution_path(), log_name)
1572
1573 self.monitor.try_copy_to_results_repository(
1574 source, destination_path=destination)
1575
1576
showard170873e2009-01-07 00:22:26 +00001577 def epilog(self):
1578 super(PreJobTask, self).epilog()
showardcdaeae82009-08-31 18:32:48 +00001579
showard775300b2009-09-09 15:30:50 +00001580 if self.success:
1581 return
showard8fe93b52008-11-18 17:53:22 +00001582
showard775300b2009-09-09 15:30:50 +00001583 self._copy_to_results_repository()
showard8cc058f2009-09-08 16:26:33 +00001584
showard775300b2009-09-09 15:30:50 +00001585 if self.host.protection == host_protections.Protection.DO_NOT_VERIFY:
showard7b2d7cb2009-10-28 19:53:03 +00001586 # effectively ignore failure for these hosts
1587 self.success = True
showard775300b2009-09-09 15:30:50 +00001588 return
1589
1590 if self.queue_entry:
1591 self.queue_entry.requeue()
1592
1593 if models.SpecialTask.objects.filter(
showard8cc058f2009-09-08 16:26:33 +00001594 task=models.SpecialTask.Task.REPAIR,
showard775300b2009-09-09 15:30:50 +00001595 queue_entry__id=self.queue_entry.id):
1596 self.host.set_status(models.Host.Status.REPAIR_FAILED)
1597 self._fail_queue_entry()
1598 return
1599
showard9bb960b2009-11-19 01:02:11 +00001600 queue_entry = models.HostQueueEntry.objects.get(
1601 id=self.queue_entry.id)
showard775300b2009-09-09 15:30:50 +00001602 else:
1603 queue_entry = None
1604
1605 models.SpecialTask.objects.create(
showard9bb960b2009-11-19 01:02:11 +00001606 host=models.Host.objects.get(id=self.host.id),
showard775300b2009-09-09 15:30:50 +00001607 task=models.SpecialTask.Task.REPAIR,
showard9bb960b2009-11-19 01:02:11 +00001608 queue_entry=queue_entry,
1609 requested_by=self.task.requested_by)
showard58721a82009-08-20 23:32:40 +00001610
showard8fe93b52008-11-18 17:53:22 +00001611
1612class VerifyTask(PreJobTask):
showarded2afea2009-07-07 20:54:07 +00001613 TASK_TYPE = models.SpecialTask.Task.VERIFY
1614
1615
showardd1195652009-12-08 22:21:02 +00001616 def __init__(self, task):
1617 super(VerifyTask, self).__init__(task, ['-v'])
showard8cc058f2009-09-08 16:26:33 +00001618 self._set_ids(host=self.host, queue_entries=[self.queue_entry])
mblighe2586682008-02-29 22:45:46 +00001619
1620
jadmanski0afbb632008-06-06 21:10:57 +00001621 def prolog(self):
showard8fe93b52008-11-18 17:53:22 +00001622 super(VerifyTask, self).prolog()
showarded2afea2009-07-07 20:54:07 +00001623
showardb18134f2009-03-20 20:52:18 +00001624 logging.info("starting verify on %s", self.host.hostname)
jadmanski0afbb632008-06-06 21:10:57 +00001625 if self.queue_entry:
showard8cc058f2009-09-08 16:26:33 +00001626 self.queue_entry.set_status(models.HostQueueEntry.Status.VERIFYING)
1627 self.host.set_status(models.Host.Status.VERIFYING)
mbligh36768f02008-02-22 18:28:33 +00001628
jamesren42318f72010-05-10 23:40:59 +00001629 # Delete any queued manual reverifies for this host. One verify will do
showarded2afea2009-07-07 20:54:07 +00001630 # and there's no need to keep records of other requests.
1631 queued_verifies = models.SpecialTask.objects.filter(
showard2fe3f1d2009-07-06 20:19:11 +00001632 host__id=self.host.id,
1633 task=models.SpecialTask.Task.VERIFY,
jamesren42318f72010-05-10 23:40:59 +00001634 is_active=False, is_complete=False, queue_entry=None)
showarded2afea2009-07-07 20:54:07 +00001635 queued_verifies = queued_verifies.exclude(id=self.task.id)
1636 queued_verifies.delete()
showard2fe3f1d2009-07-06 20:19:11 +00001637
mbligh36768f02008-02-22 18:28:33 +00001638
jadmanski0afbb632008-06-06 21:10:57 +00001639 def epilog(self):
1640 super(VerifyTask, self).epilog()
showard2fe3f1d2009-07-06 20:19:11 +00001641 if self.success:
showard8cc058f2009-09-08 16:26:33 +00001642 if self.queue_entry:
1643 self.queue_entry.on_pending()
1644 else:
1645 self.host.set_status(models.Host.Status.READY)
mbligh36768f02008-02-22 18:28:33 +00001646
1647
mbligh4608b002010-01-05 18:22:35 +00001648class CleanupTask(PreJobTask):
1649 # note this can also run post-job, but when it does, it's running standalone
1650 # against the host (not related to the job), so it's not considered a
1651 # PostJobTask
1652
1653 TASK_TYPE = models.SpecialTask.Task.CLEANUP
1654
1655
1656 def __init__(self, task, recover_run_monitor=None):
1657 super(CleanupTask, self).__init__(task, ['--cleanup'])
1658 self._set_ids(host=self.host, queue_entries=[self.queue_entry])
1659
1660
1661 def prolog(self):
1662 super(CleanupTask, self).prolog()
1663 logging.info("starting cleanup task for host: %s", self.host.hostname)
1664 self.host.set_status(models.Host.Status.CLEANING)
1665 if self.queue_entry:
1666 self.queue_entry.set_status(models.HostQueueEntry.Status.VERIFYING)
1667
1668
1669 def _finish_epilog(self):
1670 if not self.queue_entry or not self.success:
1671 return
1672
1673 do_not_verify_protection = host_protections.Protection.DO_NOT_VERIFY
1674 should_run_verify = (
1675 self.queue_entry.job.run_verify
1676 and self.host.protection != do_not_verify_protection)
1677 if should_run_verify:
1678 entry = models.HostQueueEntry.objects.get(id=self.queue_entry.id)
1679 models.SpecialTask.objects.create(
1680 host=models.Host.objects.get(id=self.host.id),
1681 queue_entry=entry,
1682 task=models.SpecialTask.Task.VERIFY)
1683 else:
1684 self.queue_entry.on_pending()
1685
1686
1687 def epilog(self):
1688 super(CleanupTask, self).epilog()
1689
1690 if self.success:
1691 self.host.update_field('dirty', 0)
1692 self.host.set_status(models.Host.Status.READY)
1693
1694 self._finish_epilog()
1695
1696
showarda9545c02009-12-18 22:44:26 +00001697class AbstractQueueTask(AgentTask, TaskWithJobKeyvals):
1698 """
1699 Common functionality for QueueTask and HostlessQueueTask
1700 """
1701 def __init__(self, queue_entries):
1702 super(AbstractQueueTask, self).__init__()
showardd1195652009-12-08 22:21:02 +00001703 self.job = queue_entries[0].job
jadmanski0afbb632008-06-06 21:10:57 +00001704 self.queue_entries = queue_entries
mbligh36768f02008-02-22 18:28:33 +00001705
1706
showard73ec0442009-02-07 02:05:20 +00001707 def _keyval_path(self):
showardd1195652009-12-08 22:21:02 +00001708 return os.path.join(self._working_directory(), self._KEYVAL_FILE)
showard73ec0442009-02-07 02:05:20 +00001709
1710
jamesrenc44ae992010-02-19 00:12:54 +00001711 def _write_control_file(self, execution_path):
1712 control_path = _drone_manager.attach_file_to_execution(
1713 execution_path, self.job.control_file)
1714 return control_path
1715
1716
showardd1195652009-12-08 22:21:02 +00001717 def _command_line(self):
jamesrenc44ae992010-02-19 00:12:54 +00001718 execution_path = self.queue_entries[0].execution_path()
1719 control_path = self._write_control_file(execution_path)
1720 hostnames = ','.join(entry.host.hostname
1721 for entry in self.queue_entries
1722 if not entry.is_hostless())
1723
1724 execution_tag = self.queue_entries[0].execution_tag()
1725 params = _autoserv_command_line(
1726 hostnames,
1727 ['-P', execution_tag, '-n',
1728 _drone_manager.absolute_path(control_path)],
1729 job=self.job, verbose=False)
1730
1731 if not self.job.is_server_job():
1732 params.append('-c')
1733
Dale Curtis30cb8eb2011-06-09 12:22:26 -07001734 if self.job.is_image_update_job():
1735 params += ['--image', self.job.update_image_path]
1736
jamesrenc44ae992010-02-19 00:12:54 +00001737 return params
showardd1195652009-12-08 22:21:02 +00001738
1739
1740 @property
1741 def num_processes(self):
1742 return len(self.queue_entries)
1743
1744
1745 @property
1746 def owner_username(self):
1747 return self.job.owner
1748
1749
1750 def _working_directory(self):
1751 return self._get_consistent_execution_path(self.queue_entries)
mblighbb421852008-03-11 22:36:16 +00001752
1753
jadmanski0afbb632008-06-06 21:10:57 +00001754 def prolog(self):
showardd9205182009-04-27 20:09:55 +00001755 queued_key, queued_time = self._job_queued_keyval(self.job)
showardc1a98d12010-01-15 00:22:22 +00001756 keyval_dict = self.job.keyval_dict()
1757 keyval_dict[queued_key] = queued_time
showardd1195652009-12-08 22:21:02 +00001758 group_name = self.queue_entries[0].get_group_name()
1759 if group_name:
1760 keyval_dict['host_group_name'] = group_name
showardf1ae3542009-05-11 19:26:02 +00001761 self._write_keyvals_before_job(keyval_dict)
jadmanski0afbb632008-06-06 21:10:57 +00001762 for queue_entry in self.queue_entries:
showard8cc058f2009-09-08 16:26:33 +00001763 queue_entry.set_status(models.HostQueueEntry.Status.RUNNING)
showarda9545c02009-12-18 22:44:26 +00001764 queue_entry.set_started_on_now()
mbligh36768f02008-02-22 18:28:33 +00001765
1766
showard35162b02009-03-03 02:17:30 +00001767 def _write_lost_process_error_file(self):
showardd1195652009-12-08 22:21:02 +00001768 error_file_path = os.path.join(self._working_directory(), 'job_failure')
showard35162b02009-03-03 02:17:30 +00001769 _drone_manager.write_lines_to_file(error_file_path,
1770 [_LOST_PROCESS_ERROR])
1771
1772
showardd3dc1992009-04-22 21:01:40 +00001773 def _finish_task(self):
showard08a36412009-05-05 01:01:13 +00001774 if not self.monitor:
1775 return
1776
showardd9205182009-04-27 20:09:55 +00001777 self._write_job_finished()
1778
showard35162b02009-03-03 02:17:30 +00001779 if self.monitor.lost_process:
1780 self._write_lost_process_error_file()
showard4ac47542009-08-31 18:32:19 +00001781
jadmanskif7fa2cc2008-10-01 14:13:23 +00001782
showardcbd74612008-11-19 21:42:02 +00001783 def _write_status_comment(self, comment):
showard170873e2009-01-07 00:22:26 +00001784 _drone_manager.write_lines_to_file(
showardd1195652009-12-08 22:21:02 +00001785 os.path.join(self._working_directory(), 'status.log'),
showard170873e2009-01-07 00:22:26 +00001786 ['INFO\t----\t----\t' + comment],
showard35162b02009-03-03 02:17:30 +00001787 paired_with_process=self.monitor.get_process())
showardcbd74612008-11-19 21:42:02 +00001788
1789
jadmanskif7fa2cc2008-10-01 14:13:23 +00001790 def _log_abort(self):
showard170873e2009-01-07 00:22:26 +00001791 if not self.monitor or not self.monitor.has_process():
1792 return
1793
jadmanskif7fa2cc2008-10-01 14:13:23 +00001794 # build up sets of all the aborted_by and aborted_on values
1795 aborted_by, aborted_on = set(), set()
1796 for queue_entry in self.queue_entries:
1797 if queue_entry.aborted_by:
1798 aborted_by.add(queue_entry.aborted_by)
1799 t = int(time.mktime(queue_entry.aborted_on.timetuple()))
1800 aborted_on.add(t)
1801
1802 # extract some actual, unique aborted by value and write it out
showard64a95952010-01-13 21:27:16 +00001803 # TODO(showard): this conditional is now obsolete, we just need to leave
1804 # it in temporarily for backwards compatibility over upgrades. delete
1805 # soon.
jadmanskif7fa2cc2008-10-01 14:13:23 +00001806 assert len(aborted_by) <= 1
1807 if len(aborted_by) == 1:
showardcbd74612008-11-19 21:42:02 +00001808 aborted_by_value = aborted_by.pop()
1809 aborted_on_value = max(aborted_on)
1810 else:
1811 aborted_by_value = 'autotest_system'
1812 aborted_on_value = int(time.time())
showard170873e2009-01-07 00:22:26 +00001813
showarda0382352009-02-11 23:36:43 +00001814 self._write_keyval_after_job("aborted_by", aborted_by_value)
1815 self._write_keyval_after_job("aborted_on", aborted_on_value)
showard170873e2009-01-07 00:22:26 +00001816
showardcbd74612008-11-19 21:42:02 +00001817 aborted_on_string = str(datetime.datetime.fromtimestamp(
1818 aborted_on_value))
1819 self._write_status_comment('Job aborted by %s on %s' %
1820 (aborted_by_value, aborted_on_string))
jadmanskic2ac77f2008-05-16 21:44:04 +00001821
1822
jadmanski0afbb632008-06-06 21:10:57 +00001823 def abort(self):
showarda9545c02009-12-18 22:44:26 +00001824 super(AbstractQueueTask, self).abort()
jadmanskif7fa2cc2008-10-01 14:13:23 +00001825 self._log_abort()
showardd3dc1992009-04-22 21:01:40 +00001826 self._finish_task()
showard21baa452008-10-21 00:08:39 +00001827
1828
jadmanski0afbb632008-06-06 21:10:57 +00001829 def epilog(self):
showarda9545c02009-12-18 22:44:26 +00001830 super(AbstractQueueTask, self).epilog()
showardd3dc1992009-04-22 21:01:40 +00001831 self._finish_task()
showarda9545c02009-12-18 22:44:26 +00001832
1833
1834class QueueTask(AbstractQueueTask):
1835 def __init__(self, queue_entries):
1836 super(QueueTask, self).__init__(queue_entries)
1837 self._set_ids(queue_entries=queue_entries)
1838
1839
1840 def prolog(self):
mbligh4608b002010-01-05 18:22:35 +00001841 self._check_queue_entry_statuses(
1842 self.queue_entries,
1843 allowed_hqe_statuses=(models.HostQueueEntry.Status.STARTING,
1844 models.HostQueueEntry.Status.RUNNING),
1845 allowed_host_statuses=(models.Host.Status.PENDING,
1846 models.Host.Status.RUNNING))
showarda9545c02009-12-18 22:44:26 +00001847
1848 super(QueueTask, self).prolog()
1849
1850 for queue_entry in self.queue_entries:
1851 self._write_host_keyvals(queue_entry.host)
1852 queue_entry.host.set_status(models.Host.Status.RUNNING)
1853 queue_entry.host.update_field('dirty', 1)
1854 if self.job.synch_count == 1 and len(self.queue_entries) == 1:
1855 # TODO(gps): Remove this if nothing needs it anymore.
1856 # A potential user is: tko/parser
1857 self.job.write_to_machines_file(self.queue_entries[0])
1858
1859
1860 def _finish_task(self):
1861 super(QueueTask, self)._finish_task()
1862
1863 for queue_entry in self.queue_entries:
1864 queue_entry.set_status(models.HostQueueEntry.Status.GATHERING)
jamesrenb8f3f352010-06-10 00:44:06 +00001865 queue_entry.host.set_status(models.Host.Status.RUNNING)
mbligh36768f02008-02-22 18:28:33 +00001866
1867
mbligh4608b002010-01-05 18:22:35 +00001868class HostlessQueueTask(AbstractQueueTask):
1869 def __init__(self, queue_entry):
1870 super(HostlessQueueTask, self).__init__([queue_entry])
1871 self.queue_entry_ids = [queue_entry.id]
1872
1873
1874 def prolog(self):
1875 self.queue_entries[0].update_field('execution_subdir', 'hostless')
1876 super(HostlessQueueTask, self).prolog()
1877
1878
mbligh4608b002010-01-05 18:22:35 +00001879 def _finish_task(self):
1880 super(HostlessQueueTask, self)._finish_task()
showardcc929362010-01-25 21:20:41 +00001881 self.queue_entries[0].set_status(models.HostQueueEntry.Status.PARSING)
mbligh4608b002010-01-05 18:22:35 +00001882
1883
showardd3dc1992009-04-22 21:01:40 +00001884class PostJobTask(AgentTask):
showardd1195652009-12-08 22:21:02 +00001885 def __init__(self, queue_entries, log_file_name):
1886 super(PostJobTask, self).__init__(log_file_name=log_file_name)
showardd3dc1992009-04-22 21:01:40 +00001887
showardd1195652009-12-08 22:21:02 +00001888 self.queue_entries = queue_entries
1889
showardd3dc1992009-04-22 21:01:40 +00001890 self._autoserv_monitor = PidfileRunMonitor()
showardd1195652009-12-08 22:21:02 +00001891 self._autoserv_monitor.attach_to_existing_process(
1892 self._working_directory())
showardd3dc1992009-04-22 21:01:40 +00001893
showardd1195652009-12-08 22:21:02 +00001894
1895 def _command_line(self):
showardd3dc1992009-04-22 21:01:40 +00001896 if _testing_mode:
showardd1195652009-12-08 22:21:02 +00001897 return 'true'
1898 return self._generate_command(
1899 _drone_manager.absolute_path(self._working_directory()))
showardd3dc1992009-04-22 21:01:40 +00001900
1901
1902 def _generate_command(self, results_dir):
1903 raise NotImplementedError('Subclasses must override this')
1904
1905
showardd1195652009-12-08 22:21:02 +00001906 @property
1907 def owner_username(self):
1908 return self.queue_entries[0].job.owner
1909
1910
1911 def _working_directory(self):
1912 return self._get_consistent_execution_path(self.queue_entries)
1913
1914
1915 def _paired_with_monitor(self):
1916 return self._autoserv_monitor
1917
1918
showardd3dc1992009-04-22 21:01:40 +00001919 def _job_was_aborted(self):
1920 was_aborted = None
showardd1195652009-12-08 22:21:02 +00001921 for queue_entry in self.queue_entries:
showardd3dc1992009-04-22 21:01:40 +00001922 queue_entry.update_from_database()
1923 if was_aborted is None: # first queue entry
1924 was_aborted = bool(queue_entry.aborted)
1925 elif was_aborted != bool(queue_entry.aborted): # subsequent entries
jamesren17cadd62010-06-16 23:26:55 +00001926 entries = ['%s (aborted: %s)' % (entry, entry.aborted)
1927 for entry in self.queue_entries]
showardd3dc1992009-04-22 21:01:40 +00001928 email_manager.manager.enqueue_notify_email(
jamesren17cadd62010-06-16 23:26:55 +00001929 'Inconsistent abort state',
1930 'Queue entries have inconsistent abort state:\n' +
1931 '\n'.join(entries))
showardd3dc1992009-04-22 21:01:40 +00001932 # don't crash here, just assume true
1933 return True
1934 return was_aborted
1935
1936
showardd1195652009-12-08 22:21:02 +00001937 def _final_status(self):
showardd3dc1992009-04-22 21:01:40 +00001938 if self._job_was_aborted():
1939 return models.HostQueueEntry.Status.ABORTED
1940
1941 # we'll use a PidfileRunMonitor to read the autoserv exit status
1942 if self._autoserv_monitor.exit_code() == 0:
1943 return models.HostQueueEntry.Status.COMPLETED
1944 return models.HostQueueEntry.Status.FAILED
1945
1946
showardd3dc1992009-04-22 21:01:40 +00001947 def _set_all_statuses(self, status):
showardd1195652009-12-08 22:21:02 +00001948 for queue_entry in self.queue_entries:
showardd3dc1992009-04-22 21:01:40 +00001949 queue_entry.set_status(status)
1950
1951
1952 def abort(self):
1953 # override AgentTask.abort() to avoid killing the process and ending
1954 # the task. post-job tasks continue when the job is aborted.
1955 pass
1956
1957
mbligh4608b002010-01-05 18:22:35 +00001958 def _pidfile_label(self):
1959 # '.autoserv_execute' -> 'autoserv'
1960 return self._pidfile_name()[1:-len('_execute')]
1961
1962
showard9bb960b2009-11-19 01:02:11 +00001963class GatherLogsTask(PostJobTask):
showardd3dc1992009-04-22 21:01:40 +00001964 """
1965 Task responsible for
1966 * gathering uncollected logs (if Autoserv crashed hard or was killed)
1967 * copying logs to the results repository
1968 * spawning CleanupTasks for hosts, if necessary
1969 * spawning a FinalReparseTask for the job
1970 """
showardd1195652009-12-08 22:21:02 +00001971 def __init__(self, queue_entries, recover_run_monitor=None):
1972 self._job = queue_entries[0].job
showardd3dc1992009-04-22 21:01:40 +00001973 super(GatherLogsTask, self).__init__(
showardd1195652009-12-08 22:21:02 +00001974 queue_entries, log_file_name='.collect_crashinfo.log')
showardd3dc1992009-04-22 21:01:40 +00001975 self._set_ids(queue_entries=queue_entries)
1976
1977
1978 def _generate_command(self, results_dir):
1979 host_list = ','.join(queue_entry.host.hostname
showardd1195652009-12-08 22:21:02 +00001980 for queue_entry in self.queue_entries)
mbligh4608b002010-01-05 18:22:35 +00001981 return [_autoserv_path , '-p',
1982 '--pidfile-label=%s' % self._pidfile_label(),
1983 '--use-existing-results', '--collect-crashinfo',
1984 '-m', host_list, '-r', results_dir]
showardd3dc1992009-04-22 21:01:40 +00001985
1986
showardd1195652009-12-08 22:21:02 +00001987 @property
1988 def num_processes(self):
1989 return len(self.queue_entries)
1990
1991
1992 def _pidfile_name(self):
jamesrenc44ae992010-02-19 00:12:54 +00001993 return drone_manager.CRASHINFO_PID_FILE
showardd1195652009-12-08 22:21:02 +00001994
1995
showardd3dc1992009-04-22 21:01:40 +00001996 def prolog(self):
mbligh4608b002010-01-05 18:22:35 +00001997 self._check_queue_entry_statuses(
1998 self.queue_entries,
1999 allowed_hqe_statuses=(models.HostQueueEntry.Status.GATHERING,),
2000 allowed_host_statuses=(models.Host.Status.RUNNING,))
showard8cc058f2009-09-08 16:26:33 +00002001
showardd3dc1992009-04-22 21:01:40 +00002002 super(GatherLogsTask, self).prolog()
showardd3dc1992009-04-22 21:01:40 +00002003
2004
showardd3dc1992009-04-22 21:01:40 +00002005 def epilog(self):
2006 super(GatherLogsTask, self).epilog()
mbligh4608b002010-01-05 18:22:35 +00002007 self._parse_results(self.queue_entries)
showard9bb960b2009-11-19 01:02:11 +00002008 self._reboot_hosts()
showard6d1c1432009-08-20 23:30:39 +00002009
showard9bb960b2009-11-19 01:02:11 +00002010
2011 def _reboot_hosts(self):
showard6d1c1432009-08-20 23:30:39 +00002012 if self._autoserv_monitor.has_process():
showardd1195652009-12-08 22:21:02 +00002013 final_success = (self._final_status() ==
showard6d1c1432009-08-20 23:30:39 +00002014 models.HostQueueEntry.Status.COMPLETED)
2015 num_tests_failed = self._autoserv_monitor.num_tests_failed()
2016 else:
2017 final_success = False
2018 num_tests_failed = 0
2019
showard9bb960b2009-11-19 01:02:11 +00002020 reboot_after = self._job.reboot_after
2021 do_reboot = (
2022 # always reboot after aborted jobs
showardd1195652009-12-08 22:21:02 +00002023 self._final_status() == models.HostQueueEntry.Status.ABORTED
jamesrendd855242010-03-02 22:23:44 +00002024 or reboot_after == model_attributes.RebootAfter.ALWAYS
2025 or (reboot_after == model_attributes.RebootAfter.IF_ALL_TESTS_PASSED
showard9bb960b2009-11-19 01:02:11 +00002026 and final_success and num_tests_failed == 0))
2027
showardd1195652009-12-08 22:21:02 +00002028 for queue_entry in self.queue_entries:
showard9bb960b2009-11-19 01:02:11 +00002029 if do_reboot:
2030 # don't pass the queue entry to the CleanupTask. if the cleanup
2031 # fails, the job doesn't care -- it's over.
2032 models.SpecialTask.objects.create(
2033 host=models.Host.objects.get(id=queue_entry.host.id),
2034 task=models.SpecialTask.Task.CLEANUP,
2035 requested_by=self._job.owner_model())
2036 else:
2037 queue_entry.host.set_status(models.Host.Status.READY)
showardd3dc1992009-04-22 21:01:40 +00002038
2039
showard0bbfc212009-04-29 21:06:13 +00002040 def run(self):
showard597bfd32009-05-08 18:22:50 +00002041 autoserv_exit_code = self._autoserv_monitor.exit_code()
2042 # only run if Autoserv exited due to some signal. if we have no exit
2043 # code, assume something bad (and signal-like) happened.
2044 if autoserv_exit_code is None or os.WIFSIGNALED(autoserv_exit_code):
showard0bbfc212009-04-29 21:06:13 +00002045 super(GatherLogsTask, self).run()
showard597bfd32009-05-08 18:22:50 +00002046 else:
2047 self.finished(True)
showard0bbfc212009-04-29 21:06:13 +00002048
2049
mbligh4608b002010-01-05 18:22:35 +00002050class SelfThrottledPostJobTask(PostJobTask):
2051 """
2052 Special AgentTask subclass that maintains its own global process limit.
2053 """
2054 _num_running_processes = 0
showarded2afea2009-07-07 20:54:07 +00002055
2056
mbligh4608b002010-01-05 18:22:35 +00002057 @classmethod
2058 def _increment_running_processes(cls):
2059 cls._num_running_processes += 1
mbligh16c722d2008-03-05 00:58:44 +00002060
mblighd5c95802008-03-05 00:33:46 +00002061
mbligh4608b002010-01-05 18:22:35 +00002062 @classmethod
2063 def _decrement_running_processes(cls):
2064 cls._num_running_processes -= 1
showard8cc058f2009-09-08 16:26:33 +00002065
2066
mbligh4608b002010-01-05 18:22:35 +00002067 @classmethod
2068 def _max_processes(cls):
2069 raise NotImplementedError
2070
2071
2072 @classmethod
2073 def _can_run_new_process(cls):
2074 return cls._num_running_processes < cls._max_processes()
2075
2076
2077 def _process_started(self):
2078 return bool(self.monitor)
2079
2080
2081 def tick(self):
2082 # override tick to keep trying to start until the process count goes
2083 # down and we can, at which point we revert to default behavior
2084 if self._process_started():
2085 super(SelfThrottledPostJobTask, self).tick()
2086 else:
2087 self._try_starting_process()
2088
2089
2090 def run(self):
2091 # override run() to not actually run unless we can
2092 self._try_starting_process()
2093
2094
2095 def _try_starting_process(self):
2096 if not self._can_run_new_process():
showard775300b2009-09-09 15:30:50 +00002097 return
2098
mbligh4608b002010-01-05 18:22:35 +00002099 # actually run the command
2100 super(SelfThrottledPostJobTask, self).run()
jamesren25663562010-04-27 18:00:55 +00002101 if self._process_started():
2102 self._increment_running_processes()
mblighd5c95802008-03-05 00:33:46 +00002103
mblighd5c95802008-03-05 00:33:46 +00002104
mbligh4608b002010-01-05 18:22:35 +00002105 def finished(self, success):
2106 super(SelfThrottledPostJobTask, self).finished(success)
2107 if self._process_started():
2108 self._decrement_running_processes()
showard8cc058f2009-09-08 16:26:33 +00002109
showard21baa452008-10-21 00:08:39 +00002110
mbligh4608b002010-01-05 18:22:35 +00002111class FinalReparseTask(SelfThrottledPostJobTask):
showardd1195652009-12-08 22:21:02 +00002112 def __init__(self, queue_entries):
2113 super(FinalReparseTask, self).__init__(queue_entries,
2114 log_file_name='.parse.log')
showard170873e2009-01-07 00:22:26 +00002115 # don't use _set_ids, since we don't want to set the host_ids
2116 self.queue_entry_ids = [entry.id for entry in queue_entries]
showardd1195652009-12-08 22:21:02 +00002117
2118
2119 def _generate_command(self, results_dir):
mbligh4608b002010-01-05 18:22:35 +00002120 return [_parser_path, '--write-pidfile', '-l', '2', '-r', '-o',
showardd1195652009-12-08 22:21:02 +00002121 results_dir]
2122
2123
2124 @property
2125 def num_processes(self):
2126 return 0 # don't include parser processes in accounting
2127
2128
2129 def _pidfile_name(self):
jamesrenc44ae992010-02-19 00:12:54 +00002130 return drone_manager.PARSER_PID_FILE
showardd1195652009-12-08 22:21:02 +00002131
2132
showard97aed502008-11-04 02:01:24 +00002133 @classmethod
mbligh4608b002010-01-05 18:22:35 +00002134 def _max_processes(cls):
2135 return scheduler_config.config.max_parse_processes
showard97aed502008-11-04 02:01:24 +00002136
2137
2138 def prolog(self):
mbligh4608b002010-01-05 18:22:35 +00002139 self._check_queue_entry_statuses(
2140 self.queue_entries,
2141 allowed_hqe_statuses=(models.HostQueueEntry.Status.PARSING,))
showard8cc058f2009-09-08 16:26:33 +00002142
showard97aed502008-11-04 02:01:24 +00002143 super(FinalReparseTask, self).prolog()
showard97aed502008-11-04 02:01:24 +00002144
2145
2146 def epilog(self):
2147 super(FinalReparseTask, self).epilog()
mbligh4608b002010-01-05 18:22:35 +00002148 self._archive_results(self.queue_entries)
showard97aed502008-11-04 02:01:24 +00002149
2150
mbligh4608b002010-01-05 18:22:35 +00002151class ArchiveResultsTask(SelfThrottledPostJobTask):
showarde1575b52010-01-15 00:21:12 +00002152 _ARCHIVING_FAILED_FILE = '.archiver_failed'
2153
mbligh4608b002010-01-05 18:22:35 +00002154 def __init__(self, queue_entries):
2155 super(ArchiveResultsTask, self).__init__(queue_entries,
2156 log_file_name='.archiving.log')
2157 # don't use _set_ids, since we don't want to set the host_ids
2158 self.queue_entry_ids = [entry.id for entry in queue_entries]
showard97aed502008-11-04 02:01:24 +00002159
2160
mbligh4608b002010-01-05 18:22:35 +00002161 def _pidfile_name(self):
jamesrenc44ae992010-02-19 00:12:54 +00002162 return drone_manager.ARCHIVER_PID_FILE
showard97aed502008-11-04 02:01:24 +00002163
2164
mbligh4608b002010-01-05 18:22:35 +00002165 def _generate_command(self, results_dir):
2166 return [_autoserv_path , '-p',
2167 '--pidfile-label=%s' % self._pidfile_label(), '-r', results_dir,
mblighe0cbc912010-03-11 18:03:07 +00002168 '--use-existing-results', '--control-filename=control.archive',
showard948eb302010-01-15 00:16:20 +00002169 os.path.join(drones.AUTOTEST_INSTALL_DIR, 'scheduler',
2170 'archive_results.control.srv')]
showard97aed502008-11-04 02:01:24 +00002171
2172
mbligh4608b002010-01-05 18:22:35 +00002173 @classmethod
2174 def _max_processes(cls):
2175 return scheduler_config.config.max_transfer_processes
showarda9545c02009-12-18 22:44:26 +00002176
2177
2178 def prolog(self):
mbligh4608b002010-01-05 18:22:35 +00002179 self._check_queue_entry_statuses(
2180 self.queue_entries,
2181 allowed_hqe_statuses=(models.HostQueueEntry.Status.ARCHIVING,))
2182
2183 super(ArchiveResultsTask, self).prolog()
showarda9545c02009-12-18 22:44:26 +00002184
2185
mbligh4608b002010-01-05 18:22:35 +00002186 def epilog(self):
2187 super(ArchiveResultsTask, self).epilog()
showard4076c632010-01-15 20:28:49 +00002188 if not self.success and self._paired_with_monitor().has_process():
showarde1575b52010-01-15 00:21:12 +00002189 failed_file = os.path.join(self._working_directory(),
2190 self._ARCHIVING_FAILED_FILE)
2191 paired_process = self._paired_with_monitor().get_process()
2192 _drone_manager.write_lines_to_file(
2193 failed_file, ['Archiving failed with exit code %s'
2194 % self.monitor.exit_code()],
2195 paired_with_process=paired_process)
mbligh4608b002010-01-05 18:22:35 +00002196 self._set_all_statuses(self._final_status())
showarda9545c02009-12-18 22:44:26 +00002197
2198
mbligh36768f02008-02-22 18:28:33 +00002199if __name__ == '__main__':
jadmanski0afbb632008-06-06 21:10:57 +00002200 main()