summaryrefslogtreecommitdiff
path: root/nova/tests/unit/api/openstack/compute/test_evacuate.py
blob: bd88bb8d6e6b0e253ce3805486d092e7e8049e3f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
#   Copyright 2013 OpenStack Foundation
#
#   Licensed under the Apache License, Version 2.0 (the "License"); you may
#   not use this file except in compliance with the License. You may obtain
#   a copy of the License at
#
#       http://www.apache.org/licenses/LICENSE-2.0
#
#   Unless required by applicable law or agreed to in writing, software
#   distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
#   WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
#   License for the specific language governing permissions and limitations
#   under the License.

from unittest import mock

import fixtures
from oslo_utils.fixture import uuidsentinel as uuids
import testtools
import webob

from nova.api.openstack.compute import evacuate as evacuate_v21
from nova.compute import api as compute_api
from nova.compute import vm_states
import nova.conf
from nova import exception
from nova import test
from nova.tests.unit.api.openstack import fakes
from nova.tests.unit import fake_instance


CONF = nova.conf.CONF


def fake_compute_api(*args, **kwargs):
    return True


def fake_compute_api_get(self, context, instance_id, **kwargs):
    # BAD_UUID is something that does not exist
    if instance_id == 'BAD_UUID':
        raise exception.InstanceNotFound(instance_id=instance_id)
    else:
        return fake_instance.fake_instance_obj(context, id=1, uuid=instance_id,
                                               task_state=None, host='host1',
                                               vm_state=vm_states.ACTIVE)


def fake_service_get_by_compute_host(self, context, host):
    if host == 'bad-host':
        raise exception.ComputeHostNotFound(host=host)
    elif host == 'unmapped-host':
        raise exception.HostMappingNotFound(name=host)
    else:
        return {
            'host_name': host,
            'service': 'compute',
            'zone': 'nova'
            }


