def test_save(self, save_in_db):
        db_mapping = get_db_mapping()
        # This isn't needed here
        db_mapping.pop("cell_mapping")
        host = db_mapping['host']
        mapping_obj = objects.HostMapping(self.context)
        mapping_obj.host = host
        mapping_obj.id = db_mapping['id']
        new_fake_cell = test_cell_mapping.get_db_mapping(id=10)
        fake_cell_obj = objects.CellMapping(self.context, **new_fake_cell)
        mapping_obj.cell_mapping = fake_cell_obj
        db_mapping.update({"cell_id": new_fake_cell["id"]})
        save_in_db.return_value = db_mapping

        mapping_obj.save()
        save_in_db.assert_called_once_with(
            self.context, test.MatchType(host_mapping.HostMapping), {
                'cell_id': new_fake_cell["id"],
                'host': host,
                'id': db_mapping['id']
            })
        self.compare_obj(
            mapping_obj,
            db_mapping,
            subs={'cell_mapping': 'cell_id'},
            comparators={'cell_mapping': self._check_cell_map_value})
예제 #2
0
    def test_new_websocket_client_internal_access_path(self, validate,
                                                       check_port):
        params = {
            'id': 1,
            'token': '123-456-789',
            'instance_uuid': uuids.instance,
            'host': 'node1',
            'port': '10000',
            'internal_access_path': 'vmid',
            'console_type': 'novnc',
            'access_url_base': 'https://example.net:6080'
        }
        validate.return_value = objects.ConsoleAuthToken(**params)

        tsock = mock.MagicMock()
        tsock.recv.return_value = "HTTP/1.1 200 OK\r\n\r\n"

        self.wh.socket.return_value = tsock
        self.wh.path = "http://127.0.0.1/?%s" % self.path
        self.wh.headers = self.fake_header

        self.wh.new_websocket_client()

        validate.assert_called_with(mock.ANY, "123-456-789")
        self.wh.socket.assert_called_with('node1', 10000, connect=True)
        tsock.send.assert_called_with(test.MatchType(bytes))
        self.wh.do_proxy.assert_called_with(tsock)
예제 #3
0
 def test_flavor_update_description(self, mock_flavor_save, mock_get):
     """Tests updating a flavor description."""
     # First create a flavor.
     flavor = self._create_flavor_success_case(self.request_body)['flavor']
     self.assertEqual('test description', flavor['description'])
     mock_get.return_value = objects.Flavor(
         flavorid=flavor['id'],
         name=flavor['name'],
         memory_mb=flavor['ram'],
         vcpus=flavor['vcpus'],
         root_gb=flavor['disk'],
         swap=flavor['swap'],
         ephemeral_gb=flavor['OS-FLV-EXT-DATA:ephemeral'],
         disabled=flavor['OS-FLV-DISABLED:disabled'],
         is_public=flavor['os-flavor-access:is_public'],
         rxtx_factor=flavor['rxtx_factor'],
         description=flavor['description'])
     # Now null out the flavor description.
     flavor = self.controller._update(
         self._get_http_request(),
         flavor['id'],
         body={'flavor': {
             'description': None
         }})['flavor']
     self.assertIsNone(flavor['description'])
     mock_get.assert_called_once_with(
         test.MatchType(fakes.FakeRequestContext), flavor['id'])
     mock_flavor_save.assert_called_once_with()
