def application(environment, start_response):
    request = webob.Request(environment)
    response = webob.Response(text='Hello world!')
    return response(environment, start_response)
Beispiel #2
0
 def fake_app(req):
     return webob.Response(req.body)
Beispiel #3
0
 def __call__(self, req):
     context = req.environ['nova.context']
     api_request = req.environ['ec2.request']
     result = None
     try:
         result = api_request.invoke(context)
     except exception.InstanceNotFound as ex:
         LOG.info(_('InstanceNotFound raised: %s'),
                  unicode(ex),
                  context=context)
         ec2_id = ec2utils.id_to_ec2_id(ex.kwargs['instance_id'])
         message = ex.message % {'instance_id': ec2_id}
         return self._error(req, context, type(ex).__name__, message)
     except exception.VolumeNotFound as ex:
         LOG.info(_('VolumeNotFound raised: %s'),
                  unicode(ex),
                  context=context)
         ec2_id = ec2utils.id_to_ec2_vol_id(ex.kwargs['volume_id'])
         message = ex.message % {'volume_id': ec2_id}
         return self._error(req, context, type(ex).__name__, message)
     except exception.SnapshotNotFound as ex:
         LOG.info(_('SnapshotNotFound raised: %s'),
                  unicode(ex),
                  context=context)
         ec2_id = ec2utils.id_to_ec2_snap_id(ex.kwargs['snapshot_id'])
         message = ex.message % {'snapshot_id': ec2_id}
         return self._error(req, context, type(ex).__name__, message)
     except exception.NotFound as ex:
         LOG.info(_('NotFound raised: %s'), unicode(ex), context=context)
         return self._error(req, context, type(ex).__name__, unicode(ex))
     except exception.ApiError as ex:
         LOG.exception(_('ApiError raised: %s'),
                       unicode(ex),
                       context=context)
         if ex.code:
             return self._error(req, context, ex.code, unicode(ex))
         else:
             return self._error(req, context,
                                type(ex).__name__, unicode(ex))
     except exception.KeyPairExists as ex:
         LOG.debug(_('KeyPairExists raised: %s'),
                   unicode(ex),
                   context=context)
         return self._error(req, context, type(ex).__name__, unicode(ex))
     except exception.InvalidParameterValue as ex:
         LOG.debug(_('InvalidParameterValue raised: %s'),
                   unicode(ex),
                   context=context)
         return self._error(req, context, type(ex).__name__, unicode(ex))
     except exception.InvalidPortRange as ex:
         LOG.debug(_('InvalidPortRange raised: %s'),
                   unicode(ex),
                   context=context)
         return self._error(req, context, type(ex).__name__, unicode(ex))
     except exception.NotAuthorized as ex:
         LOG.info(_('NotAuthorized raised: %s'),
                  unicode(ex),
                  context=context)
         return self._error(req, context, type(ex).__name__, unicode(ex))
     except exception.InvalidRequest as ex:
         LOG.debug(_('InvalidRequest raised: %s'),
                   unicode(ex),
                   context=context)
         return self._error(req, context, type(ex).__name__, unicode(ex))
     except Exception as ex:
         extra = {'environment': req.environ}
         LOG.exception(_('Unexpected error raised: %s'),
                       unicode(ex),
                       extra=extra,
                       context=context)
         return self._error(
             req, context, 'UnknownError',
             _('An unknown error has occurred. '
               'Please try your request again.'))
     else:
         resp = webob.Response()
         resp.status = 200
         resp.headers['Content-Type'] = 'text/xml'
         resp.body = str(result)
         return resp
Beispiel #4
0
 def _get_webob_response(self):
     request = webob.Request.blank('/')
     response = webob.Response()
     response.request = request
     return response
Beispiel #5
0
 def __call__(self, environ, start_response):
     """Assert that headers are correctly set up when finally called."""
     resp = webob.Response()
     resp.body = six.b('SUCCESS')
     return resp(environ, start_response)