class EvacuateTestV21(test.NoDBTestCase):
    validation_error = exception.ValidationError
    _methods = ('resize', 'evacuate')

    def setUp(self):
        super(EvacuateTestV21, self).setUp()
        self.stub_out('nova.compute.api.API.get', fake_compute_api_get)
        self.stub_out('nova.compute.api.HostAPI.service_get_by_compute_host',
                      fake_service_get_by_compute_host)
        self.mock_neutron_extension_list = self.useFixture(
            fixtures.MockPatch(
                'nova.network.neutron.API._refresh_neutron_extensions_cache'
            )
        ).mock
        self.mock_neutron_extension_list.return_value = {'extensions': []}
        self.UUID = uuids.fake
        for _method in self._methods:
            self.stub_out('nova.compute.api.API.%s' % _method,
                          fake_compute_api)
        self._set_up_controller()
        self.admin_req = fakes.HTTPRequest.blank('', use_admin_context=True)
        self.req = fakes.HTTPRequest.blank('')

    def _set_up_controller(self):
        self.controller = evacuate_v21.EvacuateController()
        self.controller_no_ext = self.controller

    def _get_evacuate_response(self, json_load, uuid=None):
        base_json_load = {'evacuate': json_load}
        response = self.controller._evacuate(self.admin_req, uuid or self.UUID,
                                             body=base_json_load)

        return response

    def _check_evacuate_failure(self, exception, body, uuid=None,
                                controller=None):
        controller = controller or self.controller
        body = {'evacuate': body}
        return self.assertRaises(exception, controller._evacuate,
                                 self.admin_req, uuid or self.UUID, body=body)

    def test_evacuate_with_valid_instance(self):
        admin_pass = 'MyNewPass'
        res = self._get_evacuate_response({'host': 'my-host',
                                           'onSharedStorage': 'False',
                                           'adminPass': admin_pass})

        self.assertEqual(admin_pass, res['adminPass'])

    def test_evacuate_with_invalid_instance(self):
        self._check_evacuate_failure(webob.exc.HTTPNotFound,
                                     {'host': 'my-host',
                                      'onSharedStorage': 'False',
                                      'adminPass': 'MyNewPass'},
                                     uuid='BAD_UUID')

    @mock.patch('nova.compute.api.API.evacuate')
    def test_evacuate_raise_badrequest_with_vtpm(self, mock_evacuate):
        mock_evacuate.side_effect = exception.OperationNotSupportedForVTPM(
            instance_uuid=uuids.instance, operation='foo')
        self._check_evacuate_failure(
            webob.exc.HTTPBadRequest,
            {'host': 'foo', 'onSharedStorage': 'False', 'adminPass': 'bar'})

    @mock.patch('nova.compute.api.API.evacuate')
    def test_evacuate_raise_badrequest_with_vdpa_interface(
        self, mock_evacuate):
        mock_evacuate.side_effect = \
            exception.OperationNotSupportedForVDPAInterface(
                instance_uuid=uuids.instance, operation='foo')
        self._check_evacuate_failure(
            webob.exc.HTTPBadRequest,
            {'host': 'foo', 'onSharedStorage': 'False', 'adminPass': 'bar'})

    @mock.patch('nova.compute.api.API.evacuate')
    def test_evacuate_raise_badrequest_for_accelerator(self, mock_evacuate):
        mock_evacuate.side_effect = \
            exception.ForbiddenWithAccelerators()
        self._check_evacuate_failure(
            webob.exc.HTTPBadRequest,
            {'host': 'foo', 'onSharedStorage': 'False', 'adminPass': 'bar'})

    def test_evacuate_with_active_service(self):
        def fake_evacuate(*args, **kwargs):
            raise exception.ComputeServiceInUse("Service still in use")

        self.stub_out('nova.compute.api.API.evacuate', fake_evacuate)
        self._check_evacuate_failure(webob.exc.HTTPBadRequest,
                                     {'host': 'my-host',
                                      'onSharedStorage': 'False',
                                      'adminPass': 'MyNewPass'})

    def test_evacuate_instance_with_no_target(self):
        admin_pass = 'MyNewPass'
        res = self._get_evacuate_response({'onSharedStorage': 'False',
                                           'adminPass': admin_pass})

        self.assertEqual(admin_pass, res['adminPass'])

    def test_evacuate_instance_without_on_shared_storage(self):
        self._check_evacuate_failure(self.validation_error,
                                     {'host': 'my-host',
                                      'adminPass': 'MyNewPass'})

    def test_evacuate_instance_with_invalid_characters_host(self):
        host = 'abc!#'
        self._check_evacuate_failure(self.validation_error,
                                     {'host': host,
                                      'onSharedStorage': 'False',
                                      'adminPass': 'MyNewPass'})

    def test_evacuate_instance_with_too_long_host(self):
        host = 'a' * 256
        self._check_evacuate_failure(self.validation_error,
                                     {'host': host,
                                      'onSharedStorage': 'False',
                                      'adminPass': 'MyNewPass'})

    def test_evacuate_instance_with_invalid_on_shared_storage(self):
        self._check_evacuate_failure(self.validation_error,
                                     {'host': 'my-host',
                                      'onSharedStorage': 'foo',
                                      'adminPass': 'MyNewPass'})

    def test_evacuate_instance_with_bad_target(self):
        self._check_evacuate_failure(webob.exc.HTTPNotFound,
                                     {'host': 'bad-host',
                                      'onSharedStorage': 'False',
                                      'adminPass': 'MyNewPass'})

    def test_evacuate_instance_with_unmapped_target(self):
        self._check_evacuate_failure(webob.exc.HTTPNotFound,
                                     {'host': 'unmapped-host',
                                      'onSharedStorage': 'False',
                                      'adminPass': 'MyNewPass'})

    def test_evacuate_instance_with_target(self):
        admin_pass = 'MyNewPass'
        res = self._get_evacuate_response({'host': 'my-host',
                                           'onSharedStorage': 'False',
                                           'adminPass': admin_pass})

        self.assertEqual(admin_pass, res['adminPass'])

    @mock.patch('nova.objects.Instance.save')
    def test_evacuate_shared_and_pass(self, mock_save):
        self._check_evacuate_failure(webob.exc.HTTPBadRequest,
                                     {'host': 'bad-host',
                                      'onSharedStorage': 'True',
                                      'adminPass': 'MyNewPass'})

    @mock.patch('nova.objects.Instance.save')
    def test_evacuate_not_shared_pass_generated(self, mock_save):
        res = self._get_evacuate_response({'host': 'my-host',
                                           'onSharedStorage': 'False'})
        self.assertEqual(CONF.password_length, len(res['adminPass']))

    @mock.patch('nova.objects.Instance.save')
    def test_evacuate_shared(self, mock_save):
        self._get_evacuate_response({'host': 'my-host',
                                     'onSharedStorage': 'True'})

    def test_evacuate_to_same_host(self):
        self._check_evacuate_failure(webob.exc.HTTPBadRequest,
                                     {'host': 'host1',
                                      'onSharedStorage': 'False',
                                      'adminPass': 'MyNewPass'})

    def test_evacuate_instance_with_empty_host(self):
        self._check_evacuate_failure(self.validation_error,
                                     {'host': '',
                                      'onSharedStorage': 'False',
                                      'adminPass': 'MyNewPass'},
                                     controller=self.controller_no_ext)

    @mock.patch('nova.objects.Instance.save')
    def test_evacuate_instance_with_underscore_in_hostname(self, mock_save):
        admin_pass = 'MyNewPass'
        # NOTE: The hostname grammar in RFC952 does not allow for
        # underscores in hostnames. However, we should test that it
        # is supported because it sometimes occurs in real systems.
        res = self._get_evacuate_response({'host': 'underscore_hostname',
                                           'onSharedStorage': 'False',
                                           'adminPass': admin_pass})

        self.assertEqual(admin_pass, res['adminPass'])

    def test_evacuate_disable_password_return(self):
        self._test_evacuate_enable_instance_password_conf(enable_pass=False)

    def test_evacuate_enable_password_return(self):
        self._test_evacuate_enable_instance_password_conf(enable_pass=True)

    @mock.patch('nova.objects.Instance.save')
    def _test_evacuate_enable_instance_password_conf(self, mock_save,
                                                     enable_pass):
        self.flags(enable_instance_password=enable_pass, group='api')

        res = self._get_evacuate_response({'host': 'underscore_hostname',
                                           'onSharedStorage': 'False'})
        if enable_pass:
            self.assertIn('adminPass', res)
        else:
            self.assertIsNone(res)