예제 #4
0
파일: test_host.py 프로젝트: daespinel/nova
 def test_event_lifecycle_callback_suspended_migrated_job_failed(
         self, find_job_type, get_job_info):
     """Tests the suspended lifecycle event with libvirt with migrated"""
     hostimpl = mock.MagicMock()
     conn = mock.MagicMock()
     fake_dom_xml = """
             <domain type='kvm'>
               <uuid>cef19ce0-0ca2-11df-855d-b19fbce37686</uuid>
             </domain>
         """
     dom = fakelibvirt.Domain(conn, fake_dom_xml, running=True)
     jobinfo = libvirt_guest.JobInfo(type=fakelibvirt.VIR_DOMAIN_JOB_NONE)
     get_job_info.return_value = jobinfo
     # If the job type is VIR_DOMAIN_JOB_NONE we'll attempt to figure out
     # the actual job status, so in this case we mock it to be a failure.
     find_job_type.return_value = fakelibvirt.VIR_DOMAIN_JOB_FAILED
     host.Host._event_lifecycle_callback(
         conn,
         dom,
         fakelibvirt.VIR_DOMAIN_EVENT_SUSPENDED,
         detail=fakelibvirt.VIR_DOMAIN_EVENT_SUSPENDED_MIGRATED,
         opaque=hostimpl)
     expected_event = hostimpl._queue_event.call_args[0][0]
     self.assertEqual(event.EVENT_LIFECYCLE_PAUSED,
                      expected_event.transition)
     get_job_info.assert_called_once_with()
     find_job_type.assert_called_once_with(test.MatchType(
         libvirt_guest.Guest),
                                           instance=None,
                                           logging_ok=False)
예제 #5
0
    def _test_set_vm_state_and_notify(self, mock_save, mock_add, mock_notifier,
                                      mock_notify_task, request_spec,
                                      payload_request_spec):
        expected_uuid = uuids.instance
        updates = dict(vm_state='fake-vm-state')
        service = 'fake-service'
        method = 'fake-method'
        exc_info = 'exc_info'

        payload = dict(request_spec=payload_request_spec,
                       instance_properties=payload_request_spec.get(
                           'instance_properties', {}),
                       instance_id=expected_uuid,
                       state='fake-vm-state',
                       method=method,
                       reason=exc_info)
        event_type = '%s.%s' % (service, method)

        scheduler_utils.set_vm_state_and_notify(self.context, expected_uuid,
                                                service, method, updates,
                                                exc_info, request_spec)
        mock_save.assert_called_once_with()
        mock_add.assert_called_once_with(self.context, mock.ANY, exc_info,
                                         mock.ANY)
        self.assertIsInstance(mock_add.call_args[0][1], objects.Instance)
        self.assertIsInstance(mock_add.call_args[0][3], tuple)
        mock_notifier.return_value.error.assert_called_once_with(
            self.context, event_type, payload)
        mock_notify_task.assert_called_once_with(self.context, method,
                                                 expected_uuid,
                                                 payload_request_spec,
                                                 updates['vm_state'], exc_info,
                                                 test.MatchType(str))
예제 #6
0
    def _check_finish_revert_migration(self,
                                       mock_image,
                                       mock_check_eph_disks,
                                       mock_revert_migration_files,
                                       mock_check_attach_config_drive,
                                       disk_type=constants.DISK):
        mock_image.return_value = objects.ImageMeta.from_dict({})
        mock_instance = fake_instance.fake_instance_obj(self.context)
        root_device = {'type': disk_type}
        block_device_info = {'root_disk': root_device, 'ephemerals': []}

        self._migrationops.finish_revert_migration(
            context=self.context,
            instance=mock_instance,
            network_info=mock.sentinel.network_info,
            block_device_info=block_device_info,
            power_on=True)

        mock_revert_migration_files.assert_called_once_with(mock_instance.name)
        if root_device['type'] == constants.DISK:
            lookup_root_vhd = (
                self._migrationops._pathutils.lookup_root_vhd_path)
            lookup_root_vhd.assert_called_once_with(mock_instance.name)
            self.assertEqual(lookup_root_vhd.return_value, root_device['path'])

        get_image_vm_gen = self._migrationops._vmops.get_image_vm_generation
        get_image_vm_gen.assert_called_once_with(
            mock_instance.uuid, test.MatchType(objects.ImageMeta))
        self._migrationops._vmops.create_instance.assert_called_once_with(
            mock_instance, mock.sentinel.network_info, root_device,
            block_device_info, get_image_vm_gen.return_value)
        mock_check_attach_config_drive.assert_called_once_with(
            mock_instance, get_image_vm_gen.return_value)
        self._migrationops._vmops.power_on.assert_called_once_with(
            mock_instance)