Beispiel #6
0
 def __call__(self, env, start_response):
     resp = webob.Response()
     resp.environ = env
     return resp(env, start_response)
Beispiel #7
0
    def delete(self, req, id):
        """Delete specified share network."""
        context = req.environ['manila.context']
        policy.check_policy(context, RESOURCE_NAME, 'delete')

        try:
            share_network = db_api.share_network_get(context, id)
        except exception.ShareNetworkNotFound as e:
            raise exc.HTTPNotFound(explanation=e.msg)

        share_instances = (
            db_api.share_instances_get_all_by_share_network(context, id)
        )
        if share_instances:
            msg = _("Can not delete share network %(id)s, it has "
                    "%(len)s share(s).") % {'id': id,
                                            'len': len(share_instances)}
            LOG.error(msg)
            raise exc.HTTPConflict(explanation=msg)

        # NOTE(ameade): Do not allow deletion of share network used by share
        # group
        sg_count = db_api.count_share_groups_in_share_network(context, id)
        if sg_count:
            msg = _("Can not delete share network %(id)s, it has %(len)s "
                    "share group(s).") % {'id': id, 'len': sg_count}
            LOG.error(msg)
            raise exc.HTTPConflict(explanation=msg)

        # NOTE(silvacarlose): Do not allow the deletion of share networks
        # if it still contains two or more subnets
        if self._share_network_contains_subnets(share_network):
            msg = _("The share network %(id)s has more than one subnet "
                    "attached. Please remove the subnets untill you have one "
                    "or no subnets remaining.") % {'id': id}
            LOG.error(msg)
            raise exc.HTTPConflict(explanation=msg)

        for subnet in share_network['share_network_subnets']:
            if not self._all_share_servers_are_auto_deletable(subnet):
                msg = _("The service cannot determine if there are any "
                        "non-managed shares on the share network subnet "
                        "%(id)s, so it cannot be deleted. Please contact the "
                        "cloud administrator to rectify.") % {
                    'id': subnet['id']}
                LOG.error(msg)
                raise exc.HTTPConflict(explanation=msg)

        for subnet in share_network['share_network_subnets']:
            for share_server in subnet['share_servers']:
                self.share_rpcapi.delete_share_server(context, share_server)

        db_api.share_network_delete(context, id)

        try:
            reservations = QUOTAS.reserve(
                context, project_id=share_network['project_id'],
                share_networks=-1, user_id=share_network['user_id'])
        except Exception:
            LOG.exception("Failed to update usages deleting "
                          "share-network.")
        else:
            QUOTAS.commit(context, reservations,
                          project_id=share_network['project_id'],
                          user_id=share_network['user_id'])
        return webob.Response(status_int=http_client.ACCEPTED)
 def fake_app(req, *args, **kwargs):
     resp = webob.Response()
     resp.status_int = 204
     return resp
Beispiel #9
0
 def attach_volume(self, request, body):
     return webob.Response(status_int=204)
 def fake_app(req, *args, **kwargs):
     self.assertNotIn(wsgi.API_VERSION_REQUEST_HEADER, req)
     resp = webob.Response()
     return resp
 def fake_app(req, *args, **kwargs):
     resp = webob.Response()
     resp.status_int = 204
     resp.headers['Vary'] = wsgi.API_VERSION_REQUEST_HEADER
     return resp
 def fake_app(req, *args, **kwargs):
     self.assertTrue(req.is_legacy_v2())
     resp = webob.Response()
     resp.status_int = 204
     return resp
Beispiel #13
0
 def func():
     return webob.Response(body=self.cache,
                           content_type='application/json')
