def test_add_visible_admin_metadata_no_existing_metadata(self):
        admin_metadata = [{
            "key": "invisible_key",
            "value": "invisible_value"
        }, {
            "key": "readonly",
            "value": "visible"
        }, {
            "key": "attached_mode",
            "value": "visible"
        }]
        volume = {'volume_admin_metadata': admin_metadata}
        utils.add_visible_admin_metadata(volume)
        self.assertEqual({
            'attached_mode': 'visible',
            'readonly': 'visible'
        }, volume['metadata'])

        admin_metadata = {
            "invisible_key": "invisible_value",
            "readonly": "visible",
            "attached_mode": "visible"
        }
        volume = {'admin_metadata': admin_metadata}
        utils.add_visible_admin_metadata(volume)
        self.assertEqual({
            'attached_mode': 'visible',
            'readonly': 'visible'
        }, volume['metadata'])
Esempio n. 2
0
    def _items(self, req, entity_maker):
        """Returns a list of volumes, transformed through entity_maker."""

        # pop out limit and offset , they are not search_opts
        search_opts = req.GET.copy()
        search_opts.pop('limit', None)
        search_opts.pop('offset', None)

        for k, v in search_opts.items():
            try:
                search_opts[k] = ast.literal_eval(v)
            except (ValueError, SyntaxError):
                LOG.debug('Could not evaluate value %s, assuming string', v)

        context = req.environ['cinder.context']
        utils.remove_invalid_filter_options(context,
                                            search_opts,
                                            self._get_volume_search_options())

        volumes = self.volume_api.get_all(context, marker=None, limit=None,
                                          sort_keys=['created_at'],
                                          sort_dirs=['desc'],
                                          filters=search_opts,
                                          viewable_admin_meta=True)

        for volume in volumes:
            utils.add_visible_admin_metadata(volume)

        limited_list = common.limited(volumes.objects, req)
        req.cache_db_volumes(limited_list)

        res = [entity_maker(context, vol) for vol in limited_list]
        return {'volumes': res}
Esempio n. 3
0
    def update(self, req, id, body):
        """Update a volume."""
        context = req.environ['cinder.context']
        update_dict = body['volume']

        self.validate_name_and_description(update_dict, check_length=False)

        # NOTE(thingee): v2 API allows name instead of display_name
        if 'name' in update_dict:
            update_dict['display_name'] = update_dict.pop('name')

        # NOTE(thingee): v2 API allows description instead of
        #                display_description
        if 'description' in update_dict:
            update_dict['display_description'] = update_dict.pop('description')

        # Not found and Invalid exceptions will be handled at the wsgi level
        try:
            volume = self.volume_api.get(context, id, viewable_admin_meta=True)
            volume_utils.notify_about_volume_usage(context, volume,
                                                   'update.start')
            self.volume_api.update(context, volume, update_dict)
        except exception.InvalidVolumeMetadataSize as error:
            raise webob.exc.HTTPRequestEntityTooLarge(explanation=error.msg)

        volume.update(update_dict)

        utils.add_visible_admin_metadata(volume)

        volume_utils.notify_about_volume_usage(context, volume,
                                               'update.end')

        return self._view_builder.detail(req, volume)
    def test_add_visible_admin_metadata_no_visible_keys(self):
        admin_metadata = [{
            "key": "invisible_key1",
            "value": "invisible_value1"
        }, {
            "key": "invisible_key2",
            "value": "invisible_value2"
        }, {
            "key": "invisible_key3",
            "value": "invisible_value3"
        }]
        metadata = [{"key": "key", "value": "value"}]
        volume = {
            'volume_admin_metadata': admin_metadata,
            'volume_metadata': metadata
        }
        utils.add_visible_admin_metadata(volume)
        self.assertEqual([{
            "key": "key",
            "value": "value"
        }], volume['volume_metadata'])

        admin_metadata = {
            "invisible_key1": "invisible_value1",
            "invisible_key2": "invisible_value2",
            "invisible_key3": "invisible_value3"
        }
        metadata = {"key": "value"}
        volume = {'admin_metadata': admin_metadata, 'metadata': metadata}
        utils.add_visible_admin_metadata(volume)
        self.assertEqual({'key': 'value'}, volume['metadata'])
Esempio n. 5
0
    def test_add_visible_admin_metadata_visible_key_only(self):
        admin_metadata = [{"key": "invisible_key", "value": "invisible_value"},
                          {"key": "readonly", "value": "visible"},
                          {"key": "attached_mode", "value": "visible"}]
        metadata = [{"key": "key", "value": "value"},
                    {"key": "readonly", "value": "existing"}]
        volume = {'volume_admin_metadata': admin_metadata,
                  'volume_metadata': metadata}
        utils.add_visible_admin_metadata(volume)
        self.assertEqual([{"key": "key", "value": "value"},
                          {"key": "readonly", "value": "visible"},
                          {"key": "attached_mode", "value": "visible"}],
                         volume['volume_metadata'])

        admin_metadata = {"invisible_key": "invisible_value",
                          "readonly": "visible",
                          "attached_mode": "visible"}
        metadata = {"key": "value", "readonly": "existing"}
        volume = {'admin_metadata': admin_metadata,
                  'metadata': metadata}
        utils.add_visible_admin_metadata(volume)
        self.assertEqual({'key': 'value',
                          'attached_mode': 'visible',
                          'readonly': 'visible'},
                         volume['metadata'])
Esempio n. 6
0
    def update(self, req, id, body):
        """Update a volume."""
        context = req.environ['cinder.context']
        update_dict = body['volume']

        self.validate_name_and_description(update_dict, check_length=False)

        # NOTE(thingee): v2 API allows name instead of display_name
        if 'name' in update_dict:
            update_dict['display_name'] = update_dict.pop('name')

        # NOTE(thingee): v2 API allows description instead of
        #                display_description
        if 'description' in update_dict:
            update_dict['display_description'] = update_dict.pop('description')

        # Not found and Invalid exceptions will be handled at the wsgi level
        try:
            volume = self.volume_api.get(context, id, viewable_admin_meta=True)
            volume_utils.notify_about_volume_usage(context, volume,
                                                   'update.start')
            self.volume_api.update(context, volume, update_dict)
        except exception.InvalidVolumeMetadataSize as error:
            raise webob.exc.HTTPRequestEntityTooLarge(explanation=error.msg)

        volume.update(update_dict)

        utils.add_visible_admin_metadata(volume)

        volume_utils.notify_about_volume_usage(context, volume, 'update.end')

        return self._view_builder.detail(req, volume)
Esempio n. 7
0
    def update(self, req, id, body):
        """Update a volume."""
        context = req.environ['cinder.context']

        if not body:
            raise exc.HTTPUnprocessableEntity()

        if 'volume' not in body:
            raise exc.HTTPUnprocessableEntity()

        volume = body['volume']
        update_dict = {}

        valid_update_keys = (
            'display_name',
            'display_description',
            'metadata',
        )

        for key in valid_update_keys:
            if key in volume:
                update_dict[key] = volume[key]

        # Not found exception will be handled at the wsgi level
        volume = self.volume_api.get(context, id, viewable_admin_meta=True)
        volume_utils.notify_about_volume_usage(context, volume, 'update.start')
        self.volume_api.update(context, volume, update_dict)

        volume.update(update_dict)

        utils.add_visible_admin_metadata(volume)

        volume_utils.notify_about_volume_usage(context, volume, 'update.end')

        return {'volume': _translate_volume_detail_view(context, volume)}
