heat内部异常如何转换为HTTP异常返回给客户端

来源:互联网 发布:linux挂载盘到home好吗 编辑:程序博客网 时间:2024/05/29 16:00

heat engine服务在处理请求时,遇到异常情况,抛出的是内部自定义的异常类型,定义在heat/common/exception.py。

而heat api需要将这些异常转换为HTTP异常结果,也就是带有错误码的异常结果,再按照HTTP协议返回给客户端。


例如,如果用heat -d stack-show命令查询一个不存在的stack,返回的HTTP消息结果如下:

DEBUG (session) RESP: [404] date: Tue, 13 Oct 2015 11:42:50 GMT connection: keep-alive content-type: application/json; charset=UTF-8 content-length: 551 x-openstack-request-id: req-6707f1b3-6fbe-45bd-ac4f-9cc235a5b7e1 RESP BODY: {"explanation": "The resource could not be found.", "code": 404, "error": {"message": "The Stack (non-exist) could not be found.", "traceback": "Traceback (most recent call last):\n\n  File \"/opt/stack/heat/heat/common/context.py\", line 293, in wrapped\n    return func(self, ctx, *args, **kwargs)\n\n  File \"/opt/stack/heat/heat/engine/service.py\", line 430, in identify_stack\n    raise exception.StackNotFound(stack_name=stack_name)\n\nStackNotFound: The Stack (non-exist) could not be found.\n", "type": "StackNotFound"}, "title": "Not Found"}

从上面的异常堆栈结果可以直观的看出,engine抛出的异常类型是exception.StackNotFound,而客户端实际收到的结果是404,也就是类型为HTTPNotFound的异常。


那么heat api是如何将engine抛出的异常转换为HTTP异常的呢?

先来看看heat engine处理RPC请求的接口如何截获内部异常。

查看EngineService实现的RPC处理接口,每个接口都有一个装饰器@context.request_context。

context.request_context的实现如下:

def request_context(func):    @six.wraps(func)    def wrapped(self, ctx, *args, **kwargs):        try:            return func(self, ctx, *args, **kwargs)        except exception.HeatException:            raise oslo_messaging.rpc.dispatcher.ExpectedException()    return wrapped

很明显,request_context封装了真正的处理接口,并且会截获内部HeatException异常。

然后,继续抛出oslo定义的ExpectedException异常,ExpectedException的实现很简单:

class ExpectedException(Exception):    def __init__(self):        self.exc_info = sys.exc_info()
就是通过sys.exc_info获取当前异常的信息。

在oslo_messaging的RPC分发函数_dispatch_and_reply中,会截获此异常,并将异常结果返回给heat api:

        try:            incoming.reply(self._dispatch(incoming.ctxt,                                          incoming.message,                                          executor_callback))        except ExpectedException as e:            incoming.reply(failure=e.exc_info, log_failure=False)

到这里,异常信息就返回给了api。


接着看heat api如何处理engine返回的异常。

这里不关注RPC client如何将engine返回的异常信息转换为相应异常类型,只需要关注api如何处理这些异常。

heat api有一个faultwrap中间件,异常类型的转换其实就是由这个中间件处理的。

查看faultwrap处理请求的逻辑:

    def process_request(self, req):        try:            return req.get_response(self.application)        except Exception as exc:            return req.get_response(Fault(self._error(exc)))
可以看到,所有抛出的异常都会在这里被截获,然后通过_error函数进行处理。

_error函数的主要作用就是将heat内部的异常转换为HTTP异常。
查看faultwrap的实现,里面有一个字典成员error_map,形式如下:

    error_map = {        'AttributeError': webob.exc.HTTPBadRequest,        'ActionInProgress': webob.exc.HTTPConflict,        'ValueError': webob.exc.HTTPBadRequest,        'EntityNotFound': webob.exc.HTTPNotFound,        'StackNotFound': webob.exc.HTTPNotFound,        'NotFound': webob.exc.HTTPNotFound,        ...    }
虽然这里只列出了部分字典内容,但也能很明显理解出这就是定义的内部异常与HTTP异常的对应关系。
_error函数就是利用该字典进行的异常转换。


最后,转换后的HTTP异常会由req.get_response处理,进而返回给客户端。

0 0
原创粉丝点击