Пример #1
0
 def not_found(context):
     raise exception.InstanceNotFound(instance_id=None)
def return_server_nonexistent(context,
                              server_id,
                              columns_to_join=None,
                              use_slave=False):
    raise exception.InstanceNotFound(instance_id=server_id)
Пример #3
0
def fake_get_not_found(self,
                       context,
                       instance_uuid,
                       want_objects=False,
                       expected_attrs=None):
    raise exception.InstanceNotFound(instance_id=instance_uuid)
Пример #4
0
 def _raise_instance_not_found(*args, **kwargs):
     raise exception.InstanceNotFound(instance_id='123')
Пример #5
0
    def test_destroy(self, mock_bldftsk, mock_cdrb, mock_cfgdrv, mock_dlt_lpar,
                     mock_unplug, mock_detach_vol):
        """Validates PowerVM destroy."""
        self.drv.host_wrapper = mock.Mock()
        self.drv.disk_dvr = mock.create_autospec(ssp.SSPDiskAdapter,
                                                 instance=True)

        mock_ftsk = pvm_tx.FeedTask('fake', [mock.Mock(spec=pvm_vios.VIOS)])
        mock_bldftsk.return_value = mock_ftsk
        block_device_info = self._fake_bdms()

        # Good path, with config drive, destroy disks
        mock_cdrb.return_value = True
        self.drv.destroy('context',
                         self.inst, [],
                         block_device_info=block_device_info)
        self.pwroff.assert_called_once_with(self.adp,
                                            self.inst,
                                            force_immediate=True)
        mock_bldftsk.assert_called_once_with(self.adp,
                                             xag=[pvm_const.XAG.VIO_SMAP])
        mock_unplug.assert_called_once()
        mock_cdrb.assert_called_once_with(self.inst)
        mock_cfgdrv.assert_called_once_with(self.adp)
        mock_cfgdrv.return_value.dlt_vopt.assert_called_once_with(
            self.inst, stg_ftsk=mock_bldftsk.return_value)
        self.assertEqual(2, mock_detach_vol.call_count)
        self.drv.disk_dvr.detach_disk.assert_called_once_with(self.inst)
        self.drv.disk_dvr.delete_disks.assert_called_once_with(
            self.drv.disk_dvr.detach_disk.return_value)
        mock_dlt_lpar.assert_called_once_with(self.adp, self.inst)

        self.pwroff.reset_mock()
        mock_bldftsk.reset_mock()
        mock_unplug.reset_mock()
        mock_cdrb.reset_mock()
        mock_cfgdrv.reset_mock()
        self.drv.disk_dvr.detach_disk.reset_mock()
        self.drv.disk_dvr.delete_disks.reset_mock()
        mock_detach_vol.reset_mock()
        mock_dlt_lpar.reset_mock()

        # No config drive, preserve disks, no block device info
        mock_cdrb.return_value = False
        self.drv.destroy('context',
                         self.inst, [],
                         block_device_info={},
                         destroy_disks=False)
        mock_cfgdrv.return_value.dlt_vopt.assert_not_called()
        mock_detach_vol.assert_not_called()
        self.drv.disk_dvr.delete_disks.assert_not_called()

        # Non-forced power_off, since preserving disks
        self.pwroff.assert_called_once_with(self.adp,
                                            self.inst,
                                            force_immediate=False)
        mock_bldftsk.assert_called_once_with(self.adp,
                                             xag=[pvm_const.XAG.VIO_SMAP])
        mock_unplug.assert_called_once()
        mock_cdrb.assert_called_once_with(self.inst)
        mock_cfgdrv.assert_not_called()
        mock_cfgdrv.return_value.dlt_vopt.assert_not_called()
        self.drv.disk_dvr.detach_disk.assert_called_once_with(self.inst)
        self.drv.disk_dvr.delete_disks.assert_not_called()
        mock_dlt_lpar.assert_called_once_with(self.adp, self.inst)

        self.pwroff.reset_mock()
        mock_bldftsk.reset_mock()
        mock_unplug.reset_mock()
        mock_cdrb.reset_mock()
        mock_cfgdrv.reset_mock()
        self.drv.disk_dvr.detach_disk.reset_mock()
        self.drv.disk_dvr.delete_disks.reset_mock()
        mock_dlt_lpar.reset_mock()

        # InstanceNotFound exception, non-forced
        self.pwroff.side_effect = exception.InstanceNotFound(
            instance_id='something')
        self.drv.destroy('context',
                         self.inst, [],
                         block_device_info={},
                         destroy_disks=False)
        self.pwroff.assert_called_once_with(self.adp,
                                            self.inst,
                                            force_immediate=False)
        self.drv.disk_dvr.detach_disk.assert_not_called()
        mock_unplug.assert_not_called()
        self.drv.disk_dvr.delete_disks.assert_not_called()
        mock_dlt_lpar.assert_not_called()

        self.pwroff.reset_mock()
        self.pwroff.side_effect = None
        mock_unplug.reset_mock()

        # Convertible (PowerVM) exception
        mock_dlt_lpar.side_effect = pvm_exc.TimeoutError("Timed out")
        self.assertRaises(exception.InstanceTerminationFailure,
                          self.drv.destroy,
                          'context',
                          self.inst, [],
                          block_device_info={})

        # Everything got called
        self.pwroff.assert_called_once_with(self.adp,
                                            self.inst,
                                            force_immediate=True)
        mock_unplug.assert_called_once()
        self.drv.disk_dvr.detach_disk.assert_called_once_with(self.inst)
        self.drv.disk_dvr.delete_disks.assert_called_once_with(
            self.drv.disk_dvr.detach_disk.return_value)
        mock_dlt_lpar.assert_called_once_with(self.adp, self.inst)

        # Other random exception raises directly
        mock_dlt_lpar.side_effect = ValueError()
        self.assertRaises(ValueError,
                          self.drv.destroy,
                          'context',
                          self.inst, [],
                          block_device_info={})
Пример #6
0
 def reboot(self, instance, network_info, reboot_type):
     """Reboot the specified instance."""
     vm = self._lookup(instance.name)
     if vm is None:
         raise exception.InstanceNotFound(instance_id=instance.id)
     self._set_vm_state(instance.name, 'Reboot')
 def server_not_found(self, instance_id):
     raise exception.InstanceNotFound(instance_id=instance_id)
Пример #8
0
 def _router_by_name(self, name):
     try:
         return filter(lambda r: r.os_name == name,
                       self._routers.itervalues())[0]
     except IndexError:
         raise exception.InstanceNotFound(instance_id=name)