Esempio n. 8
0
    def _items(self, req, entity_maker):
        """Returns a list of volumes, transformed through entity_maker."""

        #pop out limit and offset , they are not search_opts
        search_opts = req.GET.copy()
        search_opts.pop('limit', None)
        search_opts.pop('offset', None)

        if 'metadata' in search_opts:
            search_opts['metadata'] = ast.literal_eval(search_opts['metadata'])

        context = req.environ['cinder.context']
        utils.remove_invalid_filter_options(context, search_opts,
                                            self._get_volume_search_options())

        volumes = self.volume_api.get_all(context,
                                          marker=None,
                                          limit=None,
                                          sort_key='created_at',
                                          sort_dir='desc',
                                          filters=search_opts,
                                          viewable_admin_meta=True)

        volumes = [dict(vol.iteritems()) for vol in volumes]

        for volume in volumes:
            utils.add_visible_admin_metadata(volume)

        limited_list = common.limited(volumes, req)
        req.cache_resource(limited_list)
        res = [entity_maker(context, vol) for vol in limited_list]
        return {'volumes': res}
Esempio n. 9
0
    def update(self, req, id, body):
        """Update a volume."""
        context = req.environ["cinder.context"]

        if not body:
            raise exc.HTTPUnprocessableEntity()

        if "volume" not in body:
            raise exc.HTTPUnprocessableEntity()

        volume = body["volume"]
        update_dict = {}

        valid_update_keys = ("display_name", "display_description", "metadata")

        for key in valid_update_keys:
            if key in volume:
                update_dict[key] = volume[key]

        try:
            volume = self.volume_api.get(context, id, viewable_admin_meta=True)
            volume_utils.notify_about_volume_usage(context, volume, "update.start")
            self.volume_api.update(context, volume, update_dict)
        except exception.NotFound:
            raise exc.HTTPNotFound()

        volume.update(update_dict)

        utils.add_visible_admin_metadata(volume)

        volume_utils.notify_about_volume_usage(context, volume, "update.end")

        return {"volume": _translate_volume_detail_view(context, volume)}
Esempio n. 10
0
    def _items(self, req, entity_maker):
        """Returns a list of volumes, transformed through entity_maker."""

        #pop out limit and offset , they are not search_opts
        search_opts = req.GET.copy()
        search_opts.pop('limit', None)
        search_opts.pop('offset', None)

        if 'metadata' in search_opts:
            search_opts['metadata'] = ast.literal_eval(search_opts['metadata'])

        context = req.environ['cinder.context']
        utils.remove_invalid_filter_options(context,
                                            search_opts,
                                            self._get_volume_search_options())

        volumes = self.volume_api.get_all(context, marker=None, limit=None,
                                          sort_key='created_at',
                                          sort_dir='desc', filters=search_opts,
                                          viewable_admin_meta=True)

        volumes = [dict(vol.iteritems()) for vol in volumes]

        for volume in volumes:
            utils.add_visible_admin_metadata(volume)

        limited_list = common.limited(volumes, req)
        req.cache_resource(limited_list)
        res = [entity_maker(context, vol) for vol in limited_list]
        return {'volumes': res}
Esempio n. 11
0
    def _items(self, req, entity_maker):
        """Returns a list of volumes, transformed through entity_maker."""

        # pop out limit and offset , they are not search_opts
        search_opts = req.GET.copy()
        search_opts.pop('limit', None)
        search_opts.pop('offset', None)

        for k, v in search_opts.items():
            try:
                search_opts[k] = ast.literal_eval(v)
            except (ValueError, SyntaxError):
                LOG.debug('Could not evaluate value %s, assuming string', v)

        context = req.environ['cinder.context']
        utils.remove_invalid_filter_options(context, search_opts,
                                            self._get_volume_search_options())

        volumes = self.volume_api.get_all(context,
                                          marker=None,
                                          limit=None,
                                          sort_keys=['created_at'],
                                          sort_dirs=['desc'],
                                          filters=search_opts,
                                          viewable_admin_meta=True)

        for volume in volumes:
            utils.add_visible_admin_metadata(volume)

        limited_list = common.limited(volumes.objects, req)
        req.cache_db_volumes(limited_list)

        res = [entity_maker(context, vol) for vol in limited_list]
        return {'volumes': res}
Esempio n. 12
0
    def update(self, req, id, body):
        """Update a volume."""
        context = req.environ['cinder.context']

        if not body:
            msg = _("Missing request body")
            raise exc.HTTPBadRequest(explanation=msg)

        if 'volume' not in body:
            msg = _("Missing required element '%s' in request body") % 'volume'
            raise exc.HTTPBadRequest(explanation=msg)

        volume = body['volume']
        update_dict = {}

        valid_update_keys = (
            'name',
            'description',
            'display_name',
            'display_description',
            'metadata',
        )

        for key in valid_update_keys:
            if key in volume:
                update_dict[key] = volume[key]

        self.validate_name_and_description(update_dict)

        # NOTE(thingee): v2 API allows name instead of display_name
        if 'name' in update_dict:
            update_dict['display_name'] = update_dict.pop('name')

        # NOTE(thingee): v2 API allows description instead of
        #                display_description
        if 'description' in update_dict:
            update_dict['display_description'] = update_dict.pop('description')

        try:
            volume = self.volume_api.get(context, id, viewable_admin_meta=True)
            volume_utils.notify_about_volume_usage(context, volume,
                                                   'update.start')
            self.volume_api.update(context, volume, update_dict)
        except exception.VolumeNotFound as error:
            raise exc.HTTPNotFound(explanation=error.msg)
        except exception.InvalidVolumeMetadata as error:
            raise webob.exc.HTTPBadRequest(explanation=error.msg)
        except exception.InvalidVolumeMetadataSize as error:
            raise webob.exc.HTTPRequestEntityTooLarge(explanation=error.msg)

        volume.update(update_dict)

        utils.add_visible_admin_metadata(volume)

        volume_utils.notify_about_volume_usage(context, volume,
                                               'update.end')

        return self._view_builder.detail(req, volume)
Esempio n. 13
0
    def update(self, req, id, body):
        """Update a volume."""
        context = req.environ['cinder.context']

        if not body:
            msg = _("Missing request body")
            raise exc.HTTPBadRequest(explanation=msg)

        if 'volume' not in body:
            msg = _("Missing required element '%s' in request body") % 'volume'
            raise exc.HTTPBadRequest(explanation=msg)

        volume = body['volume']
        update_dict = {}

        valid_update_keys = (
            'name',
            'description',
            'display_name',
            'display_description',
            'metadata',
        )

        for key in valid_update_keys:
            if key in volume:
                update_dict[key] = volume[key]

        self.validate_name_and_description(update_dict)

        # NOTE(thingee): v2 API allows name instead of display_name
        if 'name' in update_dict:
            update_dict['display_name'] = update_dict.pop('name')

        # NOTE(thingee): v2 API allows description instead of
        #                display_description
        if 'description' in update_dict:
            update_dict['display_description'] = update_dict.pop('description')

        # Not found and Invalid exceptions will be handled at the wsgi level
        try:
            volume = self.volume_api.get(context, id, viewable_admin_meta=True)
            volume_utils.notify_about_volume_usage(context, volume,
                                                   'update.start')
            self.volume_api.update(context, volume, update_dict)
        except exception.InvalidVolumeMetadataSize as error:
            raise webob.exc.HTTPRequestEntityTooLarge(explanation=error.msg)

        volume.update(update_dict)

        utils.add_visible_admin_metadata(volume)

        volume_utils.notify_about_volume_usage(context, volume,
                                               'update.end')

        return self._view_builder.detail(req, volume)