Beispiel #14
0
        except TypeError:
            msg = _("Missing parameter dict")
            raise webob.exc.HTTPBadRequest(explanation=msg)
        except KeyError:
            msg = _("Address not specified")
            raise webob.exc.HTTPBadRequest(explanation=msg)

        try:
            instance = self.compute_api.get(context, id)
            self.compute_api.associate_floating_ip(context, instance, address)
        except exception.ApiError, e:
            raise webob.exc.HTTPBadRequest(explanation=e.message)
        except exception.NotAuthorized, e:
            raise webob.exc.HTTPUnauthorized()

        return webob.Response(status_int=202)

    @wsgi.action('removeFloatingIp')
    def _remove_floating_ip(self, req, id, body):
        """Dissociate floating_ip from an instance."""
        context = req.environ['nova.context']

        try:
            address = body['removeFloatingIp']['address']
        except TypeError:
            msg = _("Missing parameter dict")
            raise webob.exc.HTTPBadRequest(explanation=msg)
        except KeyError:
            msg = _("Address not specified")
            raise webob.exc.HTTPBadRequest(explanation=msg)
Beispiel #15
0
 def on_error(self, state, e):
     if state.request.method == 'OPTIONS':
         return webob.Response()
Beispiel #16
0
            msg = 'There was a problem while contacting the image scaler: %s' % \
                  error.reason
            resp = webob.exc.HTTPServiceUnavailable(msg)
            return resp

        # get the Content-Type.
        uinfo = upcopy.info()
        c_t = uinfo.gettype()
        content_length = uinfo.getheader('Content-Length', None)
        # sometimes Last-Modified isn't present; use now() when that happens.
        try:
            last_modified = time.mktime(uinfo.getdate('Last-Modified'))
        except TypeError:
            last_modified = time.mktime(time.localtime())

        resp = webob.Response(app_iter=upcopy, content_type=c_t)
        # add in the headers if we've got them
        for header in ['Content-Length', 'Content-Disposition', 'Last-Modified', 'Accept-Ranges']:
            if(uinfo.getheader(header)):
                resp.headers.add(header, uinfo.getheader(header))

        # also add CORS; see also our CORS middleware
        resp.headers.add('Access-Control-Allow-Origin', '*')

        return resp

    def handle_request(self, env, start_response):
        req = webob.Request(env)

        # Double (or triple, etc.) slashes in the URL should be ignored; collapse them. fixes bug 32864
        req.path_info = re.sub(r'/{2,}', '/', req.path_info)
Beispiel #17
0
    def _create_backup(self, req, id, body):
        """Backup a server instance.

        Images now have an `image_type` associated with them, which can be
        'snapshot' or the backup type, like 'daily' or 'weekly'.

        If the image_type is backup-like, then the rotation factor can be
        included and that will cause the oldest backups that exceed the
        rotation factor to be deleted.

        """
        context = req.environ["nova.context"]
        authorize(context, 'createBackup')
        entity = body["createBackup"]

        try:
            image_name = entity["name"]
            backup_type = entity["backup_type"]
            rotation = entity["rotation"]

        except KeyError as missing_key:
            msg = _("createBackup entity requires %s attribute") % missing_key
            raise exc.HTTPBadRequest(explanation=msg)

        except TypeError:
            msg = _("Malformed createBackup entity")
            raise exc.HTTPBadRequest(explanation=msg)

        try:
            rotation = int(rotation)
        except ValueError:
            msg = _("createBackup attribute 'rotation' must be an integer")
            raise exc.HTTPBadRequest(explanation=msg)
        if rotation < 0:
            msg = _("createBackup attribute 'rotation' must be greater "
                    "than or equal to zero")
            raise exc.HTTPBadRequest(explanation=msg)

        props = {}
        metadata = entity.get('metadata', {})
        common.check_img_metadata_properties_quota(context, metadata)
        try:
            props.update(metadata)
        except ValueError:
            msg = _("Invalid metadata")
            raise exc.HTTPBadRequest(explanation=msg)

        instance = common.get_instance(self.compute_api,
                                       context,
                                       id,
                                       want_objects=True)
        try:
            image = self.compute_api.backup(context,
                                            instance,
                                            image_name,
                                            backup_type,
                                            rotation,
                                            extra_properties=props)
        except exception.InstanceInvalidState as state_error:
            common.raise_http_conflict_for_instance_invalid_state(
                state_error, 'createBackup', id)

        resp = webob.Response(status_int=202)

        # build location of newly-created image entity if rotation is not zero
        if rotation > 0:
            image_id = str(image['id'])
            image_ref = os.path.join(req.application_url, 'images', image_id)
            resp.headers['Location'] = image_ref

        return resp
