Merge branch '7167-keep-rsync-test-setup' into 7167-keep-rsync
[arvados.git] / services / nodemanager / tests / test_computenode_dispatch.py
1 #!/usr/bin/env python
2
3 from __future__ import absolute_import, print_function
4
5 import time
6 import unittest
7
8 import arvados.errors as arverror
9 import httplib2
10 import mock
11 import pykka
12
13 import arvnodeman.computenode.dispatch as dispatch
14 from . import testutil
15
16 class ComputeNodeSetupActorTestCase(testutil.ActorTestMixin, unittest.TestCase):
17     def make_mocks(self, arvados_effect=None):
18         if arvados_effect is None:
19             arvados_effect = [testutil.arvados_node_mock()]
20         self.arvados_effect = arvados_effect
21         self.timer = testutil.MockTimer()
22         self.api_client = mock.MagicMock(name='api_client')
23         self.api_client.nodes().create().execute.side_effect = arvados_effect
24         self.api_client.nodes().update().execute.side_effect = arvados_effect
25         self.cloud_client = mock.MagicMock(name='cloud_client')
26         self.cloud_client.create_node.return_value = testutil.cloud_node_mock(1)
27
28     def make_actor(self, arv_node=None):
29         if not hasattr(self, 'timer'):
30             self.make_mocks(arvados_effect=[arv_node])
31         self.setup_actor = dispatch.ComputeNodeSetupActor.start(
32             self.timer, self.api_client, self.cloud_client,
33             testutil.MockSize(1), arv_node).proxy()
34
35     def test_creation_without_arvados_node(self):
36         self.make_actor()
37         self.assertEqual(self.arvados_effect[-1],
38                          self.setup_actor.arvados_node.get(self.TIMEOUT))
39         self.assertTrue(self.api_client.nodes().create().execute.called)
40         self.assertEqual(self.cloud_client.create_node(),
41                          self.setup_actor.cloud_node.get(self.TIMEOUT))
42
43     def test_creation_with_arvados_node(self):
44         self.make_actor(testutil.arvados_node_mock())
45         self.assertEqual(self.arvados_effect[-1],
46                          self.setup_actor.arvados_node.get(self.TIMEOUT))
47         self.assertTrue(self.api_client.nodes().update().execute.called)
48         self.assertEqual(self.cloud_client.create_node(),
49                          self.setup_actor.cloud_node.get(self.TIMEOUT))
50
51     def test_failed_arvados_calls_retried(self):
52         self.make_mocks([
53                 arverror.ApiError(httplib2.Response({'status': '500'}), ""),
54                 testutil.arvados_node_mock(),
55                 ])
56         self.make_actor()
57         self.wait_for_assignment(self.setup_actor, 'arvados_node')
58
59     def test_failed_cloud_calls_retried(self):
60         self.make_mocks()
61         self.cloud_client.create_node.side_effect = [
62             Exception("test cloud creation error"),
63             self.cloud_client.create_node.return_value,
64             ]
65         self.make_actor()
66         self.wait_for_assignment(self.setup_actor, 'cloud_node')
67
68     def test_failed_post_create_retried(self):
69         self.make_mocks()
70         self.cloud_client.post_create_node.side_effect = [
71             Exception("test cloud post-create error"), None]
72         self.make_actor()
73         done = self.FUTURE_CLASS()
74         self.setup_actor.subscribe(done.set)
75         done.get(self.TIMEOUT)
76         self.assertEqual(2, self.cloud_client.post_create_node.call_count)
77
78     def test_stop_when_no_cloud_node(self):
79         self.make_mocks(
80             arverror.ApiError(httplib2.Response({'status': '500'}), ""))
81         self.make_actor()
82         self.assertTrue(
83             self.setup_actor.stop_if_no_cloud_node().get(self.TIMEOUT))
84         self.assertTrue(
85             self.setup_actor.actor_ref.actor_stopped.wait(self.TIMEOUT))
86
87     def test_no_stop_when_cloud_node(self):
88         self.make_actor()
89         self.wait_for_assignment(self.setup_actor, 'cloud_node')
90         self.assertFalse(
91             self.setup_actor.stop_if_no_cloud_node().get(self.TIMEOUT))
92         self.assertTrue(self.stop_proxy(self.setup_actor),
93                         "actor was stopped by stop_if_no_cloud_node")
94
95     def test_subscribe(self):
96         self.make_mocks(
97             arverror.ApiError(httplib2.Response({'status': '500'}), ""))
98         self.make_actor()
99         subscriber = mock.Mock(name='subscriber_mock')
100         self.setup_actor.subscribe(subscriber)
101         self.api_client.nodes().create().execute.side_effect = [
102             testutil.arvados_node_mock()]
103         self.wait_for_assignment(self.setup_actor, 'cloud_node')
104         self.assertEqual(self.setup_actor.actor_ref.actor_urn,
105                          subscriber.call_args[0][0].actor_ref.actor_urn)
106
107     def test_late_subscribe(self):
108         self.make_actor()
109         subscriber = mock.Mock(name='subscriber_mock')
110         self.wait_for_assignment(self.setup_actor, 'cloud_node')
111         self.setup_actor.subscribe(subscriber).get(self.TIMEOUT)
112         self.stop_proxy(self.setup_actor)
113         self.assertEqual(self.setup_actor.actor_ref.actor_urn,
114                          subscriber.call_args[0][0].actor_ref.actor_urn)
115
116
117 class ComputeNodeShutdownActorMixin(testutil.ActorTestMixin):
118     def make_mocks(self, cloud_node=None, arvados_node=None,
119                    shutdown_open=True):
120         self.timer = testutil.MockTimer()
121         self.shutdowns = testutil.MockShutdownTimer()
122         self.shutdowns._set_state(shutdown_open, 300)
123         self.cloud_client = mock.MagicMock(name='cloud_client')
124         self.arvados_client = mock.MagicMock(name='arvados_client')
125         self.updates = mock.MagicMock(name='update_mock')
126         if cloud_node is None:
127             cloud_node = testutil.cloud_node_mock()
128         self.cloud_node = cloud_node
129         self.arvados_node = arvados_node
130
131     def make_actor(self, cancellable=True, start_time=None):
132         if not hasattr(self, 'timer'):
133             self.make_mocks()
134         if start_time is None:
135             start_time = time.time()
136         monitor_actor = dispatch.ComputeNodeMonitorActor.start(
137             self.cloud_node, start_time, self.shutdowns,
138             testutil.cloud_node_fqdn, self.timer, self.updates, self.cloud_client,
139             self.arvados_node)
140         self.shutdown_actor = self.ACTOR_CLASS.start(
141             self.timer, self.cloud_client, self.arvados_client, monitor_actor,
142             cancellable).proxy()
143         self.monitor_actor = monitor_actor.proxy()
144
145     def check_success_flag(self, expected, allow_msg_count=1):
146         # allow_msg_count is the number of internal messages that may
147         # need to be handled for shutdown to finish.
148         for try_num in range(1 + allow_msg_count):
149             last_flag = self.shutdown_actor.success.get(self.TIMEOUT)
150             if last_flag is expected:
151                 break
152         else:
153             self.fail("success flag {} is not {}".format(last_flag, expected))
154
155     def test_uncancellable_shutdown(self, *mocks):
156         self.make_mocks(shutdown_open=False)
157         self.cloud_client.destroy_node.return_value = False
158         self.make_actor(cancellable=False)
159         self.check_success_flag(None, 0)
160         self.shutdowns._set_state(True, 600)
161         self.cloud_client.destroy_node.return_value = True
162         self.check_success_flag(True)
163
164     def test_arvados_node_cleaned_after_shutdown(self, *mocks):
165         cloud_node = testutil.cloud_node_mock(62)
166         arv_node = testutil.arvados_node_mock(62)
167         self.make_mocks(cloud_node, arv_node)
168         self.make_actor()
169         self.check_success_flag(True, 3)
170         update_mock = self.arvados_client.nodes().update
171         self.assertTrue(update_mock.called)
172         update_kwargs = update_mock.call_args_list[0][1]
173         self.assertEqual(arv_node['uuid'], update_kwargs.get('uuid'))
174         self.assertIn('body', update_kwargs)
175         for clear_key in ['slot_number', 'hostname', 'ip_address',
176                           'first_ping_at', 'last_ping_at']:
177             self.assertIn(clear_key, update_kwargs['body'])
178             self.assertIsNone(update_kwargs['body'][clear_key])
179         self.assertTrue(update_mock().execute.called)
180
181     def test_arvados_node_not_cleaned_after_shutdown_cancelled(self, *mocks):
182         cloud_node = testutil.cloud_node_mock(61)
183         arv_node = testutil.arvados_node_mock(61)
184         self.make_mocks(cloud_node, arv_node, shutdown_open=False)
185         self.make_actor(cancellable=True)
186         self.check_success_flag(False, 2)
187         self.assertFalse(self.arvados_client.nodes().update.called)
188
189
190 class ComputeNodeShutdownActorTestCase(ComputeNodeShutdownActorMixin,
191                                        unittest.TestCase):
192     ACTOR_CLASS = dispatch.ComputeNodeShutdownActor
193
194     def test_easy_shutdown(self):
195         self.make_actor(start_time=0)
196         self.check_success_flag(True)
197         self.assertTrue(self.cloud_client.destroy_node.called)
198
199     def test_shutdown_cancelled_when_window_closes(self):
200         self.make_mocks(shutdown_open=False)
201         self.make_actor()
202         self.check_success_flag(False, 2)
203         self.assertFalse(self.cloud_client.destroy_node.called)
204
205     def test_shutdown_retries_when_cloud_fails(self):
206         self.make_mocks()
207         self.cloud_client.destroy_node.return_value = False
208         self.make_actor(start_time=0)
209         self.assertIsNone(self.shutdown_actor.success.get(self.TIMEOUT))
210         self.cloud_client.destroy_node.return_value = True
211         self.check_success_flag(True)
212
213     def test_late_subscribe(self):
214         self.make_actor()
215         subscriber = mock.Mock(name='subscriber_mock')
216         self.shutdown_actor.subscribe(subscriber).get(self.TIMEOUT)
217         self.stop_proxy(self.shutdown_actor)
218         self.assertTrue(subscriber.called)
219         self.assertEqual(self.shutdown_actor.actor_ref.actor_urn,
220                          subscriber.call_args[0][0].actor_ref.actor_urn)
221
222
223 class ComputeNodeUpdateActorTestCase(testutil.ActorTestMixin,
224                                      unittest.TestCase):
225     def make_actor(self):
226         self.driver = mock.MagicMock(name='driver_mock')
227         self.updater = dispatch.ComputeNodeUpdateActor.start(self.driver).proxy()
228
229     def test_node_sync(self):
230         self.make_actor()
231         cloud_node = testutil.cloud_node_mock()
232         arv_node = testutil.arvados_node_mock()
233         self.updater.sync_node(cloud_node, arv_node).get(self.TIMEOUT)
234         self.driver().sync_node.assert_called_with(cloud_node, arv_node)
235
236
237 class ComputeNodeMonitorActorTestCase(testutil.ActorTestMixin,
238                                       unittest.TestCase):
239     def make_mocks(self, node_num):
240         self.shutdowns = testutil.MockShutdownTimer()
241         self.shutdowns._set_state(False, 300)
242         self.timer = mock.MagicMock(name='timer_mock')
243         self.updates = mock.MagicMock(name='update_mock')
244         self.cloud_mock = testutil.cloud_node_mock(node_num)
245         self.subscriber = mock.Mock(name='subscriber_mock')
246         self.cloud_client = mock.MagicMock(name='cloud_client')
247         self.cloud_client.broken.return_value = False
248
249     def make_actor(self, node_num=1, arv_node=None, start_time=None):
250         if not hasattr(self, 'cloud_mock'):
251             self.make_mocks(node_num)
252         if start_time is None:
253             start_time = time.time()
254         self.node_actor = dispatch.ComputeNodeMonitorActor.start(
255             self.cloud_mock, start_time, self.shutdowns,
256             testutil.cloud_node_fqdn, self.timer, self.updates, self.cloud_client,
257             arv_node, boot_fail_after=300).proxy()
258         self.node_actor.subscribe(self.subscriber).get(self.TIMEOUT)
259
260     def node_state(self, *states):
261         return self.node_actor.in_state(*states).get(self.TIMEOUT)
262
263     def test_in_state_when_unpaired(self):
264         self.make_actor()
265         self.assertIsNone(self.node_state('idle', 'busy'))
266
267     def test_in_state_when_pairing_stale(self):
268         self.make_actor(arv_node=testutil.arvados_node_mock(
269                 job_uuid=None, age=90000))
270         self.assertIsNone(self.node_state('idle', 'busy'))
271
272     def test_in_state_when_no_state_available(self):
273         self.make_actor(arv_node=testutil.arvados_node_mock(
274                 crunch_worker_state=None))
275         self.assertIsNone(self.node_state('idle', 'busy'))
276
277     def test_in_idle_state(self):
278         self.make_actor(2, arv_node=testutil.arvados_node_mock(job_uuid=None))
279         self.assertTrue(self.node_state('idle'))
280         self.assertFalse(self.node_state('busy'))
281         self.assertTrue(self.node_state('idle', 'busy'))
282
283     def test_in_busy_state(self):
284         self.make_actor(3, arv_node=testutil.arvados_node_mock(job_uuid=True))
285         self.assertFalse(self.node_state('idle'))
286         self.assertTrue(self.node_state('busy'))
287         self.assertTrue(self.node_state('idle', 'busy'))
288
289     def test_init_shutdown_scheduling(self):
290         self.make_actor()
291         self.assertTrue(self.timer.schedule.called)
292         self.assertEqual(300, self.timer.schedule.call_args[0][0])
293
294     def test_shutdown_window_close_scheduling(self):
295         self.make_actor()
296         self.shutdowns._set_state(False, 600)
297         self.timer.schedule.reset_mock()
298         self.node_actor.consider_shutdown().get(self.TIMEOUT)
299         self.stop_proxy(self.node_actor)
300         self.assertTrue(self.timer.schedule.called)
301         self.assertEqual(600, self.timer.schedule.call_args[0][0])
302         self.assertFalse(self.subscriber.called)
303
304     def test_shutdown_subscription(self):
305         self.make_actor(start_time=0)
306         self.shutdowns._set_state(True, 600)
307         self.node_actor.consider_shutdown().get(self.TIMEOUT)
308         self.assertTrue(self.subscriber.called)
309         self.assertEqual(self.node_actor.actor_ref.actor_urn,
310                          self.subscriber.call_args[0][0].actor_ref.actor_urn)
311
312     def test_no_shutdown_booting(self):
313         self.make_actor()
314         self.shutdowns._set_state(True, 600)
315         self.assertFalse(self.node_actor.shutdown_eligible().get(self.TIMEOUT))
316
317     def test_shutdown_without_arvados_node(self):
318         self.make_actor(start_time=0)
319         self.shutdowns._set_state(True, 600)
320         self.assertTrue(self.node_actor.shutdown_eligible().get(self.TIMEOUT))
321
322     def test_no_shutdown_missing(self):
323         arv_node = testutil.arvados_node_mock(10, job_uuid=None,
324                                               crunch_worker_state="down",
325                                               last_ping_at='1970-01-01T01:02:03.04050607Z')
326         self.make_actor(10, arv_node)
327         self.shutdowns._set_state(True, 600)
328         self.assertFalse(self.node_actor.shutdown_eligible().get(self.TIMEOUT))
329
330     def test_no_shutdown_running_broken(self):
331         arv_node = testutil.arvados_node_mock(12, job_uuid=None,
332                                               crunch_worker_state="down")
333         self.make_actor(12, arv_node)
334         self.shutdowns._set_state(True, 600)
335         self.cloud_client.broken.return_value = True
336         self.assertFalse(self.node_actor.shutdown_eligible().get(self.TIMEOUT))
337
338     def test_shutdown_missing_broken(self):
339         arv_node = testutil.arvados_node_mock(11, job_uuid=None,
340                                               crunch_worker_state="down",
341                                               last_ping_at='1970-01-01T01:02:03.04050607Z')
342         self.make_actor(11, arv_node)
343         self.shutdowns._set_state(True, 600)
344         self.cloud_client.broken.return_value = True
345         self.assertTrue(self.node_actor.shutdown_eligible().get(self.TIMEOUT))
346
347     def test_no_shutdown_when_window_closed(self):
348         self.make_actor(3, testutil.arvados_node_mock(3, job_uuid=None))
349         self.assertFalse(self.node_actor.shutdown_eligible().get(self.TIMEOUT))
350
351     def test_no_shutdown_when_node_running_job(self):
352         self.make_actor(4, testutil.arvados_node_mock(4, job_uuid=True))
353         self.shutdowns._set_state(True, 600)
354         self.assertFalse(self.node_actor.shutdown_eligible().get(self.TIMEOUT))
355
356     def test_no_shutdown_when_node_state_unknown(self):
357         self.make_actor(5, testutil.arvados_node_mock(
358             5, crunch_worker_state=None))
359         self.shutdowns._set_state(True, 600)
360         self.assertFalse(self.node_actor.shutdown_eligible().get(self.TIMEOUT))
361
362     def test_no_shutdown_when_node_state_stale(self):
363         self.make_actor(6, testutil.arvados_node_mock(6, age=90000))
364         self.shutdowns._set_state(True, 600)
365         self.assertFalse(self.node_actor.shutdown_eligible().get(self.TIMEOUT))
366
367     def test_arvados_node_match(self):
368         self.make_actor(2)
369         arv_node = testutil.arvados_node_mock(
370             2, hostname='compute-two.zzzzz.arvadosapi.com')
371         pair_id = self.node_actor.offer_arvados_pair(arv_node).get(self.TIMEOUT)
372         self.assertEqual(self.cloud_mock.id, pair_id)
373         self.stop_proxy(self.node_actor)
374         self.updates.sync_node.assert_called_with(self.cloud_mock, arv_node)
375
376     def test_arvados_node_mismatch(self):
377         self.make_actor(3)
378         arv_node = testutil.arvados_node_mock(1)
379         self.assertIsNone(
380             self.node_actor.offer_arvados_pair(arv_node).get(self.TIMEOUT))
381
382     def test_arvados_node_mismatch_first_ping_too_early(self):
383         self.make_actor(4)
384         arv_node = testutil.arvados_node_mock(
385             4, first_ping_at='1971-03-02T14:15:16.1717282Z')
386         self.assertIsNone(
387             self.node_actor.offer_arvados_pair(arv_node).get(self.TIMEOUT))
388
389     def test_update_cloud_node(self):
390         self.make_actor(1)
391         self.make_mocks(2)
392         self.cloud_mock.id = '1'
393         self.node_actor.update_cloud_node(self.cloud_mock)
394         current_cloud = self.node_actor.cloud_node.get(self.TIMEOUT)
395         self.assertEqual([testutil.ip_address_mock(2)],
396                          current_cloud.private_ips)
397
398     def test_missing_cloud_node_update(self):
399         self.make_actor(1)
400         self.node_actor.update_cloud_node(None)
401         current_cloud = self.node_actor.cloud_node.get(self.TIMEOUT)
402         self.assertEqual([testutil.ip_address_mock(1)],
403                          current_cloud.private_ips)
404
405     def test_update_arvados_node(self):
406         self.make_actor(3)
407         job_uuid = 'zzzzz-jjjjj-updatejobnode00'
408         new_arvados = testutil.arvados_node_mock(3, job_uuid)
409         self.node_actor.update_arvados_node(new_arvados)
410         current_arvados = self.node_actor.arvados_node.get(self.TIMEOUT)
411         self.assertEqual(job_uuid, current_arvados['job_uuid'])
412
413     def test_missing_arvados_node_update(self):
414         self.make_actor(4, testutil.arvados_node_mock(4))
415         self.node_actor.update_arvados_node(None)
416         current_arvados = self.node_actor.arvados_node.get(self.TIMEOUT)
417         self.assertEqual(testutil.ip_address_mock(4),
418                          current_arvados['ip_address'])
419
420     def test_update_arvados_node_syncs_when_fqdn_mismatch(self):
421         self.make_mocks(5)
422         self.cloud_mock.extra['testname'] = 'cloudfqdn.zzzzz.arvadosapi.com'
423         self.make_actor()
424         arv_node = testutil.arvados_node_mock(5)
425         self.node_actor.update_arvados_node(arv_node).get(self.TIMEOUT)
426         self.assertEqual(1, self.updates.sync_node.call_count)
427
428     def test_update_arvados_node_skips_sync_when_fqdn_match(self):
429         self.make_mocks(6)
430         arv_node = testutil.arvados_node_mock(6)
431         self.cloud_mock.extra['testname'] ='{n[hostname]}.{n[domain]}'.format(
432             n=arv_node)
433         self.make_actor()
434         self.node_actor.update_arvados_node(arv_node).get(self.TIMEOUT)
435         self.assertEqual(0, self.updates.sync_node.call_count)