Clean up Deckhand 405/404 error handling

If a method is not allowed, Deckhand currently uses convoluted logic
to throw a 405. Instead, Deckhand should rely on falcon's native
logic which already does that.

This PS relies on falcon logic to throw a 404/405 when an endpoint
is invalid or if a HTTP verb is not support for an endpoint
(respectively).

This PS also adds a VersionsResource to Deckhand to allow information
about the API versions to be returned. This implementation is modeled
after Shipyard [0].

[0] c84e91bad1/shipyard_airflow/control/api.py (L32)

Change-Id: I805801892dbe1a6bca4d0ba5d445fee554c256f8
This commit is contained in:
Felipe Monteiro 2017-09-20 19:22:17 +01:00
parent 905ca1732b
commit 279418673a
6 changed files with 39 additions and 73 deletions

View File

@ -20,10 +20,10 @@ from oslo_log import log as logging
from deckhand.control import base
from deckhand.control import buckets
from deckhand.control import middleware
from deckhand.control import revision_documents
from deckhand.control import revision_tags
from deckhand.control import revisions
from deckhand.control import versions
from deckhand.db.sqlalchemy import api as db_api
CONF = cfg.CONF
@ -40,28 +40,6 @@ def _get_config_files(env=None):
return [os.path.join(dirname, config_file) for config_file in CONFIG_FILES]
def _get_routing_map():
ROUTING_MAP = {
'/api/v1.0/bucket/[A-za-z0-9\-]+/documents': ['PUT'],
'/api/v1.0/revisions': ['GET', 'DELETE'],
'/api/v1.0/revisions/[A-za-z0-9\-]+': ['GET'],
'/api/v1.0/revisions/[A-za-z0-9\-]+/tags': ['GET', 'DELETE'],
'/api/v1.0/revisions/[A-za-z0-9\-]+/tags/[A-za-z0-9\-]+': [
'GET', 'POST', 'DELETE'],
'/api/v1.0/revisions/[A-za-z0-9\-]+/documents': ['GET']
}
for route in ROUTING_MAP.keys():
# Denote the start of the regex with "^".
route_re = '^.*' + route
# Debite the end of the regex with "$". Allow for an optional "/" at
# the end of each request uri.
route_re = route_re + '[/]{0,1}$'
ROUTING_MAP[route_re] = ROUTING_MAP.pop(route)
return ROUTING_MAP
def start_api(state_manager=None):
"""Main entry point for initializing the Deckhand API service.
@ -77,9 +55,7 @@ def start_api(state_manager=None):
db_api.drop_db()
db_api.setup_db()
control_api = falcon.API(
request_type=base.DeckhandRequest,
middleware=[middleware.ContextMiddleware(_get_routing_map())])
control_api = falcon.API(request_type=base.DeckhandRequest)
v1_0_routes = [
('bucket/{bucket_name}/documents', buckets.BucketsResource()),
@ -95,4 +71,6 @@ def start_api(state_manager=None):
for path, res in v1_0_routes:
control_api.add_route(os.path.join('/api/v1.0', path), res)
control_api.add_route('/versions', versions.VersionsResource())
return control_api

View File

@ -16,9 +16,6 @@ import yaml
import falcon
from oslo_context import context
from oslo_log import log as logging
LOG = logging.getLogger(__name__)
class BaseResource(object):
@ -26,6 +23,7 @@ class BaseResource(object):
def on_options(self, req, resp):
self_attrs = dir(self)
methods = ['GET', 'HEAD', 'POST', 'PUT', 'DELETE', 'PATCH']
allowed_methods = []
@ -39,7 +37,7 @@ class BaseResource(object):
def to_yaml_body(self, dict_body):
"""Converts JSON body into YAML response body.
:dict_body: response body to be converted to YAML.
:param dict_body: response body to be converted to YAML.
:returns: YAML encoding of `dict_body`.
"""
if isinstance(dict_body, dict):

View File

@ -1,40 +0,0 @@
# Copyright 2017 AT&T Intellectual Property. All other 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.
import re
import falcon
class ContextMiddleware(object):
def __init__(self, routing_map):
self.routing_map = routing_map
def process_request(self, req, resp):
# Determine whether the method is allowed.
req_method = req.method
req_uri = req.uri
found = False
for route_pattern, allowed_methods in self.routing_map.items():
if re.match(route_pattern, req_uri):
if req_method not in allowed_methods:
raise falcon.HTTPMethodNotAllowed(allowed_methods)
else:
found = True
break
if not found:
raise falcon.HTTPMethodNotAllowed([])

View File

@ -0,0 +1,30 @@
# Copyright 2017 AT&T Intellectual Property. All other 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.
import falcon
from deckhand.control import base as api_base
class VersionsResource(api_base.BaseResource):
def on_get(self, req, resp):
resp.body = self.to_yaml_body({
'v1.0': {
'path': '/api/v1.0',
'status': 'stable'
}
})
resp.append_header('Content-Type', 'application/x-yaml')
resp.status = falcon.HTTP_200

View File

@ -172,13 +172,13 @@ class Document(BASE, DeckhandBase):
def register_models(engine):
"""Create database tables for all models with the given engine."""
models = [Bucket, Document, Revision]
models = [Bucket, Document, Revision, RevisionTag]
for model in models:
model.metadata.create_all(engine)
def unregister_models(engine):
"""Drop database tables for all models with the given engine."""
models = [Bucket, Document, Revision]
models = [Bucket, Document, Revision, RevisionTag]
for model in models:
model.metadata.drop_all(engine)

View File

@ -47,7 +47,7 @@ class TestApi(test_base.DeckhandTestCase):
self.assertEqual(mock_falcon_api, result)
mock_falcon.API.assert_called_once_with(
request_type=base.DeckhandRequest, middleware=[mock.ANY])
request_type=base.DeckhandRequest)
mock_falcon_api.add_route.assert_has_calls([
mock.call('/api/v1.0/bucket/{bucket_name}/documents',
self.buckets_resource()),