blob: 403ea381098e97293a12c59af73f79e5b5f580f8 [file] [log] [blame]
showardce38e0c2008-05-29 19:36:16 +00001#!/usr/bin/python
Dan Shid0e09ab2013-09-09 15:28:55 -07002#pylint: disable-msg=C0111
showardce38e0c2008-05-29 19:36:16 +00003
Dan Shid0e09ab2013-09-09 15:28:55 -07004import gc, time
showardce38e0c2008-05-29 19:36:16 +00005import common
showard364fe862008-10-17 02:01:16 +00006from autotest_lib.frontend import setup_django_environment
showardb6d16622009-05-26 19:35:29 +00007from autotest_lib.frontend.afe import frontend_test_utils
jadmanski3d161b02008-06-06 15:43:36 +00008from autotest_lib.client.common_lib.test_utils import mock
showardf13a9e22009-12-18 22:54:09 +00009from autotest_lib.client.common_lib.test_utils import unittest
jamesrenc44ae992010-02-19 00:12:54 +000010from autotest_lib.database import database_connection
showardb1e51872008-10-07 11:08:18 +000011from autotest_lib.frontend.afe import models
beeps5e2bb4a2013-10-28 11:26:45 -070012from autotest_lib.scheduler import agent_task
showard170873e2009-01-07 00:22:26 +000013from autotest_lib.scheduler import monitor_db, drone_manager, email_manager
beeps5e2bb4a2013-10-28 11:26:45 -070014from autotest_lib.scheduler import pidfile_monitor
Dale Curtisaa513362011-03-01 17:27:44 -080015from autotest_lib.scheduler import scheduler_config, gc_stats, host_scheduler
showard78f5b012009-12-23 00:05:59 +000016from autotest_lib.scheduler import monitor_db_functional_test
jamesrenc44ae992010-02-19 00:12:54 +000017from autotest_lib.scheduler import scheduler_models
showardce38e0c2008-05-29 19:36:16 +000018
19_DEBUG = False
20
showarda3c58572009-03-12 20:36:59 +000021
showard9bb960b2009-11-19 01:02:11 +000022class DummyAgentTask(object):
showardd1195652009-12-08 22:21:02 +000023 num_processes = 1
24 owner_username = 'my_user'
showard9bb960b2009-11-19 01:02:11 +000025
jamesren76fcf192010-04-21 20:39:50 +000026 def get_drone_hostnames_allowed(self):
27 return None
28
showard9bb960b2009-11-19 01:02:11 +000029
showard170873e2009-01-07 00:22:26 +000030class DummyAgent(object):
showard8cc058f2009-09-08 16:26:33 +000031 started = False
showard170873e2009-01-07 00:22:26 +000032 _is_done = False
showardd1195652009-12-08 22:21:02 +000033 host_ids = ()
34 queue_entry_ids = ()
35
36 def __init__(self):
37 self.task = DummyAgentTask()
showard170873e2009-01-07 00:22:26 +000038
showard170873e2009-01-07 00:22:26 +000039
40 def tick(self):
showard8cc058f2009-09-08 16:26:33 +000041 self.started = True
showard170873e2009-01-07 00:22:26 +000042
43
44 def is_done(self):
45 return self._is_done
46
47
48 def set_done(self, done):
49 self._is_done = done
showard04c82c52008-05-29 19:38:12 +000050
showard56193bb2008-08-13 20:07:41 +000051
52class IsRow(mock.argument_comparator):
53 def __init__(self, row_id):
54 self.row_id = row_id
showardce38e0c2008-05-29 19:36:16 +000055
56
showard56193bb2008-08-13 20:07:41 +000057 def is_satisfied_by(self, parameter):
58 return list(parameter)[0] == self.row_id
59
60
61 def __str__(self):
62 return 'row with id %s' % self.row_id
63
64
showardd3dc1992009-04-22 21:01:40 +000065class IsAgentWithTask(mock.argument_comparator):
mbligh1ef218d2009-08-03 16:57:56 +000066 def __init__(self, task):
67 self._task = task
showardd3dc1992009-04-22 21:01:40 +000068
69
mbligh1ef218d2009-08-03 16:57:56 +000070 def is_satisfied_by(self, parameter):
71 if not isinstance(parameter, monitor_db.Agent):
72 return False
73 tasks = list(parameter.queue.queue)
74 if len(tasks) != 1:
75 return False
76 return tasks[0] == self._task
showardd3dc1992009-04-22 21:01:40 +000077
78
showard6b733412009-04-27 20:09:18 +000079def _set_host_and_qe_ids(agent_or_task, id_list=None):
80 if id_list is None:
81 id_list = []
82 agent_or_task.host_ids = agent_or_task.queue_entry_ids = id_list
83
84
showardb6d16622009-05-26 19:35:29 +000085class BaseSchedulerTest(unittest.TestCase,
86 frontend_test_utils.FrontendTestMixin):
showard50c0e712008-09-22 16:20:37 +000087 _config_section = 'AUTOTEST_WEB'
showardce38e0c2008-05-29 19:36:16 +000088
jadmanski0afbb632008-06-06 21:10:57 +000089 def _do_query(self, sql):
showardb1e51872008-10-07 11:08:18 +000090 self._database.execute(sql)
showardce38e0c2008-05-29 19:36:16 +000091
92
showardb6d16622009-05-26 19:35:29 +000093 def _set_monitor_stubs(self):
94 # Clear the instance cache as this is a brand new database.
jamesrenc44ae992010-02-19 00:12:54 +000095 scheduler_models.DBObject._clear_instance_cache()
showardce38e0c2008-05-29 19:36:16 +000096
showardb1e51872008-10-07 11:08:18 +000097 self._database = (
showard78f5b012009-12-23 00:05:59 +000098 database_connection.TranslatingDatabase.get_test_database(
99 translators=monitor_db_functional_test._DB_TRANSLATORS))
100 self._database.connect(db_type='django')
showardb1e51872008-10-07 11:08:18 +0000101 self._database.debug = _DEBUG
showardce38e0c2008-05-29 19:36:16 +0000102
showard78f5b012009-12-23 00:05:59 +0000103 self.god.stub_with(monitor_db, '_db', self._database)
beeps7d8a1b12013-10-29 17:58:34 -0700104 self.god.stub_with(monitor_db.BaseDispatcher,
105 '_get_pending_queue_entries',
106 self._get_pending_hqes)
jamesrenc44ae992010-02-19 00:12:54 +0000107 self.god.stub_with(scheduler_models, '_db', self._database)
108 self.god.stub_with(drone_manager.instance(), '_results_dir',
showard78f5b012009-12-23 00:05:59 +0000109 '/test/path')
jamesrenc44ae992010-02-19 00:12:54 +0000110 self.god.stub_with(drone_manager.instance(), '_temporary_directory',
showard78f5b012009-12-23 00:05:59 +0000111 '/test/path/tmp')
showard56193bb2008-08-13 20:07:41 +0000112
jamesrenc44ae992010-02-19 00:12:54 +0000113 monitor_db.initialize_globals()
114 scheduler_models.initialize_globals()
115
showard56193bb2008-08-13 20:07:41 +0000116
showard56193bb2008-08-13 20:07:41 +0000117 def setUp(self):
showardb6d16622009-05-26 19:35:29 +0000118 self._frontend_common_setup()
showard56193bb2008-08-13 20:07:41 +0000119 self._set_monitor_stubs()
120 self._dispatcher = monitor_db.Dispatcher()
showardce38e0c2008-05-29 19:36:16 +0000121
122
showard56193bb2008-08-13 20:07:41 +0000123 def tearDown(self):
showardb6d16622009-05-26 19:35:29 +0000124 self._database.disconnect()
125 self._frontend_common_teardown()
showardce38e0c2008-05-29 19:36:16 +0000126
127
showard56193bb2008-08-13 20:07:41 +0000128 def _update_hqe(self, set, where=''):
showardeab66ce2009-12-23 00:03:56 +0000129 query = 'UPDATE afe_host_queue_entries SET ' + set
showard56193bb2008-08-13 20:07:41 +0000130 if where:
131 query += ' WHERE ' + where
132 self._do_query(query)
133
134
beeps7d8a1b12013-10-29 17:58:34 -0700135 def _get_pending_hqes(self):
136 query_string=('afe_jobs.priority DESC, '
137 'ifnull(nullif(host_id, NULL), host_id) DESC, '
138 'ifnull(nullif(meta_host, NULL), meta_host) DESC, '
139 'job_id')
140 return list(scheduler_models.HostQueueEntry.fetch(
141 joins='INNER JOIN afe_jobs ON (job_id=afe_jobs.id)',
142 where='NOT complete AND NOT active AND status="Queued"',
143 order_by=query_string))
144
145
showardb2e2c322008-10-14 17:33:55 +0000146class DispatcherSchedulingTest(BaseSchedulerTest):
showard56193bb2008-08-13 20:07:41 +0000147 _jobs_scheduled = []
148
showard89f84db2009-03-12 20:39:13 +0000149
150 def tearDown(self):
151 super(DispatcherSchedulingTest, self).tearDown()
152
153
showard56193bb2008-08-13 20:07:41 +0000154 def _set_monitor_stubs(self):
155 super(DispatcherSchedulingTest, self)._set_monitor_stubs()
showard89f84db2009-03-12 20:39:13 +0000156
showard8cc058f2009-09-08 16:26:33 +0000157 def hqe__do_schedule_pre_job_tasks_stub(queue_entry):
158 """Called by HostQueueEntry.run()."""
showard77182562009-06-10 00:16:05 +0000159 self._record_job_scheduled(queue_entry.job.id, queue_entry.host.id)
showard89f84db2009-03-12 20:39:13 +0000160 queue_entry.set_status('Starting')
showard89f84db2009-03-12 20:39:13 +0000161
jamesrenc44ae992010-02-19 00:12:54 +0000162 self.god.stub_with(scheduler_models.HostQueueEntry,
showard8cc058f2009-09-08 16:26:33 +0000163 '_do_schedule_pre_job_tasks',
164 hqe__do_schedule_pre_job_tasks_stub)
showard89f84db2009-03-12 20:39:13 +0000165
showard56193bb2008-08-13 20:07:41 +0000166
167 def _record_job_scheduled(self, job_id, host_id):
168 record = (job_id, host_id)
169 self.assert_(record not in self._jobs_scheduled,
170 'Job %d scheduled on host %d twice' %
171 (job_id, host_id))
172 self._jobs_scheduled.append(record)
173
174
175 def _assert_job_scheduled_on(self, job_id, host_id):
176 record = (job_id, host_id)
177 self.assert_(record in self._jobs_scheduled,
178 'Job %d not scheduled on host %d as expected\n'
179 'Jobs scheduled: %s' %
180 (job_id, host_id, self._jobs_scheduled))
181 self._jobs_scheduled.remove(record)
182
183
showard89f84db2009-03-12 20:39:13 +0000184 def _assert_job_scheduled_on_number_of(self, job_id, host_ids, number):
185 """Assert job was scheduled on exactly number hosts out of a set."""
186 found = []
187 for host_id in host_ids:
188 record = (job_id, host_id)
189 if record in self._jobs_scheduled:
190 found.append(record)
191 self._jobs_scheduled.remove(record)
192 if len(found) < number:
193 self.fail('Job %d scheduled on fewer than %d hosts in %s.\n'
194 'Jobs scheduled: %s' % (job_id, number, host_ids, found))
195 elif len(found) > number:
196 self.fail('Job %d scheduled on more than %d hosts in %s.\n'
197 'Jobs scheduled: %s' % (job_id, number, host_ids, found))
198
199
showard56193bb2008-08-13 20:07:41 +0000200 def _check_for_extra_schedulings(self):
201 if len(self._jobs_scheduled) != 0:
202 self.fail('Extra jobs scheduled: ' +
203 str(self._jobs_scheduled))
204
205
jadmanski0afbb632008-06-06 21:10:57 +0000206 def _convert_jobs_to_metahosts(self, *job_ids):
207 sql_tuple = '(' + ','.join(str(i) for i in job_ids) + ')'
showardeab66ce2009-12-23 00:03:56 +0000208 self._do_query('UPDATE afe_host_queue_entries SET '
jadmanski0afbb632008-06-06 21:10:57 +0000209 'meta_host=host_id, host_id=NULL '
210 'WHERE job_id IN ' + sql_tuple)
showardce38e0c2008-05-29 19:36:16 +0000211
212
jadmanski0afbb632008-06-06 21:10:57 +0000213 def _lock_host(self, host_id):
showardeab66ce2009-12-23 00:03:56 +0000214 self._do_query('UPDATE afe_hosts SET locked=1 WHERE id=' +
jadmanski0afbb632008-06-06 21:10:57 +0000215 str(host_id))
showardce38e0c2008-05-29 19:36:16 +0000216
217
jadmanski0afbb632008-06-06 21:10:57 +0000218 def setUp(self):
showard56193bb2008-08-13 20:07:41 +0000219 super(DispatcherSchedulingTest, self).setUp()
jadmanski0afbb632008-06-06 21:10:57 +0000220 self._jobs_scheduled = []
showardce38e0c2008-05-29 19:36:16 +0000221
222
jamesren883492a2010-02-12 00:45:18 +0000223 def _run_scheduler(self):
224 for _ in xrange(2): # metahost scheduling can take two cycles
225 self._dispatcher._schedule_new_jobs()
226
227
jadmanski0afbb632008-06-06 21:10:57 +0000228 def _test_basic_scheduling_helper(self, use_metahosts):
229 'Basic nonmetahost scheduling'
230 self._create_job_simple([1], use_metahosts)
231 self._create_job_simple([2], use_metahosts)
jamesren883492a2010-02-12 00:45:18 +0000232 self._run_scheduler()
jadmanski0afbb632008-06-06 21:10:57 +0000233 self._assert_job_scheduled_on(1, 1)
234 self._assert_job_scheduled_on(2, 2)
235 self._check_for_extra_schedulings()
showardce38e0c2008-05-29 19:36:16 +0000236
237
jadmanski0afbb632008-06-06 21:10:57 +0000238 def _test_priorities_helper(self, use_metahosts):
239 'Test prioritization ordering'
240 self._create_job_simple([1], use_metahosts)
241 self._create_job_simple([2], use_metahosts)
242 self._create_job_simple([1,2], use_metahosts)
243 self._create_job_simple([1], use_metahosts, priority=1)
jamesren883492a2010-02-12 00:45:18 +0000244 self._run_scheduler()
jadmanski0afbb632008-06-06 21:10:57 +0000245 self._assert_job_scheduled_on(4, 1) # higher priority
246 self._assert_job_scheduled_on(2, 2) # earlier job over later
247 self._check_for_extra_schedulings()
showardce38e0c2008-05-29 19:36:16 +0000248
249
jadmanski0afbb632008-06-06 21:10:57 +0000250 def _test_hosts_ready_helper(self, use_metahosts):
251 """
252 Only hosts that are status=Ready, unlocked and not invalid get
253 scheduled.
254 """
255 self._create_job_simple([1], use_metahosts)
showardeab66ce2009-12-23 00:03:56 +0000256 self._do_query('UPDATE afe_hosts SET status="Running" WHERE id=1')
jamesren883492a2010-02-12 00:45:18 +0000257 self._run_scheduler()
jadmanski0afbb632008-06-06 21:10:57 +0000258 self._check_for_extra_schedulings()
showardce38e0c2008-05-29 19:36:16 +0000259
showardeab66ce2009-12-23 00:03:56 +0000260 self._do_query('UPDATE afe_hosts SET status="Ready", locked=1 '
jadmanski0afbb632008-06-06 21:10:57 +0000261 'WHERE id=1')
jamesren883492a2010-02-12 00:45:18 +0000262 self._run_scheduler()
jadmanski0afbb632008-06-06 21:10:57 +0000263 self._check_for_extra_schedulings()
showardce38e0c2008-05-29 19:36:16 +0000264
showardeab66ce2009-12-23 00:03:56 +0000265 self._do_query('UPDATE afe_hosts SET locked=0, invalid=1 '
jadmanski0afbb632008-06-06 21:10:57 +0000266 'WHERE id=1')
jamesren883492a2010-02-12 00:45:18 +0000267 self._run_scheduler()
showard5df2b192008-07-03 19:51:57 +0000268 if not use_metahosts:
269 self._assert_job_scheduled_on(1, 1)
jadmanski0afbb632008-06-06 21:10:57 +0000270 self._check_for_extra_schedulings()
showardce38e0c2008-05-29 19:36:16 +0000271
272
jadmanski0afbb632008-06-06 21:10:57 +0000273 def _test_hosts_idle_helper(self, use_metahosts):
274 'Only idle hosts get scheduled'
showard2bab8f42008-11-12 18:15:22 +0000275 self._create_job(hosts=[1], active=True)
jadmanski0afbb632008-06-06 21:10:57 +0000276 self._create_job_simple([1], use_metahosts)
jamesren883492a2010-02-12 00:45:18 +0000277 self._run_scheduler()
jadmanski0afbb632008-06-06 21:10:57 +0000278 self._check_for_extra_schedulings()
showardce38e0c2008-05-29 19:36:16 +0000279
280
showard63a34772008-08-18 19:32:50 +0000281 def _test_obey_ACLs_helper(self, use_metahosts):
showardeab66ce2009-12-23 00:03:56 +0000282 self._do_query('DELETE FROM afe_acl_groups_hosts WHERE host_id=1')
showard63a34772008-08-18 19:32:50 +0000283 self._create_job_simple([1], use_metahosts)
jamesren883492a2010-02-12 00:45:18 +0000284 self._run_scheduler()
showard63a34772008-08-18 19:32:50 +0000285 self._check_for_extra_schedulings()
286
287
jadmanski0afbb632008-06-06 21:10:57 +0000288 def test_basic_scheduling(self):
289 self._test_basic_scheduling_helper(False)
showardce38e0c2008-05-29 19:36:16 +0000290
291
jadmanski0afbb632008-06-06 21:10:57 +0000292 def test_priorities(self):
293 self._test_priorities_helper(False)
showardce38e0c2008-05-29 19:36:16 +0000294
295
jadmanski0afbb632008-06-06 21:10:57 +0000296 def test_hosts_ready(self):
297 self._test_hosts_ready_helper(False)
showardce38e0c2008-05-29 19:36:16 +0000298
299
jadmanski0afbb632008-06-06 21:10:57 +0000300 def test_hosts_idle(self):
301 self._test_hosts_idle_helper(False)
showardce38e0c2008-05-29 19:36:16 +0000302
303
showard63a34772008-08-18 19:32:50 +0000304 def test_obey_ACLs(self):
305 self._test_obey_ACLs_helper(False)
306
307
showard2924b0a2009-06-18 23:16:15 +0000308 def test_one_time_hosts_ignore_ACLs(self):
showardeab66ce2009-12-23 00:03:56 +0000309 self._do_query('DELETE FROM afe_acl_groups_hosts WHERE host_id=1')
310 self._do_query('UPDATE afe_hosts SET invalid=1 WHERE id=1')
showard2924b0a2009-06-18 23:16:15 +0000311 self._create_job_simple([1])
jamesren883492a2010-02-12 00:45:18 +0000312 self._run_scheduler()
showard2924b0a2009-06-18 23:16:15 +0000313 self._assert_job_scheduled_on(1, 1)
314 self._check_for_extra_schedulings()
315
316
showard63a34772008-08-18 19:32:50 +0000317 def test_non_metahost_on_invalid_host(self):
318 """
319 Non-metahost entries can get scheduled on invalid hosts (this is how
320 one-time hosts work).
321 """
showardeab66ce2009-12-23 00:03:56 +0000322 self._do_query('UPDATE afe_hosts SET invalid=1')
showard63a34772008-08-18 19:32:50 +0000323 self._test_basic_scheduling_helper(False)
324
325
jadmanski0afbb632008-06-06 21:10:57 +0000326 def test_metahost_scheduling(self):
showard63a34772008-08-18 19:32:50 +0000327 """
328 Basic metahost scheduling
329 """
jadmanski0afbb632008-06-06 21:10:57 +0000330 self._test_basic_scheduling_helper(True)
showardce38e0c2008-05-29 19:36:16 +0000331
332
jadmanski0afbb632008-06-06 21:10:57 +0000333 def test_metahost_priorities(self):
334 self._test_priorities_helper(True)
showardce38e0c2008-05-29 19:36:16 +0000335
336
jadmanski0afbb632008-06-06 21:10:57 +0000337 def test_metahost_hosts_ready(self):
338 self._test_hosts_ready_helper(True)
showardce38e0c2008-05-29 19:36:16 +0000339
340
jadmanski0afbb632008-06-06 21:10:57 +0000341 def test_metahost_hosts_idle(self):
342 self._test_hosts_idle_helper(True)
showardce38e0c2008-05-29 19:36:16 +0000343
344
showard63a34772008-08-18 19:32:50 +0000345 def test_metahost_obey_ACLs(self):
346 self._test_obey_ACLs_helper(True)
347
348
jadmanski0afbb632008-06-06 21:10:57 +0000349 def test_nonmetahost_over_metahost(self):
350 """
351 Non-metahost entries should take priority over metahost entries
352 for the same host
353 """
354 self._create_job(metahosts=[1])
355 self._create_job(hosts=[1])
jamesren883492a2010-02-12 00:45:18 +0000356 self._run_scheduler()
jadmanski0afbb632008-06-06 21:10:57 +0000357 self._assert_job_scheduled_on(2, 1)
358 self._check_for_extra_schedulings()
showardce38e0c2008-05-29 19:36:16 +0000359
360
Aviv Keshet1f23b692013-05-14 11:13:55 -0700361# TODO: Revive this test.
362# def test_HostScheduler_get_host_atomic_group_id(self):
363# job = self._create_job(metahosts=[self.label6.id])
364# queue_entry = scheduler_models.HostQueueEntry.fetch(
365# where='job_id=%d' % job.id)[0]
366# # Indirectly initialize the internal state of the host scheduler.
367# self._dispatcher._refresh_pending_queue_entries()
368#
369# # Test the host scheduler
370# host_scheduler = self._dispatcher._host_scheduler
371#
372#
373# # Two labels each in a different atomic group. This should log an
374# # error and continue.
375# orig_logging_error = logging.error
376# def mock_logging_error(message, *args):
377# mock_logging_error._num_calls += 1
378# # Test the logging call itself, we just wrapped it to count it.
379# orig_logging_error(message, *args)
380# mock_logging_error._num_calls = 0
381# self.god.stub_with(logging, 'error', mock_logging_error)
382# host_scheduler.refresh([])
383# self.assertNotEquals(None, host_scheduler._get_host_atomic_group_id(
384# [self.label4.id, self.label8.id], queue_entry))
385# self.assertTrue(mock_logging_error._num_calls > 0)
386# self.god.unstub(logging, 'error')
beeps7d8a1b12013-10-29 17:58:34 -0700387#
Aviv Keshet1f23b692013-05-14 11:13:55 -0700388# # Two labels both in the same atomic group, this should not raise an
389# # error, it will merely cause the job to schedule on the intersection.
390# self.assertEquals(1, host_scheduler._get_host_atomic_group_id(
391# [self.label4.id, self.label5.id]))
392#
393# self.assertEquals(None, host_scheduler._get_host_atomic_group_id([]))
394# self.assertEquals(None, host_scheduler._get_host_atomic_group_id(
395# [self.label3.id, self.label7.id, self.label6.id]))
396# self.assertEquals(1, host_scheduler._get_host_atomic_group_id(
397# [self.label4.id, self.label7.id, self.label6.id]))
398# self.assertEquals(1, host_scheduler._get_host_atomic_group_id(
399# [self.label7.id, self.label5.id]))
showard89f84db2009-03-12 20:39:13 +0000400
showard56193bb2008-08-13 20:07:41 +0000401 def test_only_schedule_queued_entries(self):
402 self._create_job(metahosts=[1])
403 self._update_hqe(set='active=1, host_id=2')
jamesren883492a2010-02-12 00:45:18 +0000404 self._run_scheduler()
showard56193bb2008-08-13 20:07:41 +0000405 self._check_for_extra_schedulings()
406
407
showardfa8629c2008-11-04 16:51:23 +0000408 def test_no_ready_hosts(self):
409 self._create_job(hosts=[1])
showardeab66ce2009-12-23 00:03:56 +0000410 self._do_query('UPDATE afe_hosts SET status="Repair Failed"')
jamesren883492a2010-02-12 00:45:18 +0000411 self._run_scheduler()
showardfa8629c2008-11-04 16:51:23 +0000412 self._check_for_extra_schedulings()
413
414
showardf13a9e22009-12-18 22:54:09 +0000415 def test_garbage_collection(self):
416 self.god.stub_with(self._dispatcher, '_seconds_between_garbage_stats',
417 999999)
418 self.god.stub_function(gc, 'collect')
419 self.god.stub_function(gc_stats, '_log_garbage_collector_stats')
420 gc.collect.expect_call().and_return(0)
421 gc_stats._log_garbage_collector_stats.expect_call()
422 # Force a garbage collection run
423 self._dispatcher._last_garbage_stats_time = 0
424 self._dispatcher._garbage_collection()
425 # The previous call should have reset the time, it won't do anything
426 # the second time. If it does, we'll get an unexpected call.
427 self._dispatcher._garbage_collection()
428
429
430
showardb2e2c322008-10-14 17:33:55 +0000431class DispatcherThrottlingTest(BaseSchedulerTest):
showard4c5374f2008-09-04 17:02:56 +0000432 """
433 Test that the dispatcher throttles:
434 * total number of running processes
435 * number of processes started per cycle
436 """
437 _MAX_RUNNING = 3
438 _MAX_STARTED = 2
439
440 def setUp(self):
441 super(DispatcherThrottlingTest, self).setUp()
showard324bf812009-01-20 23:23:38 +0000442 scheduler_config.config.max_processes_per_drone = self._MAX_RUNNING
showardd1ee1dd2009-01-07 21:33:08 +0000443 scheduler_config.config.max_processes_started_per_cycle = (
444 self._MAX_STARTED)
showard4c5374f2008-09-04 17:02:56 +0000445
jamesren76fcf192010-04-21 20:39:50 +0000446 def fake_max_runnable_processes(fake_self, username,
447 drone_hostnames_allowed):
showardd1195652009-12-08 22:21:02 +0000448 running = sum(agent.task.num_processes
showard324bf812009-01-20 23:23:38 +0000449 for agent in self._agents
showard8cc058f2009-09-08 16:26:33 +0000450 if agent.started and not agent.is_done())
showard324bf812009-01-20 23:23:38 +0000451 return self._MAX_RUNNING - running
452 self.god.stub_with(drone_manager.DroneManager, 'max_runnable_processes',
453 fake_max_runnable_processes)
showard2fa51692009-01-13 23:48:08 +0000454
showard4c5374f2008-09-04 17:02:56 +0000455
showard4c5374f2008-09-04 17:02:56 +0000456 def _setup_some_agents(self, num_agents):
showard170873e2009-01-07 00:22:26 +0000457 self._agents = [DummyAgent() for i in xrange(num_agents)]
showard4c5374f2008-09-04 17:02:56 +0000458 self._dispatcher._agents = list(self._agents)
459
460
461 def _run_a_few_cycles(self):
462 for i in xrange(4):
463 self._dispatcher._handle_agents()
464
465
466 def _assert_agents_started(self, indexes, is_started=True):
467 for i in indexes:
showard8cc058f2009-09-08 16:26:33 +0000468 self.assert_(self._agents[i].started == is_started,
showard4c5374f2008-09-04 17:02:56 +0000469 'Agent %d %sstarted' %
470 (i, is_started and 'not ' or ''))
471
472
473 def _assert_agents_not_started(self, indexes):
474 self._assert_agents_started(indexes, False)
475
476
477 def test_throttle_total(self):
478 self._setup_some_agents(4)
479 self._run_a_few_cycles()
480 self._assert_agents_started([0, 1, 2])
481 self._assert_agents_not_started([3])
482
483
484 def test_throttle_per_cycle(self):
485 self._setup_some_agents(3)
486 self._dispatcher._handle_agents()
487 self._assert_agents_started([0, 1])
488 self._assert_agents_not_started([2])
489
490
491 def test_throttle_with_synchronous(self):
492 self._setup_some_agents(2)
showardd1195652009-12-08 22:21:02 +0000493 self._agents[0].task.num_processes = 3
showard4c5374f2008-09-04 17:02:56 +0000494 self._run_a_few_cycles()
495 self._assert_agents_started([0])
496 self._assert_agents_not_started([1])
497
498
499 def test_large_agent_starvation(self):
500 """
501 Ensure large agents don't get starved by lower-priority agents.
502 """
503 self._setup_some_agents(3)
showardd1195652009-12-08 22:21:02 +0000504 self._agents[1].task.num_processes = 3
showard4c5374f2008-09-04 17:02:56 +0000505 self._run_a_few_cycles()
506 self._assert_agents_started([0])
507 self._assert_agents_not_started([1, 2])
508
509 self._agents[0].set_done(True)
510 self._run_a_few_cycles()
511 self._assert_agents_started([1])
512 self._assert_agents_not_started([2])
513
514
515 def test_zero_process_agent(self):
516 self._setup_some_agents(5)
showardd1195652009-12-08 22:21:02 +0000517 self._agents[4].task.num_processes = 0
showard4c5374f2008-09-04 17:02:56 +0000518 self._run_a_few_cycles()
519 self._assert_agents_started([0, 1, 2, 4])
520 self._assert_agents_not_started([3])
521
522
jadmanski3d161b02008-06-06 15:43:36 +0000523class PidfileRunMonitorTest(unittest.TestCase):
showard170873e2009-01-07 00:22:26 +0000524 execution_tag = 'test_tag'
jadmanski0afbb632008-06-06 21:10:57 +0000525 pid = 12345
showard170873e2009-01-07 00:22:26 +0000526 process = drone_manager.Process('myhost', pid)
showard21baa452008-10-21 00:08:39 +0000527 num_tests_failed = 1
jadmanski3d161b02008-06-06 15:43:36 +0000528
jadmanski0afbb632008-06-06 21:10:57 +0000529 def setUp(self):
530 self.god = mock.mock_god()
showard170873e2009-01-07 00:22:26 +0000531 self.mock_drone_manager = self.god.create_mock_class(
532 drone_manager.DroneManager, 'drone_manager')
beeps5e2bb4a2013-10-28 11:26:45 -0700533 self.god.stub_with(pidfile_monitor, '_drone_manager',
showard170873e2009-01-07 00:22:26 +0000534 self.mock_drone_manager)
535 self.god.stub_function(email_manager.manager, 'enqueue_notify_email')
beeps5e2bb4a2013-10-28 11:26:45 -0700536 self.god.stub_with(pidfile_monitor, '_get_pidfile_timeout_secs',
showardec6a3b92009-09-25 20:29:13 +0000537 self._mock_get_pidfile_timeout_secs)
showard170873e2009-01-07 00:22:26 +0000538
539 self.pidfile_id = object()
540
showardd3dc1992009-04-22 21:01:40 +0000541 (self.mock_drone_manager.get_pidfile_id_from
542 .expect_call(self.execution_tag,
jamesrenc44ae992010-02-19 00:12:54 +0000543 pidfile_name=drone_manager.AUTOSERV_PID_FILE)
showardd3dc1992009-04-22 21:01:40 +0000544 .and_return(self.pidfile_id))
showard170873e2009-01-07 00:22:26 +0000545
beeps5e2bb4a2013-10-28 11:26:45 -0700546 self.monitor = pidfile_monitor.PidfileRunMonitor()
showard170873e2009-01-07 00:22:26 +0000547 self.monitor.attach_to_existing_process(self.execution_tag)
jadmanski3d161b02008-06-06 15:43:36 +0000548
jadmanski0afbb632008-06-06 21:10:57 +0000549 def tearDown(self):
550 self.god.unstub_all()
jadmanski3d161b02008-06-06 15:43:36 +0000551
552
showardec6a3b92009-09-25 20:29:13 +0000553 def _mock_get_pidfile_timeout_secs(self):
554 return 300
555
556
showard170873e2009-01-07 00:22:26 +0000557 def setup_pidfile(self, pid=None, exit_code=None, tests_failed=None,
558 use_second_read=False):
559 contents = drone_manager.PidfileContents()
560 if pid is not None:
561 contents.process = drone_manager.Process('myhost', pid)
562 contents.exit_status = exit_code
563 contents.num_tests_failed = tests_failed
564 self.mock_drone_manager.get_pidfile_contents.expect_call(
565 self.pidfile_id, use_second_read=use_second_read).and_return(
566 contents)
567
568
jadmanski0afbb632008-06-06 21:10:57 +0000569 def set_not_yet_run(self):
showard170873e2009-01-07 00:22:26 +0000570 self.setup_pidfile()
jadmanski3d161b02008-06-06 15:43:36 +0000571
572
showard3dd6b882008-10-27 19:21:39 +0000573 def set_empty_pidfile(self):
showard170873e2009-01-07 00:22:26 +0000574 self.setup_pidfile()
showard3dd6b882008-10-27 19:21:39 +0000575
576
showard170873e2009-01-07 00:22:26 +0000577 def set_running(self, use_second_read=False):
578 self.setup_pidfile(self.pid, use_second_read=use_second_read)
jadmanski3d161b02008-06-06 15:43:36 +0000579
580
showard170873e2009-01-07 00:22:26 +0000581 def set_complete(self, error_code, use_second_read=False):
582 self.setup_pidfile(self.pid, error_code, self.num_tests_failed,
583 use_second_read=use_second_read)
584
585
586 def _check_monitor(self, expected_pid, expected_exit_status,
587 expected_num_tests_failed):
588 if expected_pid is None:
589 self.assertEquals(self.monitor._state.process, None)
590 else:
591 self.assertEquals(self.monitor._state.process.pid, expected_pid)
592 self.assertEquals(self.monitor._state.exit_status, expected_exit_status)
593 self.assertEquals(self.monitor._state.num_tests_failed,
594 expected_num_tests_failed)
595
596
597 self.god.check_playback()
jadmanski3d161b02008-06-06 15:43:36 +0000598
599
showard21baa452008-10-21 00:08:39 +0000600 def _test_read_pidfile_helper(self, expected_pid, expected_exit_status,
601 expected_num_tests_failed):
602 self.monitor._read_pidfile()
showard170873e2009-01-07 00:22:26 +0000603 self._check_monitor(expected_pid, expected_exit_status,
604 expected_num_tests_failed)
jadmanski3d161b02008-06-06 15:43:36 +0000605
606
showard21baa452008-10-21 00:08:39 +0000607 def _get_expected_tests_failed(self, expected_exit_status):
608 if expected_exit_status is None:
609 expected_tests_failed = None
610 else:
611 expected_tests_failed = self.num_tests_failed
612 return expected_tests_failed
613
614
jadmanski0afbb632008-06-06 21:10:57 +0000615 def test_read_pidfile(self):
616 self.set_not_yet_run()
showard21baa452008-10-21 00:08:39 +0000617 self._test_read_pidfile_helper(None, None, None)
jadmanski3d161b02008-06-06 15:43:36 +0000618
showard3dd6b882008-10-27 19:21:39 +0000619 self.set_empty_pidfile()
620 self._test_read_pidfile_helper(None, None, None)
621
jadmanski0afbb632008-06-06 21:10:57 +0000622 self.set_running()
showard21baa452008-10-21 00:08:39 +0000623 self._test_read_pidfile_helper(self.pid, None, None)
jadmanski3d161b02008-06-06 15:43:36 +0000624
jadmanski0afbb632008-06-06 21:10:57 +0000625 self.set_complete(123)
showard21baa452008-10-21 00:08:39 +0000626 self._test_read_pidfile_helper(self.pid, 123, self.num_tests_failed)
jadmanski3d161b02008-06-06 15:43:36 +0000627
628
jadmanski0afbb632008-06-06 21:10:57 +0000629 def test_read_pidfile_error(self):
showard170873e2009-01-07 00:22:26 +0000630 self.mock_drone_manager.get_pidfile_contents.expect_call(
631 self.pidfile_id, use_second_read=False).and_return(
632 drone_manager.InvalidPidfile('error'))
beeps5e2bb4a2013-10-28 11:26:45 -0700633 self.assertRaises(pidfile_monitor.PidfileRunMonitor._PidfileException,
showard21baa452008-10-21 00:08:39 +0000634 self.monitor._read_pidfile)
jadmanski0afbb632008-06-06 21:10:57 +0000635 self.god.check_playback()
jadmanski3d161b02008-06-06 15:43:36 +0000636
637
showard170873e2009-01-07 00:22:26 +0000638 def setup_is_running(self, is_running):
639 self.mock_drone_manager.is_process_running.expect_call(
640 self.process).and_return(is_running)
jadmanski3d161b02008-06-06 15:43:36 +0000641
642
showard21baa452008-10-21 00:08:39 +0000643 def _test_get_pidfile_info_helper(self, expected_pid, expected_exit_status,
644 expected_num_tests_failed):
645 self.monitor._get_pidfile_info()
showard170873e2009-01-07 00:22:26 +0000646 self._check_monitor(expected_pid, expected_exit_status,
647 expected_num_tests_failed)
jadmanski3d161b02008-06-06 15:43:36 +0000648
649
jadmanski0afbb632008-06-06 21:10:57 +0000650 def test_get_pidfile_info(self):
showard21baa452008-10-21 00:08:39 +0000651 """
652 normal cases for get_pidfile_info
653 """
jadmanski0afbb632008-06-06 21:10:57 +0000654 # running
655 self.set_running()
showard170873e2009-01-07 00:22:26 +0000656 self.setup_is_running(True)
showard21baa452008-10-21 00:08:39 +0000657 self._test_get_pidfile_info_helper(self.pid, None, None)
jadmanski3d161b02008-06-06 15:43:36 +0000658
jadmanski0afbb632008-06-06 21:10:57 +0000659 # exited during check
660 self.set_running()
showard170873e2009-01-07 00:22:26 +0000661 self.setup_is_running(False)
662 self.set_complete(123, use_second_read=True) # pidfile gets read again
showard21baa452008-10-21 00:08:39 +0000663 self._test_get_pidfile_info_helper(self.pid, 123, self.num_tests_failed)
jadmanski3d161b02008-06-06 15:43:36 +0000664
jadmanski0afbb632008-06-06 21:10:57 +0000665 # completed
666 self.set_complete(123)
showard21baa452008-10-21 00:08:39 +0000667 self._test_get_pidfile_info_helper(self.pid, 123, self.num_tests_failed)
jadmanski3d161b02008-06-06 15:43:36 +0000668
669
jadmanski0afbb632008-06-06 21:10:57 +0000670 def test_get_pidfile_info_running_no_proc(self):
showard21baa452008-10-21 00:08:39 +0000671 """
672 pidfile shows process running, but no proc exists
673 """
jadmanski0afbb632008-06-06 21:10:57 +0000674 # running but no proc
675 self.set_running()
showard170873e2009-01-07 00:22:26 +0000676 self.setup_is_running(False)
677 self.set_running(use_second_read=True)
678 email_manager.manager.enqueue_notify_email.expect_call(
jadmanski0afbb632008-06-06 21:10:57 +0000679 mock.is_string_comparator(), mock.is_string_comparator())
showard21baa452008-10-21 00:08:39 +0000680 self._test_get_pidfile_info_helper(self.pid, 1, 0)
jadmanski0afbb632008-06-06 21:10:57 +0000681 self.assertTrue(self.monitor.lost_process)
jadmanski3d161b02008-06-06 15:43:36 +0000682
683
jadmanski0afbb632008-06-06 21:10:57 +0000684 def test_get_pidfile_info_not_yet_run(self):
showard21baa452008-10-21 00:08:39 +0000685 """
686 pidfile hasn't been written yet
687 """
jadmanski0afbb632008-06-06 21:10:57 +0000688 self.set_not_yet_run()
showard21baa452008-10-21 00:08:39 +0000689 self._test_get_pidfile_info_helper(None, None, None)
jadmanski3d161b02008-06-06 15:43:36 +0000690
jadmanski3d161b02008-06-06 15:43:36 +0000691
showard170873e2009-01-07 00:22:26 +0000692 def test_process_failed_to_write_pidfile(self):
jadmanski0afbb632008-06-06 21:10:57 +0000693 self.set_not_yet_run()
showard170873e2009-01-07 00:22:26 +0000694 email_manager.manager.enqueue_notify_email.expect_call(
695 mock.is_string_comparator(), mock.is_string_comparator())
showardec6a3b92009-09-25 20:29:13 +0000696 self.monitor._start_time = (time.time() -
beeps5e2bb4a2013-10-28 11:26:45 -0700697 pidfile_monitor._get_pidfile_timeout_secs() - 1)
showard35162b02009-03-03 02:17:30 +0000698 self._test_get_pidfile_info_helper(None, 1, 0)
699 self.assertTrue(self.monitor.lost_process)
jadmanski3d161b02008-06-06 15:43:36 +0000700
701
702class AgentTest(unittest.TestCase):
jadmanski0afbb632008-06-06 21:10:57 +0000703 def setUp(self):
704 self.god = mock.mock_god()
showard6b733412009-04-27 20:09:18 +0000705 self._dispatcher = self.god.create_mock_class(monitor_db.Dispatcher,
706 'dispatcher')
jadmanski3d161b02008-06-06 15:43:36 +0000707
708
jadmanski0afbb632008-06-06 21:10:57 +0000709 def tearDown(self):
710 self.god.unstub_all()
jadmanski3d161b02008-06-06 15:43:36 +0000711
712
showard170873e2009-01-07 00:22:26 +0000713 def _create_mock_task(self, name):
beeps5e2bb4a2013-10-28 11:26:45 -0700714 task = self.god.create_mock_class(agent_task.AgentTask, name)
showard418785b2009-11-23 20:19:59 +0000715 task.num_processes = 1
showard6b733412009-04-27 20:09:18 +0000716 _set_host_and_qe_ids(task)
showard170873e2009-01-07 00:22:26 +0000717 return task
718
showard8cc058f2009-09-08 16:26:33 +0000719 def _create_agent(self, task):
720 agent = monitor_db.Agent(task)
showard6b733412009-04-27 20:09:18 +0000721 agent.dispatcher = self._dispatcher
722 return agent
723
724
725 def _finish_agent(self, agent):
726 while not agent.is_done():
727 agent.tick()
728
showard170873e2009-01-07 00:22:26 +0000729
showard8cc058f2009-09-08 16:26:33 +0000730 def test_agent_abort(self):
731 task = self._create_mock_task('task')
732 task.poll.expect_call()
733 task.is_done.expect_call().and_return(False)
734 task.abort.expect_call()
735 task.aborted = True
jadmanski3d161b02008-06-06 15:43:36 +0000736
showard8cc058f2009-09-08 16:26:33 +0000737 agent = self._create_agent(task)
showard6b733412009-04-27 20:09:18 +0000738 agent.tick()
739 agent.abort()
740 self._finish_agent(agent)
741 self.god.check_playback()
742
743
showard08a36412009-05-05 01:01:13 +0000744 def _test_agent_abort_before_started_helper(self, ignore_abort=False):
showard20f9bdd2009-04-29 19:48:33 +0000745 task = self._create_mock_task('task')
showard08a36412009-05-05 01:01:13 +0000746 task.abort.expect_call()
747 if ignore_abort:
748 task.aborted = False
749 task.poll.expect_call()
750 task.is_done.expect_call().and_return(True)
showard08a36412009-05-05 01:01:13 +0000751 task.success = True
752 else:
753 task.aborted = True
754
showard8cc058f2009-09-08 16:26:33 +0000755 agent = self._create_agent(task)
showard20f9bdd2009-04-29 19:48:33 +0000756 agent.abort()
showard20f9bdd2009-04-29 19:48:33 +0000757 self._finish_agent(agent)
758 self.god.check_playback()
759
760
showard08a36412009-05-05 01:01:13 +0000761 def test_agent_abort_before_started(self):
762 self._test_agent_abort_before_started_helper()
763 self._test_agent_abort_before_started_helper(True)
764
765
jamesrenc44ae992010-02-19 00:12:54 +0000766class JobSchedulingTest(BaseSchedulerTest):
showarde58e3f82008-11-20 19:04:59 +0000767 def _test_run_helper(self, expect_agent=True, expect_starting=False,
768 expect_pending=False):
769 if expect_starting:
770 expected_status = models.HostQueueEntry.Status.STARTING
771 elif expect_pending:
772 expected_status = models.HostQueueEntry.Status.PENDING
773 else:
774 expected_status = models.HostQueueEntry.Status.VERIFYING
jamesrenc44ae992010-02-19 00:12:54 +0000775 job = scheduler_models.Job.fetch('id = 1')[0]
776 queue_entry = scheduler_models.HostQueueEntry.fetch('id = 1')[0]
showard77182562009-06-10 00:16:05 +0000777 assert queue_entry.job is job
showard8cc058f2009-09-08 16:26:33 +0000778 job.run_if_ready(queue_entry)
showardb2e2c322008-10-14 17:33:55 +0000779
showard2bab8f42008-11-12 18:15:22 +0000780 self.god.check_playback()
showard8cc058f2009-09-08 16:26:33 +0000781
782 self._dispatcher._schedule_delay_tasks()
783 self._dispatcher._schedule_running_host_queue_entries()
784 agent = self._dispatcher._agents[0]
785
showard77182562009-06-10 00:16:05 +0000786 actual_status = models.HostQueueEntry.smart_get(1).status
787 self.assertEquals(expected_status, actual_status)
showard2bab8f42008-11-12 18:15:22 +0000788
showard9976ce92008-10-15 20:28:13 +0000789 if not expect_agent:
790 self.assertEquals(agent, None)
791 return
792
showardb2e2c322008-10-14 17:33:55 +0000793 self.assert_(isinstance(agent, monitor_db.Agent))
showard8cc058f2009-09-08 16:26:33 +0000794 self.assert_(agent.task)
795 return agent.task
showardc9ae1782009-01-30 01:42:37 +0000796
797
showard77182562009-06-10 00:16:05 +0000798 def test_run_if_ready_delays(self):
799 # Also tests Job.run_with_ready_delay() on atomic group jobs.
800 django_job = self._create_job(hosts=[5, 6], atomic_group=1)
jamesrenc44ae992010-02-19 00:12:54 +0000801 job = scheduler_models.Job(django_job.id)
showard77182562009-06-10 00:16:05 +0000802 self.assertEqual(1, job.synch_count)
803 django_hqes = list(models.HostQueueEntry.objects.filter(job=job.id))
804 self.assertEqual(2, len(django_hqes))
805 self.assertEqual(2, django_hqes[0].atomic_group.max_number_of_machines)
806
807 def set_hqe_status(django_hqe, status):
808 django_hqe.status = status
809 django_hqe.save()
jamesrenc44ae992010-02-19 00:12:54 +0000810 scheduler_models.HostQueueEntry(django_hqe.id).host.set_status(status)
showard77182562009-06-10 00:16:05 +0000811
812 # An initial state, our synch_count is 1
813 set_hqe_status(django_hqes[0], models.HostQueueEntry.Status.VERIFYING)
814 set_hqe_status(django_hqes[1], models.HostQueueEntry.Status.PENDING)
815
816 # So that we don't depend on the config file value during the test.
817 self.assert_(scheduler_config.config
818 .secs_to_wait_for_atomic_group_hosts is not None)
819 self.god.stub_with(scheduler_config.config,
820 'secs_to_wait_for_atomic_group_hosts', 123456)
821
jamesrenc44ae992010-02-19 00:12:54 +0000822 # Get the pending one as a scheduler_models.HostQueueEntry object.
823 hqe = scheduler_models.HostQueueEntry(django_hqes[1].id)
showard77182562009-06-10 00:16:05 +0000824 self.assert_(not job._delay_ready_task)
825 self.assertTrue(job.is_ready())
826
827 # Ready with one pending, one verifying and an atomic group should
828 # result in a DelayCallTask to re-check if we're ready a while later.
showard8cc058f2009-09-08 16:26:33 +0000829 job.run_if_ready(hqe)
830 self.assertEquals('Waiting', hqe.status)
831 self._dispatcher._schedule_delay_tasks()
832 self.assertEquals('Pending', hqe.status)
833 agent = self._dispatcher._agents[0]
showard77182562009-06-10 00:16:05 +0000834 self.assert_(job._delay_ready_task)
835 self.assert_(isinstance(agent, monitor_db.Agent))
showard8cc058f2009-09-08 16:26:33 +0000836 self.assert_(agent.task)
837 delay_task = agent.task
jamesrenc44ae992010-02-19 00:12:54 +0000838 self.assert_(isinstance(delay_task, scheduler_models.DelayedCallTask))
showard77182562009-06-10 00:16:05 +0000839 self.assert_(not delay_task.is_done())
840
showard8cc058f2009-09-08 16:26:33 +0000841 self.god.stub_function(delay_task, 'abort')
842
showard77182562009-06-10 00:16:05 +0000843 self.god.stub_function(job, 'run')
844
showardd2014822009-10-12 20:26:58 +0000845 self.god.stub_function(job, '_pending_count')
showardd07a5f32009-12-07 19:36:20 +0000846 self.god.stub_with(job, 'synch_count', 9)
847 self.god.stub_function(job, 'request_abort')
showardd2014822009-10-12 20:26:58 +0000848
showard77182562009-06-10 00:16:05 +0000849 # Test that the DelayedCallTask's callback queued up above does the
showardd2014822009-10-12 20:26:58 +0000850 # correct thing and does not call run if there are not enough hosts
851 # in pending after the delay.
showardd2014822009-10-12 20:26:58 +0000852 job._pending_count.expect_call().and_return(0)
showardd07a5f32009-12-07 19:36:20 +0000853 job.request_abort.expect_call()
showardd2014822009-10-12 20:26:58 +0000854 delay_task._callback()
855 self.god.check_playback()
856
857 # Test that the DelayedCallTask's callback queued up above does the
858 # correct thing and returns the Agent returned by job.run() if
859 # there are still enough hosts pending after the delay.
showardd07a5f32009-12-07 19:36:20 +0000860 job.synch_count = 4
showardd2014822009-10-12 20:26:58 +0000861 job._pending_count.expect_call().and_return(4)
showard8cc058f2009-09-08 16:26:33 +0000862 job.run.expect_call(hqe)
863 delay_task._callback()
864 self.god.check_playback()
showard77182562009-06-10 00:16:05 +0000865
showardd2014822009-10-12 20:26:58 +0000866 job._pending_count.expect_call().and_return(4)
867
showard77182562009-06-10 00:16:05 +0000868 # Adjust the delay deadline so that enough time has passed.
869 job._delay_ready_task.end_time = time.time() - 111111
showard8cc058f2009-09-08 16:26:33 +0000870 job.run.expect_call(hqe)
showard77182562009-06-10 00:16:05 +0000871 # ...the delay_expired condition should cause us to call run()
showard8cc058f2009-09-08 16:26:33 +0000872 self._dispatcher._handle_agents()
873 self.god.check_playback()
874 delay_task.success = False
showard77182562009-06-10 00:16:05 +0000875
876 # Adjust the delay deadline back so that enough time has not passed.
877 job._delay_ready_task.end_time = time.time() + 111111
showard8cc058f2009-09-08 16:26:33 +0000878 self._dispatcher._handle_agents()
879 self.god.check_playback()
showard77182562009-06-10 00:16:05 +0000880
showard77182562009-06-10 00:16:05 +0000881 # Now max_number_of_machines HQEs are in pending state. Remaining
882 # delay will now be ignored.
jamesrenc44ae992010-02-19 00:12:54 +0000883 other_hqe = scheduler_models.HostQueueEntry(django_hqes[0].id)
showard8cc058f2009-09-08 16:26:33 +0000884 self.god.unstub(job, 'run')
showardd2014822009-10-12 20:26:58 +0000885 self.god.unstub(job, '_pending_count')
showardd07a5f32009-12-07 19:36:20 +0000886 self.god.unstub(job, 'synch_count')
887 self.god.unstub(job, 'request_abort')
showard77182562009-06-10 00:16:05 +0000888 # ...the over_max_threshold test should cause us to call run()
showard8cc058f2009-09-08 16:26:33 +0000889 delay_task.abort.expect_call()
890 other_hqe.on_pending()
891 self.assertEquals('Starting', other_hqe.status)
892 self.assertEquals('Starting', hqe.status)
893 self.god.stub_function(job, 'run')
894 self.god.unstub(delay_task, 'abort')
showard77182562009-06-10 00:16:05 +0000895
showard8cc058f2009-09-08 16:26:33 +0000896 hqe.set_status('Pending')
897 other_hqe.set_status('Pending')
showard708b3522009-08-20 23:26:15 +0000898 # Now we're not over the max for the atomic group. But all assigned
899 # hosts are in pending state. over_max_threshold should make us run().
showard8cc058f2009-09-08 16:26:33 +0000900 hqe.atomic_group.max_number_of_machines += 1
901 hqe.atomic_group.save()
902 job.run.expect_call(hqe)
903 hqe.on_pending()
904 self.god.check_playback()
905 hqe.atomic_group.max_number_of_machines -= 1
906 hqe.atomic_group.save()
showard708b3522009-08-20 23:26:15 +0000907
jamesrenc44ae992010-02-19 00:12:54 +0000908 other_hqe = scheduler_models.HostQueueEntry(django_hqes[0].id)
showard8cc058f2009-09-08 16:26:33 +0000909 self.assertTrue(hqe.job is other_hqe.job)
showard77182562009-06-10 00:16:05 +0000910 # DBObject classes should reuse instances so these should be the same.
911 self.assertEqual(job, other_hqe.job)
showard8cc058f2009-09-08 16:26:33 +0000912 self.assertEqual(other_hqe.job, hqe.job)
showard77182562009-06-10 00:16:05 +0000913 # Be sure our delay was not lost during the other_hqe construction.
showard8cc058f2009-09-08 16:26:33 +0000914 self.assertEqual(job._delay_ready_task, delay_task)
showard77182562009-06-10 00:16:05 +0000915 self.assert_(job._delay_ready_task)
916 self.assertFalse(job._delay_ready_task.is_done())
917 self.assertFalse(job._delay_ready_task.aborted)
918
919 # We want the real run() to be called below.
920 self.god.unstub(job, 'run')
921
922 # We pass in the other HQE this time the same way it would happen
923 # for real when one host finishes verifying and enters pending.
showard8cc058f2009-09-08 16:26:33 +0000924 job.run_if_ready(other_hqe)
showard77182562009-06-10 00:16:05 +0000925
926 # The delayed task must be aborted by the actual run() call above.
927 self.assertTrue(job._delay_ready_task.aborted)
928 self.assertFalse(job._delay_ready_task.success)
929 self.assertTrue(job._delay_ready_task.is_done())
930
931 # Check that job run() and _finish_run() were called by the above:
showard8cc058f2009-09-08 16:26:33 +0000932 self._dispatcher._schedule_running_host_queue_entries()
933 agent = self._dispatcher._agents[0]
934 self.assert_(agent.task)
935 task = agent.task
936 self.assert_(isinstance(task, monitor_db.QueueTask))
showard77182562009-06-10 00:16:05 +0000937 # Requery these hqes in order to verify the status from the DB.
938 django_hqes = list(models.HostQueueEntry.objects.filter(job=job.id))
939 for entry in django_hqes:
940 self.assertEqual(models.HostQueueEntry.Status.STARTING,
941 entry.status)
942
943 # We're already running, but more calls to run_with_ready_delay can
944 # continue to come in due to straggler hosts enter Pending. Make
945 # sure we don't do anything.
showard8cc058f2009-09-08 16:26:33 +0000946 self.god.stub_function(job, 'run')
947 job.run_with_ready_delay(hqe)
948 self.god.check_playback()
949 self.god.unstub(job, 'run')
showard77182562009-06-10 00:16:05 +0000950
951
showardf1ae3542009-05-11 19:26:02 +0000952 def test_run_synchronous_atomic_group_ready(self):
953 self._create_job(hosts=[5, 6], atomic_group=1, synchronous=True)
954 self._update_hqe("status='Pending', execution_subdir=''")
955
showard8cc058f2009-09-08 16:26:33 +0000956 queue_task = self._test_run_helper(expect_starting=True)
showardf1ae3542009-05-11 19:26:02 +0000957
958 self.assert_(isinstance(queue_task, monitor_db.QueueTask))
showard77182562009-06-10 00:16:05 +0000959 # Atomic group jobs that do not depend on a specific label in the
960 # atomic group will use the atomic group name as their group name.
showardd1195652009-12-08 22:21:02 +0000961 self.assertEquals(queue_task.queue_entries[0].get_group_name(),
962 'atomic1')
showardf1ae3542009-05-11 19:26:02 +0000963
964
965 def test_run_synchronous_atomic_group_with_label_ready(self):
966 job = self._create_job(hosts=[5, 6], atomic_group=1, synchronous=True)
967 job.dependency_labels.add(self.label4)
968 self._update_hqe("status='Pending', execution_subdir=''")
969
showard8cc058f2009-09-08 16:26:33 +0000970 queue_task = self._test_run_helper(expect_starting=True)
showardf1ae3542009-05-11 19:26:02 +0000971
972 self.assert_(isinstance(queue_task, monitor_db.QueueTask))
973 # Atomic group jobs that also specify a label in the atomic group
974 # will use the label name as their group name.
showardd1195652009-12-08 22:21:02 +0000975 self.assertEquals(queue_task.queue_entries[0].get_group_name(),
976 'label4')
showardf1ae3542009-05-11 19:26:02 +0000977
978
jamesrenc44ae992010-02-19 00:12:54 +0000979 def test_run_synchronous_ready(self):
980 self._create_job(hosts=[1, 2], synchronous=True)
981 self._update_hqe("status='Pending', execution_subdir=''")
showard21baa452008-10-21 00:08:39 +0000982
jamesrenc44ae992010-02-19 00:12:54 +0000983 queue_task = self._test_run_helper(expect_starting=True)
showard8cc058f2009-09-08 16:26:33 +0000984
jamesrenc44ae992010-02-19 00:12:54 +0000985 self.assert_(isinstance(queue_task, monitor_db.QueueTask))
986 self.assertEquals(queue_task.job.id, 1)
987 hqe_ids = [hqe.id for hqe in queue_task.queue_entries]
988 self.assertEquals(hqe_ids, [1, 2])
showard21baa452008-10-21 00:08:39 +0000989
990
jamesrenc44ae992010-02-19 00:12:54 +0000991 def test_schedule_running_host_queue_entries_fail(self):
992 self._create_job(hosts=[2])
993 self._update_hqe("status='%s', execution_subdir=''" %
994 models.HostQueueEntry.Status.PENDING)
995 job = scheduler_models.Job.fetch('id = 1')[0]
996 queue_entry = scheduler_models.HostQueueEntry.fetch('id = 1')[0]
997 assert queue_entry.job is job
998 job.run_if_ready(queue_entry)
999 self.assertEqual(queue_entry.status,
1000 models.HostQueueEntry.Status.STARTING)
1001 self.assert_(queue_entry.execution_subdir)
1002 self.god.check_playback()
showard21baa452008-10-21 00:08:39 +00001003
jamesrenc44ae992010-02-19 00:12:54 +00001004 class dummy_test_agent(object):
1005 task = 'dummy_test_agent'
1006 self._dispatcher._register_agent_for_ids(
1007 self._dispatcher._host_agents, [queue_entry.host.id],
1008 dummy_test_agent)
showard21baa452008-10-21 00:08:39 +00001009
jamesrenc44ae992010-02-19 00:12:54 +00001010 # Attempted to schedule on a host that already has an agent.
Dale Curtisaa513362011-03-01 17:27:44 -08001011 self.assertRaises(host_scheduler.SchedulerError,
jamesrenc44ae992010-02-19 00:12:54 +00001012 self._dispatcher._schedule_running_host_queue_entries)
showardf1ae3542009-05-11 19:26:02 +00001013
1014
jamesren47bd7372010-03-13 00:58:17 +00001015 def test_schedule_hostless_job(self):
1016 job = self._create_job(hostless=True)
1017 self.assertEqual(1, job.hostqueueentry_set.count())
1018 hqe_query = scheduler_models.HostQueueEntry.fetch(
1019 'id = %s' % job.hostqueueentry_set.all()[0].id)
1020 self.assertEqual(1, len(hqe_query))
1021 hqe = hqe_query[0]
1022
1023 self.assertEqual(models.HostQueueEntry.Status.QUEUED, hqe.status)
1024 self.assertEqual(0, len(self._dispatcher._agents))
1025
1026 self._dispatcher._schedule_new_jobs()
1027
1028 self.assertEqual(models.HostQueueEntry.Status.STARTING, hqe.status)
1029 self.assertEqual(1, len(self._dispatcher._agents))
1030
1031 self._dispatcher._schedule_new_jobs()
1032
1033 # No change to previously schedule hostless job, and no additional agent
1034 self.assertEqual(models.HostQueueEntry.Status.STARTING, hqe.status)
1035 self.assertEqual(1, len(self._dispatcher._agents))
1036
1037
showardf1ae3542009-05-11 19:26:02 +00001038class TopLevelFunctionsTest(unittest.TestCase):
mblighe7d9c602009-07-02 19:02:33 +00001039 def setUp(self):
1040 self.god = mock.mock_god()
1041
1042
1043 def tearDown(self):
1044 self.god.unstub_all()
1045
1046
showardf1ae3542009-05-11 19:26:02 +00001047 def test_autoserv_command_line(self):
1048 machines = 'abcd12,efgh34'
showardf1ae3542009-05-11 19:26:02 +00001049 extra_args = ['-Z', 'hello']
showardf65b7402009-12-18 22:44:35 +00001050 expected_command_line_base = set((monitor_db._autoserv_path, '-p',
1051 '-m', machines, '-r',
1052 drone_manager.WORKING_DIRECTORY))
showardf1ae3542009-05-11 19:26:02 +00001053
showardf65b7402009-12-18 22:44:35 +00001054 expected_command_line = expected_command_line_base.union(
1055 ['--verbose']).union(extra_args)
1056 command_line = set(
1057 monitor_db._autoserv_command_line(machines, extra_args))
1058 self.assertEqual(expected_command_line, command_line)
showardf1ae3542009-05-11 19:26:02 +00001059
1060 class FakeJob(object):
1061 owner = 'Bob'
1062 name = 'fake job name'
Aviv Keshet1f23b692013-05-14 11:13:55 -07001063 test_retry = 0
mblighe7d9c602009-07-02 19:02:33 +00001064 id = 1337
1065
1066 class FakeHQE(object):
1067 job = FakeJob
showardf1ae3542009-05-11 19:26:02 +00001068
showardf65b7402009-12-18 22:44:35 +00001069 expected_command_line = expected_command_line_base.union(
1070 ['-u', FakeJob.owner, '-l', FakeJob.name])
1071 command_line = set(monitor_db._autoserv_command_line(
1072 machines, extra_args=[], queue_entry=FakeHQE, verbose=False))
1073 self.assertEqual(expected_command_line, command_line)
showardf1ae3542009-05-11 19:26:02 +00001074
showard21baa452008-10-21 00:08:39 +00001075
jamesren76fcf192010-04-21 20:39:50 +00001076class AgentTaskTest(unittest.TestCase,
1077 frontend_test_utils.FrontendTestMixin):
1078 def setUp(self):
1079 self._frontend_common_setup()
1080
1081
1082 def tearDown(self):
1083 self._frontend_common_teardown()
1084
1085
1086 def _setup_drones(self):
1087 self.god.stub_function(models.DroneSet, 'drone_sets_enabled')
1088 models.DroneSet.drone_sets_enabled.expect_call().and_return(True)
1089
1090 drones = []
1091 for x in xrange(4):
1092 drones.append(models.Drone.objects.create(hostname=str(x)))
1093
1094 drone_set_1 = models.DroneSet.objects.create(name='1')
1095 drone_set_1.drones.add(*drones[0:2])
1096 drone_set_2 = models.DroneSet.objects.create(name='2')
1097 drone_set_2.drones.add(*drones[2:4])
1098 drone_set_3 = models.DroneSet.objects.create(name='3')
1099
1100 job_1 = self._create_job_simple([self.hosts[0].id],
1101 drone_set=drone_set_1)
1102 job_2 = self._create_job_simple([self.hosts[0].id],
1103 drone_set=drone_set_2)
1104 job_3 = self._create_job_simple([self.hosts[0].id],
1105 drone_set=drone_set_3)
1106
jamesrendd77e012010-04-28 18:07:30 +00001107 job_4 = self._create_job_simple([self.hosts[0].id])
1108 job_4.drone_set = None
1109 job_4.save()
jamesren76fcf192010-04-21 20:39:50 +00001110
jamesrendd77e012010-04-28 18:07:30 +00001111 hqe_1 = job_1.hostqueueentry_set.all()[0]
1112 hqe_2 = job_2.hostqueueentry_set.all()[0]
1113 hqe_3 = job_3.hostqueueentry_set.all()[0]
1114 hqe_4 = job_4.hostqueueentry_set.all()[0]
1115
beeps5e2bb4a2013-10-28 11:26:45 -07001116 return (hqe_1, hqe_2, hqe_3, hqe_4), agent_task.AgentTask()
jamesren76fcf192010-04-21 20:39:50 +00001117
1118
jamesrendd77e012010-04-28 18:07:30 +00001119 def test_get_drone_hostnames_allowed_no_drones_in_set(self):
jamesren76fcf192010-04-21 20:39:50 +00001120 hqes, task = self._setup_drones()
jamesrendd77e012010-04-28 18:07:30 +00001121 task.queue_entry_ids = (hqes[2].id,)
jamesren76fcf192010-04-21 20:39:50 +00001122 self.assertEqual(set(), task.get_drone_hostnames_allowed())
1123 self.god.check_playback()
1124
1125
jamesrendd77e012010-04-28 18:07:30 +00001126 def test_get_drone_hostnames_allowed_no_drone_set(self):
1127 hqes, task = self._setup_drones()
1128 hqe = hqes[3]
1129 task.queue_entry_ids = (hqe.id,)
1130
1131 result = object()
1132
1133 self.god.stub_function(task, '_user_or_global_default_drone_set')
1134 task._user_or_global_default_drone_set.expect_call(
1135 hqe.job, hqe.job.user()).and_return(result)
1136
1137 self.assertEqual(result, task.get_drone_hostnames_allowed())
1138 self.god.check_playback()
1139
1140
jamesren76fcf192010-04-21 20:39:50 +00001141 def test_get_drone_hostnames_allowed_success(self):
1142 hqes, task = self._setup_drones()
jamesrendd77e012010-04-28 18:07:30 +00001143 task.queue_entry_ids = (hqes[0].id,)
jamesren76fcf192010-04-21 20:39:50 +00001144 self.assertEqual(set(('0','1')), task.get_drone_hostnames_allowed())
1145 self.god.check_playback()
1146
1147
1148 def test_get_drone_hostnames_allowed_multiple_jobs(self):
1149 hqes, task = self._setup_drones()
jamesrendd77e012010-04-28 18:07:30 +00001150 task.queue_entry_ids = (hqes[0].id, hqes[1].id)
jamesren76fcf192010-04-21 20:39:50 +00001151 self.assertRaises(AssertionError,
1152 task.get_drone_hostnames_allowed)
1153 self.god.check_playback()
1154
1155
jamesrendd77e012010-04-28 18:07:30 +00001156 def test_get_drone_hostnames_allowed_no_hqe(self):
1157 class MockSpecialTask(object):
1158 requested_by = object()
1159
beeps5e2bb4a2013-10-28 11:26:45 -07001160 class MockSpecialAgentTask(agent_task.SpecialAgentTask):
jamesrendd77e012010-04-28 18:07:30 +00001161 task = MockSpecialTask()
1162 queue_entry_ids = []
1163 def __init__(self, *args, **kwargs):
1164 pass
1165
1166 task = MockSpecialAgentTask()
1167 self.god.stub_function(models.DroneSet, 'drone_sets_enabled')
1168 self.god.stub_function(task, '_user_or_global_default_drone_set')
1169
1170 result = object()
1171 models.DroneSet.drone_sets_enabled.expect_call().and_return(True)
1172 task._user_or_global_default_drone_set.expect_call(
1173 task.task, MockSpecialTask.requested_by).and_return(result)
1174
1175 self.assertEqual(result, task.get_drone_hostnames_allowed())
1176 self.god.check_playback()
1177
1178
1179 def _setup_test_user_or_global_default_drone_set(self):
1180 result = object()
1181 class MockDroneSet(object):
1182 def get_drone_hostnames(self):
1183 return result
1184
1185 self.god.stub_function(models.DroneSet, 'get_default')
1186 models.DroneSet.get_default.expect_call().and_return(MockDroneSet())
1187 return result
1188
1189
1190 def test_user_or_global_default_drone_set(self):
1191 expected = object()
1192 class MockDroneSet(object):
1193 def get_drone_hostnames(self):
1194 return expected
1195 class MockUser(object):
1196 drone_set = MockDroneSet()
1197
1198 self._setup_test_user_or_global_default_drone_set()
1199
beeps5e2bb4a2013-10-28 11:26:45 -07001200 actual = agent_task.AgentTask()._user_or_global_default_drone_set(
jamesrendd77e012010-04-28 18:07:30 +00001201 None, MockUser())
1202
1203 self.assertEqual(expected, actual)
1204 self.god.check_playback()
1205
1206
1207 def test_user_or_global_default_drone_set_no_user(self):
1208 expected = self._setup_test_user_or_global_default_drone_set()
beeps5e2bb4a2013-10-28 11:26:45 -07001209 actual = agent_task.AgentTask()._user_or_global_default_drone_set(
jamesrendd77e012010-04-28 18:07:30 +00001210 None, None)
1211
1212 self.assertEqual(expected, actual)
1213 self.god.check_playback()
1214
1215
1216 def test_user_or_global_default_drone_set_no_user_drone_set(self):
1217 class MockUser(object):
1218 drone_set = None
1219 login = None
1220
1221 expected = self._setup_test_user_or_global_default_drone_set()
beeps5e2bb4a2013-10-28 11:26:45 -07001222 actual = agent_task.AgentTask()._user_or_global_default_drone_set(
jamesrendd77e012010-04-28 18:07:30 +00001223 None, MockUser())
1224
1225 self.assertEqual(expected, actual)
1226 self.god.check_playback()
1227
1228
showardce38e0c2008-05-29 19:36:16 +00001229if __name__ == '__main__':
jadmanski0afbb632008-06-06 21:10:57 +00001230 unittest.main()