Пример #9
0
    def snapshot(self, context, instance, snapshot_name):
        """Create snapshot from a running VM instance.

        Steps followed are:

        1. Get the name of the vmdk file which the VM points to right now.
           Can be a chain of snapshots, so we need to know the last in the
           chain.
        2. Create the snapshot. A new vmdk is created which the VM points to
           now. The earlier vmdk becomes read-only.
        3. Call CopyVirtualDisk which coalesces the disk chain to form a single
           vmdk, rather a .vmdk metadata file and a -flat.vmdk disk data file.
        4. Now upload the -flat.vmdk file to the image store.
        5. Delete the coalesced .vmdk and -flat.vmdk created.
        """
        vm_ref = self._get_vm_ref_from_the_name(instance.name)
        if vm_ref is None:
            raise exception.InstanceNotFound(instance_id=instance.id)

        client_factory = self._session._get_vim().client.factory
        service_content = self._session._get_vim().get_service_content()

        def _get_vm_and_vmdk_attribs():
            # Get the vmdk file name that the VM is pointing to
            hardware_devices = self._session._call_method(
                vim_util, "get_dynamic_property", vm_ref, "VirtualMachine",
                "config.hardware.device")
            _vmdk_info = vm_util.get_vmdk_file_path_and_adapter_type(
                client_factory, hardware_devices)
            vmdk_file_path_before_snapshot, adapter_type = _vmdk_info
            datastore_name = vm_util.split_datastore_path(
                vmdk_file_path_before_snapshot)[0]
            os_type = self._session._call_method(vim_util,
                                                 "get_dynamic_property",
                                                 vm_ref, "VirtualMachine",
                                                 "summary.config.guestId")
            return (vmdk_file_path_before_snapshot, adapter_type,
                    datastore_name, os_type)

        (vmdk_file_path_before_snapshot, adapter_type, datastore_name,
         os_type) = _get_vm_and_vmdk_attribs()

        def _create_vm_snapshot():
            # Create a snapshot of the VM
            LOG.debug(_("Creating Snapshot of the VM instance"),
                      instance=instance)
            snapshot_task = self._session._call_method(
                self._session._get_vim(),
                "CreateSnapshot_Task",
                vm_ref,
                name="%s-snapshot" % instance.name,
                description="Taking Snapshot of the VM",
                memory=True,
                quiesce=True)
            self._session._wait_for_task(instance['uuid'], snapshot_task)
            LOG.debug(_("Created Snapshot of the VM instance"),
                      instance=instance)

        _create_vm_snapshot()

        def _check_if_tmp_folder_exists():
            # Copy the contents of the VM that were there just before the
            # snapshot was taken
            ds_ref_ret = vim_util.get_dynamic_property(
                self._session._get_vim(), vm_ref, "VirtualMachine",
                "datastore")
            if not ds_ref_ret:
                raise exception.DatastoreNotFound()
            ds_ref = ds_ref_ret.ManagedObjectReference[0]
            ds_browser = vim_util.get_dynamic_property(
                self._session._get_vim(), ds_ref, "Datastore", "browser")
            # Check if the vmware-tmp folder exists or not. If not, create one
            tmp_folder_path = vm_util.build_datastore_path(
                datastore_name, "vmware-tmp")
            if not self._path_exists(ds_browser, tmp_folder_path):
                self._mkdir(
                    vm_util.build_datastore_path(datastore_name, "vmware-tmp"))

        _check_if_tmp_folder_exists()

        # Generate a random vmdk file name to which the coalesced vmdk content
        # will be copied to. A random name is chosen so that we don't have
        # name clashes.
        random_name = str(uuid.uuid4())
        dest_vmdk_file_location = vm_util.build_datastore_path(
            datastore_name, "vmware-tmp/%s.vmdk" % random_name)
        dc_ref = self._get_datacenter_name_and_ref()[0]

        def _copy_vmdk_content():
            # Copy the contents of the disk ( or disks, if there were snapshots
            # done earlier) to a temporary vmdk file.
            copy_spec = vm_util.get_copy_virtual_disk_spec(
                client_factory, adapter_type)
            LOG.debug(_('Copying disk data before snapshot of the VM'),
                      instance=instance)
            copy_disk_task = self._session._call_method(
                self._session._get_vim(),
                "CopyVirtualDisk_Task",
                service_content.virtualDiskManager,
                sourceName=vmdk_file_path_before_snapshot,
                sourceDatacenter=dc_ref,
                destName=dest_vmdk_file_location,
                destDatacenter=dc_ref,
                destSpec=copy_spec,
                force=False)
            self._session._wait_for_task(instance['uuid'], copy_disk_task)
            LOG.debug(_("Copied disk data before snapshot of the VM"),
                      instance=instance)

        _copy_vmdk_content()

        cookies = self._session._get_vim().client.options.transport.cookiejar

        def _upload_vmdk_to_image_repository():
            # Upload the contents of -flat.vmdk file which has the disk data.
            LOG.debug(_("Uploading image %s") % snapshot_name,
                      instance=instance)
            vmware_images.upload_image(
                context,
                snapshot_name,
                instance,
                os_type=os_type,
                adapter_type=adapter_type,
                image_version=1,
                host=self._session._host_ip,
                data_center_name=self._get_datacenter_name_and_ref()[1],
                datastore_name=datastore_name,
                cookies=cookies,
                file_path="vmware-tmp/%s-flat.vmdk" % random_name)
            LOG.debug(_("Uploaded image %s") % snapshot_name,
                      instance=instance)

        _upload_vmdk_to_image_repository()

        def _clean_temp_data():
            """
            Delete temporary vmdk files generated in image handling
            operations.
            """
            # Delete the temporary vmdk created above.
            LOG.debug(_("Deleting temporary vmdk file %s") %
                      dest_vmdk_file_location,
                      instance=instance)
            remove_disk_task = self._session._call_method(
                self._session._get_vim(),
                "DeleteVirtualDisk_Task",
                service_content.virtualDiskManager,
                name=dest_vmdk_file_location,
                datacenter=dc_ref)
            self._session._wait_for_task(instance['uuid'], remove_disk_task)
            LOG.debug(_("Deleted temporary vmdk file %s") %
                      dest_vmdk_file_location,
                      instance=instance)

        _clean_temp_data()
Пример #10
0
 def test_force_complete_instance_not_found(self):
     self._test_force_complete_failed_with_exception(
         exception.InstanceNotFound(instance_id=''), webob.exc.HTTPNotFound)
class AdminPasswordTestV21(test.NoDBTestCase):
    def setUp(self):
        super(AdminPasswordTestV21, self).setUp()
        self.stubs.Set(compute_api.API, 'set_admin_password',
                       fake_set_admin_password)
        self.stubs.Set(compute_api.API, 'get', fake_get)
        self.controller = admin_password_v21.AdminPasswordController()
        self.fake_req = fakes.HTTPRequest.blank('')

    def test_change_password(self):
        body = {'changePassword': {'adminPass': '******'}}
        self.controller.change_password(self.fake_req, '1', body=body)
        self.assertEqual(self.controller.change_password.wsgi_code, 202)

    def test_change_password_empty_string(self):
        body = {'changePassword': {'adminPass': ''}}
        self.controller.change_password(self.fake_req, '1', body=body)
        self.assertEqual(self.controller.change_password.wsgi_code, 202)

    @mock.patch('nova.compute.api.API.set_admin_password',
                side_effect=NotImplementedError())
    def test_change_password_with_non_implement(self, mock_set_admin_password):
        body = {'changePassword': {'adminPass': '******'}}
        self.assertRaises(webob.exc.HTTPNotImplemented,
                          self.controller.change_password,
                          self.fake_req,
                          '1',
                          body=body)

    @mock.patch('nova.compute.api.API.get',
                side_effect=exception.InstanceNotFound(instance_id='1'))
    def test_change_password_with_non_existed_instance(self, mock_get):
        body = {'changePassword': {'adminPass': '******'}}
        self.assertRaises(webob.exc.HTTPNotFound,
                          self.controller.change_password,
                          self.fake_req,
                          '1',
                          body=body)

    def test_change_password_with_non_string_password(self):
        body = {'changePassword': {'adminPass': 1234}}
        self.assertRaises(exception.ValidationError,
                          self.controller.change_password,
                          self.fake_req,
                          '1',
                          body=body)

    @mock.patch('nova.compute.api.API.set_admin_password',
                side_effect=exception.InstancePasswordSetFailed(instance="1",
                                                                reason=''))
    def test_change_password_failed(self, mock_set_admin_password):
        body = {'changePassword': {'adminPass': '******'}}
        self.assertRaises(webob.exc.HTTPConflict,
                          self.controller.change_password,
                          self.fake_req,
                          '1',
                          body=body)

    def test_change_password_without_admin_password(self):
        body = {'changPassword': {}}
        self.assertRaises(exception.ValidationError,
                          self.controller.change_password,
                          self.fake_req,
                          '1',
                          body=body)

    def test_change_password_none(self):
        body = {'changePassword': None}
        self.assertRaises(exception.ValidationError,
                          self.controller.change_password,
                          self.fake_req,
                          '1',
                          body=body)
 def fake_get(self, context, instance_uuid):
     raise exception.InstanceNotFound(instance_id=instance_uuid)