Esempio n. 14
0
    def _get_volumes(self, req, is_detail):
        """Returns a list of volumes, transformed through view builder."""

        context = req.environ['cinder.context']
        req_version = req.api_version_request

        params = req.params.copy()
        marker, limit, offset = common.get_pagination_params(params)
        sort_keys, sort_dirs = common.get_sort_params(params)
        filters = params

        show_count = False
        if req_version.matches(
                mv.SUPPORT_COUNT_INFO) and 'with_count' in filters:
            show_count = utils.get_bool_param('with_count', filters)
            filters.pop('with_count')

        self._process_volume_filtering(context=context,
                                       filters=filters,
                                       req_version=req_version)

        # NOTE(thingee): v2 API allows name instead of display_name
        if 'name' in sort_keys:
            sort_keys[sort_keys.index('name')] = 'display_name'

        if 'name' in filters:
            filters['display_name'] = filters.pop('name')

        strict = req.api_version_request.matches(mv.VOLUME_LIST_BOOTABLE, None)
        self.volume_api.check_volume_filters(filters, strict)

        volumes = self.volume_api.get_all(context,
                                          marker,
                                          limit,
                                          sort_keys=sort_keys,
                                          sort_dirs=sort_dirs,
                                          filters=filters.copy(),
                                          viewable_admin_meta=True,
                                          offset=offset)
        total_count = None
        if show_count:
            total_count = self.volume_api.calculate_resource_count(
                context, 'volume', filters)

        for volume in volumes:
            utils.add_visible_admin_metadata(volume)

        req.cache_db_volumes(volumes.objects)

        if is_detail:
            volumes = self._view_builder.detail_list(req, volumes, total_count)
        else:
            volumes = self._view_builder.summary_list(req, volumes,
                                                      total_count)
        return volumes
Esempio n. 15
0
    def update(self, req, id, body):
        """Update a volume."""
        context = req.environ['cinder.context']

        if not body:
            msg = _("Missing request body")
            raise exc.HTTPBadRequest(explanation=msg)

        if 'volume' not in body:
            msg = _("Missing required element '%s' in request body") % 'volume'
            raise exc.HTTPBadRequest(explanation=msg)

        volume = body['volume']
        update_dict = {}

        valid_update_keys = (
            'name',
            'description',
            'display_name',
            'display_description',
            'metadata',
        )

        for key in valid_update_keys:
            if key in volume:
                update_dict[key] = volume[key]

        # NOTE(thingee): v2 API allows name instead of display_name
        if 'name' in update_dict:
            update_dict['display_name'] = update_dict['name']
            del update_dict['name']

        # NOTE(thingee): v2 API allows name instead of display_name
        if 'description' in update_dict:
            update_dict['display_description'] = update_dict['description']
            del update_dict['description']

        try:
            volume = self.volume_api.get(context, id)
            volume_utils.notify_about_volume_usage(context, volume,
                                                   'update.start')
            self.volume_api.update(context, volume, update_dict)
        except exception.NotFound:
            msg = _("Volume could not be found")
            raise exc.HTTPNotFound(explanation=msg)

        volume.update(update_dict)

        utils.add_visible_admin_metadata(context, volume, self.volume_api)

        volume_utils.notify_about_volume_usage(context, volume,
                                               'update.end')

        return self._view_builder.detail(req, volume)
Esempio n. 16
0
    def show(self, req, id):
        """Return data about the given volume."""
        context = req.environ['cinder.context']

        # Not found exception will be handled at the wsgi level
        vol = self.volume_api.get(context, id, viewable_admin_meta=True)
        req.cache_db_volume(vol)

        utils.add_visible_admin_metadata(vol)

        return self._view_builder.detail(req, vol)
Esempio n. 17
0
    def show(self, req, id):
        """Return data about the given volume."""
        context = req.environ['cinder.context']

        # Not found exception will be handled at the wsgi level
        vol = self.volume_api.get(context, id, viewable_admin_meta=True)
        req.cache_db_volume(vol)

        utils.add_visible_admin_metadata(vol)

        return self._view_builder.detail(req, vol)
Esempio n. 18
0
    def _get_volumes(self, req, is_detail):
        """Returns a list of volumes, transformed through view builder."""

        context = req.environ['cinder.context']
        req_version = req.api_version_request

        params = req.params.copy()
        marker, limit, offset = common.get_pagination_params(params)
        sort_keys, sort_dirs = common.get_sort_params(params)
        filters = params

        show_count = False
        if req_version.matches(
                mv.SUPPORT_COUNT_INFO) and 'with_count' in filters:
            show_count = utils.get_bool_param('with_count', filters)
            filters.pop('with_count')

        self._process_volume_filtering(context=context, filters=filters,
                                       req_version=req_version)

        # NOTE(thingee): v2 API allows name instead of display_name
        if 'name' in sort_keys:
            sort_keys[sort_keys.index('name')] = 'display_name'

        if 'name' in filters:
            filters['display_name'] = filters.pop('name')

        strict = req.api_version_request.matches(
            mv.VOLUME_LIST_BOOTABLE, None)
        self.volume_api.check_volume_filters(filters, strict)

        volumes = self.volume_api.get_all(context, marker, limit,
                                          sort_keys=sort_keys,
                                          sort_dirs=sort_dirs,
                                          filters=filters.copy(),
                                          viewable_admin_meta=True,
                                          offset=offset)
        total_count = None
        if show_count:
            total_count = self.volume_api.calculate_resource_count(
                context, 'volume', filters)

        for volume in volumes:
            utils.add_visible_admin_metadata(volume)

        req.cache_db_volumes(volumes.objects)

        if is_detail:
            volumes = self._view_builder.detail_list(
                req, volumes, total_count)
        else:
            volumes = self._view_builder.summary_list(
                req, volumes, total_count)
        return volumes
Esempio n. 19
0
    def update(self, req, id, body):
        """Update a volume."""
        context = req.environ['cinder.context']

        if not body:
            msg = _("Missing request body")
            raise exc.HTTPBadRequest(explanation=msg)

        if 'volume' not in body:
            msg = _("Missing required element '%s' in request body") % 'volume'
            raise exc.HTTPBadRequest(explanation=msg)

        volume = body['volume']
        update_dict = {}

        valid_update_keys = (
            'name',
            'description',
            'display_name',
            'display_description',
            'metadata',
        )

        for key in valid_update_keys:
            if key in volume:
                update_dict[key] = volume[key]

        # NOTE(thingee): v2 API allows name instead of display_name
        if 'name' in update_dict:
            update_dict['display_name'] = update_dict['name']
            del update_dict['name']

        # NOTE(thingee): v2 API allows name instead of display_name
        if 'description' in update_dict:
            update_dict['display_description'] = update_dict['description']
            del update_dict['description']

        try:
            volume = self.volume_api.get(context, id, viewable_admin_meta=True)
            volume_utils.notify_about_volume_usage(context, volume,
                                                   'update.start')
            self.volume_api.update(context, volume, update_dict)
        except exception.NotFound:
            msg = _("Volume could not be found")
            raise exc.HTTPNotFound(explanation=msg)

        volume.update(update_dict)

        utils.add_visible_admin_metadata(volume)

        volume_utils.notify_about_volume_usage(context, volume,
                                               'update.end')

        return self._view_builder.detail(req, volume)
Esempio n. 20
0
    def _get_volumes(self, req, is_detail):
        """Returns a list of volumes, transformed through view builder."""

        context = req.environ['cinder.context']

        params = req.params.copy()
        marker = params.pop('marker', None)
        limit = params.pop('limit', None)
        sort_keys, sort_dirs = common.get_sort_params(params)
        params.pop('offset', None)
        filters = params

        utils.remove_invalid_filter_options(context,
                                            filters,
                                            self._get_volume_filter_options())

        # NOTE(thingee): v2 API allows name instead of display_name
        if 'name' in sort_keys:
            sort_keys[sort_keys.index('name')] = 'display_name'

        if 'name' in filters:
            filters['display_name'] = filters['name']
            del filters['name']

        for k, v in filters.items():
            try:
                filters[k] = ast.literal_eval(v)
            except (ValueError, SyntaxError):
                LOG.debug('Could not evaluate value %s, assuming string', v)

        volumes = self.volume_api.get_all(context, marker, limit,
                                          sort_keys=sort_keys,
                                          sort_dirs=sort_dirs,
                                          filters=filters,
                                          viewable_admin_meta=True)

        volumes = [dict(vol) for vol in volumes]

        for volume in volumes:
            utils.add_visible_admin_metadata(volume)

        limited_list = common.limited(volumes, req)
        volume_count = len(volumes)
        req.cache_db_volumes(limited_list)

        if is_detail:
            volumes = self._view_builder.detail_list(req, limited_list,
                                                     volume_count)
        else:
            volumes = self._view_builder.summary_list(req, limited_list,
                                                      volume_count)
        return volumes
