~gandelman-a/ubuntu/precise/nova/UCA_2012.2.1

« back to all changes in this revision

Viewing changes to nova/api/direct.py

  • Committer: Package Import Robot
  • Author(s): Chuck Short
  • Date: 2012-05-24 13:12:53 UTC
  • mfrom: (1.1.55)
  • Revision ID: package-import@ubuntu.com-20120524131253-ommql08fg1en06ut
Tags: 2012.2~f1-0ubuntu1
* New upstream release.
* Prepare for quantal:
  - Dropped debian/patches/upstream/0006-Use-project_id-in-ec2.cloud._format_image.patch
  - Dropped debian/patches/upstream/0005-Populate-image-properties-with-project_id-again.patch
  - Dropped debian/patches/upstream/0004-Fixed-bug-962840-added-a-test-case.patch
  - Dropped debian/patches/upstream/0003-Allow-unprivileged-RADOS-users-to-access-rbd-volumes.patch
  - Dropped debian/patches/upstream/0002-Stop-libvirt-test-from-deleting-instances-dir.patch
  - Dropped debian/patches/upstream/0001-fix-bug-where-nova-ignores-glance-host-in-imageref.patch 
  - Dropped debian/patches/0001-fix-useexisting-deprecation-warnings.patch
* debian/control: Add python-keystone as a dependency. (LP: #907197)
* debian/patches/kombu_tests_timeout.patch: Refreshed.
* debian/nova.conf, debian/nova-common.postinst: Convert to new ini
  file configuration
* debian/patches/nova-manage_flagfile_location.patch: Refreshed

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# vim: tabstop=4 shiftwidth=4 softtabstop=4
2
 
 
3
 
# Copyright 2010 United States Government as represented by the
4
 
# Administrator of the National Aeronautics and Space Administration.
5
 
# All Rights Reserved.
6
 
#
7
 
#    Licensed under the Apache License, Version 2.0 (the "License"); you may
8
 
#    not use this file except in compliance with the License. You may obtain
9
 
#    a copy of the License at
10
 
#
11
 
#         http://www.apache.org/licenses/LICENSE-2.0
12
 
#
13
 
#    Unless required by applicable law or agreed to in writing, software
14
 
#    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
15
 
#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
16
 
#    License for the specific language governing permissions and limitations
17
 
#    under the License.
18
 
 
19
 
"""Public HTTP interface that allows services to self-register.
20
 
 
21
 
The general flow of a request is:
22
 
    - Request is parsed into WSGI bits.
23
 
    - Some middleware checks authentication.
24
 
    - Routing takes place based on the URL to find a controller.
25
 
      (/controller/method)
26
 
    - Parameters are parsed from the request and passed to a method on the
27
 
      controller as keyword arguments.
28
 
      - Optionally 'json' is decoded to provide all the parameters.
29
 
    - Actual work is done and a result is returned.
30
 
    - That result is turned into json and returned.
31
 
 
32
 
"""
33
 
 
34
 
import inspect
35
 
import urllib
36
 
 
37
 
import routes
38
 
import webob
39
 
 
40
 
import nova.api.openstack.wsgi
41
 
from nova import context
42
 
from nova import exception
43
 
from nova import utils
44
 
from nova import wsgi
45
 
 
46
 
 
47
 
# Global storage for registering modules.
48
 
ROUTES = {}
49
 
 
50
 
 
51
 
def register_service(path, handle):
52
 
    """Register a service handle at a given path.
53
 
 
54
 
    Services registered in this way will be made available to any instances of
55
 
    nova.api.direct.Router.
56
 
 
57
 
    :param path: `routes` path, can be a basic string like "/path"
58
 
    :param handle: an object whose methods will be made available via the api
59
 
 
60
 
    """
61
 
    ROUTES[path] = handle
62
 
 
63
 
 
64
 
class Router(wsgi.Router):
65
 
    """A simple WSGI router configured via `register_service`.
66
 
 
67
 
    This is a quick way to attach multiple services to a given endpoint.
68
 
    It will automatically load the routes registered in the `ROUTES` global.
69
 
 
70
 
    TODO(termie): provide a paste-deploy version of this.
71
 
 
72
 
    """
73
 
 
74
 
    def __init__(self, mapper=None):
75
 
        if mapper is None:
76
 
            mapper = routes.Mapper()
77
 
 
78
 
        self._load_registered_routes(mapper)
79
 
        super(Router, self).__init__(mapper=mapper)
80
 
 
81
 
    def _load_registered_routes(self, mapper):
82
 
        for route in ROUTES:
83
 
            mapper.connect('/%s/{action}' % route,
84
 
                           controller=ServiceWrapper(ROUTES[route]))
85
 
 
86
 
 
87
 
class DelegatedAuthMiddleware(wsgi.Middleware):
88
 
    """A simple and naive authentication middleware.
89
 
 
90
 
    Designed mostly to provide basic support for alternative authentication
91
 
    schemes, this middleware only desires the identity of the user and will
92
 
    generate the appropriate nova.context.RequestContext for the rest of the
93
 
    application. This allows any middleware above it in the stack to
94
 
    authenticate however it would like while only needing to conform to a
95
 
    minimal interface.
96
 
 
97
 
    Expects two headers to determine identity:
98
 
     - X-OpenStack-User
99
 
     - X-OpenStack-Project
100
 
 
101
 
    This middleware is tied to identity management and will need to be kept
102
 
    in sync with any changes to the way identity is dealt with internally.
103
 
 
104
 
    """
105
 
 
106
 
    def process_request(self, request):
107
 
        os_user = request.headers['X-OpenStack-User']
108
 
        os_project = request.headers['X-OpenStack-Project']
109
 
        context_ref = context.RequestContext(user_id=os_user,
110
 
                                             project_id=os_project)
111
 
        request.environ['openstack.context'] = context_ref
112
 
 
113
 
 
114
 
class JsonParamsMiddleware(wsgi.Middleware):
115
 
    """Middleware to allow method arguments to be passed as serialized JSON.
116
 
 
117
 
    Accepting arguments as JSON is useful for accepting data that may be more
118
 
    complex than simple primitives.
119
 
 
120
 
    In this case we accept it as urlencoded data under the key 'json' as in
121
 
    json=<urlencoded_json> but this could be extended to accept raw JSON
122
 
    in the POST body.
123
 
 
124
 
    Filters out the parameters `self`, `context` and anything beginning with
125
 
    an underscore.
126
 
 
127
 
    """
128
 
 
129
 
    def process_request(self, request):
130
 
        if 'json' not in request.params:
131
 
            return
132
 
 
133
 
        params_json = request.params['json']
134
 
        params_parsed = utils.loads(params_json)
135
 
        params = {}
136
 
        for k, v in params_parsed.iteritems():
137
 
            if k in ('self', 'context'):
138
 
                continue
139
 
            if k.startswith('_'):
140
 
                continue
141
 
            params[k] = v
142
 
 
143
 
        request.environ['openstack.params'] = params
144
 
 
145
 
 
146
 
class PostParamsMiddleware(wsgi.Middleware):
147
 
    """Middleware to allow method arguments to be passed as POST parameters.
148
 
 
149
 
    Filters out the parameters `self`, `context` and anything beginning with
150
 
    an underscore.
151
 
 
152
 
    """
153
 
 
154
 
    def process_request(self, request):
155
 
        params_parsed = request.params
156
 
        params = {}
157
 
        for k, v in params_parsed.iteritems():
158
 
            if k in ('self', 'context'):
159
 
                continue
160
 
            if k.startswith('_'):
161
 
                continue
162
 
            params[k] = v
163
 
 
164
 
        request.environ['openstack.params'] = params
165
 
 
166
 
 
167
 
class Reflection(object):
168
 
    """Reflection methods to list available methods.
169
 
 
170
 
    This is an object that expects to be registered via register_service.
171
 
    These methods allow the endpoint to be self-describing. They introspect
172
 
    the exposed methods and provide call signatures and documentation for
173
 
    them allowing quick experimentation.
174
 
 
175
 
    """
176
 
 
177
 
    def __init__(self):
178
 
        self._methods = {}
179
 
        self._controllers = {}
180
 
 
181
 
    def _gather_methods(self):
182
 
        """Introspect available methods and generate documentation for them."""
183
 
        methods = {}
184
 
        controllers = {}
185
 
        for route, handler in ROUTES.iteritems():
186
 
            controllers[route] = handler.__doc__.split('\n')[0]
187
 
            for k in dir(handler):
188
 
                if k.startswith('_'):
189
 
                    continue
190
 
                f = getattr(handler, k)
191
 
                if not callable(f):
192
 
                    continue
193
 
 
194
 
                # bunch of ugly formatting stuff
195
 
                argspec = inspect.getargspec(f)
196
 
                args = [x for x in argspec[0]
197
 
                        if x != 'self' and x != 'context']
198
 
                defaults = argspec[3] and argspec[3] or []
199
 
                args_r = list(reversed(args))
200
 
                defaults_r = list(reversed(defaults))
201
 
 
202
 
                args_out = []
203
 
                while args_r:
204
 
                    if defaults_r:
205
 
                        args_out.append((args_r.pop(0),
206
 
                                         repr(defaults_r.pop(0))))
207
 
                    else:
208
 
                        args_out.append((str(args_r.pop(0)),))
209
 
 
210
 
                # if the method accepts keywords
211
 
                if argspec[2]:
212
 
                    args_out.insert(0, ('**%s' % argspec[2],))
213
 
 
214
 
                if f.__doc__:
215
 
                    short_doc = f.__doc__.split('\n')[0]
216
 
                    doc = f.__doc__
217
 
                else:
218
 
                    short_doc = doc = _('not available')
219
 
 
220
 
                methods['/%s/%s' % (route, k)] = {
221
 
                        'short_doc': short_doc,
222
 
                        'doc': doc,
223
 
                        'name': k,
224
 
                        'args': list(reversed(args_out))}
225
 
 
226
 
        self._methods = methods
227
 
        self._controllers = controllers
228
 
 
229
 
    def get_controllers(self, context):
230
 
        """List available controllers."""
231
 
        if not self._controllers:
232
 
            self._gather_methods()
233
 
 
234
 
        return self._controllers
235
 
 
236
 
    def get_methods(self, context):
237
 
        """List available methods."""
238
 
        if not self._methods:
239
 
            self._gather_methods()
240
 
 
241
 
        method_list = self._methods.keys()
242
 
        method_list.sort()
243
 
        methods = {}
244
 
        for k in method_list:
245
 
            methods[k] = self._methods[k]['short_doc']
246
 
        return methods
247
 
 
248
 
    def get_method_info(self, context, method):
249
 
        """Get detailed information about a method."""
250
 
        if not self._methods:
251
 
            self._gather_methods()
252
 
        return self._methods[method]
253
 
 
254
 
 
255
 
class ServiceWrapper(object):
256
 
    """Wrapper to dynamically provide a WSGI controller for arbitrary objects.
257
 
 
258
 
    With lightweight introspection allows public methods on the object to
259
 
    be accessed via simple WSGI routing and parameters and serializes the
260
 
    return values.
261
 
 
262
 
    Automatically used be nova.api.direct.Router to wrap registered instances.
263
 
 
264
 
    """
265
 
 
266
 
    def __init__(self, service_handle):
267
 
        self.service_handle = service_handle
268
 
 
269
 
    @webob.dec.wsgify(RequestClass=nova.api.openstack.wsgi.Request)
270
 
    def __call__(self, req):
271
 
        arg_dict = req.environ['wsgiorg.routing_args'][1]
272
 
        action = arg_dict['action']
273
 
        del arg_dict['action']
274
 
 
275
 
        context = req.environ['openstack.context']
276
 
        # allow middleware up the stack to override the params
277
 
        params = {}
278
 
        if 'openstack.params' in req.environ:
279
 
            params = req.environ['openstack.params']
280
 
 
281
 
        # TODO(termie): do some basic normalization on methods
282
 
        method = getattr(self.service_handle, action)
283
 
 
284
 
        # NOTE(vish): make sure we have no unicode keys for py2.6.
285
 
        params = dict([(str(k), v) for (k, v) in params.iteritems()])
286
 
        result = method(context, **params)
287
 
 
288
 
        if result is None or isinstance(result, basestring):
289
 
            return result
290
 
 
291
 
        try:
292
 
            content_type = req.best_match_content_type()
293
 
            serializer = {
294
 
              'application/xml': nova.api.openstack.wsgi.XMLDictSerializer(),
295
 
              'application/json': nova.api.openstack.wsgi.JSONDictSerializer(),
296
 
            }[content_type]
297
 
            return serializer.serialize(result)
298
 
        except Exception, e:
299
 
            raise exception.Error(_("Returned non-serializeable type: %s")
300
 
                                  % result)
301
 
 
302
 
 
303
 
class Limited(object):
304
 
    __notdoc = """Limit the available methods on a given object.
305
 
 
306
 
    (Not a docstring so that the docstring can be conditionally overridden.)
307
 
 
308
 
    Useful when defining a public API that only exposes a subset of an
309
 
    internal API.
310
 
 
311
 
    Expected usage of this class is to define a subclass that lists the allowed
312
 
    methods in the 'allowed' variable.
313
 
 
314
 
    Additionally where appropriate methods can be added or overwritten, for
315
 
    example to provide backwards compatibility.
316
 
 
317
 
    The wrapping approach has been chosen so that the wrapped API can maintain
318
 
    its own internal consistency, for example if it calls "self.create" it
319
 
    should get its own create method rather than anything we do here.
320
 
 
321
 
    """
322
 
 
323
 
    _allowed = None
324
 
 
325
 
    def __init__(self, proxy):
326
 
        self._proxy = proxy
327
 
        if not self.__doc__:  # pylint: disable=E0203
328
 
            self.__doc__ = proxy.__doc__
329
 
        if not self._allowed:
330
 
            self._allowed = []
331
 
 
332
 
    def __getattr__(self, key):
333
 
        """Only return methods that are named in self._allowed."""
334
 
        if key not in self._allowed:
335
 
            raise AttributeError()
336
 
        return getattr(self._proxy, key)
337
 
 
338
 
    def __dir__(self):
339
 
        """Only return methods that are named in self._allowed."""
340
 
        return [x for x in dir(self._proxy) if x in self._allowed]
341
 
 
342
 
 
343
 
class Proxy(object):
344
 
    """Pretend a Direct API endpoint is an object.
345
 
 
346
 
    This is mostly useful in testing at the moment though it should be easily
347
 
    extendable to provide a basic API library functionality.
348
 
 
349
 
    In testing we use this to stub out internal objects to verify that results
350
 
    from the API are serializable.
351
 
 
352
 
    """
353
 
 
354
 
    def __init__(self, app, prefix=None):
355
 
        self.app = app
356
 
        self.prefix = prefix
357
 
 
358
 
    def __do_request(self, path, context, **kwargs):
359
 
        req = wsgi.Request.blank(path)
360
 
        req.method = 'POST'
361
 
        req.body = urllib.urlencode({'json': utils.dumps(kwargs)})
362
 
        req.environ['openstack.context'] = context
363
 
        resp = req.get_response(self.app)
364
 
        try:
365
 
            return utils.loads(resp.body)
366
 
        except Exception:
367
 
            return resp.body
368
 
 
369
 
    def __getattr__(self, key):
370
 
        if self.prefix is None:
371
 
            return self.__class__(self.app, prefix=key)
372
 
 
373
 
        def _wrapper(context, **kwargs):
374
 
            return self.__do_request('/%s/%s' % (self.prefix, key),
375
 
                                     context,
376
 
                                     **kwargs)
377
 
        _wrapper.func_name = key
378
 
        return _wrapper