Пример #13
0
def fake_compute_api_raises_instance_not_found(*args, **kwargs):
    raise exception.InstanceNotFound(instance_id='fake_id')
Пример #14
0
def fake_compute_get_not_found(*args, **kwargs):
    raise exception.InstanceNotFound(instance_id=UUID1)
Пример #15
0
class AdminPasswordTestV21(test.NoDBTestCase):
    validiation_error = exception.ValidationError

    def setUp(self):
        super(AdminPasswordTestV21, self).setUp()
        self.stubs.Set(compute_api.API, 'set_admin_password',
                       fake_set_admin_password)
        self.stubs.Set(compute_api.API, 'get', fake_get)
        self.fake_req = fakes.HTTPRequest.blank('')

    def _get_action(self):
        return admin_password_v21.AdminPasswordController().change_password

    def _check_status(self, expected_status, res, controller_method):
        self.assertEqual(expected_status, controller_method.wsgi_code)

    def test_change_password(self):
        body = {'changePassword': {'adminPass': '******'}}
        res = self._get_action()(self.fake_req, '1', body=body)
        self._check_status(202, res, self._get_action())

    def test_change_password_empty_string(self):
        body = {'changePassword': {'adminPass': ''}}
        res = self._get_action()(self.fake_req, '1', body=body)
        self._check_status(202, res, self._get_action())

    @mock.patch('nova.compute.api.API.set_admin_password',
                side_effect=NotImplementedError())
    def test_change_password_with_non_implement(self, mock_set_admin_password):
        body = {'changePassword': {'adminPass': '******'}}
        self.assertRaises(webob.exc.HTTPNotImplemented,
                          self._get_action(),
                          self.fake_req,
                          '1',
                          body=body)

    @mock.patch('nova.compute.api.API.get',
                side_effect=exception.InstanceNotFound(instance_id='1'))
    def test_change_password_with_non_existed_instance(self, mock_get):
        body = {'changePassword': {'adminPass': '******'}}
        self.assertRaises(webob.exc.HTTPNotFound,
                          self._get_action(),
                          self.fake_req,
                          '1',
                          body=body)

    def test_change_password_with_non_string_password(self):
        body = {'changePassword': {'adminPass': 1234}}
        self.assertRaises(self.validiation_error,
                          self._get_action(),
                          self.fake_req,
                          '1',
                          body=body)

    @mock.patch('nova.compute.api.API.set_admin_password',
                side_effect=exception.InstancePasswordSetFailed(instance="1",
                                                                reason=''))
    def test_change_password_failed(self, mock_set_admin_password):
        body = {'changePassword': {'adminPass': '******'}}
        self.assertRaises(webob.exc.HTTPConflict,
                          self._get_action(),
                          self.fake_req,
                          '1',
                          body=body)

    def test_change_password_without_admin_password(self):
        body = {'changPassword': {}}
        self.assertRaises(self.validiation_error,
                          self._get_action(),
                          self.fake_req,
                          '1',
                          body=body)

    def test_change_password_none(self):
        body = {'changePassword': {'adminPass': None}}
        self.assertRaises(self.validiation_error,
                          self._get_action(),
                          self.fake_req,
                          '1',
                          body=body)

    def test_change_password_adminpass_none(self):
        body = {'changePassword': None}
        self.assertRaises(self.validiation_error,
                          self._get_action(),
                          self.fake_req,
                          '1',
                          body=body)

    def test_change_password_bad_request(self):
        body = {'changePassword': {'pass': '******'}}
        self.assertRaises(self.validiation_error,
                          self._get_action(),
                          self.fake_req,
                          '1',
                          body=body)

    def test_server_change_password_pass_disabled(self):
        # run with enable_instance_password disabled to verify adminPass
        # is missing from response. See lp bug 921814
        self.flags(enable_instance_password=False)
        body = {'changePassword': {'adminPass': '******'}}
        res = self._get_action()(self.fake_req, '1', body=body)
        self._check_status(202, res, self._get_action())

    @mock.patch('nova.compute.api.API.set_admin_password',
                side_effect=exception.InstanceInvalidState(
                    instance_uuid='fake',
                    attr='vm_state',
                    state='stopped',
                    method='set_admin_password'))
    def test_change_password_invalid_state(self, mock_set_admin_password):
        body = {'changePassword': {'adminPass': '******'}}
        self.assertRaises(webob.exc.HTTPConflict,
                          self._get_action(),
                          self.fake_req,
                          'fake',
                          body=body)