Esempio n. 21
0
    def show(self, req, id):
        """Return data about the given volume."""
        context = req.environ['cinder.context']

        try:
            vol = self.volume_api.get(context, id, viewable_admin_meta=True)
            req.cache_db_volume(vol)
        except exception.NotFound:
            raise exc.HTTPNotFound()

        utils.add_visible_admin_metadata(vol)

        return {'volume': _translate_volume_detail_view(context, vol)}
Esempio n. 22
0
    def show(self, req, id):
        """Return data about the given volume."""
        context = req.environ['cinder.context']

        try:
            vol = self.volume_api.get(context, id, viewable_admin_meta=True)
            req.cache_resource(vol)
        except exception.NotFound:
            raise exc.HTTPNotFound()

        utils.add_visible_admin_metadata(vol)

        return {'volume': _translate_volume_detail_view(context, vol)}
Esempio n. 23
0
    def show(self, req, id):
        """Return data about the given volume."""
        context = req.environ['cinder.context']

        try:
            vol = self.volume_api.get(context, id, viewable_admin_meta=True)
            req.cache_db_volume(vol)
        except exception.VolumeNotFound as error:
            raise exc.HTTPNotFound(explanation=error.msg)

        utils.add_visible_admin_metadata(vol)

        return self._view_builder.detail(req, vol)
Esempio n. 24
0
    def show(self, req, id):
        """Return data about the given volume."""
        context = req.environ['cinder.context']

        try:
            vol = self.volume_api.get(context, id, viewable_admin_meta=True)
            req.cache_db_volume(vol)
        except exception.VolumeNotFound as error:
            raise exc.HTTPNotFound(explanation=error.msg)

        utils.add_visible_admin_metadata(vol)

        return self._view_builder.detail(req, vol)
Esempio n. 25
0
    def _get_volumes(self, req, is_detail):
        """Returns a list of volumes, transformed through view builder."""

        context = req.environ['cinder.context']
        req_version = req.api_version_request

        params = req.params.copy()
        marker, limit, offset = common.get_pagination_params(params)
        sort_keys, sort_dirs = common.get_sort_params(params)
        filters = params

        if req_version.matches(None, "3.3"):
            filters.pop('glance_metadata', None)

        if req_version.matches(None, "3.9"):
            filters.pop('group_id', None)

        utils.remove_invalid_filter_options(context, filters,
                                            self._get_volume_filter_options())
        # NOTE(thingee): v2 API allows name instead of display_name
        if 'name' in sort_keys:
            sort_keys[sort_keys.index('name')] = 'display_name'

        if 'name' in filters:
            filters['display_name'] = filters.pop('name')

        if 'group_id' in filters:
            filters['consistencygroup_id'] = filters.pop('group_id')

        strict = req.api_version_request.matches("3.2", None)
        self.volume_api.check_volume_filters(filters, strict)

        volumes = self.volume_api.get_all(context,
                                          marker,
                                          limit,
                                          sort_keys=sort_keys,
                                          sort_dirs=sort_dirs,
                                          filters=filters,
                                          viewable_admin_meta=True,
                                          offset=offset)

        for volume in volumes:
            utils.add_visible_admin_metadata(volume)

        req.cache_db_volumes(volumes.objects)

        if is_detail:
            volumes = self._view_builder.detail_list(req, volumes)
        else:
            volumes = self._view_builder.summary_list(req, volumes)
        return volumes
Esempio n. 26
0
    def show(self, req, id):
        """Return data about the given volume."""
        context = req.environ['cinder.context']

        try:
            vol = self.volume_api.get(context, id)
            req.cache_resource(vol)
        except exception.NotFound:
            msg = _("Volume could not be found")
            raise exc.HTTPNotFound(explanation=msg)

        utils.add_visible_admin_metadata(context, vol, self.volume_api)

        return self._view_builder.detail(req, vol)
Esempio n. 27
0
    def show(self, req, id):
        """Return data about the given volume."""
        context = req.environ['cinder.context']

        try:
            vol = self.volume_api.get(context, id, viewable_admin_meta=True)
            req.cache_resource(vol)
        except exception.NotFound:
            msg = _("Volume could not be found")
            raise exc.HTTPNotFound(explanation=msg)

        utils.add_visible_admin_metadata(vol)

        return self._view_builder.detail(req, vol)
Esempio n. 28
0
    def _get_volumes(self, req, is_detail):
        """Returns a list of volumes, transformed through view builder."""

        context = req.environ['cinder.context']
        req_version = req.api_version_request

        params = req.params.copy()
        marker, limit, offset = common.get_pagination_params(params)
        sort_keys, sort_dirs = common.get_sort_params(params)
        filters = params

        if req_version.matches(None, "3.3"):
            filters.pop('glance_metadata', None)

        if req_version.matches(None, "3.9"):
            filters.pop('group_id', None)

        utils.remove_invalid_filter_options(context, filters,
                                            self._get_volume_filter_options())
        # NOTE(thingee): v2 API allows name instead of display_name
        if 'name' in sort_keys:
            sort_keys[sort_keys.index('name')] = 'display_name'

        if 'name' in filters:
            filters['display_name'] = filters.pop('name')

        if 'group_id' in filters:
            filters['consistencygroup_id'] = filters.pop('group_id')

        strict = req.api_version_request.matches("3.2", None)
        self.volume_api.check_volume_filters(filters, strict)

        volumes = self.volume_api.get_all(context, marker, limit,
                                          sort_keys=sort_keys,
                                          sort_dirs=sort_dirs,
                                          filters=filters,
                                          viewable_admin_meta=True,
                                          offset=offset)

        for volume in volumes:
            utils.add_visible_admin_metadata(volume)

        req.cache_db_volumes(volumes.objects)

        if is_detail:
            volumes = self._view_builder.detail_list(req, volumes)
        else:
            volumes = self._view_builder.summary_list(req, volumes)
        return volumes
Esempio n. 29
0
    def update(self, req, id, body):
        """Update a volume."""
        context = req.environ["cinder.context"]

        if not body:
            msg = _("Missing request body")
            raise exc.HTTPBadRequest(explanation=msg)

        if "volume" not in body:
            msg = _("Missing required element '%s' in request body") % "volume"
            raise exc.HTTPBadRequest(explanation=msg)

        volume = body["volume"]
        update_dict = {}

        valid_update_keys = ("name", "description", "display_name", "display_description", "metadata")

        for key in valid_update_keys:
            if key in volume:
                update_dict[key] = volume[key]

        self.validate_name_and_description(update_dict)

        # NOTE(thingee): v2 API allows name instead of display_name
        if "name" in update_dict:
            update_dict["display_name"] = update_dict.pop("name")

        # NOTE(thingee): v2 API allows description instead of
        #                display_description
        if "description" in update_dict:
            update_dict["display_description"] = update_dict.pop("description")

        try:
            volume = self.volume_api.get(context, id, viewable_admin_meta=True)
            volume_utils.notify_about_volume_usage(context, volume, "update.start")
            self.volume_api.update(context, volume, update_dict)
        except exception.VolumeNotFound as error:
            raise exc.HTTPNotFound(explanation=error.msg)

        volume.update(update_dict)

        utils.add_visible_admin_metadata(volume)

        volume_utils.notify_about_volume_usage(context, volume, "update.end")

        return self._view_builder.detail(req, volume)
