blob: 62bf6b47fc866fe003e4bb1450b0d61c09e06765 [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
Prashanth B0e960282014-05-13 19:38:28 -070015from autotest_lib.scheduler import scheduler_config, gc_stats
Prashanth B372613d2014-05-05 08:40:21 -070016from autotest_lib.scheduler import monitor_db_cleanup
showard78f5b012009-12-23 00:05:59 +000017from autotest_lib.scheduler import monitor_db_functional_test
Prashanth B0e960282014-05-13 19:38:28 -070018from autotest_lib.scheduler import scheduler_lib
jamesrenc44ae992010-02-19 00:12:54 +000019from autotest_lib.scheduler import scheduler_models
showardce38e0c2008-05-29 19:36:16 +000020
21_DEBUG = False
22
showarda3c58572009-03-12 20:36:59 +000023
showard9bb960b2009-11-19 01:02:11 +000024class DummyAgentTask(object):
showardd1195652009-12-08 22:21:02 +000025 num_processes = 1
26 owner_username = 'my_user'
showard9bb960b2009-11-19 01:02:11 +000027
jamesren76fcf192010-04-21 20:39:50 +000028 def get_drone_hostnames_allowed(self):
29 return None
30
showard9bb960b2009-11-19 01:02:11 +000031
showard170873e2009-01-07 00:22:26 +000032class DummyAgent(object):
showard8cc058f2009-09-08 16:26:33 +000033 started = False
showard170873e2009-01-07 00:22:26 +000034 _is_done = False
showardd1195652009-12-08 22:21:02 +000035 host_ids = ()
36 queue_entry_ids = ()
37
38 def __init__(self):
39 self.task = DummyAgentTask()
showard170873e2009-01-07 00:22:26 +000040
showard170873e2009-01-07 00:22:26 +000041
42 def tick(self):
showard8cc058f2009-09-08 16:26:33 +000043 self.started = True
showard170873e2009-01-07 00:22:26 +000044
45
46 def is_done(self):
47 return self._is_done
48
49
50 def set_done(self, done):
51 self._is_done = done
showard04c82c52008-05-29 19:38:12 +000052
showard56193bb2008-08-13 20:07:41 +000053
54class IsRow(mock.argument_comparator):
55 def __init__(self, row_id):
56 self.row_id = row_id
showardce38e0c2008-05-29 19:36:16 +000057
58
showard56193bb2008-08-13 20:07:41 +000059 def is_satisfied_by(self, parameter):
60 return list(parameter)[0] == self.row_id
61
62
63 def __str__(self):
64 return 'row with id %s' % self.row_id
65
66
showardd3dc1992009-04-22 21:01:40 +000067class IsAgentWithTask(mock.argument_comparator):
mbligh1ef218d2009-08-03 16:57:56 +000068 def __init__(self, task):
69 self._task = task
showardd3dc1992009-04-22 21:01:40 +000070
71
mbligh1ef218d2009-08-03 16:57:56 +000072 def is_satisfied_by(self, parameter):
73 if not isinstance(parameter, monitor_db.Agent):
74 return False
75 tasks = list(parameter.queue.queue)
76 if len(tasks) != 1:
77 return False
78 return tasks[0] == self._task
showardd3dc1992009-04-22 21:01:40 +000079
80
showard6b733412009-04-27 20:09:18 +000081def _set_host_and_qe_ids(agent_or_task, id_list=None):
82 if id_list is None:
83 id_list = []
84 agent_or_task.host_ids = agent_or_task.queue_entry_ids = id_list
85
86
showardb6d16622009-05-26 19:35:29 +000087class BaseSchedulerTest(unittest.TestCase,
88 frontend_test_utils.FrontendTestMixin):
showard50c0e712008-09-22 16:20:37 +000089 _config_section = 'AUTOTEST_WEB'
showardce38e0c2008-05-29 19:36:16 +000090
jadmanski0afbb632008-06-06 21:10:57 +000091 def _do_query(self, sql):
showardb1e51872008-10-07 11:08:18 +000092 self._database.execute(sql)
showardce38e0c2008-05-29 19:36:16 +000093
94
showardb6d16622009-05-26 19:35:29 +000095 def _set_monitor_stubs(self):
96 # Clear the instance cache as this is a brand new database.
jamesrenc44ae992010-02-19 00:12:54 +000097 scheduler_models.DBObject._clear_instance_cache()
showardce38e0c2008-05-29 19:36:16 +000098
showardb1e51872008-10-07 11:08:18 +000099 self._database = (
showard78f5b012009-12-23 00:05:59 +0000100 database_connection.TranslatingDatabase.get_test_database(
101 translators=monitor_db_functional_test._DB_TRANSLATORS))
102 self._database.connect(db_type='django')
showardb1e51872008-10-07 11:08:18 +0000103 self._database.debug = _DEBUG
showardce38e0c2008-05-29 19:36:16 +0000104
Prashanth B0e960282014-05-13 19:38:28 -0700105 connection_manager = scheduler_lib.ConnectionManager(autocommit=False)
106 self.god.stub_with(connection_manager, 'db_connection', self._database)
107 self.god.stub_with(monitor_db, '_db_manager', connection_manager)
beeps7d8a1b12013-10-29 17:58:34 -0700108 self.god.stub_with(monitor_db.BaseDispatcher,
109 '_get_pending_queue_entries',
110 self._get_pending_hqes)
jamesrenc44ae992010-02-19 00:12:54 +0000111 self.god.stub_with(scheduler_models, '_db', self._database)
112 self.god.stub_with(drone_manager.instance(), '_results_dir',
showard78f5b012009-12-23 00:05:59 +0000113 '/test/path')
jamesrenc44ae992010-02-19 00:12:54 +0000114 self.god.stub_with(drone_manager.instance(), '_temporary_directory',
showard78f5b012009-12-23 00:05:59 +0000115 '/test/path/tmp')
showard56193bb2008-08-13 20:07:41 +0000116
jamesrenc44ae992010-02-19 00:12:54 +0000117 monitor_db.initialize_globals()
118 scheduler_models.initialize_globals()
119
showard56193bb2008-08-13 20:07:41 +0000120
showard56193bb2008-08-13 20:07:41 +0000121 def setUp(self):
showardb6d16622009-05-26 19:35:29 +0000122 self._frontend_common_setup()
showard56193bb2008-08-13 20:07:41 +0000123 self._set_monitor_stubs()
124 self._dispatcher = monitor_db.Dispatcher()
showardce38e0c2008-05-29 19:36:16 +0000125
126
showard56193bb2008-08-13 20:07:41 +0000127 def tearDown(self):
showardb6d16622009-05-26 19:35:29 +0000128 self._database.disconnect()
129 self._frontend_common_teardown()
showardce38e0c2008-05-29 19:36:16 +0000130
131
showard56193bb2008-08-13 20:07:41 +0000132 def _update_hqe(self, set, where=''):
showardeab66ce2009-12-23 00:03:56 +0000133 query = 'UPDATE afe_host_queue_entries SET ' + set
showard56193bb2008-08-13 20:07:41 +0000134 if where:
135 query += ' WHERE ' + where
136 self._do_query(query)
137
138
beeps7d8a1b12013-10-29 17:58:34 -0700139 def _get_pending_hqes(self):
140 query_string=('afe_jobs.priority DESC, '
141 'ifnull(nullif(host_id, NULL), host_id) DESC, '
142 'ifnull(nullif(meta_host, NULL), meta_host) DESC, '
143 'job_id')
144 return list(scheduler_models.HostQueueEntry.fetch(
145 joins='INNER JOIN afe_jobs ON (job_id=afe_jobs.id)',
146 where='NOT complete AND NOT active AND status="Queued"',
147 order_by=query_string))
148
149
showardb2e2c322008-10-14 17:33:55 +0000150class DispatcherSchedulingTest(BaseSchedulerTest):
showard56193bb2008-08-13 20:07:41 +0000151 _jobs_scheduled = []
152
showard89f84db2009-03-12 20:39:13 +0000153
154 def tearDown(self):
155 super(DispatcherSchedulingTest, self).tearDown()
156
157
showard56193bb2008-08-13 20:07:41 +0000158 def _set_monitor_stubs(self):
159 super(DispatcherSchedulingTest, self)._set_monitor_stubs()
showard89f84db2009-03-12 20:39:13 +0000160
showard8cc058f2009-09-08 16:26:33 +0000161 def hqe__do_schedule_pre_job_tasks_stub(queue_entry):
162 """Called by HostQueueEntry.run()."""
showard77182562009-06-10 00:16:05 +0000163 self._record_job_scheduled(queue_entry.job.id, queue_entry.host.id)
showard89f84db2009-03-12 20:39:13 +0000164 queue_entry.set_status('Starting')
showard89f84db2009-03-12 20:39:13 +0000165
jamesrenc44ae992010-02-19 00:12:54 +0000166 self.god.stub_with(scheduler_models.HostQueueEntry,
showard8cc058f2009-09-08 16:26:33 +0000167 '_do_schedule_pre_job_tasks',
168 hqe__do_schedule_pre_job_tasks_stub)
showard89f84db2009-03-12 20:39:13 +0000169
showard56193bb2008-08-13 20:07:41 +0000170
171 def _record_job_scheduled(self, job_id, host_id):
172 record = (job_id, host_id)
173 self.assert_(record not in self._jobs_scheduled,
174 'Job %d scheduled on host %d twice' %
175 (job_id, host_id))
176 self._jobs_scheduled.append(record)
177
178
179 def _assert_job_scheduled_on(self, job_id, host_id):
180 record = (job_id, host_id)
181 self.assert_(record in self._jobs_scheduled,
182 'Job %d not scheduled on host %d as expected\n'
183 'Jobs scheduled: %s' %
184 (job_id, host_id, self._jobs_scheduled))
185 self._jobs_scheduled.remove(record)
186
187
showard89f84db2009-03-12 20:39:13 +0000188 def _assert_job_scheduled_on_number_of(self, job_id, host_ids, number):
189 """Assert job was scheduled on exactly number hosts out of a set."""
190 found = []
191 for host_id in host_ids:
192 record = (job_id, host_id)
193 if record in self._jobs_scheduled:
194 found.append(record)
195 self._jobs_scheduled.remove(record)
196 if len(found) < number:
197 self.fail('Job %d scheduled on fewer than %d hosts in %s.\n'
198 'Jobs scheduled: %s' % (job_id, number, host_ids, found))
199 elif len(found) > number:
200 self.fail('Job %d scheduled on more than %d hosts in %s.\n'
201 'Jobs scheduled: %s' % (job_id, number, host_ids, found))
202
203
showard56193bb2008-08-13 20:07:41 +0000204 def _check_for_extra_schedulings(self):
205 if len(self._jobs_scheduled) != 0:
206 self.fail('Extra jobs scheduled: ' +
207 str(self._jobs_scheduled))
208
209
jadmanski0afbb632008-06-06 21:10:57 +0000210 def _convert_jobs_to_metahosts(self, *job_ids):
211 sql_tuple = '(' + ','.join(str(i) for i in job_ids) + ')'
showardeab66ce2009-12-23 00:03:56 +0000212 self._do_query('UPDATE afe_host_queue_entries SET '
jadmanski0afbb632008-06-06 21:10:57 +0000213 'meta_host=host_id, host_id=NULL '
214 'WHERE job_id IN ' + sql_tuple)
showardce38e0c2008-05-29 19:36:16 +0000215
216
jadmanski0afbb632008-06-06 21:10:57 +0000217 def _lock_host(self, host_id):
showardeab66ce2009-12-23 00:03:56 +0000218 self._do_query('UPDATE afe_hosts SET locked=1 WHERE id=' +
jadmanski0afbb632008-06-06 21:10:57 +0000219 str(host_id))
showardce38e0c2008-05-29 19:36:16 +0000220
221
jadmanski0afbb632008-06-06 21:10:57 +0000222 def setUp(self):
showard56193bb2008-08-13 20:07:41 +0000223 super(DispatcherSchedulingTest, self).setUp()
jadmanski0afbb632008-06-06 21:10:57 +0000224 self._jobs_scheduled = []
showardce38e0c2008-05-29 19:36:16 +0000225
226
jamesren883492a2010-02-12 00:45:18 +0000227 def _run_scheduler(self):
beepscc9fc702013-12-02 12:45:38 -0800228 self._dispatcher._host_scheduler.tick()
jamesren883492a2010-02-12 00:45:18 +0000229 for _ in xrange(2): # metahost scheduling can take two cycles
230 self._dispatcher._schedule_new_jobs()
231
232
jadmanski0afbb632008-06-06 21:10:57 +0000233 def _test_basic_scheduling_helper(self, use_metahosts):
234 'Basic nonmetahost scheduling'
235 self._create_job_simple([1], use_metahosts)
236 self._create_job_simple([2], use_metahosts)
jamesren883492a2010-02-12 00:45:18 +0000237 self._run_scheduler()
jadmanski0afbb632008-06-06 21:10:57 +0000238 self._assert_job_scheduled_on(1, 1)
239 self._assert_job_scheduled_on(2, 2)
240 self._check_for_extra_schedulings()
showardce38e0c2008-05-29 19:36:16 +0000241
242
jadmanski0afbb632008-06-06 21:10:57 +0000243 def _test_priorities_helper(self, use_metahosts):
244 'Test prioritization ordering'
245 self._create_job_simple([1], use_metahosts)
246 self._create_job_simple([2], use_metahosts)
247 self._create_job_simple([1,2], use_metahosts)
248 self._create_job_simple([1], use_metahosts, priority=1)
jamesren883492a2010-02-12 00:45:18 +0000249 self._run_scheduler()
jadmanski0afbb632008-06-06 21:10:57 +0000250 self._assert_job_scheduled_on(4, 1) # higher priority
251 self._assert_job_scheduled_on(2, 2) # earlier job over later
252 self._check_for_extra_schedulings()
showardce38e0c2008-05-29 19:36:16 +0000253
254
jadmanski0afbb632008-06-06 21:10:57 +0000255 def _test_hosts_ready_helper(self, use_metahosts):
256 """
257 Only hosts that are status=Ready, unlocked and not invalid get
258 scheduled.
259 """
260 self._create_job_simple([1], use_metahosts)
showardeab66ce2009-12-23 00:03:56 +0000261 self._do_query('UPDATE afe_hosts SET status="Running" 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 status="Ready", locked=1 '
jadmanski0afbb632008-06-06 21:10:57 +0000266 'WHERE id=1')
jamesren883492a2010-02-12 00:45:18 +0000267 self._run_scheduler()
jadmanski0afbb632008-06-06 21:10:57 +0000268 self._check_for_extra_schedulings()
showardce38e0c2008-05-29 19:36:16 +0000269
showardeab66ce2009-12-23 00:03:56 +0000270 self._do_query('UPDATE afe_hosts SET locked=0, invalid=1 '
jadmanski0afbb632008-06-06 21:10:57 +0000271 'WHERE id=1')
jamesren883492a2010-02-12 00:45:18 +0000272 self._run_scheduler()
showard5df2b192008-07-03 19:51:57 +0000273 if not use_metahosts:
274 self._assert_job_scheduled_on(1, 1)
jadmanski0afbb632008-06-06 21:10:57 +0000275 self._check_for_extra_schedulings()
showardce38e0c2008-05-29 19:36:16 +0000276
277
jadmanski0afbb632008-06-06 21:10:57 +0000278 def _test_hosts_idle_helper(self, use_metahosts):
279 'Only idle hosts get scheduled'
showard2bab8f42008-11-12 18:15:22 +0000280 self._create_job(hosts=[1], active=True)
jadmanski0afbb632008-06-06 21:10:57 +0000281 self._create_job_simple([1], use_metahosts)
jamesren883492a2010-02-12 00:45:18 +0000282 self._run_scheduler()
jadmanski0afbb632008-06-06 21:10:57 +0000283 self._check_for_extra_schedulings()
showardce38e0c2008-05-29 19:36:16 +0000284
285
showard63a34772008-08-18 19:32:50 +0000286 def _test_obey_ACLs_helper(self, use_metahosts):
showardeab66ce2009-12-23 00:03:56 +0000287 self._do_query('DELETE FROM afe_acl_groups_hosts WHERE host_id=1')
showard63a34772008-08-18 19:32:50 +0000288 self._create_job_simple([1], use_metahosts)
jamesren883492a2010-02-12 00:45:18 +0000289 self._run_scheduler()
showard63a34772008-08-18 19:32:50 +0000290 self._check_for_extra_schedulings()
291
292
jadmanski0afbb632008-06-06 21:10:57 +0000293 def test_basic_scheduling(self):
294 self._test_basic_scheduling_helper(False)
showardce38e0c2008-05-29 19:36:16 +0000295
296
jadmanski0afbb632008-06-06 21:10:57 +0000297 def test_priorities(self):
298 self._test_priorities_helper(False)
showardce38e0c2008-05-29 19:36:16 +0000299
300
jadmanski0afbb632008-06-06 21:10:57 +0000301 def test_hosts_ready(self):
302 self._test_hosts_ready_helper(False)
showardce38e0c2008-05-29 19:36:16 +0000303
304
jadmanski0afbb632008-06-06 21:10:57 +0000305 def test_hosts_idle(self):
306 self._test_hosts_idle_helper(False)
showardce38e0c2008-05-29 19:36:16 +0000307
308
showard63a34772008-08-18 19:32:50 +0000309 def test_obey_ACLs(self):
310 self._test_obey_ACLs_helper(False)
311
312
showard2924b0a2009-06-18 23:16:15 +0000313 def test_one_time_hosts_ignore_ACLs(self):
showardeab66ce2009-12-23 00:03:56 +0000314 self._do_query('DELETE FROM afe_acl_groups_hosts WHERE host_id=1')
315 self._do_query('UPDATE afe_hosts SET invalid=1 WHERE id=1')
showard2924b0a2009-06-18 23:16:15 +0000316 self._create_job_simple([1])
jamesren883492a2010-02-12 00:45:18 +0000317 self._run_scheduler()
showard2924b0a2009-06-18 23:16:15 +0000318 self._assert_job_scheduled_on(1, 1)
319 self._check_for_extra_schedulings()
320
321
showard63a34772008-08-18 19:32:50 +0000322 def test_non_metahost_on_invalid_host(self):
323 """
324 Non-metahost entries can get scheduled on invalid hosts (this is how
325 one-time hosts work).
326 """
showardeab66ce2009-12-23 00:03:56 +0000327 self._do_query('UPDATE afe_hosts SET invalid=1')
showard63a34772008-08-18 19:32:50 +0000328 self._test_basic_scheduling_helper(False)
329
330
jadmanski0afbb632008-06-06 21:10:57 +0000331 def test_metahost_scheduling(self):
showard63a34772008-08-18 19:32:50 +0000332 """
333 Basic metahost scheduling
334 """
jadmanski0afbb632008-06-06 21:10:57 +0000335 self._test_basic_scheduling_helper(True)
showardce38e0c2008-05-29 19:36:16 +0000336
337
jadmanski0afbb632008-06-06 21:10:57 +0000338 def test_metahost_priorities(self):
339 self._test_priorities_helper(True)
showardce38e0c2008-05-29 19:36:16 +0000340
341
jadmanski0afbb632008-06-06 21:10:57 +0000342 def test_metahost_hosts_ready(self):
343 self._test_hosts_ready_helper(True)
showardce38e0c2008-05-29 19:36:16 +0000344
345
jadmanski0afbb632008-06-06 21:10:57 +0000346 def test_metahost_hosts_idle(self):
347 self._test_hosts_idle_helper(True)
showardce38e0c2008-05-29 19:36:16 +0000348
349
showard63a34772008-08-18 19:32:50 +0000350 def test_metahost_obey_ACLs(self):
351 self._test_obey_ACLs_helper(True)
352
353
jadmanski0afbb632008-06-06 21:10:57 +0000354 def test_nonmetahost_over_metahost(self):
355 """
356 Non-metahost entries should take priority over metahost entries
357 for the same host
358 """
359 self._create_job(metahosts=[1])
360 self._create_job(hosts=[1])
jamesren883492a2010-02-12 00:45:18 +0000361 self._run_scheduler()
jadmanski0afbb632008-06-06 21:10:57 +0000362 self._assert_job_scheduled_on(2, 1)
363 self._check_for_extra_schedulings()
showardce38e0c2008-05-29 19:36:16 +0000364
365
Aviv Keshet1f23b692013-05-14 11:13:55 -0700366# TODO: Revive this test.
367# def test_HostScheduler_get_host_atomic_group_id(self):
368# job = self._create_job(metahosts=[self.label6.id])
369# queue_entry = scheduler_models.HostQueueEntry.fetch(
370# where='job_id=%d' % job.id)[0]
371# # Indirectly initialize the internal state of the host scheduler.
372# self._dispatcher._refresh_pending_queue_entries()
373#
374# # Test the host scheduler
375# host_scheduler = self._dispatcher._host_scheduler
376#
377#
378# # Two labels each in a different atomic group. This should log an
379# # error and continue.
380# orig_logging_error = logging.error
381# def mock_logging_error(message, *args):
382# mock_logging_error._num_calls += 1
383# # Test the logging call itself, we just wrapped it to count it.
384# orig_logging_error(message, *args)
385# mock_logging_error._num_calls = 0
386# self.god.stub_with(logging, 'error', mock_logging_error)
387# host_scheduler.refresh([])
388# self.assertNotEquals(None, host_scheduler._get_host_atomic_group_id(
389# [self.label4.id, self.label8.id], queue_entry))
390# self.assertTrue(mock_logging_error._num_calls > 0)
391# self.god.unstub(logging, 'error')
beeps7d8a1b12013-10-29 17:58:34 -0700392#
Aviv Keshet1f23b692013-05-14 11:13:55 -0700393# # Two labels both in the same atomic group, this should not raise an
394# # error, it will merely cause the job to schedule on the intersection.
395# self.assertEquals(1, host_scheduler._get_host_atomic_group_id(
396# [self.label4.id, self.label5.id]))
397#
398# self.assertEquals(None, host_scheduler._get_host_atomic_group_id([]))
399# self.assertEquals(None, host_scheduler._get_host_atomic_group_id(
400# [self.label3.id, self.label7.id, self.label6.id]))
401# self.assertEquals(1, host_scheduler._get_host_atomic_group_id(
402# [self.label4.id, self.label7.id, self.label6.id]))
403# self.assertEquals(1, host_scheduler._get_host_atomic_group_id(
404# [self.label7.id, self.label5.id]))
showard89f84db2009-03-12 20:39:13 +0000405
showard56193bb2008-08-13 20:07:41 +0000406 def test_only_schedule_queued_entries(self):
407 self._create_job(metahosts=[1])
408 self._update_hqe(set='active=1, host_id=2')
jamesren883492a2010-02-12 00:45:18 +0000409 self._run_scheduler()
showard56193bb2008-08-13 20:07:41 +0000410 self._check_for_extra_schedulings()
411
412
showardfa8629c2008-11-04 16:51:23 +0000413 def test_no_ready_hosts(self):
414 self._create_job(hosts=[1])
showardeab66ce2009-12-23 00:03:56 +0000415 self._do_query('UPDATE afe_hosts SET status="Repair Failed"')
jamesren883492a2010-02-12 00:45:18 +0000416 self._run_scheduler()
showardfa8629c2008-11-04 16:51:23 +0000417 self._check_for_extra_schedulings()
418
419
showardf13a9e22009-12-18 22:54:09 +0000420 def test_garbage_collection(self):
421 self.god.stub_with(self._dispatcher, '_seconds_between_garbage_stats',
422 999999)
423 self.god.stub_function(gc, 'collect')
424 self.god.stub_function(gc_stats, '_log_garbage_collector_stats')
425 gc.collect.expect_call().and_return(0)
426 gc_stats._log_garbage_collector_stats.expect_call()
427 # Force a garbage collection run
428 self._dispatcher._last_garbage_stats_time = 0
429 self._dispatcher._garbage_collection()
430 # The previous call should have reset the time, it won't do anything
431 # the second time. If it does, we'll get an unexpected call.
432 self._dispatcher._garbage_collection()
433
434
Prashanth B372613d2014-05-05 08:40:21 -0700435 def test_overlapping_jobs(self):
436 """Test that we can detect overlapping jobs."""
437 self._create_job_simple([1], True)
438 self._run_scheduler()
439 self._do_query('UPDATE afe_hosts SET leased=0 where id=1')
440 self._create_job_simple([1], True)
441 self._run_scheduler()
442 jobs = monitor_db_cleanup.UserCleanup.get_overlapping_jobs()
443 self.assertTrue(jobs[0]['job_id'] == 1 and jobs[0]['host_id'] == 1 and
444 jobs[1]['job_id'] == 2 and jobs[1]['host_id'] == 1)
445
showardf13a9e22009-12-18 22:54:09 +0000446
showardb2e2c322008-10-14 17:33:55 +0000447class DispatcherThrottlingTest(BaseSchedulerTest):
showard4c5374f2008-09-04 17:02:56 +0000448 """
449 Test that the dispatcher throttles:
450 * total number of running processes
451 * number of processes started per cycle
452 """
453 _MAX_RUNNING = 3
454 _MAX_STARTED = 2
455
456 def setUp(self):
457 super(DispatcherThrottlingTest, self).setUp()
showard324bf812009-01-20 23:23:38 +0000458 scheduler_config.config.max_processes_per_drone = self._MAX_RUNNING
showardd1ee1dd2009-01-07 21:33:08 +0000459 scheduler_config.config.max_processes_started_per_cycle = (
460 self._MAX_STARTED)
showard4c5374f2008-09-04 17:02:56 +0000461
jamesren76fcf192010-04-21 20:39:50 +0000462 def fake_max_runnable_processes(fake_self, username,
463 drone_hostnames_allowed):
showardd1195652009-12-08 22:21:02 +0000464 running = sum(agent.task.num_processes
showard324bf812009-01-20 23:23:38 +0000465 for agent in self._agents
showard8cc058f2009-09-08 16:26:33 +0000466 if agent.started and not agent.is_done())
showard324bf812009-01-20 23:23:38 +0000467 return self._MAX_RUNNING - running
468 self.god.stub_with(drone_manager.DroneManager, 'max_runnable_processes',
469 fake_max_runnable_processes)
showard2fa51692009-01-13 23:48:08 +0000470
showard4c5374f2008-09-04 17:02:56 +0000471
showard4c5374f2008-09-04 17:02:56 +0000472 def _setup_some_agents(self, num_agents):
showard170873e2009-01-07 00:22:26 +0000473 self._agents = [DummyAgent() for i in xrange(num_agents)]
showard4c5374f2008-09-04 17:02:56 +0000474 self._dispatcher._agents = list(self._agents)
475
476
477 def _run_a_few_cycles(self):
478 for i in xrange(4):
479 self._dispatcher._handle_agents()
480
481
482 def _assert_agents_started(self, indexes, is_started=True):
483 for i in indexes:
showard8cc058f2009-09-08 16:26:33 +0000484 self.assert_(self._agents[i].started == is_started,
showard4c5374f2008-09-04 17:02:56 +0000485 'Agent %d %sstarted' %
486 (i, is_started and 'not ' or ''))
487
488
489 def _assert_agents_not_started(self, indexes):
490 self._assert_agents_started(indexes, False)
491
492
493 def test_throttle_total(self):
494 self._setup_some_agents(4)
495 self._run_a_few_cycles()
496 self._assert_agents_started([0, 1, 2])
497 self._assert_agents_not_started([3])
498
499
500 def test_throttle_per_cycle(self):
501 self._setup_some_agents(3)
502 self._dispatcher._handle_agents()
503 self._assert_agents_started([0, 1])
504 self._assert_agents_not_started([2])
505
506
507 def test_throttle_with_synchronous(self):
508 self._setup_some_agents(2)
showardd1195652009-12-08 22:21:02 +0000509 self._agents[0].task.num_processes = 3
showard4c5374f2008-09-04 17:02:56 +0000510 self._run_a_few_cycles()
511 self._assert_agents_started([0])
512 self._assert_agents_not_started([1])
513
514
515 def test_large_agent_starvation(self):
516 """
517 Ensure large agents don't get starved by lower-priority agents.
518 """
519 self._setup_some_agents(3)
showardd1195652009-12-08 22:21:02 +0000520 self._agents[1].task.num_processes = 3
showard4c5374f2008-09-04 17:02:56 +0000521 self._run_a_few_cycles()
522 self._assert_agents_started([0])
523 self._assert_agents_not_started([1, 2])
524
525 self._agents[0].set_done(True)
526 self._run_a_few_cycles()
527 self._assert_agents_started([1])
528 self._assert_agents_not_started([2])
529
530
531 def test_zero_process_agent(self):
532 self._setup_some_agents(5)
showardd1195652009-12-08 22:21:02 +0000533 self._agents[4].task.num_processes = 0
showard4c5374f2008-09-04 17:02:56 +0000534 self._run_a_few_cycles()
535 self._assert_agents_started([0, 1, 2, 4])
536 self._assert_agents_not_started([3])
537
538
jadmanski3d161b02008-06-06 15:43:36 +0000539class PidfileRunMonitorTest(unittest.TestCase):
showard170873e2009-01-07 00:22:26 +0000540 execution_tag = 'test_tag'
jadmanski0afbb632008-06-06 21:10:57 +0000541 pid = 12345
showard170873e2009-01-07 00:22:26 +0000542 process = drone_manager.Process('myhost', pid)
showard21baa452008-10-21 00:08:39 +0000543 num_tests_failed = 1
jadmanski3d161b02008-06-06 15:43:36 +0000544
jadmanski0afbb632008-06-06 21:10:57 +0000545 def setUp(self):
546 self.god = mock.mock_god()
showard170873e2009-01-07 00:22:26 +0000547 self.mock_drone_manager = self.god.create_mock_class(
548 drone_manager.DroneManager, 'drone_manager')
beeps5e2bb4a2013-10-28 11:26:45 -0700549 self.god.stub_with(pidfile_monitor, '_drone_manager',
showard170873e2009-01-07 00:22:26 +0000550 self.mock_drone_manager)
551 self.god.stub_function(email_manager.manager, 'enqueue_notify_email')
beeps5e2bb4a2013-10-28 11:26:45 -0700552 self.god.stub_with(pidfile_monitor, '_get_pidfile_timeout_secs',
showardec6a3b92009-09-25 20:29:13 +0000553 self._mock_get_pidfile_timeout_secs)
showard170873e2009-01-07 00:22:26 +0000554
555 self.pidfile_id = object()
556
showardd3dc1992009-04-22 21:01:40 +0000557 (self.mock_drone_manager.get_pidfile_id_from
558 .expect_call(self.execution_tag,
jamesrenc44ae992010-02-19 00:12:54 +0000559 pidfile_name=drone_manager.AUTOSERV_PID_FILE)
showardd3dc1992009-04-22 21:01:40 +0000560 .and_return(self.pidfile_id))
showard170873e2009-01-07 00:22:26 +0000561
beeps5e2bb4a2013-10-28 11:26:45 -0700562 self.monitor = pidfile_monitor.PidfileRunMonitor()
showard170873e2009-01-07 00:22:26 +0000563 self.monitor.attach_to_existing_process(self.execution_tag)
jadmanski3d161b02008-06-06 15:43:36 +0000564
jadmanski0afbb632008-06-06 21:10:57 +0000565 def tearDown(self):
566 self.god.unstub_all()
jadmanski3d161b02008-06-06 15:43:36 +0000567
568
showardec6a3b92009-09-25 20:29:13 +0000569 def _mock_get_pidfile_timeout_secs(self):
570 return 300
571
572
showard170873e2009-01-07 00:22:26 +0000573 def setup_pidfile(self, pid=None, exit_code=None, tests_failed=None,
574 use_second_read=False):
575 contents = drone_manager.PidfileContents()
576 if pid is not None:
577 contents.process = drone_manager.Process('myhost', pid)
578 contents.exit_status = exit_code
579 contents.num_tests_failed = tests_failed
580 self.mock_drone_manager.get_pidfile_contents.expect_call(
581 self.pidfile_id, use_second_read=use_second_read).and_return(
582 contents)
583
584
jadmanski0afbb632008-06-06 21:10:57 +0000585 def set_not_yet_run(self):
showard170873e2009-01-07 00:22:26 +0000586 self.setup_pidfile()
jadmanski3d161b02008-06-06 15:43:36 +0000587
588
showard3dd6b882008-10-27 19:21:39 +0000589 def set_empty_pidfile(self):
showard170873e2009-01-07 00:22:26 +0000590 self.setup_pidfile()
showard3dd6b882008-10-27 19:21:39 +0000591
592
showard170873e2009-01-07 00:22:26 +0000593 def set_running(self, use_second_read=False):
594 self.setup_pidfile(self.pid, use_second_read=use_second_read)
jadmanski3d161b02008-06-06 15:43:36 +0000595
596
showard170873e2009-01-07 00:22:26 +0000597 def set_complete(self, error_code, use_second_read=False):
598 self.setup_pidfile(self.pid, error_code, self.num_tests_failed,
599 use_second_read=use_second_read)
600
601
602 def _check_monitor(self, expected_pid, expected_exit_status,
603 expected_num_tests_failed):
604 if expected_pid is None:
605 self.assertEquals(self.monitor._state.process, None)
606 else:
607 self.assertEquals(self.monitor._state.process.pid, expected_pid)
608 self.assertEquals(self.monitor._state.exit_status, expected_exit_status)
609 self.assertEquals(self.monitor._state.num_tests_failed,
610 expected_num_tests_failed)
611
612
613 self.god.check_playback()
jadmanski3d161b02008-06-06 15:43:36 +0000614
615
showard21baa452008-10-21 00:08:39 +0000616 def _test_read_pidfile_helper(self, expected_pid, expected_exit_status,
617 expected_num_tests_failed):
618 self.monitor._read_pidfile()
showard170873e2009-01-07 00:22:26 +0000619 self._check_monitor(expected_pid, expected_exit_status,
620 expected_num_tests_failed)
jadmanski3d161b02008-06-06 15:43:36 +0000621
622
showard21baa452008-10-21 00:08:39 +0000623 def _get_expected_tests_failed(self, expected_exit_status):
624 if expected_exit_status is None:
625 expected_tests_failed = None
626 else:
627 expected_tests_failed = self.num_tests_failed
628 return expected_tests_failed
629
630
jadmanski0afbb632008-06-06 21:10:57 +0000631 def test_read_pidfile(self):
632 self.set_not_yet_run()
showard21baa452008-10-21 00:08:39 +0000633 self._test_read_pidfile_helper(None, None, None)
jadmanski3d161b02008-06-06 15:43:36 +0000634
showard3dd6b882008-10-27 19:21:39 +0000635 self.set_empty_pidfile()
636 self._test_read_pidfile_helper(None, None, None)
637
jadmanski0afbb632008-06-06 21:10:57 +0000638 self.set_running()
showard21baa452008-10-21 00:08:39 +0000639 self._test_read_pidfile_helper(self.pid, None, None)
jadmanski3d161b02008-06-06 15:43:36 +0000640
jadmanski0afbb632008-06-06 21:10:57 +0000641 self.set_complete(123)
showard21baa452008-10-21 00:08:39 +0000642 self._test_read_pidfile_helper(self.pid, 123, self.num_tests_failed)
jadmanski3d161b02008-06-06 15:43:36 +0000643
644
jadmanski0afbb632008-06-06 21:10:57 +0000645 def test_read_pidfile_error(self):
showard170873e2009-01-07 00:22:26 +0000646 self.mock_drone_manager.get_pidfile_contents.expect_call(
647 self.pidfile_id, use_second_read=False).and_return(
648 drone_manager.InvalidPidfile('error'))
beeps5e2bb4a2013-10-28 11:26:45 -0700649 self.assertRaises(pidfile_monitor.PidfileRunMonitor._PidfileException,
showard21baa452008-10-21 00:08:39 +0000650 self.monitor._read_pidfile)
jadmanski0afbb632008-06-06 21:10:57 +0000651 self.god.check_playback()
jadmanski3d161b02008-06-06 15:43:36 +0000652
653
showard170873e2009-01-07 00:22:26 +0000654 def setup_is_running(self, is_running):
655 self.mock_drone_manager.is_process_running.expect_call(
656 self.process).and_return(is_running)
jadmanski3d161b02008-06-06 15:43:36 +0000657
658
showard21baa452008-10-21 00:08:39 +0000659 def _test_get_pidfile_info_helper(self, expected_pid, expected_exit_status,
660 expected_num_tests_failed):
661 self.monitor._get_pidfile_info()
showard170873e2009-01-07 00:22:26 +0000662 self._check_monitor(expected_pid, expected_exit_status,
663 expected_num_tests_failed)
jadmanski3d161b02008-06-06 15:43:36 +0000664
665
jadmanski0afbb632008-06-06 21:10:57 +0000666 def test_get_pidfile_info(self):
showard21baa452008-10-21 00:08:39 +0000667 """
668 normal cases for get_pidfile_info
669 """
jadmanski0afbb632008-06-06 21:10:57 +0000670 # running
671 self.set_running()
showard170873e2009-01-07 00:22:26 +0000672 self.setup_is_running(True)
showard21baa452008-10-21 00:08:39 +0000673 self._test_get_pidfile_info_helper(self.pid, None, None)
jadmanski3d161b02008-06-06 15:43:36 +0000674
jadmanski0afbb632008-06-06 21:10:57 +0000675 # exited during check
676 self.set_running()
showard170873e2009-01-07 00:22:26 +0000677 self.setup_is_running(False)
678 self.set_complete(123, use_second_read=True) # pidfile gets read again
showard21baa452008-10-21 00:08:39 +0000679 self._test_get_pidfile_info_helper(self.pid, 123, self.num_tests_failed)
jadmanski3d161b02008-06-06 15:43:36 +0000680
jadmanski0afbb632008-06-06 21:10:57 +0000681 # completed
682 self.set_complete(123)
showard21baa452008-10-21 00:08:39 +0000683 self._test_get_pidfile_info_helper(self.pid, 123, self.num_tests_failed)
jadmanski3d161b02008-06-06 15:43:36 +0000684
685
jadmanski0afbb632008-06-06 21:10:57 +0000686 def test_get_pidfile_info_running_no_proc(self):
showard21baa452008-10-21 00:08:39 +0000687 """
688 pidfile shows process running, but no proc exists
689 """
jadmanski0afbb632008-06-06 21:10:57 +0000690 # running but no proc
691 self.set_running()
showard170873e2009-01-07 00:22:26 +0000692 self.setup_is_running(False)
693 self.set_running(use_second_read=True)
694 email_manager.manager.enqueue_notify_email.expect_call(
jadmanski0afbb632008-06-06 21:10:57 +0000695 mock.is_string_comparator(), mock.is_string_comparator())
showard21baa452008-10-21 00:08:39 +0000696 self._test_get_pidfile_info_helper(self.pid, 1, 0)
jadmanski0afbb632008-06-06 21:10:57 +0000697 self.assertTrue(self.monitor.lost_process)
jadmanski3d161b02008-06-06 15:43:36 +0000698
699
jadmanski0afbb632008-06-06 21:10:57 +0000700 def test_get_pidfile_info_not_yet_run(self):
showard21baa452008-10-21 00:08:39 +0000701 """
702 pidfile hasn't been written yet
703 """
jadmanski0afbb632008-06-06 21:10:57 +0000704 self.set_not_yet_run()
showard21baa452008-10-21 00:08:39 +0000705 self._test_get_pidfile_info_helper(None, None, None)
jadmanski3d161b02008-06-06 15:43:36 +0000706
jadmanski3d161b02008-06-06 15:43:36 +0000707
showard170873e2009-01-07 00:22:26 +0000708 def test_process_failed_to_write_pidfile(self):
jadmanski0afbb632008-06-06 21:10:57 +0000709 self.set_not_yet_run()
showard170873e2009-01-07 00:22:26 +0000710 email_manager.manager.enqueue_notify_email.expect_call(
711 mock.is_string_comparator(), mock.is_string_comparator())
showardec6a3b92009-09-25 20:29:13 +0000712 self.monitor._start_time = (time.time() -
beeps5e2bb4a2013-10-28 11:26:45 -0700713 pidfile_monitor._get_pidfile_timeout_secs() - 1)
showard35162b02009-03-03 02:17:30 +0000714 self._test_get_pidfile_info_helper(None, 1, 0)
715 self.assertTrue(self.monitor.lost_process)
jadmanski3d161b02008-06-06 15:43:36 +0000716
717
718class AgentTest(unittest.TestCase):
jadmanski0afbb632008-06-06 21:10:57 +0000719 def setUp(self):
720 self.god = mock.mock_god()
showard6b733412009-04-27 20:09:18 +0000721 self._dispatcher = self.god.create_mock_class(monitor_db.Dispatcher,
722 'dispatcher')
jadmanski3d161b02008-06-06 15:43:36 +0000723
724
jadmanski0afbb632008-06-06 21:10:57 +0000725 def tearDown(self):
726 self.god.unstub_all()
jadmanski3d161b02008-06-06 15:43:36 +0000727
728
showard170873e2009-01-07 00:22:26 +0000729 def _create_mock_task(self, name):
beeps5e2bb4a2013-10-28 11:26:45 -0700730 task = self.god.create_mock_class(agent_task.AgentTask, name)
showard418785b2009-11-23 20:19:59 +0000731 task.num_processes = 1
showard6b733412009-04-27 20:09:18 +0000732 _set_host_and_qe_ids(task)
showard170873e2009-01-07 00:22:26 +0000733 return task
734
showard8cc058f2009-09-08 16:26:33 +0000735 def _create_agent(self, task):
736 agent = monitor_db.Agent(task)
showard6b733412009-04-27 20:09:18 +0000737 agent.dispatcher = self._dispatcher
738 return agent
739
740
741 def _finish_agent(self, agent):
742 while not agent.is_done():
743 agent.tick()
744
showard170873e2009-01-07 00:22:26 +0000745
showard8cc058f2009-09-08 16:26:33 +0000746 def test_agent_abort(self):
747 task = self._create_mock_task('task')
748 task.poll.expect_call()
749 task.is_done.expect_call().and_return(False)
750 task.abort.expect_call()
751 task.aborted = True
jadmanski3d161b02008-06-06 15:43:36 +0000752
showard8cc058f2009-09-08 16:26:33 +0000753 agent = self._create_agent(task)
showard6b733412009-04-27 20:09:18 +0000754 agent.tick()
755 agent.abort()
756 self._finish_agent(agent)
757 self.god.check_playback()
758
759
showard08a36412009-05-05 01:01:13 +0000760 def _test_agent_abort_before_started_helper(self, ignore_abort=False):
showard20f9bdd2009-04-29 19:48:33 +0000761 task = self._create_mock_task('task')
showard08a36412009-05-05 01:01:13 +0000762 task.abort.expect_call()
763 if ignore_abort:
764 task.aborted = False
765 task.poll.expect_call()
766 task.is_done.expect_call().and_return(True)
showard08a36412009-05-05 01:01:13 +0000767 task.success = True
768 else:
769 task.aborted = True
770
showard8cc058f2009-09-08 16:26:33 +0000771 agent = self._create_agent(task)
showard20f9bdd2009-04-29 19:48:33 +0000772 agent.abort()
showard20f9bdd2009-04-29 19:48:33 +0000773 self._finish_agent(agent)
774 self.god.check_playback()
775
776
showard08a36412009-05-05 01:01:13 +0000777 def test_agent_abort_before_started(self):
778 self._test_agent_abort_before_started_helper()
779 self._test_agent_abort_before_started_helper(True)
780
781
jamesrenc44ae992010-02-19 00:12:54 +0000782class JobSchedulingTest(BaseSchedulerTest):
showarde58e3f82008-11-20 19:04:59 +0000783 def _test_run_helper(self, expect_agent=True, expect_starting=False,
784 expect_pending=False):
785 if expect_starting:
786 expected_status = models.HostQueueEntry.Status.STARTING
787 elif expect_pending:
788 expected_status = models.HostQueueEntry.Status.PENDING
789 else:
790 expected_status = models.HostQueueEntry.Status.VERIFYING
jamesrenc44ae992010-02-19 00:12:54 +0000791 job = scheduler_models.Job.fetch('id = 1')[0]
792 queue_entry = scheduler_models.HostQueueEntry.fetch('id = 1')[0]
showard77182562009-06-10 00:16:05 +0000793 assert queue_entry.job is job
showard8cc058f2009-09-08 16:26:33 +0000794 job.run_if_ready(queue_entry)
showardb2e2c322008-10-14 17:33:55 +0000795
showard2bab8f42008-11-12 18:15:22 +0000796 self.god.check_playback()
showard8cc058f2009-09-08 16:26:33 +0000797
798 self._dispatcher._schedule_delay_tasks()
799 self._dispatcher._schedule_running_host_queue_entries()
800 agent = self._dispatcher._agents[0]
801
showard77182562009-06-10 00:16:05 +0000802 actual_status = models.HostQueueEntry.smart_get(1).status
803 self.assertEquals(expected_status, actual_status)
showard2bab8f42008-11-12 18:15:22 +0000804
showard9976ce92008-10-15 20:28:13 +0000805 if not expect_agent:
806 self.assertEquals(agent, None)
807 return
808
showardb2e2c322008-10-14 17:33:55 +0000809 self.assert_(isinstance(agent, monitor_db.Agent))
showard8cc058f2009-09-08 16:26:33 +0000810 self.assert_(agent.task)
811 return agent.task
showardc9ae1782009-01-30 01:42:37 +0000812
813
showard77182562009-06-10 00:16:05 +0000814 def test_run_if_ready_delays(self):
815 # Also tests Job.run_with_ready_delay() on atomic group jobs.
816 django_job = self._create_job(hosts=[5, 6], atomic_group=1)
jamesrenc44ae992010-02-19 00:12:54 +0000817 job = scheduler_models.Job(django_job.id)
showard77182562009-06-10 00:16:05 +0000818 self.assertEqual(1, job.synch_count)
819 django_hqes = list(models.HostQueueEntry.objects.filter(job=job.id))
820 self.assertEqual(2, len(django_hqes))
821 self.assertEqual(2, django_hqes[0].atomic_group.max_number_of_machines)
822
823 def set_hqe_status(django_hqe, status):
824 django_hqe.status = status
825 django_hqe.save()
jamesrenc44ae992010-02-19 00:12:54 +0000826 scheduler_models.HostQueueEntry(django_hqe.id).host.set_status(status)
showard77182562009-06-10 00:16:05 +0000827
828 # An initial state, our synch_count is 1
829 set_hqe_status(django_hqes[0], models.HostQueueEntry.Status.VERIFYING)
830 set_hqe_status(django_hqes[1], models.HostQueueEntry.Status.PENDING)
831
832 # So that we don't depend on the config file value during the test.
833 self.assert_(scheduler_config.config
834 .secs_to_wait_for_atomic_group_hosts is not None)
835 self.god.stub_with(scheduler_config.config,
836 'secs_to_wait_for_atomic_group_hosts', 123456)
837
jamesrenc44ae992010-02-19 00:12:54 +0000838 # Get the pending one as a scheduler_models.HostQueueEntry object.
839 hqe = scheduler_models.HostQueueEntry(django_hqes[1].id)
showard77182562009-06-10 00:16:05 +0000840 self.assert_(not job._delay_ready_task)
841 self.assertTrue(job.is_ready())
842
843 # Ready with one pending, one verifying and an atomic group should
844 # result in a DelayCallTask to re-check if we're ready a while later.
showard8cc058f2009-09-08 16:26:33 +0000845 job.run_if_ready(hqe)
846 self.assertEquals('Waiting', hqe.status)
847 self._dispatcher._schedule_delay_tasks()
848 self.assertEquals('Pending', hqe.status)
849 agent = self._dispatcher._agents[0]
showard77182562009-06-10 00:16:05 +0000850 self.assert_(job._delay_ready_task)
851 self.assert_(isinstance(agent, monitor_db.Agent))
showard8cc058f2009-09-08 16:26:33 +0000852 self.assert_(agent.task)
853 delay_task = agent.task
jamesrenc44ae992010-02-19 00:12:54 +0000854 self.assert_(isinstance(delay_task, scheduler_models.DelayedCallTask))
showard77182562009-06-10 00:16:05 +0000855 self.assert_(not delay_task.is_done())
856
showard8cc058f2009-09-08 16:26:33 +0000857 self.god.stub_function(delay_task, 'abort')
858
showard77182562009-06-10 00:16:05 +0000859 self.god.stub_function(job, 'run')
860
showardd2014822009-10-12 20:26:58 +0000861 self.god.stub_function(job, '_pending_count')
showardd07a5f32009-12-07 19:36:20 +0000862 self.god.stub_with(job, 'synch_count', 9)
863 self.god.stub_function(job, 'request_abort')
showardd2014822009-10-12 20:26:58 +0000864
showard77182562009-06-10 00:16:05 +0000865 # Test that the DelayedCallTask's callback queued up above does the
showardd2014822009-10-12 20:26:58 +0000866 # correct thing and does not call run if there are not enough hosts
867 # in pending after the delay.
showardd2014822009-10-12 20:26:58 +0000868 job._pending_count.expect_call().and_return(0)
showardd07a5f32009-12-07 19:36:20 +0000869 job.request_abort.expect_call()
showardd2014822009-10-12 20:26:58 +0000870 delay_task._callback()
871 self.god.check_playback()
872
873 # Test that the DelayedCallTask's callback queued up above does the
874 # correct thing and returns the Agent returned by job.run() if
875 # there are still enough hosts pending after the delay.
showardd07a5f32009-12-07 19:36:20 +0000876 job.synch_count = 4
showardd2014822009-10-12 20:26:58 +0000877 job._pending_count.expect_call().and_return(4)
showard8cc058f2009-09-08 16:26:33 +0000878 job.run.expect_call(hqe)
879 delay_task._callback()
880 self.god.check_playback()
showard77182562009-06-10 00:16:05 +0000881
showardd2014822009-10-12 20:26:58 +0000882 job._pending_count.expect_call().and_return(4)
883
showard77182562009-06-10 00:16:05 +0000884 # Adjust the delay deadline so that enough time has passed.
885 job._delay_ready_task.end_time = time.time() - 111111
showard8cc058f2009-09-08 16:26:33 +0000886 job.run.expect_call(hqe)
showard77182562009-06-10 00:16:05 +0000887 # ...the delay_expired condition should cause us to call run()
showard8cc058f2009-09-08 16:26:33 +0000888 self._dispatcher._handle_agents()
889 self.god.check_playback()
890 delay_task.success = False
showard77182562009-06-10 00:16:05 +0000891
892 # Adjust the delay deadline back so that enough time has not passed.
893 job._delay_ready_task.end_time = time.time() + 111111
showard8cc058f2009-09-08 16:26:33 +0000894 self._dispatcher._handle_agents()
895 self.god.check_playback()
showard77182562009-06-10 00:16:05 +0000896
showard77182562009-06-10 00:16:05 +0000897 # Now max_number_of_machines HQEs are in pending state. Remaining
898 # delay will now be ignored.
jamesrenc44ae992010-02-19 00:12:54 +0000899 other_hqe = scheduler_models.HostQueueEntry(django_hqes[0].id)
showard8cc058f2009-09-08 16:26:33 +0000900 self.god.unstub(job, 'run')
showardd2014822009-10-12 20:26:58 +0000901 self.god.unstub(job, '_pending_count')
showardd07a5f32009-12-07 19:36:20 +0000902 self.god.unstub(job, 'synch_count')
903 self.god.unstub(job, 'request_abort')
showard77182562009-06-10 00:16:05 +0000904 # ...the over_max_threshold test should cause us to call run()
showard8cc058f2009-09-08 16:26:33 +0000905 delay_task.abort.expect_call()
906 other_hqe.on_pending()
907 self.assertEquals('Starting', other_hqe.status)
908 self.assertEquals('Starting', hqe.status)
909 self.god.stub_function(job, 'run')
910 self.god.unstub(delay_task, 'abort')
showard77182562009-06-10 00:16:05 +0000911
showard8cc058f2009-09-08 16:26:33 +0000912 hqe.set_status('Pending')
913 other_hqe.set_status('Pending')
showard708b3522009-08-20 23:26:15 +0000914 # Now we're not over the max for the atomic group. But all assigned
915 # hosts are in pending state. over_max_threshold should make us run().
showard8cc058f2009-09-08 16:26:33 +0000916 hqe.atomic_group.max_number_of_machines += 1
917 hqe.atomic_group.save()
918 job.run.expect_call(hqe)
919 hqe.on_pending()
920 self.god.check_playback()
921 hqe.atomic_group.max_number_of_machines -= 1
922 hqe.atomic_group.save()
showard708b3522009-08-20 23:26:15 +0000923
jamesrenc44ae992010-02-19 00:12:54 +0000924 other_hqe = scheduler_models.HostQueueEntry(django_hqes[0].id)
showard8cc058f2009-09-08 16:26:33 +0000925 self.assertTrue(hqe.job is other_hqe.job)
showard77182562009-06-10 00:16:05 +0000926 # DBObject classes should reuse instances so these should be the same.
927 self.assertEqual(job, other_hqe.job)
showard8cc058f2009-09-08 16:26:33 +0000928 self.assertEqual(other_hqe.job, hqe.job)
showard77182562009-06-10 00:16:05 +0000929 # Be sure our delay was not lost during the other_hqe construction.
showard8cc058f2009-09-08 16:26:33 +0000930 self.assertEqual(job._delay_ready_task, delay_task)
showard77182562009-06-10 00:16:05 +0000931 self.assert_(job._delay_ready_task)
932 self.assertFalse(job._delay_ready_task.is_done())
933 self.assertFalse(job._delay_ready_task.aborted)
934
935 # We want the real run() to be called below.
936 self.god.unstub(job, 'run')
937
938 # We pass in the other HQE this time the same way it would happen
939 # for real when one host finishes verifying and enters pending.
showard8cc058f2009-09-08 16:26:33 +0000940 job.run_if_ready(other_hqe)
showard77182562009-06-10 00:16:05 +0000941
942 # The delayed task must be aborted by the actual run() call above.
943 self.assertTrue(job._delay_ready_task.aborted)
944 self.assertFalse(job._delay_ready_task.success)
945 self.assertTrue(job._delay_ready_task.is_done())
946
947 # Check that job run() and _finish_run() were called by the above:
showard8cc058f2009-09-08 16:26:33 +0000948 self._dispatcher._schedule_running_host_queue_entries()
949 agent = self._dispatcher._agents[0]
950 self.assert_(agent.task)
951 task = agent.task
952 self.assert_(isinstance(task, monitor_db.QueueTask))
showard77182562009-06-10 00:16:05 +0000953 # Requery these hqes in order to verify the status from the DB.
954 django_hqes = list(models.HostQueueEntry.objects.filter(job=job.id))
955 for entry in django_hqes:
956 self.assertEqual(models.HostQueueEntry.Status.STARTING,
957 entry.status)
958
959 # We're already running, but more calls to run_with_ready_delay can
960 # continue to come in due to straggler hosts enter Pending. Make
961 # sure we don't do anything.
showard8cc058f2009-09-08 16:26:33 +0000962 self.god.stub_function(job, 'run')
963 job.run_with_ready_delay(hqe)
964 self.god.check_playback()
965 self.god.unstub(job, 'run')
showard77182562009-06-10 00:16:05 +0000966
967
showardf1ae3542009-05-11 19:26:02 +0000968 def test_run_synchronous_atomic_group_ready(self):
969 self._create_job(hosts=[5, 6], atomic_group=1, synchronous=True)
970 self._update_hqe("status='Pending', execution_subdir=''")
971
showard8cc058f2009-09-08 16:26:33 +0000972 queue_task = self._test_run_helper(expect_starting=True)
showardf1ae3542009-05-11 19:26:02 +0000973
974 self.assert_(isinstance(queue_task, monitor_db.QueueTask))
showard77182562009-06-10 00:16:05 +0000975 # Atomic group jobs that do not depend on a specific label in the
976 # atomic group will use the atomic group name as their group name.
showardd1195652009-12-08 22:21:02 +0000977 self.assertEquals(queue_task.queue_entries[0].get_group_name(),
978 'atomic1')
showardf1ae3542009-05-11 19:26:02 +0000979
980
981 def test_run_synchronous_atomic_group_with_label_ready(self):
982 job = self._create_job(hosts=[5, 6], atomic_group=1, synchronous=True)
983 job.dependency_labels.add(self.label4)
984 self._update_hqe("status='Pending', execution_subdir=''")
985
showard8cc058f2009-09-08 16:26:33 +0000986 queue_task = self._test_run_helper(expect_starting=True)
showardf1ae3542009-05-11 19:26:02 +0000987
988 self.assert_(isinstance(queue_task, monitor_db.QueueTask))
989 # Atomic group jobs that also specify a label in the atomic group
990 # will use the label name as their group name.
showardd1195652009-12-08 22:21:02 +0000991 self.assertEquals(queue_task.queue_entries[0].get_group_name(),
992 'label4')
showardf1ae3542009-05-11 19:26:02 +0000993
994
jamesrenc44ae992010-02-19 00:12:54 +0000995 def test_run_synchronous_ready(self):
996 self._create_job(hosts=[1, 2], synchronous=True)
997 self._update_hqe("status='Pending', execution_subdir=''")
showard21baa452008-10-21 00:08:39 +0000998
jamesrenc44ae992010-02-19 00:12:54 +0000999 queue_task = self._test_run_helper(expect_starting=True)
showard8cc058f2009-09-08 16:26:33 +00001000
jamesrenc44ae992010-02-19 00:12:54 +00001001 self.assert_(isinstance(queue_task, monitor_db.QueueTask))
1002 self.assertEquals(queue_task.job.id, 1)
1003 hqe_ids = [hqe.id for hqe in queue_task.queue_entries]
1004 self.assertEquals(hqe_ids, [1, 2])
showard21baa452008-10-21 00:08:39 +00001005
1006
jamesrenc44ae992010-02-19 00:12:54 +00001007 def test_schedule_running_host_queue_entries_fail(self):
1008 self._create_job(hosts=[2])
1009 self._update_hqe("status='%s', execution_subdir=''" %
1010 models.HostQueueEntry.Status.PENDING)
1011 job = scheduler_models.Job.fetch('id = 1')[0]
1012 queue_entry = scheduler_models.HostQueueEntry.fetch('id = 1')[0]
1013 assert queue_entry.job is job
1014 job.run_if_ready(queue_entry)
1015 self.assertEqual(queue_entry.status,
1016 models.HostQueueEntry.Status.STARTING)
1017 self.assert_(queue_entry.execution_subdir)
1018 self.god.check_playback()
showard21baa452008-10-21 00:08:39 +00001019
jamesrenc44ae992010-02-19 00:12:54 +00001020 class dummy_test_agent(object):
1021 task = 'dummy_test_agent'
1022 self._dispatcher._register_agent_for_ids(
1023 self._dispatcher._host_agents, [queue_entry.host.id],
1024 dummy_test_agent)
showard21baa452008-10-21 00:08:39 +00001025
jamesrenc44ae992010-02-19 00:12:54 +00001026 # Attempted to schedule on a host that already has an agent.
Prashanth B0e960282014-05-13 19:38:28 -07001027 self.assertRaises(scheduler_lib.SchedulerError,
jamesrenc44ae992010-02-19 00:12:54 +00001028 self._dispatcher._schedule_running_host_queue_entries)
showardf1ae3542009-05-11 19:26:02 +00001029
1030
jamesren47bd7372010-03-13 00:58:17 +00001031 def test_schedule_hostless_job(self):
1032 job = self._create_job(hostless=True)
1033 self.assertEqual(1, job.hostqueueentry_set.count())
1034 hqe_query = scheduler_models.HostQueueEntry.fetch(
1035 'id = %s' % job.hostqueueentry_set.all()[0].id)
1036 self.assertEqual(1, len(hqe_query))
1037 hqe = hqe_query[0]
1038
1039 self.assertEqual(models.HostQueueEntry.Status.QUEUED, hqe.status)
1040 self.assertEqual(0, len(self._dispatcher._agents))
1041
1042 self._dispatcher._schedule_new_jobs()
1043
1044 self.assertEqual(models.HostQueueEntry.Status.STARTING, hqe.status)
1045 self.assertEqual(1, len(self._dispatcher._agents))
1046
1047 self._dispatcher._schedule_new_jobs()
1048
1049 # No change to previously schedule hostless job, and no additional agent
1050 self.assertEqual(models.HostQueueEntry.Status.STARTING, hqe.status)
1051 self.assertEqual(1, len(self._dispatcher._agents))
1052
1053
showardf1ae3542009-05-11 19:26:02 +00001054class TopLevelFunctionsTest(unittest.TestCase):
mblighe7d9c602009-07-02 19:02:33 +00001055 def setUp(self):
1056 self.god = mock.mock_god()
1057
1058
1059 def tearDown(self):
1060 self.god.unstub_all()
1061
1062
showardf1ae3542009-05-11 19:26:02 +00001063 def test_autoserv_command_line(self):
1064 machines = 'abcd12,efgh34'
showardf1ae3542009-05-11 19:26:02 +00001065 extra_args = ['-Z', 'hello']
showardf65b7402009-12-18 22:44:35 +00001066 expected_command_line_base = set((monitor_db._autoserv_path, '-p',
1067 '-m', machines, '-r',
1068 drone_manager.WORKING_DIRECTORY))
showardf1ae3542009-05-11 19:26:02 +00001069
showardf65b7402009-12-18 22:44:35 +00001070 expected_command_line = expected_command_line_base.union(
1071 ['--verbose']).union(extra_args)
1072 command_line = set(
1073 monitor_db._autoserv_command_line(machines, extra_args))
1074 self.assertEqual(expected_command_line, command_line)
showardf1ae3542009-05-11 19:26:02 +00001075
1076 class FakeJob(object):
1077 owner = 'Bob'
1078 name = 'fake job name'
Aviv Keshet1f23b692013-05-14 11:13:55 -07001079 test_retry = 0
mblighe7d9c602009-07-02 19:02:33 +00001080 id = 1337
1081
1082 class FakeHQE(object):
1083 job = FakeJob
showardf1ae3542009-05-11 19:26:02 +00001084
showardf65b7402009-12-18 22:44:35 +00001085 expected_command_line = expected_command_line_base.union(
1086 ['-u', FakeJob.owner, '-l', FakeJob.name])
1087 command_line = set(monitor_db._autoserv_command_line(
1088 machines, extra_args=[], queue_entry=FakeHQE, verbose=False))
1089 self.assertEqual(expected_command_line, command_line)
showardf1ae3542009-05-11 19:26:02 +00001090
showard21baa452008-10-21 00:08:39 +00001091
jamesren76fcf192010-04-21 20:39:50 +00001092class AgentTaskTest(unittest.TestCase,
1093 frontend_test_utils.FrontendTestMixin):
1094 def setUp(self):
1095 self._frontend_common_setup()
1096
1097
1098 def tearDown(self):
1099 self._frontend_common_teardown()
1100
1101
1102 def _setup_drones(self):
1103 self.god.stub_function(models.DroneSet, 'drone_sets_enabled')
1104 models.DroneSet.drone_sets_enabled.expect_call().and_return(True)
1105
1106 drones = []
1107 for x in xrange(4):
1108 drones.append(models.Drone.objects.create(hostname=str(x)))
1109
1110 drone_set_1 = models.DroneSet.objects.create(name='1')
1111 drone_set_1.drones.add(*drones[0:2])
1112 drone_set_2 = models.DroneSet.objects.create(name='2')
1113 drone_set_2.drones.add(*drones[2:4])
1114 drone_set_3 = models.DroneSet.objects.create(name='3')
1115
1116 job_1 = self._create_job_simple([self.hosts[0].id],
1117 drone_set=drone_set_1)
1118 job_2 = self._create_job_simple([self.hosts[0].id],
1119 drone_set=drone_set_2)
1120 job_3 = self._create_job_simple([self.hosts[0].id],
1121 drone_set=drone_set_3)
1122
jamesrendd77e012010-04-28 18:07:30 +00001123 job_4 = self._create_job_simple([self.hosts[0].id])
1124 job_4.drone_set = None
1125 job_4.save()
jamesren76fcf192010-04-21 20:39:50 +00001126
jamesrendd77e012010-04-28 18:07:30 +00001127 hqe_1 = job_1.hostqueueentry_set.all()[0]
1128 hqe_2 = job_2.hostqueueentry_set.all()[0]
1129 hqe_3 = job_3.hostqueueentry_set.all()[0]
1130 hqe_4 = job_4.hostqueueentry_set.all()[0]
1131
beeps5e2bb4a2013-10-28 11:26:45 -07001132 return (hqe_1, hqe_2, hqe_3, hqe_4), agent_task.AgentTask()
jamesren76fcf192010-04-21 20:39:50 +00001133
1134
jamesrendd77e012010-04-28 18:07:30 +00001135 def test_get_drone_hostnames_allowed_no_drones_in_set(self):
jamesren76fcf192010-04-21 20:39:50 +00001136 hqes, task = self._setup_drones()
jamesrendd77e012010-04-28 18:07:30 +00001137 task.queue_entry_ids = (hqes[2].id,)
jamesren76fcf192010-04-21 20:39:50 +00001138 self.assertEqual(set(), task.get_drone_hostnames_allowed())
1139 self.god.check_playback()
1140
1141
jamesrendd77e012010-04-28 18:07:30 +00001142 def test_get_drone_hostnames_allowed_no_drone_set(self):
1143 hqes, task = self._setup_drones()
1144 hqe = hqes[3]
1145 task.queue_entry_ids = (hqe.id,)
1146
1147 result = object()
1148
1149 self.god.stub_function(task, '_user_or_global_default_drone_set')
1150 task._user_or_global_default_drone_set.expect_call(
1151 hqe.job, hqe.job.user()).and_return(result)
1152
1153 self.assertEqual(result, task.get_drone_hostnames_allowed())
1154 self.god.check_playback()
1155
1156
jamesren76fcf192010-04-21 20:39:50 +00001157 def test_get_drone_hostnames_allowed_success(self):
1158 hqes, task = self._setup_drones()
jamesrendd77e012010-04-28 18:07:30 +00001159 task.queue_entry_ids = (hqes[0].id,)
jamesren76fcf192010-04-21 20:39:50 +00001160 self.assertEqual(set(('0','1')), task.get_drone_hostnames_allowed())
1161 self.god.check_playback()
1162
1163
1164 def test_get_drone_hostnames_allowed_multiple_jobs(self):
1165 hqes, task = self._setup_drones()
jamesrendd77e012010-04-28 18:07:30 +00001166 task.queue_entry_ids = (hqes[0].id, hqes[1].id)
jamesren76fcf192010-04-21 20:39:50 +00001167 self.assertRaises(AssertionError,
1168 task.get_drone_hostnames_allowed)
1169 self.god.check_playback()
1170
1171
jamesrendd77e012010-04-28 18:07:30 +00001172 def test_get_drone_hostnames_allowed_no_hqe(self):
1173 class MockSpecialTask(object):
1174 requested_by = object()
1175
beeps5e2bb4a2013-10-28 11:26:45 -07001176 class MockSpecialAgentTask(agent_task.SpecialAgentTask):
jamesrendd77e012010-04-28 18:07:30 +00001177 task = MockSpecialTask()
1178 queue_entry_ids = []
1179 def __init__(self, *args, **kwargs):
1180 pass
1181
1182 task = MockSpecialAgentTask()
1183 self.god.stub_function(models.DroneSet, 'drone_sets_enabled')
1184 self.god.stub_function(task, '_user_or_global_default_drone_set')
1185
1186 result = object()
1187 models.DroneSet.drone_sets_enabled.expect_call().and_return(True)
1188 task._user_or_global_default_drone_set.expect_call(
1189 task.task, MockSpecialTask.requested_by).and_return(result)
1190
1191 self.assertEqual(result, task.get_drone_hostnames_allowed())
1192 self.god.check_playback()
1193
1194
1195 def _setup_test_user_or_global_default_drone_set(self):
1196 result = object()
1197 class MockDroneSet(object):
1198 def get_drone_hostnames(self):
1199 return result
1200
1201 self.god.stub_function(models.DroneSet, 'get_default')
1202 models.DroneSet.get_default.expect_call().and_return(MockDroneSet())
1203 return result
1204
1205
1206 def test_user_or_global_default_drone_set(self):
1207 expected = object()
1208 class MockDroneSet(object):
1209 def get_drone_hostnames(self):
1210 return expected
1211 class MockUser(object):
1212 drone_set = MockDroneSet()
1213
1214 self._setup_test_user_or_global_default_drone_set()
1215
beeps5e2bb4a2013-10-28 11:26:45 -07001216 actual = agent_task.AgentTask()._user_or_global_default_drone_set(
jamesrendd77e012010-04-28 18:07:30 +00001217 None, MockUser())
1218
1219 self.assertEqual(expected, actual)
1220 self.god.check_playback()
1221
1222
1223 def test_user_or_global_default_drone_set_no_user(self):
1224 expected = self._setup_test_user_or_global_default_drone_set()
beeps5e2bb4a2013-10-28 11:26:45 -07001225 actual = agent_task.AgentTask()._user_or_global_default_drone_set(
jamesrendd77e012010-04-28 18:07:30 +00001226 None, None)
1227
1228 self.assertEqual(expected, actual)
1229 self.god.check_playback()
1230
1231
1232 def test_user_or_global_default_drone_set_no_user_drone_set(self):
1233 class MockUser(object):
1234 drone_set = None
1235 login = None
1236
1237 expected = self._setup_test_user_or_global_default_drone_set()
beeps5e2bb4a2013-10-28 11:26:45 -07001238 actual = agent_task.AgentTask()._user_or_global_default_drone_set(
jamesrendd77e012010-04-28 18:07:30 +00001239 None, MockUser())
1240
1241 self.assertEqual(expected, actual)
1242 self.god.check_playback()
1243
1244
Dan Shi76af8022013-10-19 01:59:49 -07001245 def test_abort_HostlessQueueTask(self):
1246 hqe = self.god.create_mock_class(scheduler_models.HostQueueEntry,
1247 'HostQueueEntry')
1248 # If hqe is still in STARTING status, aborting the task should finish
1249 # without changing hqe's status.
1250 hqe.status = models.HostQueueEntry.Status.STARTING
1251 hqe.job = None
1252 hqe.id = 0
1253 task = monitor_db.HostlessQueueTask(hqe)
1254 task.abort()
1255
1256 # If hqe is in RUNNING status, aborting the task should change hqe's
1257 # status to Parsing, so FinalReparseTask can be scheduled.
1258 hqe.set_status.expect_call('Parsing')
1259 hqe.status = models.HostQueueEntry.Status.RUNNING
1260 hqe.job = None
1261 hqe.id = 0
1262 task = monitor_db.HostlessQueueTask(hqe)
1263 task.abort()
1264
1265
showardce38e0c2008-05-29 19:36:16 +00001266if __name__ == '__main__':
jadmanski0afbb632008-06-06 21:10:57 +00001267 unittest.main()