예제 #7
0
    def _test_create(self, params, mock_validate_bdm, no_image=False):
        body = self._get_servers_body(no_image)
        body['server'].update(params)

        req = fakes.HTTPRequest.blank('/v2/fake/servers')
        req.method = 'POST'
        req.headers['content-type'] = 'application/json'

        req.body = jsonutils.dump_as_bytes(body)

        self.controller.create(req, body=body).obj['server']
        mock_validate_bdm.assert_called_once_with(
            test.MatchType(fakes.FakeRequestContext),
            test.MatchType(objects.Instance),
            test.MatchType(objects.Flavor),
            test.MatchType(objects.BlockDeviceMappingList),
            False)
예제 #8
0
    def test_match_type_simple(self):
        matcher = test.MatchType(dict)

        self.assertEqual(matcher, {})
        self.assertEqual(matcher, {"hello": "world"})
        self.assertEqual(matcher, {"hello": ["world"]})
        self.assertNotEqual(matcher, [])
        self.assertNotEqual(matcher, [{"hello": "world"}])
        self.assertNotEqual(matcher, 123)
        self.assertNotEqual(matcher, "foo")
예제 #9
0
        def _do_test(mock_service_update, mock_service_get_by_host_and_binary,
                     mock_update_compute_provider_status):
            mock_service_get_by_host_and_binary.return_value = expected_result
            mock_service_update.return_value = expected_result

            result = self.host_api.service_update_by_host_and_binary(
                self.ctxt, host_name, binary, params_to_update)
            self._compare_obj(result, expected_result)
            mock_update_compute_provider_status.assert_called_once_with(
                self.ctxt, test.MatchType(objects.Service))
예제 #10
0
    def test_match_type_object(self):
        class Hello(object):
            pass

        class World(object):
            pass

        matcher = test.MatchType(Hello)

        self.assertEqual(matcher, Hello())
        self.assertNotEqual(matcher, World())
        self.assertNotEqual(matcher, 123)
        self.assertNotEqual(matcher, "foo")
예제 #11
0
    def test_save_to_api(self, api_update_mock, mock_notify):
        api_update_mock.return_value = fake_aggregate
        agg = aggregate.Aggregate(context=self.context)
        agg.id = 123
        agg.name = 'fake-api-aggregate'
        agg.save()
        self.compare_obj(agg, fake_aggregate, subs=SUBS)
        api_update_mock.assert_called_once_with(self.context,
                                                123,
                                                {'name': 'fake-api-aggregate'})

        api_update_mock.assert_called_once_with(self.context,
            123, {'name': 'fake-api-aggregate'})

        mock_notify.assert_has_calls([
            mock.call(context=self.context,
                      aggregate=test.MatchType(aggregate.Aggregate),
                      action='update_prop', phase='start'),
            mock.call(context=self.context,
                      aggregate=test.MatchType(aggregate.Aggregate),
                      action='update_prop', phase='end')])
        self.assertEqual(2, mock_notify.call_count)
 def test_flavor_update_description(self, mock_flavor_save, mock_get):
     """Tests updating a flavor description."""
     # First create a flavor.
     flavor = self._create_flavor_success_case(self.request_body)['flavor']
     self.assertEqual('test description', flavor['description'])
     mock_get.return_value = self.get_flavor(flavor)
     # Now null out the flavor description.
     flavor = self.controller._update(
         self._get_http_request(), flavor['id'],
         body={'flavor': {'description': None}})['flavor']
     self.assertIsNone(flavor['description'])
     mock_get.assert_called_once_with(
         test.MatchType(fakes.FakeRequestContext), flavor['id'])
     mock_flavor_save.assert_called_once_with()