Esempio n. 30
0
    def _get_volumes(self, req, is_detail):
        """Returns a list of volumes, transformed through view builder."""

        context = req.environ['cinder.context']

        params = req.params.copy()
        marker = params.pop('marker', None)
        limit = params.pop('limit', None)
        sort_key = params.pop('sort_key', 'created_at')
        sort_dir = params.pop('sort_dir', 'desc')
        params.pop('offset', None)
        filters = params

        utils.remove_invalid_filter_options(context, filters,
                                            self._get_volume_filter_options())

        # NOTE(thingee): v2 API allows name instead of display_name
        if 'name' in filters:
            filters['display_name'] = filters['name']
            del filters['name']

        if 'metadata' in filters:
            filters['metadata'] = ast.literal_eval(filters['metadata'])

        volumes = self.volume_api.get_all(context,
                                          marker,
                                          limit,
                                          sort_key,
                                          sort_dir,
                                          filters,
                                          viewable_admin_meta=True)

        volumes = [dict(vol.iteritems()) for vol in volumes]

        for volume in volumes:
            utils.add_visible_admin_metadata(volume)

        limited_list = common.limited(volumes, req)

        if is_detail:
            volumes = self._view_builder.detail_list(req, limited_list)
        else:
            volumes = self._view_builder.summary_list(req, limited_list)
        req.cache_resource(limited_list)
        return volumes
Esempio n. 31
0
    def _get_volumes(self, req, is_detail):
        """Returns a list of volumes, transformed through view builder."""

        context = req.environ['cinder.context']

        params = req.params.copy()
        marker, limit, offset = common.get_pagination_params(params)
        sort_keys, sort_dirs = common.get_sort_params(params)
        filters = params

        # NOTE(wanghao): Always removing glance_metadata since we support it
        # only in API version >= 3.4.
        filters.pop('glance_metadata', None)
        utils.remove_invalid_filter_options(context, filters,
                                            self._get_volume_filter_options())

        # NOTE(thingee): v2 API allows name instead of display_name
        if 'name' in sort_keys:
            sort_keys[sort_keys.index('name')] = 'display_name'

        if 'name' in filters:
            filters['display_name'] = filters['name']
            del filters['name']

        self.volume_api.check_volume_filters(filters)
        volumes = self.volume_api.get_all(context,
                                          marker,
                                          limit,
                                          sort_keys=sort_keys,
                                          sort_dirs=sort_dirs,
                                          filters=filters,
                                          viewable_admin_meta=True,
                                          offset=offset)

        for volume in volumes:
            utils.add_visible_admin_metadata(volume)

        req.cache_db_volumes(volumes.objects)

        if is_detail:
            volumes = self._view_builder.detail_list(req, volumes)
        else:
            volumes = self._view_builder.summary_list(req, volumes)
        return volumes
Esempio n. 32
0
    def _get_volumes(self, req, is_detail):
        """Returns a list of volumes, transformed through view builder."""

        context = req.environ['cinder.context']

        params = req.params.copy()
        marker, limit, offset = common.get_pagination_params(params)
        sort_keys, sort_dirs = common.get_sort_params(params)
        filters = params

        # NOTE(wanghao): Always removing glance_metadata since we support it
        # only in API version >= 3.4.
        filters.pop('glance_metadata', None)
        utils.remove_invalid_filter_options(context,
                                            filters,
                                            self._get_volume_filter_options())

        # NOTE(thingee): v2 API allows name instead of display_name
        if 'name' in sort_keys:
            sort_keys[sort_keys.index('name')] = 'display_name'

        if 'name' in filters:
            filters['display_name'] = filters['name']
            del filters['name']

        self.volume_api.check_volume_filters(filters)
        volumes = self.volume_api.get_all(context, marker, limit,
                                          sort_keys=sort_keys,
                                          sort_dirs=sort_dirs,
                                          filters=filters,
                                          viewable_admin_meta=True,
                                          offset=offset)

        for volume in volumes:
            utils.add_visible_admin_metadata(volume)

        req.cache_db_volumes(volumes.objects)

        if is_detail:
            volumes = self._view_builder.detail_list(req, volumes)
        else:
            volumes = self._view_builder.summary_list(req, volumes)
        return volumes
Esempio n. 33
0
    def _get_volumes(self, req, is_detail):
        """Returns a list of volumes, transformed through view builder."""

        context = req.environ['cinder.context']

        params = req.params.copy()
        marker = params.pop('marker', None)
        limit = params.pop('limit', None)
        sort_key = params.pop('sort_key', 'created_at')
        sort_dir = params.pop('sort_dir', 'desc')
        params.pop('offset', None)
        filters = params

        utils.remove_invalid_filter_options(context,
                                            filters,
                                            self._get_volume_filter_options())

        # NOTE(thingee): v2 API allows name instead of display_name
        if 'name' in filters:
            filters['display_name'] = filters['name']
            del filters['name']

        if 'metadata' in filters:
            filters['metadata'] = ast.literal_eval(filters['metadata'])

        volumes = self.volume_api.get_all(context, marker, limit, sort_key,
                                          sort_dir, filters,
                                          viewable_admin_meta=True)

        volumes = [dict(vol.iteritems()) for vol in volumes]

        for volume in volumes:
            utils.add_visible_admin_metadata(volume)

        limited_list = common.limited(volumes, req)

        if is_detail:
            volumes = self._view_builder.detail_list(req, limited_list)
        else:
            volumes = self._view_builder.summary_list(req, limited_list)
        req.cache_resource(limited_list)
        return volumes
Esempio n. 34
0
    def _get_volumes(self, req, is_detail):
        """Returns a list of volumes, transformed through view builder."""

        context = req.environ["cinder.context"]

        params = req.params.copy()
        marker, limit, offset = common.get_pagination_params(params)
        sort_keys, sort_dirs = common.get_sort_params(params)
        filters = params

        utils.remove_invalid_filter_options(context, filters, self._get_volume_filter_options())

        # NOTE(thingee): v2 API allows name instead of display_name
        if "name" in sort_keys:
            sort_keys[sort_keys.index("name")] = "display_name"

        if "name" in filters:
            filters["display_name"] = filters["name"]
            del filters["name"]

        self.volume_api.check_volume_filters(filters)
        volumes = self.volume_api.get_all(
            context,
            marker,
            limit,
            sort_keys=sort_keys,
            sort_dirs=sort_dirs,
            filters=filters,
            viewable_admin_meta=True,
            offset=offset,
        )

        for volume in volumes:
            utils.add_visible_admin_metadata(volume)

        req.cache_db_volumes(volumes.objects)

        if is_detail:
            volumes = self._view_builder.detail_list(req, volumes)
        else:
            volumes = self._view_builder.summary_list(req, volumes)
        return volumes
Esempio n. 35
0
    def test_add_visible_admin_metadata_no_visible_keys(self):
        admin_metadata = [
            {"key": "invisible_key1", "value": "invisible_value1"},
            {"key": "invisible_key2", "value": "invisible_value2"},
            {"key": "invisible_key3", "value": "invisible_value3"}]
        metadata = [{"key": "key", "value": "value"}]
        volume = {'volume_admin_metadata': admin_metadata,
                  'volume_metadata': metadata}
        utils.add_visible_admin_metadata(volume)
        self.assertEqual([{"key": "key", "value": "value"}],
                         volume['volume_metadata'])

        admin_metadata = {"invisible_key1": "invisible_value1",
                          "invisible_key2": "invisible_value2",
                          "invisible_key3": "invisible_value3"}
        metadata = {"key": "value"}
        volume = {'admin_metadata': admin_metadata,
                  'metadata': metadata}
        utils.add_visible_admin_metadata(volume)
        self.assertEqual({'key': 'value'}, volume['metadata'])
