summaryrefslogtreecommitdiffstats
path: root/nova/api/openstack/compute/plugins/v3/flavor_access.py
blob: 459a4041b332006f798390015772f8884bed8e2e (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
# vim: tabstop=4 shiftwidth=4 softtabstop=4

# Copyright (c) 2011 OpenStack Foundation
# All Rights Reserved.
#
#    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.

"""The flavor access extension."""

import webob

from nova.api.openstack import extensions
from nova.api.openstack import wsgi
from nova.api.openstack import xmlutil
from nova.compute import flavors
from nova import exception

ALIAS = 'os-flavor-access'
authorize = extensions.soft_extension_authorizer('compute', 'v3:' + ALIAS)


def make_flavor(elem):
    elem.set('{%s}is_public' % FlavorAccess.namespace,
             '%s:is_public' % FlavorAccess.alias)


def make_flavor_access(elem):
    elem.set('flavor_id')
    elem.set('tenant_id')


class FlavorTemplate(xmlutil.TemplateBuilder):
    def construct(self):
        root = xmlutil.TemplateElement('flavor', selector='flavor')
        make_flavor(root)
        alias = FlavorAccess.alias
        namespace = FlavorAccess.namespace
        return xmlutil.SlaveTemplate(root, 1, nsmap={alias: namespace})


class FlavorsTemplate(xmlutil.TemplateBuilder):
    def construct(self):
        root = xmlutil.TemplateElement('flavors')
        elem = xmlutil.SubTemplateElement(root, 'flavor', selector='flavors')
        make_flavor(elem)
        alias = FlavorAccess.alias
        namespace = FlavorAccess.namespace
        return xmlutil.SlaveTemplate(root, 1, nsmap={alias: namespace})


class FlavorAccessTemplate(xmlutil.TemplateBuilder):
    def construct(self):
        root = xmlutil.TemplateElement('flavor_access')
        elem = xmlutil.SubTemplateElement(root, 'access',
                                          selector='flavor_access')
        make_flavor_access(elem)
        return xmlutil.MasterTemplate(root, 1)


def _marshall_flavor_access(flavor_id):
    rval = []
    try:
        access_list = flavors.\
                      get_flavor_access_by_flavor_id(flavor_id)
    except exception.FlavorNotFound:
        explanation = _("Flavor not found.")
        raise webob.exc.HTTPNotFound(explanation=explanation)

    for access in access_list:
        rval.append({'flavor_id': flavor_id,
                     'tenant_id': access['project_id']})

    return {'flavor_access': rval}


class FlavorAccessController(object):
    """The flavor access API controller for the OpenStack API."""

    def __init__(self):
        super(FlavorAccessController, self).__init__()

    @wsgi.serializers(xml=FlavorAccessTemplate)
    def index(self, req, flavor_id):
        context = req.environ['nova.context']
        authorize(context)

        try:
            flavor = flavors.get_flavor_by_flavor_id(flavor_id)
        except exception.FlavorNotFound:
            explanation = _("Flavor not found.")
            raise webob.exc.HTTPNotFound(explanation=explanation)

        # public flavor to all projects
        if flavor['is_public']:
            explanation = _("Access list not available for public flavors.")
            raise webob.exc.HTTPNotFound(explanation=explanation)

        # private flavor to listed projects only
        return _marshall_flavor_access(flavor_id)


class FlavorActionController(wsgi.Controller):
    """The flavor access API controller for the OpenStack API."""

    def _check_body(self, body):
        if body is None or body == "":
            raise webob.exc.HTTPBadRequest(explanation=_("No request body"))

    def _get_flavor_refs(self, context):
        """Return a dictionary mapping flavorid to flavor_ref."""

        flavor_refs = flavors.get_all_flavors(context)
        rval = {}
        for name, obj in flavor_refs.iteritems():
            rval[obj['flavorid']] = obj
        return rval

    def _extend_flavor(self, flavor_rval, flavor_ref):
        key = "%s:is_public" % (FlavorAccess.alias)
        flavor_rval[key] = flavor_ref['is_public']

    @wsgi.extends
    def show(self, req, resp_obj, id):
        context = req.environ['nova.context']
        if authorize(context):
            # Attach our slave template to the response object
            resp_obj.attach(xml=FlavorTemplate())
            db_flavor = req.get_db_flavor(id)

            self._extend_flavor(resp_obj.obj['flavor'], db_flavor)

    @wsgi.extends
    def detail(self, req, resp_obj):
        context = req.environ['nova.context']
        if authorize(context):
            # Attach our slave template to the response object
            resp_obj.attach(xml=FlavorsTemplate())

            flavors = list(resp_obj.obj['flavors'])
            for flavor_rval in flavors:
                db_flavor = req.get_db_flavor(flavor_rval['id'])
                self._extend_flavor(flavor_rval, db_flavor)

    @wsgi.extends(action='create')
    def create(self, req, body, resp_obj):
        context = req.environ['nova.context']
        if authorize(context):
            # Attach our slave template to the response object
            resp_obj.attach(xml=FlavorTemplate())

            db_flavor = req.get_db_flavor(resp_obj.obj['flavor']['id'])

            self._extend_flavor(resp_obj.obj['flavor'], db_flavor)

    @wsgi.serializers(xml=FlavorAccessTemplate)
    @wsgi.action("addTenantAccess")
    def _addTenantAccess(self, req, id, body):
        context = req.environ['nova.context']
        authorize(context)
        self._check_body(body)

        vals = body['addTenantAccess']
        tenant = vals['tenant']

        try:
            flavors.add_flavor_access(id, tenant, context)
        except exception.FlavorAccessExists as err:
            raise webob.exc.HTTPConflict(explanation=err.format_message())

        return _marshall_flavor_access(id)

    @wsgi.serializers(xml=FlavorAccessTemplate)
    @wsgi.action("removeTenantAccess")
    def _removeTenantAccess(self, req, id, body):
        context = req.environ['nova.context']
        authorize(context)
        self._check_body(body)

        vals = body['removeTenantAccess']
        tenant = vals['tenant']

        try:
            flavors.remove_flavor_access(id, tenant, context)
        except exception.FlavorAccessNotFound as e:
            raise webob.exc.HTTPNotFound(explanation=e.format_message())

        return _marshall_flavor_access(id)


class FlavorAccess(extensions.V3APIExtensionBase):
    """Flavor access support."""

    name = "FlavorAccess"
    alias = ALIAS
    namespace = "http://docs.openstack.org/compute/ext/%s/api/v3" % ALIAS
    version = 1

    def get_resources(self):
        res = extensions.ResourceExtension(
            ALIAS,
            controller=FlavorAccessController(),
            parent=dict(member_name='flavor', collection_name='flavors'))

        return [res]

    def get_controller_extensions(self):
        extension = extensions.ControllerExtension(
                self, 'flavors', FlavorActionController())

        return [extension]