Пример #16
0
class SimpleTenantUsageTestV21(test.TestCase):
    version = '2.1'
    policy_rule_prefix = "os_compute_api:os-simple-tenant-usage"
    controller = simple_tenant_usage_v21.SimpleTenantUsageController()

    def setUp(self):
        super(SimpleTenantUsageTestV21, self).setUp()
        self.admin_context = context.RequestContext('fakeadmin_0',
                                                    'faketenant_0',
                                                    is_admin=True)
        self.user_context = context.RequestContext('fakeadmin_0',
                                                   'faketenant_0',
                                                   is_admin=False)
        self.alt_user_context = context.RequestContext('fakeadmin_0',
                                                       'faketenant_1',
                                                       is_admin=False)
        self.num_cells = len(
            objects.CellMappingList.get_all(self.admin_context))

    def _test_verify_index(self, start, stop, limit=None):
        url = '?start=%s&end=%s'
        if limit:
            url += '&limit=%s' % (limit)
        req = fakes.HTTPRequest.blank(url %
                                      (start.isoformat(), stop.isoformat()),
                                      version=self.version)
        req.environ['nova.context'] = self.admin_context
        res_dict = self.controller.index(req)

        usages = res_dict['tenant_usages']

        if limit:
            num = 1
        else:
            # NOTE(danms): We call our fake data mock once per cell,
            # and the default fixture has two cells (cell0 and cell1),
            # so all our math will be doubled.
            num = self.num_cells

        for i in range(TENANTS):
            self.assertEqual(SERVERS * HOURS * num,
                             int(usages[i]['total_hours']))
            self.assertEqual(SERVERS * (ROOT_GB + EPHEMERAL_GB) * HOURS * num,
                             int(usages[i]['total_local_gb_usage']))
            self.assertEqual(SERVERS * MEMORY_MB * HOURS * num,
                             int(usages[i]['total_memory_mb_usage']))
            self.assertEqual(SERVERS * VCPUS * HOURS * num,
                             int(usages[i]['total_vcpus_usage']))
            self.assertFalse(usages[i].get('server_usages'))

        if limit:
            self.assertIn('tenant_usages_links', res_dict)
            self.assertEqual('next', res_dict['tenant_usages_links'][0]['rel'])
        else:
            self.assertNotIn('tenant_usages_links', res_dict)

    # NOTE(artom) Test for bugs 1643444 and 1692893 (duplicates). We simulate a
    # situation where an instance has been deleted (moved to shadow table) and
    # its corresponding instance_extra row has been archived (deleted from
    # shadow table).
    @mock.patch('nova.objects.InstanceList.get_active_by_window_joined',
                fake_get_active_deleted_flavorless)
    @mock.patch.object(
        objects.Instance,
        '_load_flavor',
        side_effect=exception.InstanceNotFound(instance_id='fake-id'))
    def test_verify_index_deleted_flavorless(self, mock_load):
        with mock.patch.object(self.controller,
                               '_get_flavor',
                               return_value=None):
            self._test_verify_index(START, STOP)

    @mock.patch('nova.objects.InstanceList.get_active_by_window_joined',
                fake_get_active_by_window_joined)
    def test_verify_index(self):
        self._test_verify_index(START, STOP)

    @mock.patch('nova.objects.InstanceList.get_active_by_window_joined',
                fake_get_active_by_window_joined)
    def test_verify_index_future_end_time(self):
        future = NOW + datetime.timedelta(hours=HOURS)
        self._test_verify_index(START, future)

    def test_verify_show(self):
        self._test_verify_show(START, STOP)

    def test_verify_show_future_end_time(self):
        future = NOW + datetime.timedelta(hours=HOURS)
        self._test_verify_show(START, future)

    @mock.patch('nova.objects.InstanceList.get_active_by_window_joined',
                fake_get_active_by_window_joined)
    def _get_tenant_usages(self, detailed=''):
        req = fakes.HTTPRequest.blank(
            '?detailed=%s&start=%s&end=%s' %
            (detailed, START.isoformat(), STOP.isoformat()),
            version=self.version)
        req.environ['nova.context'] = self.admin_context

        # Make sure that get_active_by_window_joined is only called with
        # expected_attrs=['flavor'].
        orig_get_active_by_window_joined = (
            objects.InstanceList.get_active_by_window_joined)

        def fake_get_active_by_window_joined(context,
                                             begin,
                                             end=None,
                                             project_id=None,
                                             host=None,
                                             expected_attrs=None,
                                             use_slave=False,
                                             limit=None,
                                             marker=None):
            self.assertEqual(['flavor'], expected_attrs)
            return orig_get_active_by_window_joined(context, begin, end,
                                                    project_id, host,
                                                    expected_attrs, use_slave)

        with mock.patch.object(objects.InstanceList,
                               'get_active_by_window_joined',
                               side_effect=fake_get_active_by_window_joined):
            res_dict = self.controller.index(req)
            return res_dict['tenant_usages']

    def test_verify_detailed_index(self):
        usages = self._get_tenant_usages('1')
        for i in range(TENANTS):
            servers = usages[i]['server_usages']
            for j in range(SERVERS):
                self.assertEqual(HOURS, int(servers[j]['hours']))

    def test_verify_simple_index(self):
        usages = self._get_tenant_usages(detailed='0')
        for i in range(TENANTS):
            self.assertIsNone(usages[i].get('server_usages'))

    def test_verify_simple_index_empty_param(self):
        # NOTE(lzyeval): 'detailed=&start=..&end=..'
        usages = self._get_tenant_usages()
        for i in range(TENANTS):
            self.assertIsNone(usages[i].get('server_usages'))

    @mock.patch('nova.objects.InstanceList.get_active_by_window_joined',
                fake_get_active_by_window_joined)
    def _test_verify_show(self, start, stop, limit=None):
        tenant_id = 1
        url = '?start=%s&end=%s'
        if limit:
            url += '&limit=%s' % (limit)
        req = fakes.HTTPRequest.blank(url %
                                      (start.isoformat(), stop.isoformat()),
                                      version=self.version)
        req.environ['nova.context'] = self.user_context
        res_dict = self.controller.show(req, tenant_id)

        if limit:
            num = 1
        else:
            # NOTE(danms): We call our fake data mock once per cell,
            # and the default fixture has two cells (cell0 and cell1),
            # so all our math will be doubled.
            num = self.num_cells

        usage = res_dict['tenant_usage']
        servers = usage['server_usages']
        self.assertEqual(TENANTS * SERVERS * num, len(usage['server_usages']))
        server_uuids = [
            getattr(uuids, 'instance_%d' % x) for x in range(SERVERS)
        ]
        for j in range(SERVERS):
            delta = STOP - START
            # NOTE(javeme): cast seconds from float to int for clarity
            uptime = int(delta.total_seconds())
            self.assertEqual(uptime, int(servers[j]['uptime']))
            self.assertEqual(HOURS, int(servers[j]['hours']))
            self.assertIn(servers[j]['instance_id'], server_uuids)

        if limit:
            self.assertIn('tenant_usage_links', res_dict)
            self.assertEqual('next', res_dict['tenant_usage_links'][0]['rel'])
        else:
            self.assertNotIn('tenant_usage_links', res_dict)

    def test_verify_show_cannot_view_other_tenant(self):
        req = fakes.HTTPRequest.blank('?start=%s&end=%s' %
                                      (START.isoformat(), STOP.isoformat()),
                                      version=self.version)
        req.environ['nova.context'] = self.alt_user_context

        rules = {
            self.policy_rule_prefix + ":show": [["role:admin"],
                                                ["project_id:%(project_id)s"]]
        }
        policy.set_rules(oslo_policy.Rules.from_dict(rules))

        try:
            self.assertRaises(exception.PolicyNotAuthorized,
                              self.controller.show, req, 'faketenant_0')
        finally:
            policy.reset()

    def test_get_tenants_usage_with_bad_start_date(self):
        future = NOW + datetime.timedelta(hours=HOURS)
        req = fakes.HTTPRequest.blank('?start=%s&end=%s' %
                                      (future.isoformat(), NOW.isoformat()),
                                      version=self.version)
        req.environ['nova.context'] = self.user_context
        self.assertRaises(webob.exc.HTTPBadRequest, self.controller.show, req,
                          'faketenant_0')

    def test_get_tenants_usage_with_invalid_start_date(self):
        req = fakes.HTTPRequest.blank('?start=%s&end=%s' %
                                      ("xxxx", NOW.isoformat()),
                                      version=self.version)
        req.environ['nova.context'] = self.user_context
        self.assertRaises(webob.exc.HTTPBadRequest, self.controller.show, req,
                          'faketenant_0')

    def _test_get_tenants_usage_with_one_date(self, date_url_param):
        req = fakes.HTTPRequest.blank('?%s' % date_url_param,
                                      version=self.version)
        req.environ['nova.context'] = self.user_context
        res = self.controller.show(req, 'faketenant_0')
        self.assertIn('tenant_usage', res)

    def test_get_tenants_usage_with_no_start_date(self):
        self._test_get_tenants_usage_with_one_date(
            'end=%s' % (NOW + datetime.timedelta(5)).isoformat())

    def test_get_tenants_usage_with_no_end_date(self):
        self._test_get_tenants_usage_with_one_date(
            'start=%s' % (NOW - datetime.timedelta(5)).isoformat())

    def test_index_additional_query_parameters(self):
        req = fakes.HTTPRequest.blank('?start=%s&end=%s&additional=1' %
                                      (START.isoformat(), STOP.isoformat()),
                                      version=self.version)
        res = self.controller.index(req)
        self.assertIn('tenant_usages', res)

    def _test_index_duplicate_query_parameters_validation(self, params):
        for param, value in params.items():
            req = fakes.HTTPRequest.blank(
                '?start=%s&%s=%s&%s=%s' %
                (START.isoformat(), param, value, param, value),
                version=self.version)

            res = self.controller.index(req)
            self.assertIn('tenant_usages', res)

    def test_index_duplicate_query_parameters_validation(self):
        params = {
            'start': START.isoformat(),
            'end': STOP.isoformat(),
            'detailed': 1
        }
        self._test_index_duplicate_query_parameters_validation(params)

    def test_show_additional_query_parameters(self):
        req = fakes.HTTPRequest.blank('?start=%s&end=%s&additional=1' %
                                      (START.isoformat(), STOP.isoformat()),
                                      version=self.version)
        res = self.controller.show(req, 1)
        self.assertIn('tenant_usage', res)

    def _test_show_duplicate_query_parameters_validation(self, params):
        for param, value in params.items():
            req = fakes.HTTPRequest.blank(
                '?start=%s&%s=%s&%s=%s' %
                (START.isoformat(), param, value, param, value),
                version=self.version)

            res = self.controller.show(req, 1)
            self.assertIn('tenant_usage', res)

    def test_show_duplicate_query_parameters_validation(self):
        params = {'start': START.isoformat(), 'end': STOP.isoformat()}
        self._test_show_duplicate_query_parameters_validation(params)
