summaryrefslogtreecommitdiff
path: root/glance/api/v2/metadef_properties.py
blob: 06787e193d5ae8e63bd3c2d5bb5adfc5bc53eaad (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
# Copyright (c) 2014 Hewlett-Packard Development Company, L.P.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import six
import webob.exc
from wsme.rest.json import fromjson
from wsme.rest.json import tojson

from glance.api import policy
from glance.api.v2 import metadef_namespaces as namespaces
from glance.api.v2.model.metadef_namespace import Namespace
from glance.api.v2.model.metadef_property_type import PropertyType
from glance.api.v2.model.metadef_property_type import PropertyTypes
from glance.common import exception
from glance.common import utils
from glance.common import wsgi
import glance.db
import glance.gateway
from glance import i18n
import glance.notifier
from glance.openstack.common import jsonutils as json
import glance.openstack.common.log as logging
import glance.schema

LOG = logging.getLogger(__name__)
_LE = i18n._LE
_LI = i18n._LI


class NamespacePropertiesController(object):
    def __init__(self, db_api=None, policy_enforcer=None):
        self.db_api = db_api or glance.db.get_api()
        self.policy = policy_enforcer or policy.Enforcer()
        self.gateway = glance.gateway.Gateway(db_api=self.db_api,
                                              policy_enforcer=self.policy)

    def _to_dict(self, model_property_type):
        # Convert the model PropertyTypes dict to a JSON encoding
        db_property_type_dict = dict()
        db_property_type_dict['schema'] = tojson(
            PropertyType, model_property_type)
        db_property_type_dict['name'] = model_property_type.name
        return db_property_type_dict

    def _to_model(self, db_property_type):
        # Convert the persisted json schema to a dict of PropertyTypes
        property_type = fromjson(
            PropertyType, db_property_type.schema)
        property_type.name = db_property_type.name
        return property_type

    def index(self, req, namespace):
        try:
            filters = dict()
            filters['namespace'] = namespace
            prop_repo = self.gateway.get_metadef_property_repo(req.context)
            db_properties = prop_repo.list(filters=filters)
            property_list = Namespace.to_model_properties(db_properties)
            namespace_properties = PropertyTypes()
            namespace_properties.properties = property_list
        except exception.Forbidden as e:
            raise webob.exc.HTTPForbidden(explanation=e.msg)
        except exception.NotFound as e:
            raise webob.exc.HTTPNotFound(explanation=e.msg)
        except Exception as e:
            LOG.error(utils.exception_to_str(e))
            raise webob.exc.HTTPInternalServerError()
        return namespace_properties

    def show(self, req, namespace, property_name):
        try:
            prop_repo = self.gateway.get_metadef_property_repo(req.context)
            db_property = prop_repo.get(namespace, property_name)
            property = self._to_model(db_property)
        except exception.Forbidden as e:
            raise webob.exc.HTTPForbidden(explanation=e.msg)
        except exception.NotFound as e:
            raise webob.exc.HTTPNotFound(explanation=e.msg)
        except Exception as e:
            LOG.error(utils.exception_to_str(e))
            raise webob.exc.HTTPInternalServerError()
        return property

    def create(self, req, namespace, property_type):
        prop_factory = self.gateway.get_metadef_property_factory(req.context)
        prop_repo = self.gateway.get_metadef_property_repo(req.context)
        try:
            new_property_type = prop_factory.new_namespace_property(
                namespace=namespace, **self._to_dict(property_type))
            prop_repo.add(new_property_type)
        except exception.Forbidden as e:
            raise webob.exc.HTTPForbidden(explanation=e.msg)
        except exception.NotFound as e:
            raise webob.exc.HTTPNotFound(explanation=e.msg)
        except exception.Duplicate as e:
            raise webob.exc.HTTPConflict(explanation=e.msg)
        except Exception as e:
            LOG.error(utils.exception_to_str(e))
            raise webob.exc.HTTPInternalServerError()
        return self._to_model(new_property_type)

    def update(self, req, namespace, property_name, property_type):
        prop_repo = self.gateway.get_metadef_property_repo(req.context)
        try:
            db_property_type = prop_repo.get(namespace, property_name)
            db_property_type.name = property_type.name
            db_property_type.schema = (self._to_dict(property_type))['schema']
            updated_property_type = prop_repo.save(db_property_type)
        except exception.Forbidden as e:
            raise webob.exc.HTTPForbidden(explanation=e.msg)
        except exception.NotFound as e:
            raise webob.exc.HTTPNotFound(explanation=e.msg)
        except exception.Duplicate as e:
            raise webob.exc.HTTPConflict(explanation=e.msg)
        except Exception as e:
            LOG.error(utils.exception_to_str(e))
            raise webob.exc.HTTPInternalServerError()
        return self._to_model(updated_property_type)

    def delete(self, req, namespace, property_name):
        prop_repo = self.gateway.get_metadef_property_repo(req.context)
        try:
            property_type = prop_repo.get(namespace, property_name)
            property_type.delete()
            prop_repo.remove(property_type)
        except exception.Forbidden as e:
            raise webob.exc.HTTPForbidden(explanation=e.msg)
        except exception.NotFound as e:
            raise webob.exc.HTTPNotFound(explanation=e.msg)
        except Exception as e:
            LOG.error(utils.exception_to_str(e))
            raise webob.exc.HTTPInternalServerError()


class RequestDeserializer(wsgi.JSONRequestDeserializer):
    _disallowed_properties = ['created_at', 'updated_at']

    def __init__(self, schema=None):
        super(RequestDeserializer, self).__init__()
        self.schema = schema or get_schema()

    def _get_request_body(self, request):
        output = super(RequestDeserializer, self).default(request)
        if 'body' not in output:
            msg = _('Body expected in request.')
            raise webob.exc.HTTPBadRequest(explanation=msg)
        return output['body']

    @classmethod
    def _check_allowed(cls, image):
        for key in cls._disallowed_properties:
            if key in image:
                msg = _("Attribute '%s' is read-only.") % key
                raise webob.exc.HTTPForbidden(explanation=msg)

    def create(self, request):
        body = self._get_request_body(request)
        self._check_allowed(body)
        try:
            self.schema.validate(body)
        except exception.InvalidObject as e:
            raise webob.exc.HTTPBadRequest(explanation=e.msg)
        property_type = fromjson(PropertyType, body)
        return dict(property_type=property_type)

    def update(self, request):
        body = self._get_request_body(request)
        self._check_allowed(body)
        try:
            self.schema.validate(body)
        except exception.InvalidObject as e:
            raise webob.exc.HTTPBadRequest(explanation=e.msg)
        property_type = fromjson(PropertyType, body)
        return dict(property_type=property_type)


class ResponseSerializer(wsgi.JSONResponseSerializer):
    def __init__(self, schema=None):
        super(ResponseSerializer, self).__init__()
        self.schema = schema

    def show(self, response, result):
        property_type_json = tojson(PropertyType, result)
        body = json.dumps(property_type_json, ensure_ascii=False)
        response.unicode_body = six.text_type(body)
        response.content_type = 'application/json'

    def index(self, response, result):
        property_type_json = tojson(PropertyTypes, result)
        body = json.dumps(property_type_json, ensure_ascii=False)
        response.unicode_body = six.text_type(body)
        response.content_type = 'application/json'

    def create(self, response, result):
        response.status_int = 201
        self.show(response, result)

    def update(self, response, result):
        response.status_int = 200
        self.show(response, result)

    def delete(self, response, result):
        response.status_int = 204


def _get_base_definitions():
    return {
        "positiveInteger": {
            "type": "integer",
            "minimum": 0
        },
        "positiveIntegerDefault0": {
            "allOf": [
                {"$ref": "#/definitions/positiveInteger"},
                {"default": 0}
            ]
        },
        "stringArray": {
            "type": "array",
            "items": {"type": "string"},
            "minItems": 1,
            "uniqueItems": True
        }
    }


def _get_base_properties():
    base_def = namespaces.get_schema_definitions()
    return base_def['property']['additionalProperties']['properties']


def get_schema():
    definitions = _get_base_definitions()
    properties = _get_base_properties()
    mandatory_attrs = PropertyType.get_mandatory_attrs()
    # name is required attribute when use as single property type
    mandatory_attrs.append('name')
    schema = glance.schema.Schema(
        'property',
        properties,
        required=mandatory_attrs,
        definitions=definitions
    )
    return schema


def get_collection_schema():
    namespace_properties_schema = get_schema()
    # Property name is a dict key and not a required attribute in
    # individual property schema inside property collections
    namespace_properties_schema.required.remove('name')
    return glance.schema.DictCollectionSchema('properties',
                                              namespace_properties_schema)


def create_resource():
    """NamespaceProperties resource factory method"""
    schema = get_schema()
    deserializer = RequestDeserializer(schema)
    serializer = ResponseSerializer(schema)
    controller = NamespacePropertiesController()
    return wsgi.Resource(controller, deserializer, serializer)