예제 #13
0
    def test_instance_has_port_with_resource_request(self):
        network_api = mock.Mock(spec=network.API())
        network_api.list_ports.return_value = {'ports': [
            {'resource_request': mock.sentinel.request}
        ]}
        res = common.instance_has_port_with_resource_request(
            mock.sentinel.uuid, network_api)

        self.assertTrue(res)
        network_api.list_ports.assert_called_once_with(
            test.MatchType(context.RequestContext),
            device_id=mock.sentinel.uuid, fields=['resource_request'])
        # assert that the neutron call uses an admin context
        ctxt = network_api.mock_calls[0][1][0]
        self.assertTrue(ctxt.is_admin)
        self.assertIsNone(ctxt.auth_token)
예제 #14
0
    def _check_finish_revert_migration(self,
                                       mock_image,
                                       mock_revert_migration_files,
                                       mock_check_attach_config_drive,
                                       boot_from_volume=False):
        mock_image.return_value = objects.ImageMeta.from_dict({})
        mock_instance = fake_instance.fake_instance_obj(self.context)
        mock_ebs_root_in_block_devices = (
            self._migrationops._volumeops.ebs_root_in_block_devices)
        mock_ebs_root_in_block_devices.return_value = boot_from_volume
        lookup_ephemeral = (
            self._migrationops._pathutils.lookup_ephemeral_vhd_path)

        self._migrationops.finish_revert_migration(
            context=self.context,
            instance=mock_instance,
            network_info=mock.sentinel.network_info,
            block_device_info=mock.sentinel.block_device,
            power_on=True)

        mock_revert_migration_files.assert_called_once_with(mock_instance.name)
        mock_ebs_root_in_block_devices.assert_called_once_with(
            mock.sentinel.block_device)
        if not boot_from_volume:
            lookup_root_vhd = (
                self._migrationops._pathutils.lookup_root_vhd_path)
            lookup_root_vhd.assert_called_once_with(mock_instance.name)
            fake_root_path = lookup_root_vhd.return_value
        else:
            fake_root_path = None

        lookup_ephemeral.assert_called_with(mock_instance.name)
        get_image_vm_gen = self._migrationops._vmops.get_image_vm_generation
        get_image_vm_gen.assert_called_once_with(
            mock_instance.uuid, fake_root_path,
            test.MatchType(objects.ImageMeta))
        self._migrationops._vmops.create_instance.assert_called_once_with(
            mock_instance, mock.sentinel.network_info,
            mock.sentinel.block_device, fake_root_path,
            lookup_ephemeral.return_value, get_image_vm_gen.return_value)
        mock_check_attach_config_drive.assert_called_once_with(
            mock_instance, get_image_vm_gen.return_value)
        self._migrationops._vmops.power_on.assert_called_once_with(
            mock_instance)
예제 #15
0
 def test_cold_migrate_same_host_old_compute_disallow(self):
     """Upgrade compat test where the resource provider does not report
     the COMPUTE_SAME_HOST_COLD_MIGRATE trait but the compute service is
     old so the API falls back to the allow_resize_to_same_host config which
     defaults to False.
     """
     server = self._create_server(networks='none')
     # Stub the compute service version check to make the compute service
     # appear old.
     fake_service = objects.Service()
     fake_service.version = (
         compute_api.MIN_COMPUTE_SAME_HOST_COLD_MIGRATE - 1)
     with mock.patch('nova.objects.Service.get_by_compute_host',
                     return_value=fake_service) as mock_get_service:
         self.api.post_server_action(server['id'], {'migrate': None})
     mock_get_service.assert_called_once_with(
         test.MatchType(nova_context.RequestContext), 'host1')
     # Since allow_resize_to_same_host defaults to False scheduling failed
     # since there are no other hosts.
     self._wait_for_migrate_no_valid_host()
