blob: 0e95909d02969e3ac27fec9fe37420344a754d76 [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
Yu-Ju Hong52ce11d2012-08-01 17:55:48 -07001060class BaseAgentTask(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 """
Yu-Ju Hong52ce11d2012-08-01 17:55:48 -07001216 Return the number of processes forked by this BaseAgentTask's process.
1217 It may only be approximate. To be overridden if necessary.
showardd1195652009-12-08 22:21:02 +00001218 """
1219 return 1
1220
1221
1222 def _paired_with_monitor(self):
1223 """
Yu-Ju Hong52ce11d2012-08-01 17:55:48 -07001224 If this BaseAgentTask's process must run on the same machine as some
showardd1195652009-12-08 22:21:02 +00001225 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 """
Yu-Ju Hong52ce11d2012-08-01 17:55:48 -07001242 Return the directory where this BaseAgentTask's process executes.
1243 Must be overridden.
showardd1195652009-12-08 22:21:02 +00001244 """
1245 raise NotImplementedError
1246
1247
1248 def _pidfile_name(self):
1249 """
Yu-Ju Hong52ce11d2012-08-01 17:55:48 -07001250 Return the name of the pidfile this BaseAgentTask's process uses. To be
showardd1195652009-12-08 22:21:02 +00001251 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()
Yu-Ju Hong52ce11d2012-08-01 17:55:48 -07001299 assert job_ids.count() == 1, ("BaseAgentTask's queue entries "
jamesren76fcf192010-04-21 20:39:50 +00001300 "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
Yu-Ju Hong52ce11d2012-08-01 17:55:48 -07001375SiteAgentTask = utils.import_site_class(
1376 __file__, 'autotest_lib.scheduler.site_monitor_db',
1377 'SiteAgentTask', BaseAgentTask)
1378
1379class AgentTask(SiteAgentTask):
1380 pass
1381
1382
showardd9205182009-04-27 20:09:55 +00001383class TaskWithJobKeyvals(object):
1384 """AgentTask mixin providing functionality to help with job keyval files."""
1385 _KEYVAL_FILE = 'keyval'
1386 def _format_keyval(self, key, value):
1387 return '%s=%s' % (key, value)
1388
1389
1390 def _keyval_path(self):
1391 """Subclasses must override this"""
lmrb7c5d272010-04-16 06:34:04 +00001392 raise NotImplementedError
showardd9205182009-04-27 20:09:55 +00001393
1394
1395 def _write_keyval_after_job(self, field, value):
1396 assert self.monitor
1397 if not self.monitor.has_process():
1398 return
1399 _drone_manager.write_lines_to_file(
1400 self._keyval_path(), [self._format_keyval(field, value)],
1401 paired_with_process=self.monitor.get_process())
1402
1403
1404 def _job_queued_keyval(self, job):
1405 return 'job_queued', int(time.mktime(job.created_on.timetuple()))
1406
1407
1408 def _write_job_finished(self):
1409 self._write_keyval_after_job("job_finished", int(time.time()))
1410
1411
showarddb502762009-09-09 15:31:20 +00001412 def _write_keyvals_before_job_helper(self, keyval_dict, keyval_path):
1413 keyval_contents = '\n'.join(self._format_keyval(key, value)
1414 for key, value in keyval_dict.iteritems())
1415 # always end with a newline to allow additional keyvals to be written
1416 keyval_contents += '\n'
showard493beaa2009-12-18 22:44:45 +00001417 _drone_manager.attach_file_to_execution(self._working_directory(),
showarddb502762009-09-09 15:31:20 +00001418 keyval_contents,
1419 file_path=keyval_path)
1420
1421
1422 def _write_keyvals_before_job(self, keyval_dict):
1423 self._write_keyvals_before_job_helper(keyval_dict, self._keyval_path())
1424
1425
1426 def _write_host_keyvals(self, host):
showardd1195652009-12-08 22:21:02 +00001427 keyval_path = os.path.join(self._working_directory(), 'host_keyvals',
showarddb502762009-09-09 15:31:20 +00001428 host.hostname)
1429 platform, all_labels = host.platform_and_labels()
Eric Li6f27d4f2010-09-29 10:55:17 -07001430 all_labels = [ urllib.quote(label) for label in all_labels ]
showarddb502762009-09-09 15:31:20 +00001431 keyval_dict = dict(platform=platform, labels=','.join(all_labels))
1432 self._write_keyvals_before_job_helper(keyval_dict, keyval_path)
1433
1434
showard8cc058f2009-09-08 16:26:33 +00001435class SpecialAgentTask(AgentTask, TaskWithJobKeyvals):
showarded2afea2009-07-07 20:54:07 +00001436 """
1437 Subclass for AgentTasks that correspond to a SpecialTask entry in the DB.
1438 """
1439
1440 TASK_TYPE = None
1441 host = None
1442 queue_entry = None
1443
showardd1195652009-12-08 22:21:02 +00001444 def __init__(self, task, extra_command_args):
1445 super(SpecialAgentTask, self).__init__()
1446
lmrb7c5d272010-04-16 06:34:04 +00001447 assert self.TASK_TYPE is not None, 'self.TASK_TYPE must be overridden'
showard8cc058f2009-09-08 16:26:33 +00001448
jamesrenc44ae992010-02-19 00:12:54 +00001449 self.host = scheduler_models.Host(id=task.host.id)
showard8cc058f2009-09-08 16:26:33 +00001450 self.queue_entry = None
1451 if task.queue_entry:
jamesrenc44ae992010-02-19 00:12:54 +00001452 self.queue_entry = scheduler_models.HostQueueEntry(
1453 id=task.queue_entry.id)
showard8cc058f2009-09-08 16:26:33 +00001454
showarded2afea2009-07-07 20:54:07 +00001455 self.task = task
1456 self._extra_command_args = extra_command_args
showarded2afea2009-07-07 20:54:07 +00001457
1458
showard8cc058f2009-09-08 16:26:33 +00001459 def _keyval_path(self):
showardd1195652009-12-08 22:21:02 +00001460 return os.path.join(self._working_directory(), self._KEYVAL_FILE)
1461
1462
1463 def _command_line(self):
1464 return _autoserv_command_line(self.host.hostname,
1465 self._extra_command_args,
1466 queue_entry=self.queue_entry)
1467
1468
1469 def _working_directory(self):
1470 return self.task.execution_path()
1471
1472
1473 @property
1474 def owner_username(self):
1475 if self.task.requested_by:
1476 return self.task.requested_by.login
1477 return None
showard8cc058f2009-09-08 16:26:33 +00001478
1479
showarded2afea2009-07-07 20:54:07 +00001480 def prolog(self):
1481 super(SpecialAgentTask, self).prolog()
showarded2afea2009-07-07 20:54:07 +00001482 self.task.activate()
showarddb502762009-09-09 15:31:20 +00001483 self._write_host_keyvals(self.host)
showarded2afea2009-07-07 20:54:07 +00001484
1485
showardde634ee2009-01-30 01:44:24 +00001486 def _fail_queue_entry(self):
showard2fe3f1d2009-07-06 20:19:11 +00001487 assert self.queue_entry
showardccbd6c52009-03-21 00:10:21 +00001488
showard2fe3f1d2009-07-06 20:19:11 +00001489 if self.queue_entry.meta_host:
showardccbd6c52009-03-21 00:10:21 +00001490 return # don't fail metahost entries, they'll be reassigned
1491
showard2fe3f1d2009-07-06 20:19:11 +00001492 self.queue_entry.update_from_database()
showard8cc058f2009-09-08 16:26:33 +00001493 if self.queue_entry.status != models.HostQueueEntry.Status.QUEUED:
showardccbd6c52009-03-21 00:10:21 +00001494 return # entry has been aborted
1495
showard2fe3f1d2009-07-06 20:19:11 +00001496 self.queue_entry.set_execution_subdir()
showardd9205182009-04-27 20:09:55 +00001497 queued_key, queued_time = self._job_queued_keyval(
showard2fe3f1d2009-07-06 20:19:11 +00001498 self.queue_entry.job)
showardd9205182009-04-27 20:09:55 +00001499 self._write_keyval_after_job(queued_key, queued_time)
1500 self._write_job_finished()
showardcdaeae82009-08-31 18:32:48 +00001501
showard8cc058f2009-09-08 16:26:33 +00001502 # copy results logs into the normal place for job results
showardcdaeae82009-08-31 18:32:48 +00001503 self.monitor.try_copy_results_on_drone(
showardd1195652009-12-08 22:21:02 +00001504 source_path=self._working_directory() + '/',
showardcdaeae82009-08-31 18:32:48 +00001505 destination_path=self.queue_entry.execution_path() + '/')
showard678df4f2009-02-04 21:36:39 +00001506
showard8cc058f2009-09-08 16:26:33 +00001507 pidfile_id = _drone_manager.get_pidfile_id_from(
1508 self.queue_entry.execution_path(),
jamesrenc44ae992010-02-19 00:12:54 +00001509 pidfile_name=drone_manager.AUTOSERV_PID_FILE)
showard8cc058f2009-09-08 16:26:33 +00001510 _drone_manager.register_pidfile(pidfile_id)
mbligh4608b002010-01-05 18:22:35 +00001511
1512 if self.queue_entry.job.parse_failed_repair:
1513 self._parse_results([self.queue_entry])
1514 else:
1515 self._archive_results([self.queue_entry])
showard8cc058f2009-09-08 16:26:33 +00001516
1517
1518 def cleanup(self):
1519 super(SpecialAgentTask, self).cleanup()
showarde60e44e2009-11-13 20:45:38 +00001520
1521 # We will consider an aborted task to be "Failed"
1522 self.task.finish(bool(self.success))
1523
showardf85a0b72009-10-07 20:48:45 +00001524 if self.monitor:
1525 if self.monitor.has_process():
1526 self._copy_results([self.task])
1527 if self.monitor.pidfile_id is not None:
1528 _drone_manager.unregister_pidfile(self.monitor.pidfile_id)
showard8cc058f2009-09-08 16:26:33 +00001529
1530
1531class RepairTask(SpecialAgentTask):
1532 TASK_TYPE = models.SpecialTask.Task.REPAIR
1533
1534
showardd1195652009-12-08 22:21:02 +00001535 def __init__(self, task):
showard8cc058f2009-09-08 16:26:33 +00001536 """\
1537 queue_entry: queue entry to mark failed if this repair fails.
1538 """
1539 protection = host_protections.Protection.get_string(
1540 task.host.protection)
1541 # normalize the protection name
1542 protection = host_protections.Protection.get_attr_name(protection)
1543
1544 super(RepairTask, self).__init__(
showardd1195652009-12-08 22:21:02 +00001545 task, ['-R', '--host-protection', protection])
showard8cc058f2009-09-08 16:26:33 +00001546
1547 # *don't* include the queue entry in IDs -- if the queue entry is
1548 # aborted, we want to leave the repair task running
1549 self._set_ids(host=self.host)
1550
1551
1552 def prolog(self):
1553 super(RepairTask, self).prolog()
1554 logging.info("repair_task starting")
1555 self.host.set_status(models.Host.Status.REPAIRING)
showardde634ee2009-01-30 01:44:24 +00001556
1557
jadmanski0afbb632008-06-06 21:10:57 +00001558 def epilog(self):
1559 super(RepairTask, self).epilog()
showard6d7b2ff2009-06-10 00:16:47 +00001560
jadmanski0afbb632008-06-06 21:10:57 +00001561 if self.success:
showard8cc058f2009-09-08 16:26:33 +00001562 self.host.set_status(models.Host.Status.READY)
jadmanski0afbb632008-06-06 21:10:57 +00001563 else:
showard8cc058f2009-09-08 16:26:33 +00001564 self.host.set_status(models.Host.Status.REPAIR_FAILED)
showard2fe3f1d2009-07-06 20:19:11 +00001565 if self.queue_entry:
showardde634ee2009-01-30 01:44:24 +00001566 self._fail_queue_entry()
mbligh36768f02008-02-22 18:28:33 +00001567
1568
showarded2afea2009-07-07 20:54:07 +00001569class PreJobTask(SpecialAgentTask):
showard775300b2009-09-09 15:30:50 +00001570 def _copy_to_results_repository(self):
1571 if not self.queue_entry or self.queue_entry.meta_host:
1572 return
1573
1574 self.queue_entry.set_execution_subdir()
1575 log_name = os.path.basename(self.task.execution_path())
1576 source = os.path.join(self.task.execution_path(), 'debug',
1577 'autoserv.DEBUG')
1578 destination = os.path.join(
1579 self.queue_entry.execution_path(), log_name)
1580
1581 self.monitor.try_copy_to_results_repository(
1582 source, destination_path=destination)
1583
1584
showard170873e2009-01-07 00:22:26 +00001585 def epilog(self):
1586 super(PreJobTask, self).epilog()
showardcdaeae82009-08-31 18:32:48 +00001587
showard775300b2009-09-09 15:30:50 +00001588 if self.success:
1589 return
showard8fe93b52008-11-18 17:53:22 +00001590
showard775300b2009-09-09 15:30:50 +00001591 self._copy_to_results_repository()
showard8cc058f2009-09-08 16:26:33 +00001592
showard775300b2009-09-09 15:30:50 +00001593 if self.host.protection == host_protections.Protection.DO_NOT_VERIFY:
showard7b2d7cb2009-10-28 19:53:03 +00001594 # effectively ignore failure for these hosts
1595 self.success = True
showard775300b2009-09-09 15:30:50 +00001596 return
1597
1598 if self.queue_entry:
1599 self.queue_entry.requeue()
1600
1601 if models.SpecialTask.objects.filter(
showard8cc058f2009-09-08 16:26:33 +00001602 task=models.SpecialTask.Task.REPAIR,
showard775300b2009-09-09 15:30:50 +00001603 queue_entry__id=self.queue_entry.id):
1604 self.host.set_status(models.Host.Status.REPAIR_FAILED)
1605 self._fail_queue_entry()
1606 return
1607
showard9bb960b2009-11-19 01:02:11 +00001608 queue_entry = models.HostQueueEntry.objects.get(
1609 id=self.queue_entry.id)
showard775300b2009-09-09 15:30:50 +00001610 else:
1611 queue_entry = None
1612
1613 models.SpecialTask.objects.create(
showard9bb960b2009-11-19 01:02:11 +00001614 host=models.Host.objects.get(id=self.host.id),
showard775300b2009-09-09 15:30:50 +00001615 task=models.SpecialTask.Task.REPAIR,
showard9bb960b2009-11-19 01:02:11 +00001616 queue_entry=queue_entry,
1617 requested_by=self.task.requested_by)
showard58721a82009-08-20 23:32:40 +00001618
showard8fe93b52008-11-18 17:53:22 +00001619
1620class VerifyTask(PreJobTask):
showarded2afea2009-07-07 20:54:07 +00001621 TASK_TYPE = models.SpecialTask.Task.VERIFY
1622
1623
showardd1195652009-12-08 22:21:02 +00001624 def __init__(self, task):
1625 super(VerifyTask, self).__init__(task, ['-v'])
showard8cc058f2009-09-08 16:26:33 +00001626 self._set_ids(host=self.host, queue_entries=[self.queue_entry])
mblighe2586682008-02-29 22:45:46 +00001627
1628
jadmanski0afbb632008-06-06 21:10:57 +00001629 def prolog(self):
showard8fe93b52008-11-18 17:53:22 +00001630 super(VerifyTask, self).prolog()
showarded2afea2009-07-07 20:54:07 +00001631
showardb18134f2009-03-20 20:52:18 +00001632 logging.info("starting verify on %s", self.host.hostname)
jadmanski0afbb632008-06-06 21:10:57 +00001633 if self.queue_entry:
showard8cc058f2009-09-08 16:26:33 +00001634 self.queue_entry.set_status(models.HostQueueEntry.Status.VERIFYING)
1635 self.host.set_status(models.Host.Status.VERIFYING)
mbligh36768f02008-02-22 18:28:33 +00001636
jamesren42318f72010-05-10 23:40:59 +00001637 # Delete any queued manual reverifies for this host. One verify will do
showarded2afea2009-07-07 20:54:07 +00001638 # and there's no need to keep records of other requests.
1639 queued_verifies = models.SpecialTask.objects.filter(
showard2fe3f1d2009-07-06 20:19:11 +00001640 host__id=self.host.id,
1641 task=models.SpecialTask.Task.VERIFY,
jamesren42318f72010-05-10 23:40:59 +00001642 is_active=False, is_complete=False, queue_entry=None)
showarded2afea2009-07-07 20:54:07 +00001643 queued_verifies = queued_verifies.exclude(id=self.task.id)
1644 queued_verifies.delete()
showard2fe3f1d2009-07-06 20:19:11 +00001645
mbligh36768f02008-02-22 18:28:33 +00001646
jadmanski0afbb632008-06-06 21:10:57 +00001647 def epilog(self):
1648 super(VerifyTask, self).epilog()
showard2fe3f1d2009-07-06 20:19:11 +00001649 if self.success:
showard8cc058f2009-09-08 16:26:33 +00001650 if self.queue_entry:
1651 self.queue_entry.on_pending()
1652 else:
1653 self.host.set_status(models.Host.Status.READY)
mbligh36768f02008-02-22 18:28:33 +00001654
1655
mbligh4608b002010-01-05 18:22:35 +00001656class CleanupTask(PreJobTask):
1657 # note this can also run post-job, but when it does, it's running standalone
1658 # against the host (not related to the job), so it's not considered a
1659 # PostJobTask
1660
1661 TASK_TYPE = models.SpecialTask.Task.CLEANUP
1662
1663
1664 def __init__(self, task, recover_run_monitor=None):
1665 super(CleanupTask, self).__init__(task, ['--cleanup'])
1666 self._set_ids(host=self.host, queue_entries=[self.queue_entry])
1667
1668
1669 def prolog(self):
1670 super(CleanupTask, self).prolog()
1671 logging.info("starting cleanup task for host: %s", self.host.hostname)
1672 self.host.set_status(models.Host.Status.CLEANING)
1673 if self.queue_entry:
1674 self.queue_entry.set_status(models.HostQueueEntry.Status.VERIFYING)
1675
1676
1677 def _finish_epilog(self):
1678 if not self.queue_entry or not self.success:
1679 return
1680
1681 do_not_verify_protection = host_protections.Protection.DO_NOT_VERIFY
1682 should_run_verify = (
1683 self.queue_entry.job.run_verify
1684 and self.host.protection != do_not_verify_protection)
1685 if should_run_verify:
1686 entry = models.HostQueueEntry.objects.get(id=self.queue_entry.id)
1687 models.SpecialTask.objects.create(
1688 host=models.Host.objects.get(id=self.host.id),
1689 queue_entry=entry,
1690 task=models.SpecialTask.Task.VERIFY)
1691 else:
1692 self.queue_entry.on_pending()
1693
1694
1695 def epilog(self):
1696 super(CleanupTask, self).epilog()
1697
1698 if self.success:
1699 self.host.update_field('dirty', 0)
1700 self.host.set_status(models.Host.Status.READY)
1701
1702 self._finish_epilog()
1703
1704
showarda9545c02009-12-18 22:44:26 +00001705class AbstractQueueTask(AgentTask, TaskWithJobKeyvals):
1706 """
1707 Common functionality for QueueTask and HostlessQueueTask
1708 """
1709 def __init__(self, queue_entries):
1710 super(AbstractQueueTask, self).__init__()
showardd1195652009-12-08 22:21:02 +00001711 self.job = queue_entries[0].job
jadmanski0afbb632008-06-06 21:10:57 +00001712 self.queue_entries = queue_entries
mbligh36768f02008-02-22 18:28:33 +00001713
1714
showard73ec0442009-02-07 02:05:20 +00001715 def _keyval_path(self):
showardd1195652009-12-08 22:21:02 +00001716 return os.path.join(self._working_directory(), self._KEYVAL_FILE)
showard73ec0442009-02-07 02:05:20 +00001717
1718
jamesrenc44ae992010-02-19 00:12:54 +00001719 def _write_control_file(self, execution_path):
1720 control_path = _drone_manager.attach_file_to_execution(
1721 execution_path, self.job.control_file)
1722 return control_path
1723
1724
showardd1195652009-12-08 22:21:02 +00001725 def _command_line(self):
jamesrenc44ae992010-02-19 00:12:54 +00001726 execution_path = self.queue_entries[0].execution_path()
1727 control_path = self._write_control_file(execution_path)
1728 hostnames = ','.join(entry.host.hostname
1729 for entry in self.queue_entries
1730 if not entry.is_hostless())
1731
1732 execution_tag = self.queue_entries[0].execution_tag()
1733 params = _autoserv_command_line(
1734 hostnames,
1735 ['-P', execution_tag, '-n',
1736 _drone_manager.absolute_path(control_path)],
1737 job=self.job, verbose=False)
1738
1739 if not self.job.is_server_job():
1740 params.append('-c')
1741
Dale Curtis30cb8eb2011-06-09 12:22:26 -07001742 if self.job.is_image_update_job():
1743 params += ['--image', self.job.update_image_path]
1744
jamesrenc44ae992010-02-19 00:12:54 +00001745 return params
showardd1195652009-12-08 22:21:02 +00001746
1747
1748 @property
1749 def num_processes(self):
1750 return len(self.queue_entries)
1751
1752
1753 @property
1754 def owner_username(self):
1755 return self.job.owner
1756
1757
1758 def _working_directory(self):
1759 return self._get_consistent_execution_path(self.queue_entries)
mblighbb421852008-03-11 22:36:16 +00001760
1761
jadmanski0afbb632008-06-06 21:10:57 +00001762 def prolog(self):
showardd9205182009-04-27 20:09:55 +00001763 queued_key, queued_time = self._job_queued_keyval(self.job)
showardc1a98d12010-01-15 00:22:22 +00001764 keyval_dict = self.job.keyval_dict()
1765 keyval_dict[queued_key] = queued_time
showardd1195652009-12-08 22:21:02 +00001766 group_name = self.queue_entries[0].get_group_name()
1767 if group_name:
1768 keyval_dict['host_group_name'] = group_name
showardf1ae3542009-05-11 19:26:02 +00001769 self._write_keyvals_before_job(keyval_dict)
jadmanski0afbb632008-06-06 21:10:57 +00001770 for queue_entry in self.queue_entries:
showard8cc058f2009-09-08 16:26:33 +00001771 queue_entry.set_status(models.HostQueueEntry.Status.RUNNING)
showarda9545c02009-12-18 22:44:26 +00001772 queue_entry.set_started_on_now()
mbligh36768f02008-02-22 18:28:33 +00001773
1774
showard35162b02009-03-03 02:17:30 +00001775 def _write_lost_process_error_file(self):
showardd1195652009-12-08 22:21:02 +00001776 error_file_path = os.path.join(self._working_directory(), 'job_failure')
showard35162b02009-03-03 02:17:30 +00001777 _drone_manager.write_lines_to_file(error_file_path,
1778 [_LOST_PROCESS_ERROR])
1779
1780
showardd3dc1992009-04-22 21:01:40 +00001781 def _finish_task(self):
showard08a36412009-05-05 01:01:13 +00001782 if not self.monitor:
1783 return
1784
showardd9205182009-04-27 20:09:55 +00001785 self._write_job_finished()
1786
showard35162b02009-03-03 02:17:30 +00001787 if self.monitor.lost_process:
1788 self._write_lost_process_error_file()
showard4ac47542009-08-31 18:32:19 +00001789
jadmanskif7fa2cc2008-10-01 14:13:23 +00001790
showardcbd74612008-11-19 21:42:02 +00001791 def _write_status_comment(self, comment):
showard170873e2009-01-07 00:22:26 +00001792 _drone_manager.write_lines_to_file(
showardd1195652009-12-08 22:21:02 +00001793 os.path.join(self._working_directory(), 'status.log'),
showard170873e2009-01-07 00:22:26 +00001794 ['INFO\t----\t----\t' + comment],
showard35162b02009-03-03 02:17:30 +00001795 paired_with_process=self.monitor.get_process())
showardcbd74612008-11-19 21:42:02 +00001796
1797
jadmanskif7fa2cc2008-10-01 14:13:23 +00001798 def _log_abort(self):
showard170873e2009-01-07 00:22:26 +00001799 if not self.monitor or not self.monitor.has_process():
1800 return
1801
jadmanskif7fa2cc2008-10-01 14:13:23 +00001802 # build up sets of all the aborted_by and aborted_on values
1803 aborted_by, aborted_on = set(), set()
1804 for queue_entry in self.queue_entries:
1805 if queue_entry.aborted_by:
1806 aborted_by.add(queue_entry.aborted_by)
1807 t = int(time.mktime(queue_entry.aborted_on.timetuple()))
1808 aborted_on.add(t)
1809
1810 # extract some actual, unique aborted by value and write it out
showard64a95952010-01-13 21:27:16 +00001811 # TODO(showard): this conditional is now obsolete, we just need to leave
1812 # it in temporarily for backwards compatibility over upgrades. delete
1813 # soon.
jadmanskif7fa2cc2008-10-01 14:13:23 +00001814 assert len(aborted_by) <= 1
1815 if len(aborted_by) == 1:
showardcbd74612008-11-19 21:42:02 +00001816 aborted_by_value = aborted_by.pop()
1817 aborted_on_value = max(aborted_on)
1818 else:
1819 aborted_by_value = 'autotest_system'
1820 aborted_on_value = int(time.time())
showard170873e2009-01-07 00:22:26 +00001821
showarda0382352009-02-11 23:36:43 +00001822 self._write_keyval_after_job("aborted_by", aborted_by_value)
1823 self._write_keyval_after_job("aborted_on", aborted_on_value)
showard170873e2009-01-07 00:22:26 +00001824
showardcbd74612008-11-19 21:42:02 +00001825 aborted_on_string = str(datetime.datetime.fromtimestamp(
1826 aborted_on_value))
1827 self._write_status_comment('Job aborted by %s on %s' %
1828 (aborted_by_value, aborted_on_string))
jadmanskic2ac77f2008-05-16 21:44:04 +00001829
1830
jadmanski0afbb632008-06-06 21:10:57 +00001831 def abort(self):
showarda9545c02009-12-18 22:44:26 +00001832 super(AbstractQueueTask, self).abort()
jadmanskif7fa2cc2008-10-01 14:13:23 +00001833 self._log_abort()
showardd3dc1992009-04-22 21:01:40 +00001834 self._finish_task()
showard21baa452008-10-21 00:08:39 +00001835
1836
jadmanski0afbb632008-06-06 21:10:57 +00001837 def epilog(self):
showarda9545c02009-12-18 22:44:26 +00001838 super(AbstractQueueTask, self).epilog()
showardd3dc1992009-04-22 21:01:40 +00001839 self._finish_task()
showarda9545c02009-12-18 22:44:26 +00001840
1841
1842class QueueTask(AbstractQueueTask):
1843 def __init__(self, queue_entries):
1844 super(QueueTask, self).__init__(queue_entries)
1845 self._set_ids(queue_entries=queue_entries)
1846
1847
1848 def prolog(self):
mbligh4608b002010-01-05 18:22:35 +00001849 self._check_queue_entry_statuses(
1850 self.queue_entries,
1851 allowed_hqe_statuses=(models.HostQueueEntry.Status.STARTING,
1852 models.HostQueueEntry.Status.RUNNING),
1853 allowed_host_statuses=(models.Host.Status.PENDING,
1854 models.Host.Status.RUNNING))
showarda9545c02009-12-18 22:44:26 +00001855
1856 super(QueueTask, self).prolog()
1857
1858 for queue_entry in self.queue_entries:
1859 self._write_host_keyvals(queue_entry.host)
1860 queue_entry.host.set_status(models.Host.Status.RUNNING)
1861 queue_entry.host.update_field('dirty', 1)
1862 if self.job.synch_count == 1 and len(self.queue_entries) == 1:
1863 # TODO(gps): Remove this if nothing needs it anymore.
1864 # A potential user is: tko/parser
1865 self.job.write_to_machines_file(self.queue_entries[0])
1866
1867
1868 def _finish_task(self):
1869 super(QueueTask, self)._finish_task()
1870
1871 for queue_entry in self.queue_entries:
1872 queue_entry.set_status(models.HostQueueEntry.Status.GATHERING)
jamesrenb8f3f352010-06-10 00:44:06 +00001873 queue_entry.host.set_status(models.Host.Status.RUNNING)
mbligh36768f02008-02-22 18:28:33 +00001874
1875
mbligh4608b002010-01-05 18:22:35 +00001876class HostlessQueueTask(AbstractQueueTask):
1877 def __init__(self, queue_entry):
1878 super(HostlessQueueTask, self).__init__([queue_entry])
1879 self.queue_entry_ids = [queue_entry.id]
1880
1881
1882 def prolog(self):
1883 self.queue_entries[0].update_field('execution_subdir', 'hostless')
1884 super(HostlessQueueTask, self).prolog()
1885
1886
mbligh4608b002010-01-05 18:22:35 +00001887 def _finish_task(self):
1888 super(HostlessQueueTask, self)._finish_task()
showardcc929362010-01-25 21:20:41 +00001889 self.queue_entries[0].set_status(models.HostQueueEntry.Status.PARSING)
mbligh4608b002010-01-05 18:22:35 +00001890
1891
showardd3dc1992009-04-22 21:01:40 +00001892class PostJobTask(AgentTask):
showardd1195652009-12-08 22:21:02 +00001893 def __init__(self, queue_entries, log_file_name):
1894 super(PostJobTask, self).__init__(log_file_name=log_file_name)
showardd3dc1992009-04-22 21:01:40 +00001895
showardd1195652009-12-08 22:21:02 +00001896 self.queue_entries = queue_entries
1897
showardd3dc1992009-04-22 21:01:40 +00001898 self._autoserv_monitor = PidfileRunMonitor()
showardd1195652009-12-08 22:21:02 +00001899 self._autoserv_monitor.attach_to_existing_process(
1900 self._working_directory())
showardd3dc1992009-04-22 21:01:40 +00001901
showardd1195652009-12-08 22:21:02 +00001902
1903 def _command_line(self):
showardd3dc1992009-04-22 21:01:40 +00001904 if _testing_mode:
showardd1195652009-12-08 22:21:02 +00001905 return 'true'
1906 return self._generate_command(
1907 _drone_manager.absolute_path(self._working_directory()))
showardd3dc1992009-04-22 21:01:40 +00001908
1909
1910 def _generate_command(self, results_dir):
1911 raise NotImplementedError('Subclasses must override this')
1912
1913
showardd1195652009-12-08 22:21:02 +00001914 @property
1915 def owner_username(self):
1916 return self.queue_entries[0].job.owner
1917
1918
1919 def _working_directory(self):
1920 return self._get_consistent_execution_path(self.queue_entries)
1921
1922
1923 def _paired_with_monitor(self):
1924 return self._autoserv_monitor
1925
1926
showardd3dc1992009-04-22 21:01:40 +00001927 def _job_was_aborted(self):
1928 was_aborted = None
showardd1195652009-12-08 22:21:02 +00001929 for queue_entry in self.queue_entries:
showardd3dc1992009-04-22 21:01:40 +00001930 queue_entry.update_from_database()
1931 if was_aborted is None: # first queue entry
1932 was_aborted = bool(queue_entry.aborted)
1933 elif was_aborted != bool(queue_entry.aborted): # subsequent entries
jamesren17cadd62010-06-16 23:26:55 +00001934 entries = ['%s (aborted: %s)' % (entry, entry.aborted)
1935 for entry in self.queue_entries]
showardd3dc1992009-04-22 21:01:40 +00001936 email_manager.manager.enqueue_notify_email(
jamesren17cadd62010-06-16 23:26:55 +00001937 'Inconsistent abort state',
1938 'Queue entries have inconsistent abort state:\n' +
1939 '\n'.join(entries))
showardd3dc1992009-04-22 21:01:40 +00001940 # don't crash here, just assume true
1941 return True
1942 return was_aborted
1943
1944
showardd1195652009-12-08 22:21:02 +00001945 def _final_status(self):
showardd3dc1992009-04-22 21:01:40 +00001946 if self._job_was_aborted():
1947 return models.HostQueueEntry.Status.ABORTED
1948
1949 # we'll use a PidfileRunMonitor to read the autoserv exit status
1950 if self._autoserv_monitor.exit_code() == 0:
1951 return models.HostQueueEntry.Status.COMPLETED
1952 return models.HostQueueEntry.Status.FAILED
1953
1954
showardd3dc1992009-04-22 21:01:40 +00001955 def _set_all_statuses(self, status):
showardd1195652009-12-08 22:21:02 +00001956 for queue_entry in self.queue_entries:
showardd3dc1992009-04-22 21:01:40 +00001957 queue_entry.set_status(status)
1958
1959
1960 def abort(self):
1961 # override AgentTask.abort() to avoid killing the process and ending
1962 # the task. post-job tasks continue when the job is aborted.
1963 pass
1964
1965
mbligh4608b002010-01-05 18:22:35 +00001966 def _pidfile_label(self):
1967 # '.autoserv_execute' -> 'autoserv'
1968 return self._pidfile_name()[1:-len('_execute')]
1969
1970
showard9bb960b2009-11-19 01:02:11 +00001971class GatherLogsTask(PostJobTask):
showardd3dc1992009-04-22 21:01:40 +00001972 """
1973 Task responsible for
1974 * gathering uncollected logs (if Autoserv crashed hard or was killed)
1975 * copying logs to the results repository
1976 * spawning CleanupTasks for hosts, if necessary
1977 * spawning a FinalReparseTask for the job
1978 """
showardd1195652009-12-08 22:21:02 +00001979 def __init__(self, queue_entries, recover_run_monitor=None):
1980 self._job = queue_entries[0].job
showardd3dc1992009-04-22 21:01:40 +00001981 super(GatherLogsTask, self).__init__(
showardd1195652009-12-08 22:21:02 +00001982 queue_entries, log_file_name='.collect_crashinfo.log')
showardd3dc1992009-04-22 21:01:40 +00001983 self._set_ids(queue_entries=queue_entries)
1984
1985
1986 def _generate_command(self, results_dir):
1987 host_list = ','.join(queue_entry.host.hostname
showardd1195652009-12-08 22:21:02 +00001988 for queue_entry in self.queue_entries)
mbligh4608b002010-01-05 18:22:35 +00001989 return [_autoserv_path , '-p',
1990 '--pidfile-label=%s' % self._pidfile_label(),
1991 '--use-existing-results', '--collect-crashinfo',
1992 '-m', host_list, '-r', results_dir]
showardd3dc1992009-04-22 21:01:40 +00001993
1994
showardd1195652009-12-08 22:21:02 +00001995 @property
1996 def num_processes(self):
1997 return len(self.queue_entries)
1998
1999
2000 def _pidfile_name(self):
jamesrenc44ae992010-02-19 00:12:54 +00002001 return drone_manager.CRASHINFO_PID_FILE
showardd1195652009-12-08 22:21:02 +00002002
2003
showardd3dc1992009-04-22 21:01:40 +00002004 def prolog(self):
mbligh4608b002010-01-05 18:22:35 +00002005 self._check_queue_entry_statuses(
2006 self.queue_entries,
2007 allowed_hqe_statuses=(models.HostQueueEntry.Status.GATHERING,),
2008 allowed_host_statuses=(models.Host.Status.RUNNING,))
showard8cc058f2009-09-08 16:26:33 +00002009
showardd3dc1992009-04-22 21:01:40 +00002010 super(GatherLogsTask, self).prolog()
showardd3dc1992009-04-22 21:01:40 +00002011
2012
showardd3dc1992009-04-22 21:01:40 +00002013 def epilog(self):
2014 super(GatherLogsTask, self).epilog()
mbligh4608b002010-01-05 18:22:35 +00002015 self._parse_results(self.queue_entries)
showard9bb960b2009-11-19 01:02:11 +00002016 self._reboot_hosts()
showard6d1c1432009-08-20 23:30:39 +00002017
showard9bb960b2009-11-19 01:02:11 +00002018
2019 def _reboot_hosts(self):
showard6d1c1432009-08-20 23:30:39 +00002020 if self._autoserv_monitor.has_process():
showardd1195652009-12-08 22:21:02 +00002021 final_success = (self._final_status() ==
showard6d1c1432009-08-20 23:30:39 +00002022 models.HostQueueEntry.Status.COMPLETED)
2023 num_tests_failed = self._autoserv_monitor.num_tests_failed()
2024 else:
2025 final_success = False
2026 num_tests_failed = 0
2027
showard9bb960b2009-11-19 01:02:11 +00002028 reboot_after = self._job.reboot_after
2029 do_reboot = (
2030 # always reboot after aborted jobs
showardd1195652009-12-08 22:21:02 +00002031 self._final_status() == models.HostQueueEntry.Status.ABORTED
jamesrendd855242010-03-02 22:23:44 +00002032 or reboot_after == model_attributes.RebootAfter.ALWAYS
2033 or (reboot_after == model_attributes.RebootAfter.IF_ALL_TESTS_PASSED
showard9bb960b2009-11-19 01:02:11 +00002034 and final_success and num_tests_failed == 0))
2035
showardd1195652009-12-08 22:21:02 +00002036 for queue_entry in self.queue_entries:
showard9bb960b2009-11-19 01:02:11 +00002037 if do_reboot:
2038 # don't pass the queue entry to the CleanupTask. if the cleanup
2039 # fails, the job doesn't care -- it's over.
2040 models.SpecialTask.objects.create(
2041 host=models.Host.objects.get(id=queue_entry.host.id),
2042 task=models.SpecialTask.Task.CLEANUP,
2043 requested_by=self._job.owner_model())
2044 else:
2045 queue_entry.host.set_status(models.Host.Status.READY)
showardd3dc1992009-04-22 21:01:40 +00002046
2047
showard0bbfc212009-04-29 21:06:13 +00002048 def run(self):
showard597bfd32009-05-08 18:22:50 +00002049 autoserv_exit_code = self._autoserv_monitor.exit_code()
2050 # only run if Autoserv exited due to some signal. if we have no exit
2051 # code, assume something bad (and signal-like) happened.
2052 if autoserv_exit_code is None or os.WIFSIGNALED(autoserv_exit_code):
showard0bbfc212009-04-29 21:06:13 +00002053 super(GatherLogsTask, self).run()
showard597bfd32009-05-08 18:22:50 +00002054 else:
2055 self.finished(True)
showard0bbfc212009-04-29 21:06:13 +00002056
2057
mbligh4608b002010-01-05 18:22:35 +00002058class SelfThrottledPostJobTask(PostJobTask):
2059 """
2060 Special AgentTask subclass that maintains its own global process limit.
2061 """
2062 _num_running_processes = 0
showarded2afea2009-07-07 20:54:07 +00002063
2064
mbligh4608b002010-01-05 18:22:35 +00002065 @classmethod
2066 def _increment_running_processes(cls):
2067 cls._num_running_processes += 1
mbligh16c722d2008-03-05 00:58:44 +00002068
mblighd5c95802008-03-05 00:33:46 +00002069
mbligh4608b002010-01-05 18:22:35 +00002070 @classmethod
2071 def _decrement_running_processes(cls):
2072 cls._num_running_processes -= 1
showard8cc058f2009-09-08 16:26:33 +00002073
2074
mbligh4608b002010-01-05 18:22:35 +00002075 @classmethod
2076 def _max_processes(cls):
2077 raise NotImplementedError
2078
2079
2080 @classmethod
2081 def _can_run_new_process(cls):
2082 return cls._num_running_processes < cls._max_processes()
2083
2084
2085 def _process_started(self):
2086 return bool(self.monitor)
2087
2088
2089 def tick(self):
2090 # override tick to keep trying to start until the process count goes
2091 # down and we can, at which point we revert to default behavior
2092 if self._process_started():
2093 super(SelfThrottledPostJobTask, self).tick()
2094 else:
2095 self._try_starting_process()
2096
2097
2098 def run(self):
2099 # override run() to not actually run unless we can
2100 self._try_starting_process()
2101
2102
2103 def _try_starting_process(self):
2104 if not self._can_run_new_process():
showard775300b2009-09-09 15:30:50 +00002105 return
2106
mbligh4608b002010-01-05 18:22:35 +00002107 # actually run the command
2108 super(SelfThrottledPostJobTask, self).run()
jamesren25663562010-04-27 18:00:55 +00002109 if self._process_started():
2110 self._increment_running_processes()
mblighd5c95802008-03-05 00:33:46 +00002111
mblighd5c95802008-03-05 00:33:46 +00002112
mbligh4608b002010-01-05 18:22:35 +00002113 def finished(self, success):
2114 super(SelfThrottledPostJobTask, self).finished(success)
2115 if self._process_started():
2116 self._decrement_running_processes()
showard8cc058f2009-09-08 16:26:33 +00002117
showard21baa452008-10-21 00:08:39 +00002118
mbligh4608b002010-01-05 18:22:35 +00002119class FinalReparseTask(SelfThrottledPostJobTask):
showardd1195652009-12-08 22:21:02 +00002120 def __init__(self, queue_entries):
2121 super(FinalReparseTask, self).__init__(queue_entries,
2122 log_file_name='.parse.log')
showard170873e2009-01-07 00:22:26 +00002123 # don't use _set_ids, since we don't want to set the host_ids
2124 self.queue_entry_ids = [entry.id for entry in queue_entries]
showardd1195652009-12-08 22:21:02 +00002125
2126
2127 def _generate_command(self, results_dir):
mbligh4608b002010-01-05 18:22:35 +00002128 return [_parser_path, '--write-pidfile', '-l', '2', '-r', '-o',
showardd1195652009-12-08 22:21:02 +00002129 results_dir]
2130
2131
2132 @property
2133 def num_processes(self):
2134 return 0 # don't include parser processes in accounting
2135
2136
2137 def _pidfile_name(self):
jamesrenc44ae992010-02-19 00:12:54 +00002138 return drone_manager.PARSER_PID_FILE
showardd1195652009-12-08 22:21:02 +00002139
2140
showard97aed502008-11-04 02:01:24 +00002141 @classmethod
mbligh4608b002010-01-05 18:22:35 +00002142 def _max_processes(cls):
2143 return scheduler_config.config.max_parse_processes
showard97aed502008-11-04 02:01:24 +00002144
2145
2146 def prolog(self):
mbligh4608b002010-01-05 18:22:35 +00002147 self._check_queue_entry_statuses(
2148 self.queue_entries,
2149 allowed_hqe_statuses=(models.HostQueueEntry.Status.PARSING,))
showard8cc058f2009-09-08 16:26:33 +00002150
showard97aed502008-11-04 02:01:24 +00002151 super(FinalReparseTask, self).prolog()
showard97aed502008-11-04 02:01:24 +00002152
2153
2154 def epilog(self):
2155 super(FinalReparseTask, self).epilog()
mbligh4608b002010-01-05 18:22:35 +00002156 self._archive_results(self.queue_entries)
showard97aed502008-11-04 02:01:24 +00002157
2158
mbligh4608b002010-01-05 18:22:35 +00002159class ArchiveResultsTask(SelfThrottledPostJobTask):
showarde1575b52010-01-15 00:21:12 +00002160 _ARCHIVING_FAILED_FILE = '.archiver_failed'
2161
mbligh4608b002010-01-05 18:22:35 +00002162 def __init__(self, queue_entries):
2163 super(ArchiveResultsTask, self).__init__(queue_entries,
2164 log_file_name='.archiving.log')
2165 # don't use _set_ids, since we don't want to set the host_ids
2166 self.queue_entry_ids = [entry.id for entry in queue_entries]
showard97aed502008-11-04 02:01:24 +00002167
2168
mbligh4608b002010-01-05 18:22:35 +00002169 def _pidfile_name(self):
jamesrenc44ae992010-02-19 00:12:54 +00002170 return drone_manager.ARCHIVER_PID_FILE
showard97aed502008-11-04 02:01:24 +00002171
2172
mbligh4608b002010-01-05 18:22:35 +00002173 def _generate_command(self, results_dir):
2174 return [_autoserv_path , '-p',
2175 '--pidfile-label=%s' % self._pidfile_label(), '-r', results_dir,
mblighe0cbc912010-03-11 18:03:07 +00002176 '--use-existing-results', '--control-filename=control.archive',
showard948eb302010-01-15 00:16:20 +00002177 os.path.join(drones.AUTOTEST_INSTALL_DIR, 'scheduler',
2178 'archive_results.control.srv')]
showard97aed502008-11-04 02:01:24 +00002179
2180
mbligh4608b002010-01-05 18:22:35 +00002181 @classmethod
2182 def _max_processes(cls):
2183 return scheduler_config.config.max_transfer_processes
showarda9545c02009-12-18 22:44:26 +00002184
2185
2186 def prolog(self):
mbligh4608b002010-01-05 18:22:35 +00002187 self._check_queue_entry_statuses(
2188 self.queue_entries,
2189 allowed_hqe_statuses=(models.HostQueueEntry.Status.ARCHIVING,))
2190
2191 super(ArchiveResultsTask, self).prolog()
showarda9545c02009-12-18 22:44:26 +00002192
2193
mbligh4608b002010-01-05 18:22:35 +00002194 def epilog(self):
2195 super(ArchiveResultsTask, self).epilog()
showard4076c632010-01-15 20:28:49 +00002196 if not self.success and self._paired_with_monitor().has_process():
showarde1575b52010-01-15 00:21:12 +00002197 failed_file = os.path.join(self._working_directory(),
2198 self._ARCHIVING_FAILED_FILE)
2199 paired_process = self._paired_with_monitor().get_process()
2200 _drone_manager.write_lines_to_file(
2201 failed_file, ['Archiving failed with exit code %s'
2202 % self.monitor.exit_code()],
2203 paired_with_process=paired_process)
mbligh4608b002010-01-05 18:22:35 +00002204 self._set_all_statuses(self._final_status())
showarda9545c02009-12-18 22:44:26 +00002205
2206
mbligh36768f02008-02-22 18:28:33 +00002207if __name__ == '__main__':
jadmanski0afbb632008-06-06 21:10:57 +00002208 main()