8f70c8baac54284e02aa7a72343f24d4b7b5e22f
[multicloud/framework.git] / multivimbroker / multivimbroker / forwarder / base.py
1 # Copyright (c) 2017 VMware, Inc.
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at:
6 #
7 #       http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
13 import logging
14
15 from django.http import HttpResponse
16 from rest_framework import status
17
18 import multivimbroker.pub.exceptions as exceptions
19 from multivimbroker.pub.utils.syscomm import getHeadersKeys
20 from multivimbroker.pub.utils.syscomm import getMultivimDriver
21 from multivimbroker.pub.utils.restcall import req_by_msb
22
23
24 logger = logging.getLogger(__name__)
25
26 class BaseHandler(object):
27
28     def _request(self,route_uri,method,body="",headers=None):
29
30         try:
31             retcode, content, status_code, resp = \
32                 req_by_msb(route_uri, method, body, headers)
33             if retcode != 0:
34                 # Execptions are handled within req_by_msb
35                 logger.error("Status code is %s, detail is %s.",
36                              status_code, content)
37
38         except exceptions.NotFound as e:
39             return HttpResponse(str(e), status=status.HTTP_404_NOT_FOUND)
40
41         except Exception as e:
42             content = e
43             status_code = status.HTTP_500_INTERNAL_SERVER_ERROR
44             logger.exception("exception: %s" % e)
45
46         response = HttpResponse(content, status=status_code)
47         for k in getHeadersKeys(resp):
48             response[k] = resp[k]
49         return response
50
51
52     def send(self,vimid,full_path,body,method,headers=None):
53
54             try:
55                 url = getMultivimDriver(vimid,full_path=full_path)
56
57             except exceptions.VimBrokerException as e:
58                 logging.exception("vimbroker exception: %s"%e)
59                 return HttpResponse(e.content,status=e.status_code)
60             except Exception as e:
61                 logging.exception("unkown exception: %s" %e)
62                 return HttpResponse(str(e),status=status.HTTP_500_INTERNAL_SERVER_ERROR)
63
64             return  self._request(url,method,body=body,headers=headers)
65