예제 #16
0
    def test_service_update_by_host_and_binary(
        self, mock_service_update, mock_service_get_by_host_and_binary,
    ):
        host_name = 'fake-host'
        binary = 'nova-compute'
        params_to_update = dict(disabled=True)
        service_id = 42
        expected_result = dict(test_service.fake_service, id=service_id)

        mock_service_get_by_host_and_binary.return_value = expected_result
        mock_service_update.return_value = expected_result

        with mock.patch.object(
            self.host_api, '_update_compute_provider_status',
        ) as mock_update_compute_provider_status:
            result = self.host_api.service_update_by_host_and_binary(
                self.ctxt, host_name, binary, params_to_update)

            self._compare_obj(result, expected_result)
            mock_update_compute_provider_status.assert_called_once_with(
                self.ctxt, test.MatchType(objects.Service))
예제 #17
0
    def test_detail_with_cell_failures(self, mock_sg,
                                       mock_get_by_instance_uuids):

        mock_get_by_instance_uuids.return_value = [
            objects.InstanceMapping(instance_uuid=UUID1,
                                    cell_mapping=objects.CellMapping(
                                        uuid=uuids.cell1,
                                        transport_url='fake://nowhere/',
                                        database_connection=uuids.cell1)),
            objects.InstanceMapping(instance_uuid=UUID2,
                                    cell_mapping=objects.CellMapping(
                                        uuid=uuids.cell2,
                                        transport_url='fake://nowhere/',
                                        database_connection=uuids.cell2))
        ]
        bdm = fake_bdms_get_all_by_instance_uuids()
        fake_bdm = fake_block_device.fake_bdm_object(
            nova_context.RequestContext, bdm[0])
        mock_sg.return_value = {
            uuids.cell1: {
                UUID1: [fake_bdm]
            },
            uuids.cell2: nova_context.raised_exception_sentinel
        }

        res = self._make_request('/detail')
        mock_get_by_instance_uuids.assert_called_once_with(
            test.MatchType(nova_context.RequestContext), [UUID1, UUID2])

        self.assertEqual(200, res.status_int)

        # we would get an empty list for the second instance
        # which is in the down cell, however this would printed
        # in the logs.
        for i, server in enumerate(self._get_servers(res.body)):
            actual = server.get('%svolumes_attached' % self.prefix)
            if i == 0:
                self.assertEqual(self.exp_volumes_detail[i], actual)
            else:
                self.assertEqual([], actual)
예제 #18
0
    def test_detail(self, mock_get_by_instance_uuids):
        mock_get_by_instance_uuids.return_value = [
            objects.InstanceMapping(instance_uuid=UUID1,
                                    cell_mapping=objects.CellMapping(
                                        uuid=uuids.cell1,
                                        transport_url='fake://nowhere/',
                                        database_connection=uuids.cell1)),
            objects.InstanceMapping(instance_uuid=UUID2,
                                    cell_mapping=objects.CellMapping(
                                        uuid=uuids.cell1,
                                        transport_url='fake://nowhere/',
                                        database_connection=uuids.cell1))
        ]

        res = self._make_request('/detail')
        mock_get_by_instance_uuids.assert_called_once_with(
            test.MatchType(nova_context.RequestContext), [UUID1, UUID2])

        self.assertEqual(200, res.status_int)
        for i, server in enumerate(self._get_servers(res.body)):
            actual = server.get('%svolumes_attached' % self.prefix)
            self.assertEqual(self.exp_volumes_detail[i], actual)
예제 #19
0
    def test_new_websocket_client_internal_access_path(self, check_token):
        check_token.return_value = {
            'host': 'node1',
            'port': '10000',
            'internal_access_path': 'vmid',
            'console_type': 'novnc',
            'access_url': 'https://example.net:6080'
        }

        tsock = mock.MagicMock()
        tsock.recv.return_value = "HTTP/1.1 200 OK\r\n\r\n"

        self.wh.socket.return_value = tsock
        self.wh.path = "http://127.0.0.1/?token=123-456-789"
        self.wh.headers = self.fake_header

        self.wh.new_websocket_client()

        check_token.assert_called_with(mock.ANY, token="123-456-789")
        self.wh.socket.assert_called_with('node1', 10000, connect=True)
        tsock.send.assert_called_with(test.MatchType(bytes))
        self.wh.do_proxy.assert_called_with(tsock)