Beispiel #18
0
    def handle_request(self, env, start_response):
        req = webob.Request(env)

        # Double (or triple, etc.) slashes in the URL should be ignored; collapse them. fixes bug 32864
        req.path_info = re.sub(r'/{2,}', '/', req.path_info)

        # Keep a copy of the original request so we can ask the scalers for it
        reqorig = req.copy()

        # Containers have 5 components: project, language, repo, zone, and shard.
        # If there's no zone in the URL, the zone is assumed to be 'public' (for b/c).
        # Shard is optional (and configurable), and is only used for large containers.
        #
        # Projects are wikipedia, wikinews, etc.
        # Languages are en, de, fr, commons, etc.
        # Repos are local, timeline, etc.
        # Zones are public, thumb, temp, etc.
        # Shard is extracted from "hash paths" in the URL and is 2 hex digits.
        #
        # These attributes are mapped to container names in the form of either:
        # (a) proj-lang-repo-zone (if not sharded)
        # (b) proj-lang-repo-zone.shard (if sharded)
        # (c) global-data-repo-zone (if not sharded)
        # (d) global-data-repo-zone.shard (if sharded)
        #
        # Rewrite wiki-global URLs of these forms:
        # (a) http://upload.wikimedia.org/math/<relpath>
        #         => http://msfe/v1/AUTH_<hash>/global-data-math-render/<relpath>
        # (b) http://upload.wikimedia.org/<proj>/<lang>/math/<relpath> (legacy)
        #         => http://msfe/v1/AUTH_<hash>/global-data-math-render/<relpath>
        #
        # Rewrite wiki-relative URLs of these forms:
        # (a) http://upload.wikimedia.org/<proj>/<lang>/<relpath>
        #         => http://msfe/v1/AUTH_<hash>/<proj>-<lang>-local-public/<relpath>
        # (b) http://upload.wikimedia.org/<proj>/<lang>/archive/<relpath>
        #         => http://msfe/v1/AUTH_<hash>/<proj>-<lang>-local-public/archive/<relpath>
        # (c) http://upload.wikimedia.org/<proj>/<lang>/thumb/<relpath>
        #         => http://msfe/v1/AUTH_<hash>/<proj>-<lang>-local-thumb/<relpath>
        # (d) http://upload.wikimedia.org/<proj>/<lang>/thumb/archive/<relpath>
        #         => http://msfe/v1/AUTH_<hash>/<proj>-<lang>-local-thumb/archive/<relpath>
        # (e) http://upload.wikimedia.org/<proj>/<lang>/thumb/temp/<relpath>
        #         => http://msfe/v1/AUTH_<hash>/<proj>-<lang>-local-thumb/temp/<relpath>
        # (f) http://upload.wikimedia.org/<proj>/<lang>/temp/<relpath>
        #         => http://msfe/v1/AUTH_<hash>/<proj>-<lang>-local-temp/<relpath>
        # (g) http://upload.wikimedia.org/<proj>/<lang>/transcoded/<relpath>
        #         => http://msfe/v1/AUTH_<hash>/<proj>-<lang>-local-transcoded/<relpath>
        # (h) http://upload.wikimedia.org/<proj>/<lang>/timeline/<relpath>
        #         => http://msfe/v1/AUTH_<hash>/<proj>-<lang>-timeline-render/<relpath>

        # regular uploads
        match = re.match(r'^/(?P<proj>[^/]+)/(?P<lang>[^/]+)/((?P<zone>transcoded|thumb|temp)/)?(?P<path>((temp|archive)/)?[0-9a-f]/(?P<shard>[0-9a-f]{2})/.+)$', req.path)
        if match:
            proj  = match.group('proj')
            lang  = match.group('lang')
            repo  = 'local'  # the upload repo name is "local"
            # Get the repo zone (if not provided that means "public")
            zone  = (match.group('zone') if match.group('zone') else 'public')
            # Get the object path relative to the zone (and thus container)
            obj   = match.group('path')  # e.g. "archive/a/ab/..."
            shard = match.group('shard')

        # timeline renderings
        if match is None:
            # /wikipedia/en/timeline/a876297c277d80dfd826e1f23dbfea3f.png
            match = re.match(r'^/(?P<proj>[^/]+)/(?P<lang>[^/]+)/(?P<repo>timeline)/(?P<path>.+)$', req.path)
            if match:
                proj  = match.group('proj')  # wikipedia
                lang  = match.group('lang')  # en
                repo  = match.group('repo')  # timeline
                zone  = 'render'
                obj   = match.group('path')  # a876297c277d80dfd826e1f23dbfea3f.png
                shard = ''

        # math renderings
        if match is None:
            # /math/c/9/f/c9f2055dadfb49853eff822a453d9ceb.png
            # /wikipedia/en/math/c/9/f/c9f2055dadfb49853eff822a453d9ceb.png (legacy)
            match = re.match(r'^(/(?P<proj>[^/]+)/(?P<lang>[^/]+))?/(?P<repo>math)/(?P<path>(?P<shard1>[0-9a-f])/(?P<shard2>[0-9a-f])/.+)$', req.path)

            if match:
                proj  = 'global'
                lang  = 'data'
                repo  = match.group('repo')  # math
                zone  = 'render'
                obj   = match.group('path')  # c/9/f/c9f2055dadfb49853eff822a453d9ceb.png
                shard = match.group('shard1') + match.group('shard2')  # c9

        # score renderings
        if match is None:
            # /score/j/q/jqn99bwy8777srpv45hxjoiu24f0636/jqn99bwy.png
            # /score/override-midi/8/i/8i9pzt87wtpy45lpz1rox8wusjkt7ki.ogg
            match = re.match(r'^/(?P<repo>score)/(?P<path>.+)$', req.path)
            if match:
                proj  = 'global'
                lang  = 'data'
                repo  = match.group('repo')  # score
                zone  = 'render'
                obj   = match.group('path')  # j/q/jqn99bwy8777srpv45hxjoiu24f0636/jqn99bwy.png
                shard = ''

        if match is None:
            match = re.match(r'^/monitoring/(?P<what>.+)$', req.path)
            if match:
                what  = match.group('what')
                if what == 'frontend':
                    headers = {'Content-Type': 'application/octet-stream'}
                    resp = webob.Response(headers=headers, body="OK\n")
                elif what == 'backend':
                    req.host = '127.0.0.1:%s' % self.bind_port
                    req.path_info = "/v1/%s/monitoring/backend" % self.account

                    app_iter = self._app_call(env)
                    status = self._get_status_int()
                    headers = self._response_headers

                    resp = webob.Response(status=status, headers=headers, app_iter=app_iter)
                else:
                    resp = webob.exc.HTTPNotFound('Monitoring type not found "%s"' % (req.path))
                return resp(env, start_response)

        if match is None:
            match = re.match(r'^/(?P<path>[^/]+)?$', req.path)
            # /index.html /favicon.ico /robots.txt etc.
            # serve from a default "root" container
            if match:
                path  = match.group('path')
                if not path:
                    path = 'index.html'

                req.host = '127.0.0.1:%s' % self.bind_port
                req.path_info = "/v1/%s/root/%s" % (self.account, path)

                app_iter = self._app_call(env)
                status = self._get_status_int()
                headers = self._response_headers

                resp = webob.Response(status=status, headers=headers, app_iter=app_iter)
                return resp(env, start_response)

        # Internally rewrite the URL based on the regex it matched...
        if match:
            # Get the per-project "conceptual" container name, e.g. "<proj><lang><repo><zone>"
            container = "%s-%s-%s-%s" % (proj, lang, repo, zone)
            # Add 2-digit shard to the container if it is supposed to be sharded.
            # We may thus have an "actual" container name like "<proj><lang><repo><zone>.<shard>"
            if ((self.shard_containers == 'all') or
               ((self.shard_containers == 'some') and (container in self.shard_container_list))):
                container += ".%s" % shard

            # Save a url with just the account name in it.
            req.path_info = "/v1/%s" % (self.account)
            port = self.bind_port
            req.host = '127.0.0.1:%s' % port
            url = req.url[:]
            # Create a path to our object's name.
            req.path_info = "/v1/%s/%s/%s" % (self.account, container, urllib2.unquote(obj))
            #self.logger.warn("new path is %s" % req.path_info)

            # do_start_response just remembers what it got called with,
            # because our 404 handler will generate a different response.
            app_iter = self._app_call(env)
            status = self._get_status_int()
            headers = self._response_headers

            if 200 <= status < 300 or status == 304:
                # We have it! Just return it as usual.
                #headers['X-Swift-Proxy']= `headers`
                return webob.Response(status=status, headers=headers,
                                      app_iter=app_iter)(env, start_response)
            elif status == 404:
                # only send thumbs to the 404 handler; just return a 404 for everything else.
                if repo == 'local' and zone == 'thumb':
                    resp = self.handle404(reqorig, url, container, obj)
                    return resp(env, start_response)
                else:
                    resp = webob.exc.HTTPNotFound('File not found: %s' % req.path)
                    return resp(env, start_response)
            elif status == 401:
                # if the Storage URL is invalid or has expired we'll get this error.
                resp = webob.exc.HTTPUnauthorized('Token may have timed out')
                return resp(env, start_response)
            else:
                resp = webob.exc.HTTPNotImplemented('Unknown Status: %s' % (status))
                return resp(env, start_response)
        else:
            resp = webob.exc.HTTPNotFound('Regexp failed to match URI: "%s"' % (req.path))
            return resp(env, start_response)
    def _invoke(self, method, context, id, group_name):
        with translate_exceptions():
            instance = self.compute_api.get(context, id)
            method(context, instance, group_name)

        return webob.Response(status_int=202)