class EvacuateTestV214(EvacuateTestV21):
    def setUp(self):
        super(EvacuateTestV214, self).setUp()
        self.admin_req = fakes.HTTPRequest.blank('', use_admin_context=True,
                                                 version='2.14')
        self.req = fakes.HTTPRequest.blank('', version='2.14')

    def _get_evacuate_response(self, json_load, uuid=None):
        json_load.pop('onSharedStorage', None)
        base_json_load = {'evacuate': json_load}
        response = self.controller._evacuate(self.admin_req, uuid or self.UUID,
                                             body=base_json_load)

        return response

    def _check_evacuate_failure(self, exception, body, uuid=None,
                                controller=None):
        controller = controller or self.controller
        body.pop('onSharedStorage', None)
        body = {'evacuate': body}
        return self.assertRaises(exception, controller._evacuate,
                                 self.admin_req, uuid or self.UUID, body=body)

    @mock.patch.object(compute_api.API, 'evacuate')
    def test_evacuate_instance(self, mock_evacuate):
        self._get_evacuate_response({})
        admin_pass = mock_evacuate.call_args_list[0][0][4]
        on_shared_storage = mock_evacuate.call_args_list[0][0][3]
        self.assertEqual(CONF.password_length, len(admin_pass))
        self.assertIsNone(on_shared_storage)

    def test_evacuate_with_valid_instance(self):
        admin_pass = 'MyNewPass'
        res = self._get_evacuate_response({'host': 'my-host',
                                           'adminPass': admin_pass})

        self.assertIsNone(res)

    @testtools.skip('Password is not returned from Microversion 2.14')
    def test_evacuate_disable_password_return(self):
        pass

    @testtools.skip('Password is not returned from Microversion 2.14')
    def test_evacuate_enable_password_return(self):
        pass

    @testtools.skip('onSharedStorage was removed from Microversion 2.14')
    def test_evacuate_instance_with_invalid_on_shared_storage(self):
        pass

    @testtools.skip('onSharedStorage was removed from Microversion 2.14')
    @mock.patch('nova.objects.Instance.save')
    def test_evacuate_not_shared_pass_generated(self, mock_save):
        pass

    @mock.patch.object(compute_api.API, 'evacuate')
    @mock.patch('nova.objects.Instance.save')
    def test_evacuate_pass_generated(self, mock_save, mock_evacuate):
        self._get_evacuate_response({'host': 'my-host'})
        self.assertEqual(CONF.password_length,
                         len(mock_evacuate.call_args_list[0][0][4]))

    def test_evacuate_instance_without_on_shared_storage(self):
        self._get_evacuate_response({'host': 'my-host',
                                     'adminPass': 'MyNewPass'})

    def test_evacuate_instance_with_no_target(self):
        admin_pass = 'MyNewPass'
        with mock.patch.object(compute_api.API, 'evacuate') as mock_evacuate:
            self._get_evacuate_response({'adminPass': admin_pass})
            self.assertEqual(admin_pass,
                             mock_evacuate.call_args_list[0][0][4])

    @testtools.skip('onSharedStorage was removed from Microversion 2.14')
    @mock.patch('nova.objects.Instance.save')
    def test_evacuate_shared_and_pass(self, mock_save):
        pass

    @testtools.skip('from Microversion 2.14 it is covered with '
                    'test_evacuate_pass_generated')
    def test_evacuate_instance_with_target(self):
        pass

    @mock.patch('nova.objects.Instance.save')
    def test_evacuate_instance_with_underscore_in_hostname(self, mock_save):
        # NOTE: The hostname grammar in RFC952 does not allow for
        # underscores in hostnames. However, we should test that it
        # is supported because it sometimes occurs in real systems.
        self._get_evacuate_response({'host': 'underscore_hostname'})