예제 #20
0
 def test_check_token_encoding(self):
     with mock.patch.object(self.manager.mc,
                            "get",
                            return_value=None) as mock_get:
         self.manager.check_token(self.context, self.u_token)
         mock_get.assert_called_once_with(test.MatchType(six.binary_type))
예제 #21
0
    def test_unshelve_volume_backed(self, mock_image_meta,
                                    mock_notify_instance_usage,
                                    mock_prep_block_device, mock_spawn,
                                    mock_get_power_state,
                                    mock_setup_network, mock_instance_claim,
                                    mock_notify_instance_action,
                                    mock_get_bdms):
        mock_bdms = mock.Mock()
        mock_get_bdms.return_value = mock_bdms
        instance = self._create_fake_instance_obj()
        node = test_compute.NODENAME
        limits = {}
        filter_properties = {'limits': limits}
        instance.task_state = task_states.UNSHELVING
        instance.save()
        image_meta = {'properties': {'base_image_ref': uuids.image_id}}
        mock_image_meta.return_value = image_meta

        tracking = {'last_state': instance.task_state}

        def fake_claim(context, instance, node, limits):
            instance.host = self.compute.host
            requests = objects.InstancePCIRequests(requests=[])
            return claims.Claim(context, instance, test_compute.NODENAME,
                                self.rt, _fake_resources(),
                                requests)
        mock_instance_claim.side_effect = fake_claim

        def check_save(expected_task_state=None):
            if tracking['last_state'] == task_states.UNSHELVING:
                self.assertEqual(task_states.SPAWNING, instance.task_state)
                tracking['last_state'] = instance.task_state
            elif tracking['last_state'] == task_states.SPAWNING:
                self.assertEqual(123, instance.power_state)
                self.assertEqual(vm_states.ACTIVE, instance.vm_state)
                self.assertIsNone(instance.task_state)
                self.assertIsNone(instance.key_data)
                self.assertFalse(instance.auto_disk_config)
                self.assertIsNone(instance.task_state)
                tracking['last_state'] = instance.task_state
            else:
                self.fail('Unexpected save!')

        with mock.patch.object(instance, 'save') as mock_save:
            mock_save.side_effect = check_save
            self.compute.unshelve_instance(self.context, instance, image=None,
                    filter_properties=filter_properties, node=node)

        mock_notify_instance_action.assert_has_calls([
            mock.call(self.context, instance, 'fake-mini',
                      action='unshelve', phase='start', bdms=mock_bdms),
            mock.call(self.context, instance, 'fake-mini',
                      action='unshelve', phase='end', bdms=mock_bdms)])

        # prepare expect call lists
        mock_notify_instance_usage_call_list = [
            mock.call(self.context, instance, 'unshelve.start'),
            mock.call(self.context, instance, 'unshelve.end')]

        mock_notify_instance_usage.assert_has_calls(
            mock_notify_instance_usage_call_list)
        mock_prep_block_device.assert_called_once_with(self.context, instance,
                mock.ANY)
        mock_setup_network.assert_called_once_with(self.context, instance,
                                                   self.compute.host)
        mock_instance_claim.assert_called_once_with(self.context, instance,
                                                    test_compute.NODENAME,
                                                    limits)
        mock_spawn.assert_called_once_with(self.context, instance,
                test.MatchType(objects.ImageMeta),
                injected_files=[], admin_password=None,
                allocations={}, network_info=[], block_device_info='fake_bdm')
        self.mock_get_allocs.assert_called_once_with(instance.uuid)
        mock_get_power_state.assert_called_once_with(self.context, instance)