Beispiel #20
0
    def _add_floating_ip(self, req, id, body):
        """Associate floating_ip to an instance."""
        context = req.environ['nova.context']
        authorize(context)

        address = body['addFloatingIp']['address']

        instance = common.get_instance(self.compute_api,
                                       context,
                                       id,
                                       want_objects=True)
        cached_nwinfo = compute_utils.get_nw_info_for_instance(instance)
        if not cached_nwinfo:
            msg = _('No nw_info cache associated with instance')
            raise webob.exc.HTTPBadRequest(explanation=msg)

        fixed_ips = cached_nwinfo.fixed_ips()
        if not fixed_ips:
            msg = _('No fixed ips associated to instance')
            raise webob.exc.HTTPBadRequest(explanation=msg)

        fixed_address = None
        if 'fixed_address' in body['addFloatingIp']:
            fixed_address = body['addFloatingIp']['fixed_address']
            for fixed in fixed_ips:
                if fixed['address'] == fixed_address:
                    break
            else:
                msg = _('Specified fixed address not assigned to instance')
                raise webob.exc.HTTPBadRequest(explanation=msg)

        if not fixed_address:
            fixed_address = fixed_ips[0]['address']
            if len(fixed_ips) > 1:
                LOG.warning(
                    _LW('multiple fixed_ips exist, using the first: '
                        '%s'), fixed_address)

        try:
            self.network_api.associate_floating_ip(context,
                                                   instance,
                                                   floating_address=address,
                                                   fixed_address=fixed_address)
        except exception.FloatingIpAssociated:
            msg = _('floating ip is already associated')
            raise webob.exc.HTTPBadRequest(explanation=msg)
        except exception.NoFloatingIpInterface:
            msg = _('l3driver call to add floating ip failed')
            raise webob.exc.HTTPBadRequest(explanation=msg)
        except exception.FloatingIpNotFoundForAddress:
            msg = _('floating ip not found')
            raise webob.exc.HTTPNotFound(explanation=msg)
        except exception.Forbidden as e:
            raise webob.exc.HTTPForbidden(explanation=e.format_message())
        except Exception as e:
            msg = _('Unable to associate floating ip %(address)s to '
                    'fixed ip %(fixed_address)s for instance %(id)s. '
                    'Error: %(error)s') % ({
                        'address': address,
                        'fixed_address': fixed_address,
                        'id': id,
                        'error': e
                    })
            LOG.exception(msg)
            raise webob.exc.HTTPBadRequest(explanation=msg)

        return webob.Response(status_int=202)