Esempio n. 36
0
    def test_add_visible_admin_metadata_visible_key_only(self):
        admin_metadata = [{
            "key": "invisible_key",
            "value": "invisible_value"
        }, {
            "key": "readonly",
            "value": "visible"
        }, {
            "key": "attached_mode",
            "value": "visible"
        }]
        metadata = [{"key": "key", "value": "value"}]
        volume = dict(volume_admin_metadata=admin_metadata,
                      volume_metadata=metadata)
        utils.add_visible_admin_metadata(volume)
        self.assertEqual(volume['volume_metadata'], [{
            "key": "key",
            "value": "value"
        }, {
            "key": "readonly",
            "value": "visible"
        }, {
            "key": "attached_mode",
            "value": "visible"
        }])

        admin_metadata = {
            "invisible_key": "invisible_value",
            "readonly": "visible",
            "attached_mode": "visible"
        }
        metadata = {"key": "value"}
        volume = dict(admin_metadata=admin_metadata, metadata=metadata)
        utils.add_visible_admin_metadata(volume)
        self.assertEqual(volume['metadata'], {
            'key': 'value',
            'attached_mode': 'visible',
            'readonly': 'visible'
        })
Esempio n. 37
0
    def update(self, req, id, body):
        """Update a volume."""
        context = req.environ['cinder.context']

        if not body:
            raise exc.HTTPUnprocessableEntity()

        if 'volume' not in body:
            raise exc.HTTPUnprocessableEntity()

        volume = body['volume']
        update_dict = {}

        valid_update_keys = (
            'display_name',
            'display_description',
            'metadata',
        )

        for key in valid_update_keys:
            if key in volume:
                update_dict[key] = volume[key]

        # Not found exception will be handled at the wsgi level
        volume = self.volume_api.get(context, id, viewable_admin_meta=True)
        volume_utils.notify_about_volume_usage(context, volume,
                                               'update.start')
        self.volume_api.update(context, volume, update_dict)

        volume.update(update_dict)

        utils.add_visible_admin_metadata(volume)

        volume_utils.notify_about_volume_usage(context, volume,
                                               'update.end')

        return {'volume': _translate_volume_detail_view(context, volume)}
Esempio n. 38
0
    def test_add_visible_admin_metadata_visible_key_only(self):
        admin_metadata = [{"key": "invisible_key", "value": "invisible_value"},
                          {"key": "readonly", "value": "visible"},
                          {"key": "attached_mode", "value": "visible"}]
        metadata = [{"key": "key", "value": "value"}]
        volume = dict(volume_admin_metadata=admin_metadata,
                      volume_metadata=metadata)
        utils.add_visible_admin_metadata(volume)
        self.assertEqual(volume['volume_metadata'],
                         [{"key": "key", "value": "value"},
                          {"key": "readonly", "value": "visible"},
                          {"key": "attached_mode", "value": "visible"}])

        admin_metadata = {"invisible_key": "invisible_value",
                          "readonly": "visible",
                          "attached_mode": "visible"}
        metadata = {"key": "value"}
        volume = dict(admin_metadata=admin_metadata,
                      metadata=metadata)
        utils.add_visible_admin_metadata(volume)
        self.assertEqual(volume['metadata'],
                         {'key': 'value',
                          'attached_mode': 'visible',
                          'readonly': 'visible'})
Esempio n. 39
0
    def create(self, req, body):
        """Creates a new volume."""
        if not self.is_valid_body(body, 'volume'):
            msg = _("Missing required element '%s' in request body") % 'volume'
            raise exc.HTTPBadRequest(explanation=msg)

        LOG.debug('Create volume request body: %s', body)
        context = req.environ['cinder.context']
        volume = body['volume']

        kwargs = {}

        # NOTE(thingee): v2 API allows name instead of display_name
        if volume.get('name'):
            volume['display_name'] = volume.get('name')
            del volume['name']

        # NOTE(thingee): v2 API allows description instead of
        #                display_description
        if volume.get('description'):
            volume['display_description'] = volume.get('description')
            del volume['description']

        req_volume_type = volume.get('volume_type', None)
        if req_volume_type:
            try:
                if not uuidutils.is_uuid_like(req_volume_type):
                    kwargs['volume_type'] = \
                        volume_types.get_volume_type_by_name(
                            context, req_volume_type)
                else:
                    kwargs['volume_type'] = volume_types.get_volume_type(
                        context, req_volume_type)
            except exception.VolumeTypeNotFound:
                msg = _("Volume type not found.")
                raise exc.HTTPNotFound(explanation=msg)

        kwargs['metadata'] = volume.get('metadata', None)

        snapshot_id = volume.get('snapshot_id')
        if snapshot_id is not None:
            try:
                kwargs['snapshot'] = self.volume_api.get_snapshot(context,
                                                                  snapshot_id)
            except exception.NotFound:
                explanation = _('snapshot id:%s not found') % snapshot_id
                raise exc.HTTPNotFound(explanation=explanation)
        else:
            kwargs['snapshot'] = None

        source_volid = volume.get('source_volid')
        if source_volid is not None:
            try:
                kwargs['source_volume'] = \
                    self.volume_api.get_volume(context,
                                               source_volid)
            except exception.NotFound:
                explanation = _('source volume id:%s not found') % source_volid
                raise exc.HTTPNotFound(explanation=explanation)
        else:
            kwargs['source_volume'] = None

        size = volume.get('size', None)
        if size is None and kwargs['snapshot'] is not None:
            size = kwargs['snapshot']['volume_size']
        elif size is None and kwargs['source_volume'] is not None:
            size = kwargs['source_volume']['size']

        LOG.audit(_("Create volume of %s GB"), size, context=context)

        if self.ext_mgr.is_loaded('os-image-create'):
            image_href = volume.get('imageRef')
            if image_href:
                image_uuid = self._image_uuid_from_href(image_href)
                kwargs['image_id'] = image_uuid

        kwargs['availability_zone'] = volume.get('availability_zone', None)
        kwargs['scheduler_hints'] = volume.get('scheduler_hints', None)

        new_volume = self.volume_api.create(context,
                                            size,
                                            volume.get('display_name'),
                                            volume.get('display_description'),
                                            **kwargs)

        # TODO(vish): Instance should be None at db layer instead of
        #             trying to lazy load, but for now we turn it into
        #             a dict to avoid an error.
        new_volume = dict(new_volume.iteritems())

        utils.add_visible_admin_metadata(context, new_volume, self.volume_api)

        retval = self._view_builder.detail(req, new_volume)

        return retval