Пример #17
0
 def fake_instance_get(_self, context, server_id, *args, **kwargs):
     for instance in FAKE_INSTANCES:
         if server_id == instance.uuid:
             return instance
     raise exception.InstanceNotFound(instance_id=server_id)
Пример #18
0
 def instance_get_by_uuid(self, ctxt, instance_uuid):
     raise exception.InstanceNotFound(instance_id=instance_uuid)
Пример #19
0
 def detach_volume(self, connection_info, instance_name, mountpoint):
     vm = self._lookup(instance_name)
     if vm is None:
         raise exception.InstanceNotFound(instance_id=instance_name)
Пример #20
0
 def power_off(self, instance, timeout=0, retry_interval=0):
     if instance.uuid in self.instances:
         self.instances[instance.uuid].state = power_state.SHUTDOWN
     else:
         raise exception.InstanceNotFound(instance_id=instance.uuid)
Пример #21
0
class VolumeAttachTestsV21(test.NoDBTestCase):
    validation_error = exception.ValidationError

    def setUp(self):
        super(VolumeAttachTestsV21, self).setUp()
        self.stubs.Set(db, 'block_device_mapping_get_all_by_instance',
                       fake_bdms_get_all_by_instance)
        self.stubs.Set(compute_api.API, 'get', fake_get_instance)
        self.stubs.Set(cinder.API, 'get', fake_get_volume)
        self.context = context.get_admin_context()
        self.expected_show = {
            'volumeAttachment': {
                'device': '/dev/fake0',
                'serverId': FAKE_UUID,
                'id': FAKE_UUID_A,
                'volumeId': FAKE_UUID_A
            }
        }
        self._set_up_controller()

    def _set_up_controller(self):
        self.attachments = volumes_v21.VolumeAttachmentController()

    def test_show(self):
        req = fakes.HTTPRequest.blank(
            '/v2/servers/id/os-volume_attachments/uuid')
        req.method = 'POST'
        req.body = jsonutils.dump_as_bytes({})
        req.headers['content-type'] = 'application/json'
        req.environ['nova.context'] = self.context

        result = self.attachments.show(req, FAKE_UUID, FAKE_UUID_A)
        self.assertEqual(self.expected_show, result)

    @mock.patch.object(
        compute_api.API,
        'get',
        side_effect=exception.InstanceNotFound(instance_id=FAKE_UUID))
    def test_show_no_instance(self, mock_mr):
        req = fakes.HTTPRequest.blank(
            '/v2/servers/id/os-volume_attachments/uuid')
        req.method = 'POST'
        req.body = jsonutils.dump_as_bytes({})
        req.headers['content-type'] = 'application/json'
        req.environ['nova.context'] = self.context

        self.assertRaises(exc.HTTPNotFound, self.attachments.show, req,
                          FAKE_UUID, FAKE_UUID_A)

    @mock.patch.object(objects.BlockDeviceMappingList,
                       'get_by_instance_uuid',
                       return_value=None)
    def test_show_no_bdms(self, mock_mr):
        req = fakes.HTTPRequest.blank(
            '/v2/servers/id/os-volume_attachments/uuid')
        req.method = 'POST'
        req.body = jsonutils.dump_as_bytes({})
        req.headers['content-type'] = 'application/json'
        req.environ['nova.context'] = self.context

        self.assertRaises(exc.HTTPNotFound, self.attachments.show, req,
                          FAKE_UUID, FAKE_UUID_A)

    def test_show_bdms_no_mountpoint(self):
        FAKE_UUID_NOTEXIST = '00000000-aaaa-aaaa-aaaa-aaaaaaaaaaaa'

        req = fakes.HTTPRequest.blank(
            '/v2/servers/id/os-volume_attachments/uuid')
        req.method = 'POST'
        req.body = jsonutils.dump_as_bytes({})
        req.headers['content-type'] = 'application/json'
        req.environ['nova.context'] = self.context

        self.assertRaises(exc.HTTPNotFound, self.attachments.show, req,
                          FAKE_UUID, FAKE_UUID_NOTEXIST)

    def test_detach(self):
        self.stubs.Set(compute_api.API, 'detach_volume', fake_detach_volume)
        req = fakes.HTTPRequest.blank(
            '/v2/servers/id/os-volume_attachments/uuid')
        req.method = 'DELETE'
        req.headers['content-type'] = 'application/json'
        req.environ['nova.context'] = self.context

        result = self.attachments.delete(req, FAKE_UUID, FAKE_UUID_A)
        # NOTE: on v2.1, http status code is set as wsgi_code of API
        # method instead of status_int in a response object.
        if isinstance(self.attachments,
                      volumes_v21.VolumeAttachmentController):
            status_int = self.attachments.delete.wsgi_code
        else:
            status_int = result.status_int
        self.assertEqual(202, status_int)

    def test_detach_vol_not_found(self):
        self.stubs.Set(compute_api.API, 'detach_volume', fake_detach_volume)
        req = fakes.HTTPRequest.blank(
            '/v2/servers/id/os-volume_attachments/uuid')
        req.method = 'DELETE'
        req.headers['content-type'] = 'application/json'
        req.environ['nova.context'] = self.context

        self.assertRaises(exc.HTTPNotFound, self.attachments.delete, req,
                          FAKE_UUID, FAKE_UUID_C)

    @mock.patch('nova.objects.BlockDeviceMapping.is_root',
                new_callable=mock.PropertyMock)
    def test_detach_vol_root(self, mock_isroot):
        req = fakes.HTTPRequest.blank(
            '/v2/servers/id/os-volume_attachments/uuid')
        req.method = 'DELETE'
        req.headers['content-type'] = 'application/json'
        req.environ['nova.context'] = self.context
        mock_isroot.return_value = True
        self.assertRaises(exc.HTTPForbidden, self.attachments.delete, req,
                          FAKE_UUID, FAKE_UUID_A)

    def test_detach_volume_from_locked_server(self):
        def fake_detach_volume_from_locked_server(self, context, instance,
                                                  volume):
            raise exception.InstanceIsLocked(instance_uuid=instance['uuid'])

        self.stubs.Set(compute_api.API, 'detach_volume',
                       fake_detach_volume_from_locked_server)
        req = fakes.HTTPRequest.blank(
            '/v2/servers/id/os-volume_attachments/uuid')
        req.method = 'DELETE'
        req.headers['content-type'] = 'application/json'
        req.environ['nova.context'] = self.context

        self.assertRaises(webob.exc.HTTPConflict, self.attachments.delete, req,
                          FAKE_UUID, FAKE_UUID_A)

    def test_attach_volume(self):
        self.stubs.Set(compute_api.API, 'attach_volume', fake_attach_volume)
        body = {
            'volumeAttachment': {
                'volumeId': FAKE_UUID_A,
                'device': '/dev/fake'
            }
        }
        req = fakes.HTTPRequest.blank('/v2/servers/id/os-volume_attachments')
        req.method = 'POST'
        req.body = jsonutils.dump_as_bytes({})
        req.headers['content-type'] = 'application/json'
        req.environ['nova.context'] = self.context
        result = self.attachments.create(req, FAKE_UUID, body=body)
        self.assertEqual('00000000-aaaa-aaaa-aaaa-000000000000',
                         result['volumeAttachment']['id'])

    @mock.patch.object(compute_api.API,
                       'attach_volume',
                       return_value='/dev/myfake')
    def test_attach_volume_with_auto_device(self, mock_attach):
        body = {'volumeAttachment': {'volumeId': FAKE_UUID_A, 'device': None}}
        req = fakes.HTTPRequest.blank('/v2/servers/id/os-volume_attachments')
        req.method = 'POST'
        req.body = jsonutils.dump_as_bytes({})
        req.headers['content-type'] = 'application/json'
        req.environ['nova.context'] = self.context
        result = self.attachments.create(req, FAKE_UUID, body=body)
        self.assertEqual('00000000-aaaa-aaaa-aaaa-000000000000',
                         result['volumeAttachment']['id'])
        self.assertEqual('/dev/myfake', result['volumeAttachment']['device'])

    def test_attach_volume_to_locked_server(self):
        def fake_attach_volume_to_locked_server(self,
                                                context,
                                                instance,
                                                volume_id,
                                                device=None):
            raise exception.InstanceIsLocked(instance_uuid=instance['uuid'])

        self.stubs.Set(compute_api.API, 'attach_volume',
                       fake_attach_volume_to_locked_server)
        body = {
            'volumeAttachment': {
                'volumeId': FAKE_UUID_A,
                'device': '/dev/fake'
            }
        }
        req = fakes.HTTPRequest.blank('/v2/servers/id/os-volume_attachments')
        req.method = 'POST'
        req.body = jsonutils.dump_as_bytes({})
        req.headers['content-type'] = 'application/json'
        req.environ['nova.context'] = self.context

        self.assertRaises(webob.exc.HTTPConflict,
                          self.attachments.create,
                          req,
                          FAKE_UUID,
                          body=body)

    def test_attach_volume_bad_id(self):
        self.stubs.Set(compute_api.API, 'attach_volume', fake_attach_volume)

        body = {
            'volumeAttachment': {
                'device': None,
                'volumeId': 'TESTVOLUME',
            }
        }

        req = fakes.HTTPRequest.blank('/v2/servers/id/os-volume_attachments')
        req.method = 'POST'
        req.body = jsonutils.dump_as_bytes({})
        req.headers['content-type'] = 'application/json'
        req.environ['nova.context'] = self.context

        self.assertRaises(self.validation_error,
                          self.attachments.create,
                          req,
                          FAKE_UUID,
                          body=body)

    def test_attach_volume_without_volumeId(self):
        self.stubs.Set(compute_api.API, 'attach_volume', fake_attach_volume)

        body = {'volumeAttachment': {'device': None}}

        req = fakes.HTTPRequest.blank('/v2/servers/id/os-volume_attachments')
        req.method = 'POST'
        req.body = jsonutils.dump_as_bytes({})
        req.headers['content-type'] = 'application/json'
        req.environ['nova.context'] = self.context

        self.assertRaises(self.validation_error,
                          self.attachments.create,
                          req,
                          FAKE_UUID,
                          body=body)

    def test_attach_volume_with_extra_arg(self):
        body = {
            'volumeAttachment': {
                'volumeId': FAKE_UUID_A,
                'device': '/dev/fake',
                'extra': 'extra_arg'
            }
        }

        req = fakes.HTTPRequest.blank('/v2/servers/id/os-volume_attachments')
        req.method = 'POST'
        req.body = jsonutils.dump_as_bytes({})
        req.headers['content-type'] = 'application/json'
        req.environ['nova.context'] = self.context

        self.assertRaises(self.validation_error,
                          self.attachments.create,
                          req,
                          FAKE_UUID,
                          body=body)

    def _test_swap(self,
                   attachments,
                   uuid=FAKE_UUID_A,
                   fake_func=None,
                   body=None):
        fake_func = fake_func or fake_swap_volume
        self.stubs.Set(compute_api.API, 'swap_volume', fake_func)
        body = body or {'volumeAttachment': {'volumeId': FAKE_UUID_B}}

        req = fakes.HTTPRequest.blank(
            '/v2/servers/id/os-volume_attachments/uuid')
        req.method = 'PUT'
        req.body = jsonutils.dump_as_bytes({})
        req.headers['content-type'] = 'application/json'
        req.environ['nova.context'] = self.context
        return attachments.update(req, FAKE_UUID, uuid, body=body)

    def test_swap_volume_for_locked_server(self):
        def fake_swap_volume_for_locked_server(self, context, instance,
                                               old_volume, new_volume):
            raise exception.InstanceIsLocked(instance_uuid=instance['uuid'])

        self.assertRaises(webob.exc.HTTPConflict,
                          self._test_swap,
                          self.attachments,
                          fake_func=fake_swap_volume_for_locked_server)

    def test_swap_volume(self):
        result = self._test_swap(self.attachments)
        # NOTE: on v2.1, http status code is set as wsgi_code of API
        # method instead of status_int in a response object.
        if isinstance(self.attachments,
                      volumes_v21.VolumeAttachmentController):
            status_int = self.attachments.update.wsgi_code
        else:
            status_int = result.status_int
        self.assertEqual(202, status_int)

    def test_swap_volume_no_attachment(self):
        self.assertRaises(exc.HTTPNotFound, self._test_swap, self.attachments,
                          FAKE_UUID_C)

    def test_swap_volume_without_volumeId(self):
        body = {'volumeAttachment': {'device': '/dev/fake'}}
        self.assertRaises(self.validation_error,
                          self._test_swap,
                          self.attachments,
                          body=body)

    def test_swap_volume_with_extra_arg(self):
        body = {
            'volumeAttachment': {
                'volumeId': FAKE_UUID_A,
                'device': '/dev/fake'
            }
        }

        self.assertRaises(self.validation_error,
                          self._test_swap,
                          self.attachments,
                          body=body)