class EvacuateTestV229(EvacuateTestV214):
    def setUp(self):
        super(EvacuateTestV229, self).setUp()
        self.admin_req = fakes.HTTPRequest.blank('', use_admin_context=True,
                                                 version='2.29')
        self.req = fakes.HTTPRequest.blank('', version='2.29')

    @mock.patch.object(compute_api.API, 'evacuate')
    def test_evacuate_instance(self, mock_evacuate):
        self._get_evacuate_response({})
        admin_pass = mock_evacuate.call_args_list[0][0][4]
        on_shared_storage = mock_evacuate.call_args_list[0][0][3]
        force = mock_evacuate.call_args_list[0][0][5]
        self.assertEqual(CONF.password_length, len(admin_pass))
        self.assertIsNone(on_shared_storage)
        self.assertFalse(force)

    def test_evacuate_with_valid_instance(self):
        admin_pass = 'MyNewPass'
        res = self._get_evacuate_response({'host': 'my-host',
                                           'adminPass': admin_pass,
                                           'force': 'false'})
        self.assertIsNone(res)

    @mock.patch.object(compute_api.API, 'evacuate')
    def test_evacuate_instance_with_forced_host(self, mock_evacuate):
        self._get_evacuate_response({'host': 'my-host',
                                     'force': 'true'})
        force = mock_evacuate.call_args_list[0][0][5]
        self.assertTrue(force)

    def test_forced_evacuate_with_no_host_provided(self):
        self._check_evacuate_failure(webob.exc.HTTPBadRequest,
                                     {'force': 'true'})


class EvacuateTestV268(EvacuateTestV229):
    def setUp(self):
        super(EvacuateTestV268, self).setUp()
        self.admin_req = fakes.HTTPRequest.blank('', use_admin_context=True,
                                                 version='2.68')
        self.req = fakes.HTTPRequest.blank('', version='2.68')

    def test_evacuate_with_valid_instance(self):
        admin_pass = 'MyNewPass'
        res = self._get_evacuate_response({'host': 'my-host',
                                           'adminPass': admin_pass})

        self.assertIsNone(res)

    @mock.patch.object(compute_api.API, 'evacuate')
    def test_evacuate_instance_with_forced_host(self, mock_evacuate):
        ex = self._check_evacuate_failure(self.validation_error,
                                          {'host': 'my-host',
                                           'force': 'true'})
        self.assertIn('force', str(ex))

    def test_forced_evacuate_with_no_host_provided(self):
        # not applicable for v2.68, which removed the 'force' parameter
        pass


class EvacuateTestV295(EvacuateTestV268):
    def setUp(self):
        super(EvacuateTestV268, self).setUp()
        self.admin_req = fakes.HTTPRequest.blank('', use_admin_context=True,
                                                 version='2.95')
        self.req = fakes.HTTPRequest.blank('', version='2.95')
        self.mock_get_min_ver = self.useFixture(fixtures.MockPatch(
            'nova.objects.service.get_minimum_version_all_cells',
            return_value=62)).mock

    def test_evacuate_version_error(self):
        self.mock_get_min_ver.return_value = 61
        self.assertRaises(webob.exc.HTTPBadRequest,
                          self._get_evacuate_response,
                          {'host': 'my-host', 'adminPass': 'foo'})

    def test_evacuate_unsupported_rpc(self):
        def fake_evacuate(*args, **kwargs):
            raise exception.UnsupportedRPCVersion(
                api="fakeapi",
                required="x.xx")

        self.stub_out('nova.compute.api.API.evacuate', fake_evacuate)
        self._check_evacuate_failure(webob.exc.HTTPConflict,
                                     {'host': 'my-host',
                                      'onSharedStorage': 'False',
                                      'adminPass': 'MyNewPass'})