Beispiel #21
0
    def _add_floating_ip(self, req, id, body):
        """Associate floating_ip to an instance."""
        context = req.environ['nova.context']
        authorize(context)

        address = body['addFloatingIp']['address']

        instance = common.get_instance(self.compute_api, context, id,
                                       expected_attrs=['flavor'])
        cached_nwinfo = compute_utils.get_nw_info_for_instance(instance)
        if not cached_nwinfo:
            LOG.warning(
                _LW('Info cache is %r during associate with no nw_info cache'),
                    instance.info_cache, instance=instance)
            msg = _('No nw_info cache associated with instance')
            raise webob.exc.HTTPBadRequest(explanation=msg)

        fixed_ips = cached_nwinfo.fixed_ips()
        if not fixed_ips:
            msg = _('No fixed IPs associated to instance')
            raise webob.exc.HTTPBadRequest(explanation=msg)

        fixed_address = None
        if 'fixed_address' in body['addFloatingIp']:
            fixed_address = body['addFloatingIp']['fixed_address']
            for fixed in fixed_ips:
                if fixed['address'] == fixed_address:
                    break
            else:
                msg = _('Specified fixed address not assigned to instance')
                raise webob.exc.HTTPBadRequest(explanation=msg)

        if not fixed_address:
            try:
                fixed_address = next(ip['address'] for ip in fixed_ips
                                     if netaddr.valid_ipv4(ip['address']))
            except StopIteration:
                msg = _('Unable to associate floating IP %(address)s '
                        'to any fixed IPs for instance %(id)s. '
                        'Instance has no fixed IPv4 addresses to '
                        'associate.') % (
                        {'address': address, 'id': id})
                raise webob.exc.HTTPBadRequest(explanation=msg)
            if len(fixed_ips) > 1:
                LOG.warning(_LW('multiple fixed_ips exist, using the first '
                                'IPv4 fixed_ip: %s'), fixed_address)

        try:
            self.network_api.associate_floating_ip(context, instance,
                                  floating_address=address,
                                  fixed_address=fixed_address)
        except exception.FloatingIpAssociated:
            msg = _('floating IP is already associated')
            raise webob.exc.HTTPBadRequest(explanation=msg)
        except exception.NoFloatingIpInterface:
            msg = _('l3driver call to add floating IP failed')
            raise webob.exc.HTTPBadRequest(explanation=msg)
        except exception.InstanceUnknownCell as e:
            raise webob.exc.HTTPNotFound(explanation=e.format_message())
        except exception.FloatingIpNotFoundForAddress:
            msg = _('floating IP not found')
            raise webob.exc.HTTPNotFound(explanation=msg)
        except exception.Forbidden as e:
            raise webob.exc.HTTPForbidden(explanation=e.format_message())
        except Exception as e:
            msg = _('Unable to associate floating IP %(address)s to '
                    'fixed IP %(fixed_address)s for instance %(id)s. '
                    'Error: %(error)s') % (
                    {'address': address, 'fixed_address': fixed_address,
                     'id': id, 'error': e})
            LOG.exception(msg)
            raise webob.exc.HTTPBadRequest(explanation=msg)

        return webob.Response(status_int=202)