Esempio n. 40
0
    def create(self, req, body):
        """Instruct Cinder to manage a storage object.

        Manages an existing backend storage object (e.g. a Linux logical
        volume or a SAN disk) by creating the Cinder objects required to manage
        it, and possibly renaming the backend storage object
        (driver dependent)

        From an API perspective, this operation behaves very much like a
        volume creation operation, except that properties such as image,
        snapshot and volume references don't make sense, because we are taking
        an existing storage object into Cinder management.

        Required HTTP Body:

        .. code-block:: json

         {
           'volume':
           {
             'host': <Cinder host on which the existing storage resides>,
             'ref':  <Driver-specific reference to existing storage object>,
           }
         }

        See the appropriate Cinder drivers' implementations of the
        manage_volume method to find out the accepted format of 'ref'.

        This API call will return with an error if any of the above elements
        are missing from the request, or if the 'host' element refers to a
        cinder host that is not registered.

        The volume will later enter the error state if it is discovered that
        'ref' is bad.

        Optional elements to 'volume' are::

         name               A name for the new volume.
         description        A description for the new volume.
         volume_type        ID or name of a volume type to associate with
                            the new Cinder volume. Does not necessarily
                            guarantee that the managed volume will have the
                            properties described in the volume_type. The
                            driver may choose to fail if it identifies that
                            the specified volume_type is not compatible with
                            the backend storage object.
         metadata           Key/value pairs to be associated with the new
                            volume.
         availability_zone  The availability zone to associate with the new
                            volume.
         bootable           If set to True, marks the volume as bootable.

        """
        context = req.environ['cinder.context']
        authorize(context)

        self.assert_valid_body(body, 'volume')

        volume = body['volume']
        self.validate_name_and_description(volume)

        # Check that the required keys are present, return an error if they
        # are not.
        required_keys = set(['ref', 'host'])
        missing_keys = list(required_keys - set(volume.keys()))

        if missing_keys:
            msg = _("The following elements are required: %s") % \
                ', '.join(missing_keys)
            raise exc.HTTPBadRequest(explanation=msg)

        LOG.debug('Manage volume request body: %s', body)

        kwargs = {}
        req_volume_type = volume.get('volume_type', None)
        if req_volume_type:
            try:
                if not uuidutils.is_uuid_like(req_volume_type):
                    kwargs['volume_type'] = \
                        volume_types.get_volume_type_by_name(
                            context, req_volume_type)
                else:
                    kwargs['volume_type'] = volume_types.get_volume_type(
                        context, req_volume_type)
            except exception.VolumeTypeNotFound as error:
                raise exc.HTTPNotFound(explanation=error.msg)
        else:
            kwargs['volume_type'] = {}

        kwargs['name'] = volume.get('name', None)
        kwargs['description'] = volume.get('description', None)
        kwargs['metadata'] = volume.get('metadata', None)
        kwargs['availability_zone'] = volume.get('availability_zone', None)
        kwargs['bootable'] = volume.get('bootable', False)
        try:
            new_volume = self.volume_api.manage_existing(context,
                                                         volume['host'],
                                                         volume['ref'],
                                                         **kwargs)
        except exception.ServiceNotFound:
            msg = _("Service not found.")
            raise exc.HTTPNotFound(explanation=msg)

        utils.add_visible_admin_metadata(new_volume)

        return self._view_builder.detail(req, new_volume)
Esempio n. 41
0
    def create(self, req, body):
        """Instruct Cinder to manage a storage object.

        Manages an existing backend storage object (e.g. a Linux logical
        volume or a SAN disk) by creating the Cinder objects required to manage
        it, and possibly renaming the backend storage object
        (driver dependent)

        From an API perspective, this operation behaves very much like a
        volume creation operation, except that properties such as image,
        snapshot and volume references don't make sense, because we are taking
        an existing storage object into Cinder management.

        Required HTTP Body:

        {
         'volume':
          {
           'host': <Cinder host on which the existing storage resides>,
           'ref':  <Driver-specific reference to the existing storage object>,
          }
        }

        See the appropriate Cinder drivers' implementations of the
        manage_volume method to find out the accepted format of 'ref'.

        This API call will return with an error if any of the above elements
        are missing from the request, or if the 'host' element refers to a
        cinder host that is not registered.

        The volume will later enter the error state if it is discovered that
        'ref' is bad.

        Optional elements to 'volume' are:
            name               A name for the new volume.
            description        A description for the new volume.
            volume_type        ID or name of a volume type to associate with
                               the new Cinder volume.  Does not necessarily
                               guarantee that the managed volume will have the
                               properties described in the volume_type.  The
                               driver may choose to fail if it identifies that
                               the specified volume_type is not compatible with
                               the backend storage object.
            metadata           Key/value pairs to be associated with the new
                               volume.
            availability_zone  The availability zone to associate with the new
                               volume.
            bootable           If set to True, marks the volume as bootable.
        """
        context = req.environ['cinder.context']
        authorize(context)

        self.assert_valid_body(body, 'volume')

        volume = body['volume']

        # Check that the required keys are present, return an error if they
        # are not.
        required_keys = set(['ref', 'host'])
        missing_keys = list(required_keys - set(volume.keys()))

        if missing_keys:
            msg = _("The following elements are required: %s") % \
                ', '.join(missing_keys)
            raise exc.HTTPBadRequest(explanation=msg)

        LOG.debug('Manage volume request body: %s', body)

        kwargs = {}
        req_volume_type = volume.get('volume_type', None)
        if req_volume_type:
            try:
                if not uuidutils.is_uuid_like(req_volume_type):
                    kwargs['volume_type'] = \
                        volume_types.get_volume_type_by_name(
                            context, req_volume_type)
                else:
                    kwargs['volume_type'] = volume_types.get_volume_type(
                        context, req_volume_type)
            except exception.VolumeTypeNotFound as error:
                raise exc.HTTPNotFound(explanation=error.msg)
        else:
            kwargs['volume_type'] = {}

        kwargs['name'] = volume.get('name', None)
        kwargs['description'] = volume.get('description', None)
        kwargs['metadata'] = volume.get('metadata', None)
        kwargs['availability_zone'] = volume.get('availability_zone', None)
        kwargs['bootable'] = volume.get('bootable', False)
        try:
            new_volume = self.volume_api.manage_existing(
                context, volume['host'], volume['ref'], **kwargs)
        except exception.ServiceNotFound:
            msg = _("Service not found.")
            raise exc.HTTPNotFound(explanation=msg)

        new_volume = dict(new_volume)
        utils.add_visible_admin_metadata(new_volume)

        return self._view_builder.detail(req, new_volume)
Esempio n. 42
0
    def create(self, req, body):
        """Creates a new volume."""
        if not self.is_valid_body(body, 'volume'):
            msg = _("Missing required element '%s' in request body") % 'volume'
            raise exc.HTTPBadRequest(explanation=msg)

        LOG.debug('Create volume request body: %s', body)
        context = req.environ['cinder.context']
        volume = body['volume']

        kwargs = {}

        # NOTE(thingee): v2 API allows name instead of display_name
        if volume.get('name'):
            volume['display_name'] = volume.get('name')
            del volume['name']

        # NOTE(thingee): v2 API allows description instead of
        #                display_description
        if volume.get('description'):
            volume['display_description'] = volume.get('description')
            del volume['description']

        req_volume_type = volume.get('volume_type', None)
        if req_volume_type:
            try:
                if not uuidutils.is_uuid_like(req_volume_type):
                    kwargs['volume_type'] = \
                        volume_types.get_volume_type_by_name(
                            context, req_volume_type)
                else:
                    kwargs['volume_type'] = volume_types.get_volume_type(
                        context, req_volume_type)
            except exception.VolumeTypeNotFound:
                msg = _("Volume type not found.")
                raise exc.HTTPNotFound(explanation=msg)

        kwargs['metadata'] = volume.get('metadata', None)

        snapshot_id = volume.get('snapshot_id')
        if snapshot_id is not None:
            try:
                kwargs['snapshot'] = self.volume_api.get_snapshot(context,
                                                                  snapshot_id)
            except exception.NotFound:
                explanation = _('snapshot id:%s not found') % snapshot_id
                raise exc.HTTPNotFound(explanation=explanation)
        else:
            kwargs['snapshot'] = None

        source_volid = volume.get('source_volid')
        if source_volid is not None:
            try:
                kwargs['source_volume'] = \
                    self.volume_api.get_volume(context,
                                               source_volid)
            except exception.NotFound:
                explanation = _('source volume id:%s not found') % source_volid
                raise exc.HTTPNotFound(explanation=explanation)
        else:
            kwargs['source_volume'] = None

        size = volume.get('size', None)
        if size is None and kwargs['snapshot'] is not None:
            size = kwargs['snapshot']['volume_size']
        elif size is None and kwargs['source_volume'] is not None:
            size = kwargs['source_volume']['size']

        LOG.audit(_("Create volume of %s GB"), size, context=context)

        if self.ext_mgr.is_loaded('os-image-create'):
            image_href = volume.get('imageRef')
            if image_href is not None:
                image_uuid = self._image_uuid_from_href(image_href)
                kwargs['image_id'] = image_uuid

        kwargs['availability_zone'] = volume.get('availability_zone', None)
        kwargs['scheduler_hints'] = volume.get('scheduler_hints', None)

        new_volume = self.volume_api.create(context,
                                            size,
                                            volume.get('display_name'),
                                            volume.get('display_description'),
                                            **kwargs)

        # TODO(vish): Instance should be None at db layer instead of
        #             trying to lazy load, but for now we turn it into
        #             a dict to avoid an error.
        new_volume = dict(new_volume.iteritems())

        utils.add_visible_admin_metadata(context, new_volume, self.volume_api)

        retval = self._view_builder.detail(req, new_volume)

        return retval
