Port parsable error middleware from Ironic
Partial-Bug: 1411871 Change-Id: Ibe67d06f0d3a685dc08b896d466dfa94513c5d10
This commit is contained in:
parent
aa45150fd4
commit
c645023c70
|
@ -15,6 +15,7 @@ import pecan
|
|||
|
||||
from magnum.api import auth
|
||||
from magnum.api import config as api_config
|
||||
from magnum.api import middleware
|
||||
|
||||
# Register options for the service
|
||||
API_SERVICE_OPTS = [
|
||||
|
@ -52,6 +53,7 @@ def setup_app(config=None):
|
|||
app = pecan.make_app(
|
||||
app_conf.pop('root'),
|
||||
logging=getattr(config, 'logging', {}),
|
||||
wrap_app=middleware.ParsableErrorMiddleware,
|
||||
**app_conf
|
||||
)
|
||||
|
||||
|
|
|
@ -13,8 +13,11 @@
|
|||
# under the License.
|
||||
|
||||
from magnum.api.middleware import auth_token
|
||||
from magnum.api.middleware import parsable_error
|
||||
|
||||
|
||||
AuthTokenMiddleware = auth_token.AuthTokenMiddleware
|
||||
ParsableErrorMiddleware = parsable_error.ParsableErrorMiddleware
|
||||
|
||||
__all__ = (AuthTokenMiddleware)
|
||||
__all__ = (AuthTokenMiddleware,
|
||||
ParsableErrorMiddleware)
|
||||
|
|
|
@ -0,0 +1,91 @@
|
|||
# -*- encoding: utf-8 -*-
|
||||
#
|
||||
# Copyright ? 2012 New Dream Network, LLC (DreamHost)
|
||||
#
|
||||
# Author: Doug Hellmann <doug.hellmann@dreamhost.com>
|
||||
#
|
||||
# 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.
|
||||
"""
|
||||
Middleware to replace the plain text message body of an error
|
||||
response with one formatted so the client can parse it.
|
||||
|
||||
Based on pecan.middleware.errordocument
|
||||
"""
|
||||
|
||||
import json
|
||||
from xml import etree as et
|
||||
|
||||
import webob
|
||||
|
||||
from magnum.openstack.common._i18n import _
|
||||
from magnum.openstack.common._i18n import _LE
|
||||
from magnum.openstack.common import log
|
||||
|
||||
LOG = log.getLogger(__name__)
|
||||
|
||||
|
||||
class ParsableErrorMiddleware(object):
|
||||
"""Replace error body with something the client can parse."""
|
||||
def __init__(self, app):
|
||||
self.app = app
|
||||
|
||||
def __call__(self, environ, start_response):
|
||||
# Request for this state, modified by replace_start_response()
|
||||
# and used when an error is being reported.
|
||||
state = {}
|
||||
|
||||
def replacement_start_response(status, headers, exc_info=None):
|
||||
"""Overrides the default response to make errors parsable."""
|
||||
try:
|
||||
status_code = int(status.split(' ')[0])
|
||||
state['status_code'] = status_code
|
||||
except (ValueError, TypeError): # pragma: nocover
|
||||
raise Exception(_(
|
||||
'ErrorDocumentMiddleware received an invalid '
|
||||
'status %s') % status)
|
||||
else:
|
||||
if (state['status_code'] // 100) not in (2, 3):
|
||||
# Remove some headers so we can replace them later
|
||||
# when we have the full error message and can
|
||||
# compute the length.
|
||||
headers = [(h, v)
|
||||
for (h, v) in headers
|
||||
if h not in ('Content-Length', 'Content-Type')
|
||||
]
|
||||
# Save the headers in case we need to modify them.
|
||||
state['headers'] = headers
|
||||
return start_response(status, headers, exc_info)
|
||||
|
||||
app_iter = self.app(environ, replacement_start_response)
|
||||
if (state['status_code'] // 100) not in (2, 3):
|
||||
req = webob.Request(environ)
|
||||
if (req.accept.best_match(['application/json', 'application/xml'])
|
||||
== 'application/xml'):
|
||||
try:
|
||||
# simple check xml is valid
|
||||
body = [et.ElementTree.tostring(
|
||||
et.ElementTree.fromstring('<error_message>'
|
||||
+ '\n'.join(app_iter)
|
||||
+ '</error_message>'))]
|
||||
except et.ElementTree.ParseError as err:
|
||||
LOG.error(_LE('Error parsing HTTP response: %s'), err)
|
||||
body = ['<error_message>%s' % state['status_code']
|
||||
+ '</error_message>']
|
||||
state['headers'].append(('Content-Type', 'application/xml'))
|
||||
else:
|
||||
body = [json.dumps({'error_message': '\n'.join(app_iter)})]
|
||||
state['headers'].append(('Content-Type', 'application/json'))
|
||||
state['headers'].append(('Content-Length', len(body[0])))
|
||||
else:
|
||||
body = app_iter
|
||||
return body
|
|
@ -136,7 +136,7 @@ class TestPatch(api_base.FunctionalTest):
|
|||
expect_errors=True)
|
||||
self.assertEqual(404, response.status_int)
|
||||
self.assertEqual('application/json', response.content_type)
|
||||
self.assertTrue(response.json['faultstring'])
|
||||
self.assertTrue(response.json['error_message'])
|
||||
|
||||
@mock.patch.object(timeutils, 'utcnow')
|
||||
def test_replace_singular(self, mock_utcnow):
|
||||
|
@ -185,7 +185,7 @@ class TestPatch(api_base.FunctionalTest):
|
|||
expect_errors=True)
|
||||
self.assertEqual('application/json', response.content_type)
|
||||
self.assertEqual(400, response.status_code)
|
||||
self.assertTrue(response.json['faultstring'])
|
||||
self.assertTrue(response.json['error_message'])
|
||||
|
||||
def test_add_root(self):
|
||||
name = 'bay_model_example_B'
|
||||
|
@ -208,7 +208,7 @@ class TestPatch(api_base.FunctionalTest):
|
|||
expect_errors=True)
|
||||
self.assertEqual('application/json', response.content_type)
|
||||
self.assertEqual(400, response.status_int)
|
||||
self.assertTrue(response.json['faultstring'])
|
||||
self.assertTrue(response.json['error_message'])
|
||||
|
||||
def test_add_multi(self):
|
||||
json = [
|
||||
|
@ -241,7 +241,7 @@ class TestPatch(api_base.FunctionalTest):
|
|||
expect_errors=True)
|
||||
self.assertEqual(400, response.status_int)
|
||||
self.assertEqual('application/json', response.content_type)
|
||||
self.assertTrue(response.json['faultstring'])
|
||||
self.assertTrue(response.json['error_message'])
|
||||
|
||||
|
||||
class TestPost(api_base.FunctionalTest):
|
||||
|
@ -297,7 +297,7 @@ class TestDelete(api_base.FunctionalTest):
|
|||
expect_errors=True)
|
||||
self.assertEqual(404, response.status_int)
|
||||
self.assertEqual('application/json', response.content_type)
|
||||
self.assertTrue(response.json['faultstring'])
|
||||
self.assertTrue(response.json['error_message'])
|
||||
|
||||
def test_delete_baymodel_with_bay(self):
|
||||
baymodel = obj_utils.create_test_baymodel(self.context)
|
||||
|
@ -306,12 +306,12 @@ class TestDelete(api_base.FunctionalTest):
|
|||
expect_errors=True)
|
||||
self.assertEqual(400, response.status_int)
|
||||
self.assertEqual('application/json', response.content_type)
|
||||
self.assertTrue(response.json['faultstring'])
|
||||
self.assertIn(baymodel.uuid, response.json['faultstring'])
|
||||
self.assertTrue(response.json['error_message'])
|
||||
self.assertIn(baymodel.uuid, response.json['error_message'])
|
||||
|
||||
def test_delete_baymodel_not_found(self):
|
||||
uuid = utils.generate_uuid()
|
||||
response = self.delete('/baymodels/%s' % uuid, expect_errors=True)
|
||||
self.assertEqual(404, response.status_int)
|
||||
self.assertEqual('application/json', response.content_type)
|
||||
self.assertTrue(response.json['faultstring'])
|
||||
self.assertTrue(response.json['error_message'])
|
||||
|
|
Loading…
Reference in New Issue