Beispiel #22
0
 def __call__(self, req):
     res = webob.Response()
     res.status = '200'
     res.headers['X-Test-Success'] = 'True'
     return res
 def update_all(self, req, volume_id, body):
     self._ensure_min_version(req, METADATA_MICRO_VERSION)
     if not self._validate_etag(req, volume_id):
         return webob.Response(status_int=http_client.PRECONDITION_FAILED)
     return super(Controller, self).update_all(req, volume_id,
                                               body)
Beispiel #24
0
    def test_default(self):
        serializer = wsgi.ResponseHeaderSerializer()
        response = webob.Response()
        serializer.serialize(response, {'v': '123'}, 'fake')

        self.assertEqual(response.status_int, 200)
    def get_user_state(self, request, suffix=''):
        """ GET all user-specific data, and any applicable feedback """
        data = self._get_user_state()

        return webob.Response(body=json.dumps(data),
                              content_type='application/json')
Beispiel #26
0
 def _abort_unauthorized():
     return webob.Response(json_encode({'faultstring': 'Unauthorized'}),
                           status=401)
Beispiel #27
0
 def fake_app(req):
     self.context = req.environ['tacker.context']
     return webob.Response()
Beispiel #28
0
 def _abort_other_errors():
     return webob.Response(json_encode(
         {'faultstring': 'Internal Server Error'}),
                           status=500)