예제 #22
0
    def test_unshelve(self, mock_setup_network,
                      mock_get_power_state, mock_spawn,
                      mock_prep_block_device, mock_notify_instance_usage,
                      mock_notify_instance_action,
                      mock_get_bdms):
        mock_bdms = mock.Mock()
        mock_get_bdms.return_value = mock_bdms
        instance = self._create_fake_instance_obj()
        instance.task_state = task_states.UNSHELVING
        instance.save()
        image = {'id': uuids.image_id}
        node = test_compute.NODENAME
        limits = {}
        filter_properties = {'limits': limits}
        host = 'fake-mini'
        cur_time = timeutils.utcnow()
        # Adding shelved_* keys in system metadata to verify
        # whether those are deleted after unshelve call.
        sys_meta = dict(instance.system_metadata)
        sys_meta['shelved_at'] = cur_time.isoformat()
        sys_meta['shelved_image_id'] = image['id']
        sys_meta['shelved_host'] = host
        instance.system_metadata = sys_meta

        self.deleted_image_id = None

        def fake_delete(self2, ctxt, image_id):
            self.deleted_image_id = image_id

        def fake_claim(context, instance, node, limits):
            instance.host = self.compute.host
            requests = objects.InstancePCIRequests(requests=[])
            return claims.Claim(context, instance, test_compute.NODENAME,
                                self.rt, _fake_resources(),
                                requests)

        tracking = {
            'last_state': instance.task_state,
            'spawned': False,
        }

        def check_save(expected_task_state=None):
            if tracking['last_state'] == task_states.UNSHELVING:
                if tracking['spawned']:
                    self.assertIsNone(instance.task_state)
                else:
                    self.assertEqual(task_states.SPAWNING, instance.task_state)
                    tracking['spawned'] = True
                tracking['last_state'] == instance.task_state
            elif tracking['last_state'] == task_states.SPAWNING:
                self.assertEqual(vm_states.ACTIVE, instance.vm_state)
                tracking['last_state'] == instance.task_state
            else:
                self.fail('Unexpected save!')

        fake_image.stub_out_image_service(self)
        self.stub_out('nova.tests.unit.image.fake._FakeImageService.delete',
                      fake_delete)

        with mock.patch.object(self.rt, 'instance_claim',
                               side_effect=fake_claim), \
                 mock.patch.object(instance, 'save') as mock_save:
            mock_save.side_effect = check_save
            self.compute.unshelve_instance(
                self.context, instance, image=image,
                filter_properties=filter_properties,
                node=node)

        mock_notify_instance_action.assert_has_calls([
            mock.call(self.context, instance, 'fake-mini',
                      action='unshelve', phase='start', bdms=mock_bdms),
            mock.call(self.context, instance, 'fake-mini',
                      action='unshelve', phase='end', bdms=mock_bdms)])

        # prepare expect call lists
        mock_notify_instance_usage_call_list = [
            mock.call(self.context, instance, 'unshelve.start'),
            mock.call(self.context, instance, 'unshelve.end')]

        mock_notify_instance_usage.assert_has_calls(
            mock_notify_instance_usage_call_list)
        mock_prep_block_device.assert_called_once_with(self.context,
            instance, mock.ANY)
        mock_setup_network.assert_called_once_with(self.context, instance,
                                                   self.compute.host)
        mock_spawn.assert_called_once_with(self.context, instance,
                test.MatchType(objects.ImageMeta), injected_files=[],
                admin_password=None, allocations={}, network_info=[],
                block_device_info='fake_bdm')
        self.mock_get_allocs.assert_called_once_with(instance.uuid)
        mock_get_power_state.assert_called_once_with(self.context, instance)

        self.assertNotIn('shelved_at', instance.system_metadata)
        self.assertNotIn('shelved_image_id', instance.system_metadata)
        self.assertNotIn('shelved_host', instance.system_metadata)
        self.assertEqual(image['id'], self.deleted_image_id)
        self.assertEqual(instance.host, self.compute.host)

        self.assertEqual(123, instance.power_state)
        self.assertEqual(vm_states.ACTIVE, instance.vm_state)
        self.assertIsNone(instance.task_state)
        self.assertIsNone(instance.key_data)
        self.assertEqual(self.compute.host, instance.host)
        self.assertFalse(instance.auto_disk_config)