Пример #22
0
 def get_info(self, instance, use_cache=True):
     if instance.uuid not in self.instances:
         raise exception.InstanceNotFound(instance_id=instance.uuid)
     i = self.instances[instance.uuid]
     return hardware.InstanceInfo(state=i.state)
Пример #23
0
 def fake_get(self, context, id, expected_attrs=None):
     raise exception.InstanceNotFound(instance_id=id)
Пример #24
0
def return_server_not_found(*arg, **kwarg):
    raise exception.InstanceNotFound(instance_id='42')
 def fake_compute_get(*args, **kwargs):
     raise exception.InstanceNotFound(instance_id='fake')
Пример #26
0
 def server_not_found(self, instance_id,
                      columns_to_join=None, use_slave=False):
     raise exception.InstanceNotFound(instance_id=instance_id)
Пример #27
0
def fake_get_not_found(self, context, instance_uuid, **kwargs):
    raise exception.InstanceNotFound(instance_id=instance_uuid)
class InterfaceAttachTestsV21(test.NoDBTestCase):
    controller_cls = attach_interfaces_v21.InterfaceAttachmentController
    validate_exc = exception.ValidationError
    in_use_exc = exc.HTTPConflict
    not_found_exc = exc.HTTPNotFound
    not_usable_exc = exc.HTTPBadRequest

    def setUp(self):
        super(InterfaceAttachTestsV21, self).setUp()
        self.flags(timeout=30, group='neutron')
        self.stub_out('nova.compute.api.API.get', fake_get_instance)
        self.expected_show = {
            'interfaceAttachment': {
                'net_id': FAKE_NET_ID1,
                'port_id': FAKE_PORT_ID1,
                'mac_addr': port_data1['mac_address'],
                'port_state': port_data1['status'],
                'fixed_ips': port_data1['fixed_ips'],
            }
        }
        self.attachments = self.controller_cls()
        show_port_patch = mock.patch.object(self.attachments.network_api,
                                            'show_port', fake_show_port)
        show_port_patch.start()
        self.addCleanup(show_port_patch.stop)
        self.req = fakes.HTTPRequest.blank('')

    @mock.patch.object(compute_api.API,
                       'get',
                       side_effect=exception.InstanceNotFound(instance_id=''))
    def _test_instance_not_found(self, func, args, mock_get, kwargs=None):
        if not kwargs:
            kwargs = {}
        self.assertRaises(exc.HTTPNotFound, func, self.req, *args, **kwargs)

    def test_show_instance_not_found(self):
        self._test_instance_not_found(self.attachments.show, ('fake', 'fake'))

    def test_index_instance_not_found(self):
        self._test_instance_not_found(self.attachments.index, ('fake', ))

    def test_detach_interface_instance_not_found(self):
        self._test_instance_not_found(self.attachments.delete,
                                      ('fake', 'fake'))

    def test_attach_interface_instance_not_found(self):
        self._test_instance_not_found(
            self.attachments.create, ('fake', ),
            kwargs={'body': {
                'interfaceAttachment': {}
            }})

    def test_show(self):
        result = self.attachments.show(self.req, FAKE_UUID1, FAKE_PORT_ID1)
        self.assertEqual(self.expected_show, result)

    def test_show_with_port_not_found(self):
        self.assertRaises(exc.HTTPNotFound, self.attachments.show, self.req,
                          FAKE_UUID2, FAKE_PORT_ID1)

    def test_show_forbidden(self):
        with mock.patch.object(self.attachments.network_api,
                               'show_port',
                               side_effect=exception.Forbidden):
            self.assertRaises(exc.HTTPForbidden, self.attachments.show,
                              self.req, FAKE_UUID1, FAKE_PORT_ID1)

    def test_delete(self):
        self.stub_out('nova.compute.api.API.detach_interface',
                      fake_detach_interface)

        inst = objects.Instance(uuid=FAKE_UUID1)
        with mock.patch.object(common, 'get_instance',
                               return_value=inst) as mock_get_instance:
            result = self.attachments.delete(self.req, FAKE_UUID1,
                                             FAKE_PORT_ID1)
            # NOTE: on v2.1, http status code is set as wsgi_code of API
            # method instead of status_int in a response object.
            if isinstance(self.attachments,
                          attach_interfaces_v21.InterfaceAttachmentController):
                status_int = self.attachments.delete.wsgi_code
            else:
                status_int = result.status_int
            self.assertEqual(202, status_int)
            ctxt = self.req.environ['nova.context']
            mock_get_instance.assert_called_with(
                self.attachments.compute_api,
                ctxt,
                FAKE_UUID1,
                expected_attrs=['device_metadata'])

    def test_detach_interface_instance_locked(self):
        def fake_detach_interface_from_locked_server(self, context, instance,
                                                     port_id):
            raise exception.InstanceIsLocked(instance_uuid=FAKE_UUID1)

        self.stub_out('nova.compute.api.API.detach_interface',
                      fake_detach_interface_from_locked_server)

        self.assertRaises(exc.HTTPConflict, self.attachments.delete, self.req,
                          FAKE_UUID1, FAKE_PORT_ID1)

    def test_delete_interface_not_found(self):
        self.stub_out('nova.compute.api.API.detach_interface',
                      fake_detach_interface)

        self.assertRaises(exc.HTTPNotFound, self.attachments.delete, self.req,
                          FAKE_UUID1, 'invalid-port-id')

    def test_attach_interface_instance_locked(self):
        def fake_attach_interface_to_locked_server(self,
                                                   context,
                                                   instance,
                                                   network_id,
                                                   port_id,
                                                   requested_ip,
                                                   tag=None):
            raise exception.InstanceIsLocked(instance_uuid=FAKE_UUID1)

        self.stub_out('nova.compute.api.API.attach_interface',
                      fake_attach_interface_to_locked_server)
        body = {}
        self.assertRaises(exc.HTTPConflict,
                          self.attachments.create,
                          self.req,
                          FAKE_UUID1,
                          body=body)

    def test_attach_interface_without_network_id(self):
        self.stub_out('nova.compute.api.API.attach_interface',
                      fake_attach_interface)
        body = {}
        result = self.attachments.create(self.req, FAKE_UUID1, body=body)
        self.assertEqual(result['interfaceAttachment']['net_id'], FAKE_NET_ID1)

    @mock.patch.object(
        compute_api.API,
        'attach_interface',
        side_effect=exception.NetworkInterfaceTaggedAttachNotSupported())
    def test_interface_tagged_attach_not_supported(self, mock_attach):
        body = {'interfaceAttachment': {'net_id': FAKE_NET_ID2}}
        self.assertRaises(exc.HTTPBadRequest,
                          self.attachments.create,
                          self.req,
                          FAKE_UUID1,
                          body=body)

    def test_attach_interface_with_network_id(self):
        self.stub_out('nova.compute.api.API.attach_interface',
                      fake_attach_interface)
        body = {'interfaceAttachment': {'net_id': FAKE_NET_ID2}}
        result = self.attachments.create(self.req, FAKE_UUID1, body=body)
        self.assertEqual(result['interfaceAttachment']['net_id'], FAKE_NET_ID2)

    def _attach_interface_bad_request_case(self, body):
        self.stub_out('nova.compute.api.API.attach_interface',
                      fake_attach_interface)
        self.assertRaises(exc.HTTPBadRequest,
                          self.attachments.create,
                          self.req,
                          FAKE_UUID1,
                          body=body)

    def _attach_interface_not_found_case(self, body):
        self.stub_out('nova.compute.api.API.attach_interface',
                      fake_attach_interface)
        self.assertRaises(self.not_found_exc,
                          self.attachments.create,
                          self.req,
                          FAKE_UUID1,
                          body=body)

    def test_attach_interface_with_port_and_network_id(self):
        body = {
            'interfaceAttachment': {
                'port_id': FAKE_PORT_ID1,
                'net_id': FAKE_NET_ID2
            }
        }
        self._attach_interface_bad_request_case(body)

    def test_attach_interface_with_not_found_network_id(self):
        body = {'interfaceAttachment': {'net_id': FAKE_BAD_NET_ID}}
        self._attach_interface_not_found_case(body)

    def test_attach_interface_with_not_found_port_id(self):
        body = {'interfaceAttachment': {'port_id': FAKE_NOT_FOUND_PORT_ID}}
        self._attach_interface_not_found_case(body)

    def test_attach_interface_with_invalid_state(self):
        def fake_attach_interface_invalid_state(*args, **kwargs):
            raise exception.InstanceInvalidState(instance_uuid='',
                                                 attr='',
                                                 state='',
                                                 method='attach_interface')

        self.stub_out('nova.compute.api.API.attach_interface',
                      fake_attach_interface_invalid_state)
        body = {'interfaceAttachment': {'net_id': FAKE_NET_ID1}}
        self.assertRaises(exc.HTTPConflict,
                          self.attachments.create,
                          self.req,
                          FAKE_UUID1,
                          body=body)

    def test_detach_interface_with_invalid_state(self):
        def fake_detach_interface_invalid_state(*args, **kwargs):
            raise exception.InstanceInvalidState(instance_uuid='',
                                                 attr='',
                                                 state='',
                                                 method='detach_interface')

        self.stub_out('nova.compute.api.API.detach_interface',
                      fake_detach_interface_invalid_state)
        self.assertRaises(exc.HTTPConflict, self.attachments.delete, self.req,
                          FAKE_UUID1, FAKE_NET_ID1)

    @mock.patch.object(compute_api.API,
                       'detach_interface',
                       side_effect=NotImplementedError())
    def test_detach_interface_with_not_implemented(self, _mock):
        self.assertRaises(exc.HTTPNotImplemented, self.attachments.delete,
                          self.req, FAKE_UUID1, FAKE_NET_ID1)

    def test_attach_interface_invalid_fixed_ip(self):
        body = {
            'interfaceAttachment': {
                'net_id': FAKE_NET_ID1,
                'fixed_ips': [{
                    'ip_address': 'invalid_ip'
                }]
            }
        }
        self.assertRaises(self.validate_exc,
                          self.attachments.create,
                          self.req,
                          FAKE_UUID1,
                          body=body)

    @mock.patch.object(compute_api.API, 'get')
    @mock.patch.object(compute_api.API, 'attach_interface')
    def test_attach_interface_fixed_ip_already_in_use(self, attach_mock,
                                                      get_mock):
        fake_instance = objects.Instance(uuid=FAKE_UUID1)
        get_mock.return_value = fake_instance
        attach_mock.side_effect = exception.FixedIpAlreadyInUse(
            address='10.0.2.2', instance_uuid=FAKE_UUID1)
        body = {}
        self.assertRaises(self.in_use_exc,
                          self.attachments.create,
                          self.req,
                          FAKE_UUID1,
                          body=body)
        ctxt = self.req.environ['nova.context']
        attach_mock.assert_called_once_with(ctxt,
                                            fake_instance,
                                            None,
                                            None,
                                            None,
                                            tag=None)
        get_mock.assert_called_once_with(ctxt,
                                         FAKE_UUID1,
                                         expected_attrs=None,
                                         cell_down_support=False)

    @mock.patch.object(compute_api.API, 'get')
    @mock.patch.object(compute_api.API, 'attach_interface')
    def test_attach_interface_port_in_use(self, attach_mock, get_mock):
        fake_instance = objects.Instance(uuid=FAKE_UUID1)
        get_mock.return_value = fake_instance
        attach_mock.side_effect = exception.PortInUse(port_id=FAKE_PORT_ID1)
        body = {}
        self.assertRaises(self.in_use_exc,
                          self.attachments.create,
                          self.req,
                          FAKE_UUID1,
                          body=body)
        ctxt = self.req.environ['nova.context']
        attach_mock.assert_called_once_with(ctxt,
                                            fake_instance,
                                            None,
                                            None,
                                            None,
                                            tag=None)
        get_mock.assert_called_once_with(ctxt,
                                         FAKE_UUID1,
                                         expected_attrs=None,
                                         cell_down_support=False)

    @mock.patch.object(compute_api.API, 'get')
    @mock.patch.object(compute_api.API, 'attach_interface')
    def test_attach_interface_port_not_usable(self, attach_mock, get_mock):
        fake_instance = objects.Instance(uuid=FAKE_UUID1)
        get_mock.return_value = fake_instance
        attach_mock.side_effect = exception.PortNotUsable(
            port_id=FAKE_PORT_ID1, instance=fake_instance.uuid)
        body = {}
        self.assertRaises(self.not_usable_exc,
                          self.attachments.create,
                          self.req,
                          FAKE_UUID1,
                          body=body)
        ctxt = self.req.environ['nova.context']
        attach_mock.assert_called_once_with(ctxt,
                                            fake_instance,
                                            None,
                                            None,
                                            None,
                                            tag=None)
        get_mock.assert_called_once_with(ctxt,
                                         FAKE_UUID1,
                                         expected_attrs=None,
                                         cell_down_support=False)

    @mock.patch.object(compute_api.API, 'get')
    @mock.patch.object(compute_api.API, 'attach_interface')
    def test_attach_interface_failed_no_network(self, attach_mock, get_mock):
        fake_instance = objects.Instance(uuid=FAKE_UUID1,
                                         project_id=FAKE_UUID2)
        get_mock.return_value = fake_instance
        attach_mock.side_effect = (exception.InterfaceAttachFailedNoNetwork(
            project_id=FAKE_UUID2))
        self.assertRaises(exc.HTTPBadRequest,
                          self.attachments.create,
                          self.req,
                          FAKE_UUID1,
                          body={})
        ctxt = self.req.environ['nova.context']
        attach_mock.assert_called_once_with(ctxt,
                                            fake_instance,
                                            None,
                                            None,
                                            None,
                                            tag=None)
        get_mock.assert_called_once_with(ctxt,
                                         FAKE_UUID1,
                                         expected_attrs=None,
                                         cell_down_support=False)

    @mock.patch.object(compute_api.API, 'get')
    @mock.patch.object(compute_api.API, 'attach_interface')
    def test_attach_interface_no_more_fixed_ips(self, attach_mock, get_mock):
        fake_instance = objects.Instance(uuid=FAKE_UUID1)
        get_mock.return_value = fake_instance
        attach_mock.side_effect = exception.NoMoreFixedIps(net=FAKE_NET_ID1)
        body = {}
        self.assertRaises(exc.HTTPBadRequest,
                          self.attachments.create,
                          self.req,
                          FAKE_UUID1,
                          body=body)
        ctxt = self.req.environ['nova.context']
        attach_mock.assert_called_once_with(ctxt,
                                            fake_instance,
                                            None,
                                            None,
                                            None,
                                            tag=None)
        get_mock.assert_called_once_with(ctxt,
                                         FAKE_UUID1,
                                         expected_attrs=None,
                                         cell_down_support=False)

    @mock.patch.object(compute_api.API, 'get')
    @mock.patch.object(compute_api.API, 'attach_interface')
    def test_attach_interface_failed_securitygroup_cannot_be_applied(
            self, attach_mock, get_mock):
        fake_instance = objects.Instance(uuid=FAKE_UUID1,
                                         project_id=FAKE_UUID2)
        get_mock.return_value = fake_instance
        attach_mock.side_effect = (exception.SecurityGroupCannotBeApplied())
        self.assertRaises(exc.HTTPBadRequest,
                          self.attachments.create,
                          self.req,
                          FAKE_UUID1,
                          body={})
        ctxt = self.req.environ['nova.context']
        attach_mock.assert_called_once_with(ctxt,
                                            fake_instance,
                                            None,
                                            None,
                                            None,
                                            tag=None)
        get_mock.assert_called_once_with(ctxt,
                                         FAKE_UUID1,
                                         expected_attrs=None,
                                         cell_down_support=False)

    def _test_attach_interface_with_invalid_parameter(self, param):
        self.stub_out('nova.compute.api.API.attach_interface',
                      fake_attach_interface)
        body = {'interface_attachment': param}
        self.assertRaises(exception.ValidationError,
                          self.attachments.create,
                          self.req,
                          FAKE_UUID1,
                          body=body)

    def test_attach_interface_instance_with_non_uuid_net_id(self):
        param = {'net_id': 'non_uuid'}
        self._test_attach_interface_with_invalid_parameter(param)

    def test_attach_interface_instance_with_non_uuid_port_id(self):
        param = {'port_id': 'non_uuid'}
        self._test_attach_interface_with_invalid_parameter(param)

    def test_attach_interface_instance_with_non_array_fixed_ips(self):
        param = {'fixed_ips': 'non_array'}
        self._test_attach_interface_with_invalid_parameter(param)
Пример #29
0
def fake_get_vnc_console_not_found(self, _context, instance, _console_type):
    raise exception.InstanceNotFound(instance_id=instance["uuid"])
Пример #30
0
 def fake_delete_console(cons_self, context, instance_id, console_id):
     raise exception.InstanceNotFound(instance_id=instance_id)