Beispiel #29
0
def make_response(**kwargs):
    body = kwargs.pop('body', None)
    return webob.Response(body)
Beispiel #30
0
    def _action_create_image(self, req, id, body):
        """Snapshot a server instance."""
        context = req.environ['nova.context']
        entity = body.get("create_image", {})

        image_name = entity.get("name")

        if not image_name:
            msg = _("create_image entity requires name attribute")
            raise exc.HTTPBadRequest(explanation=msg)

        props = {}
        metadata = entity.get('metadata', {})
        common.check_img_metadata_properties_quota(context, metadata)
        try:
            props.update(metadata)
        except ValueError:
            msg = _("Invalid metadata")
            raise exc.HTTPBadRequest(explanation=msg)

        instance = self._get_server(context, req, id)

        bdms = objects.BlockDeviceMappingList.get_by_instance_uuid(
            context, instance.uuid)

        try:
            if self.compute_api.is_volume_backed_instance(
                    context, instance, bdms):
                img = instance['image_ref']
                if not img:
                    props = bdms.root_metadata(context,
                                               self.compute_api.image_api,
                                               self.compute_api.volume_api)
                    image_meta = {'properties': props}
                else:
                    image_meta = self.compute_api.image_api.get(context, img)

                image = self.compute_api.snapshot_volume_backed(
                    context,
                    instance,
                    image_meta,
                    image_name,
                    extra_properties=props)
            else:
                image = self.compute_api.snapshot(context,
                                                  instance,
                                                  image_name,
                                                  extra_properties=props)
        except exception.InstanceInvalidState as state_error:
            common.raise_http_conflict_for_instance_invalid_state(
                state_error, 'create_image')
        except exception.Invalid as err:
            raise exc.HTTPBadRequest(explanation=err.format_message())

        # build location of newly-created image entity
        image_id = str(image['id'])
        image_ref = glance.generate_image_url(image_id)

        resp = webob.Response(status_int=202)
        resp.headers['Location'] = image_ref
        return resp