예제 #23
0
    def test_unshelve_spawn_fails_cleanup_volume_connections(
            self, mock_terminate_volume_connections, mock_image_meta,
            mock_notify_instance_usage, mock_prep_block_device, mock_spawn,
            mock_setup_network, mock_instance_claim,
            mock_notify_instance_action, mock_get_bdms):
        """Tests error handling when a instance fails to unshelve and makes
        sure that volume connections are cleaned up from the host
        and that the host/node values are unset on the instance.
        """
        mock_bdms = mock.Mock()
        mock_get_bdms.return_value = mock_bdms
        instance = self._create_fake_instance_obj()
        node = test_compute.NODENAME
        limits = {}
        filter_properties = {'limits': limits}
        instance.task_state = task_states.UNSHELVING
        instance.save()
        image_meta = {'properties': {'base_image_ref': uuids.image_id}}
        mock_image_meta.return_value = image_meta

        tracking = {'last_state': instance.task_state}

        def fake_claim(context, instance, node, allocations, limits):
            instance.host = self.compute.host
            instance.node = node
            requests = objects.InstancePCIRequests(requests=[])
            return claims.Claim(context,
                                instance,
                                node,
                                self.rt,
                                _fake_resources(),
                                requests,
                                limits=limits)

        mock_instance_claim.side_effect = fake_claim

        def check_save(expected_task_state=None):
            if tracking['last_state'] == task_states.UNSHELVING:
                # This is before we've failed.
                self.assertEqual(task_states.SPAWNING, instance.task_state)
                tracking['last_state'] = instance.task_state
            elif tracking['last_state'] == task_states.SPAWNING:
                # This is after we've failed.
                self.assertIsNone(instance.host)
                self.assertIsNone(instance.node)
                self.assertIsNone(instance.task_state)
                tracking['last_state'] = instance.task_state
            else:
                self.fail('Unexpected save!')

        with mock.patch.object(instance, 'save') as mock_save:
            mock_save.side_effect = check_save
            self.assertRaises(test.TestingException,
                              self.compute.unshelve_instance,
                              self.context,
                              instance,
                              image=None,
                              filter_properties=filter_properties,
                              node=node,
                              request_spec=objects.RequestSpec())

        mock_notify_instance_action.assert_called_once_with(self.context,
                                                            instance,
                                                            'fake-mini',
                                                            action='unshelve',
                                                            phase='start',
                                                            bdms=mock_bdms)
        mock_notify_instance_usage.assert_called_once_with(
            self.context, instance, 'unshelve.start')
        mock_prep_block_device.assert_called_once_with(self.context, instance,
                                                       mock_bdms)
        mock_setup_network.assert_called_once_with(self.context, instance,
                                                   self.compute.host)
        mock_instance_claim.assert_called_once_with(self.context, instance,
                                                    test_compute.NODENAME, {},
                                                    limits)
        mock_spawn.assert_called_once_with(self.context,
                                           instance,
                                           test.MatchType(objects.ImageMeta),
                                           injected_files=[],
                                           admin_password=None,
                                           allocations={},
                                           network_info=[],
                                           block_device_info='fake_bdm')
        mock_terminate_volume_connections.assert_called_once_with(
            self.context, instance, mock_bdms)
예제 #24
0
 def test_connect_to_rados_unicode_arg(self):
     self.driver._connect_to_rados(u'unicode_pool')
     self.mock_rados.Rados.open_ioctx.assert_called_with(
         test.MatchType(str))