Esempio n. 43
0
    def create(self, req, body):
        """Instruct Cinder to manage a storage object.

        Manages an existing backend storage object (e.g. a Linux logical
        volume or a SAN disk) by creating the Cinder objects required to manage
        it, and possibly renaming the backend storage object
        (driver dependent)

        From an API perspective, this operation behaves very much like a
        volume creation operation, except that properties such as image,
        snapshot and volume references don't make sense, because we are taking
        an existing storage object into Cinder management.

        Required HTTP Body:

        .. code-block:: json

         {
           "volume": {
             "host": "<Cinder host on which the existing storage resides>",
             "cluster": "<Cinder cluster on which the storage resides>",
             "ref": "<Driver-specific reference to existing storage object>"
           }
         }

        See the appropriate Cinder drivers' implementations of the
        manage_volume method to find out the accepted format of 'ref'.

        This API call will return with an error if any of the above elements
        are missing from the request, or if the 'host' element refers to a
        cinder host that is not registered.

        The volume will later enter the error state if it is discovered that
        'ref' is bad.

        Optional elements to 'volume' are::

         name               A name for the new volume.
         description        A description for the new volume.
         volume_type        ID or name of a volume type to associate with
                            the new Cinder volume. Does not necessarily
                            guarantee that the managed volume will have the
                            properties described in the volume_type. The
                            driver may choose to fail if it identifies that
                            the specified volume_type is not compatible with
                            the backend storage object.
         metadata           Key/value pairs to be associated with the new
                            volume.
         availability_zone  The availability zone to associate with the new
                            volume.
         bootable           If set to True, marks the volume as bootable.

        """
        context = req.environ['cinder.context']
        context.authorize(policy.MANAGE_POLICY)
        volume = body['volume']

        cluster_name, host = common.get_cluster_host(
            req, volume, mv.VOLUME_MIGRATE_CLUSTER)

        LOG.debug('Manage volume request body: %s', body)

        kwargs = {}
        req_volume_type = volume.get('volume_type', None)
        if req_volume_type:
            try:
                kwargs['volume_type'] = volume_types.get_by_name_or_id(
                    context, req_volume_type)
            except exception.VolumeTypeNotFound:
                msg = _("Cannot find requested '%s' "
                        "volume type") % req_volume_type
                raise exception.InvalidVolumeType(reason=msg)
        else:
            kwargs['volume_type'] = {}

        if volume.get('name'):
            kwargs['name'] = volume.get('name').strip()
        if volume.get('description'):
            kwargs['description'] = volume.get('description').strip()

        kwargs['metadata'] = volume.get('metadata', None)
        kwargs['availability_zone'] = volume.get('availability_zone', None)
        bootable = volume.get('bootable', False)
        kwargs['bootable'] = strutils.bool_from_string(bootable, strict=True)

        try:
            new_volume = self.volume_api.manage_existing(context,
                                                         host,
                                                         cluster_name,
                                                         volume['ref'],
                                                         **kwargs)
        except exception.ServiceNotFound:
            msg = _("%(name)s '%(value)s' not found") % {
                'name': 'Host' if host else 'Cluster',
                'value': host or cluster_name}
            raise exception.ServiceUnavailable(message=msg)

        utils.add_visible_admin_metadata(new_volume)

        return self._view_builder.detail(req, new_volume)
Esempio n. 44
0
    def create(self, req, body):
        """Instruct Cinder to manage a storage object.

        Manages an existing backend storage object (e.g. a Linux logical
        volume or a SAN disk) by creating the Cinder objects required to manage
        it, and possibly renaming the backend storage object
        (driver dependent)

        From an API perspective, this operation behaves very much like a
        volume creation operation, except that properties such as image,
        snapshot and volume references don't make sense, because we are taking
        an existing storage object into Cinder management.

        Required HTTP Body:

        .. code-block:: json

         {
           "volume": {
             "host": "<Cinder host on which the existing storage resides>",
             "cluster": "<Cinder cluster on which the storage resides>",
             "ref": "<Driver-specific reference to existing storage object>"
           }
         }

        See the appropriate Cinder drivers' implementations of the
        manage_volume method to find out the accepted format of 'ref'.

        This API call will return with an error if any of the above elements
        are missing from the request, or if the 'host' element refers to a
        cinder host that is not registered.

        The volume will later enter the error state if it is discovered that
        'ref' is bad.

        Optional elements to 'volume' are::

         name               A name for the new volume.
         description        A description for the new volume.
         volume_type        ID or name of a volume type to associate with
                            the new Cinder volume. Does not necessarily
                            guarantee that the managed volume will have the
                            properties described in the volume_type. The
                            driver may choose to fail if it identifies that
                            the specified volume_type is not compatible with
                            the backend storage object.
         metadata           Key/value pairs to be associated with the new
                            volume.
         availability_zone  The availability zone to associate with the new
                            volume.
         bootable           If set to True, marks the volume as bootable.

        """
        context = req.environ['cinder.context']
        context.authorize(policy.MANAGE_POLICY)

        self.assert_valid_body(body, 'volume')

        volume = body['volume']
        self.validate_name_and_description(volume)

        # Check that the required keys are present, return an error if they
        # are not.
        if 'ref' not in volume:
            raise exception.MissingRequired(element='ref')

        cluster_name, host = common.get_cluster_host(req, volume,
                                                     mv.VOLUME_MIGRATE_CLUSTER)

        LOG.debug('Manage volume request body: %s', body)

        kwargs = {}
        req_volume_type = volume.get('volume_type', None)
        if req_volume_type:
            try:
                kwargs['volume_type'] = volume_types.get_by_name_or_id(
                    context, req_volume_type)
            except exception.VolumeTypeNotFound:
                msg = _("Cannot find requested '%s' "
                        "volume type") % req_volume_type
                raise exception.InvalidVolumeType(reason=msg)
        else:
            kwargs['volume_type'] = {}

        kwargs['name'] = volume.get('name', None)
        kwargs['description'] = volume.get('description', None)
        kwargs['metadata'] = volume.get('metadata', None)
        kwargs['availability_zone'] = volume.get('availability_zone', None)
        kwargs['bootable'] = utils.get_bool_param('bootable', volume)

        utils.check_metadata_properties(kwargs['metadata'])

        try:
            new_volume = self.volume_api.manage_existing(
                context, host, cluster_name, volume['ref'], **kwargs)
        except exception.ServiceNotFound:
            msg = _("%(name)s '%(value)s' not found") % {
                'name': 'Host' if host else 'Cluster',
                'value': host or cluster_name
            }
            raise exception.ServiceUnavailable(message=msg)

        utils.add_visible_admin_metadata(new_volume)

        return self._view_builder.detail(req, new_volume)