Fix issue of routing requests
[multicloud/framework.git] / multivimbroker / multivimbroker / forwarder / views.py
1 # Copyright 2017 Wind River Systems, 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 # See the License for the specific language governing permissions and
13 # limitations under the License.
14 import logging
15 import re
16
17 from django.http import HttpResponse
18 from django.views.decorators.csrf import csrf_exempt
19
20 from rest_framework import status
21
22 from multivimbroker.pub.utils.restcall import req_by_msb
23 from multivimbroker.pub.msapi.extsys import get_vim_by_id
24
25 logger = logging.getLogger(__name__)
26
27
28 @csrf_exempt
29 def route(request, vimid=''):
30     """ get vim info from vimid from local cache first
31         and then to ESR if cache miss
32     """
33     content = ""
34     status_code = status.HTTP_200_OK
35     try:
36         vim = get_vim_by_id(vimid)
37         if vim["type"] and vim["version"]:
38             pass
39
40     except Exception as e:
41         logger.error("get_vim_by_id, exception: %s" % e)
42         return HttpResponse("Not a valid VIM instance", status=status.HTTP_404_NOT_FOUND)
43
44     try:
45         if vim and vim["type"] == "openstack":
46             if vim["version"] == "kilo":
47                 multivimdriver = "multivim-kilo"
48             elif vim["version"] == "newton":
49                 multivimdriver = "multivim-newton"
50             else:
51                 # if vim type is openstack, use latest "newton" version as default
52                 multivimdriver = "multivim-newton"
53         elif vim and vim["type"] == "vmware":
54             multivimdriver = "multivim-vio"
55         else:
56             logger.error("wrong vim id: %s, return from extsys:%s" %
57                          vimid, vim)
58             return HttpResponse("Not support VIM type", status=status.HTTP_404_NOT_FOUND)
59
60         route_uri = re.sub('multivim', multivimdriver, request.get_full_path())
61
62         retcode, content, status_code = \
63             req_by_msb(route_uri, request.method, request.body)
64         if retcode != 0:
65             # Execptions are handled within req_by_msb
66             logger.error("Status code is %s, detail is %s.",
67                          status_code, content)
68     except Exception as e:
69         content = e
70         status_code = status.HTTP_500_INTERNAL_SERVER_ERROR
71         logger.error("exception: %s" % e)
72     return HttpResponse(content, status=status_code)