summaryrefslogtreecommitdiffstats
path: root/windriver/titanium_cloud/resource/views/capacity.py
blob: 0d44d0c45b76e36ae39018a77b9ebed0c9febea0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
# Copyright (c) 2017-2018 Wind River Systems, Inc.
#
# 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 logging
import json
import traceback

from rest_framework import status

from django.conf import settings
from common.exceptions import VimDriverNewtonException
from newton_base.util import VimDriverUtils

from keystoneauth1.exceptions import HttpError
from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView
from common.msapi import extsys


logger = logging.getLogger(__name__)


class CapacityCheck(APIView):

    def __init__(self):
        self._logger = logger

    def post(self, request, vimid=""):
        self._logger.info("vimid, data> %s, %s" % (vimid, request.data))
        self._logger.debug("META> %s" % request.META)

        hasEnoughResource = False
        try :
            resource_demand = request.data

            #get token:
            cloud_owner, regionid = extsys.decode_vim_id(vimid)
            interface = 'public'
            service = {'service_type': 'compute',
                       'interface': interface,
                       'region_id': regionid}

            tenant_name = None
            vim = VimDriverUtils.get_vim_info(vimid)
            sess = VimDriverUtils.get_session(vim, tenant_name)

            #get limit for this tenant
            req_resouce = "/limits"
            self._logger.info("check limits> URI:%s" % req_resouce)
            resp = sess.get(req_resouce, endpoint_filter=service)
            self._logger.info("check limits> status:%s" % resp.status_code)
            content = resp.json()
            compute_limits = content['limits']['absolute']
            self._logger.debug("check limits> resp data:%s" % content)

            #get total resource of this cloud region
            req_resouce = "/os-hypervisors/statistics"
            self._logger.info("check os-hypervisors statistics> URI:%s" % req_resouce)
            resp = sess.get(req_resouce, endpoint_filter=service)
            self._logger.info("check os-hypervisors statistics> status:%s" % resp.status_code)
            content = resp.json()
            hypervisor_statistics = content['hypervisor_statistics']
            self._logger.debug("check os-hypervisors statistics> resp data:%s" % content)

            #get storage limit for this tenant
            service['service_type'] = 'volumev2'
            req_resouce = "/limits"
            self._logger.info("check volumev2 limits> URI:%s" % req_resouce)
            resp = sess.get(req_resouce, endpoint_filter=service)
            self._logger.info("check volumev2> status:%s" % resp.status_code)
            content = resp.json()
            storage_limits = content['limits']['absolute']
            self._logger.debug("check volumev2> resp data:%s" % content)

            # compute actual available resource for this tenant
            remainVCPU = compute_limits['maxTotalCores'] - compute_limits['totalCoresUsed']

            if (compute_limits['maxTotalCores'] > hypervisor_statistics['vcpus']):
                if hypervisor_statistics['vcpus'] > compute_limits['totalCoresUsed']:
                    remainVCPU = hypervisor_statistics['vcpus'] - compute_limits['totalCoresUsed']
                else:
                    remainVCPU = 0

            remainMEM = compute_limits['maxTotalRAMSize'] - compute_limits['totalRAMUsed']
            if hypervisor_statistics['free_ram_mb'] > remainMEM:
                remainMEM = hypervisor_statistics['free_ram_mb']

            remainStorage = storage_limits['maxTotalVolumeGigabytes'] - storage_limits['totalGigabytesUsed']
            if (remainStorage < hypervisor_statistics['free_disk_gb']):
                remainStorage = hypervisor_statistics['free_disk_gb']

            # compare resource demanded with available
            if (int(resource_demand['vCPU']) >= remainVCPU):
                hasEnoughResource = False
            elif (int(resource_demand['Memory']) >= remainMEM):
                hasEnoughResource = False
            elif (int(resource_demand['Storage']) >= remainStorage):
                hasEnoughResource = False
            else:
                hasEnoughResource = True

            self._logger.info("RESP with data> result:%s" % hasEnoughResource)
            return Response(data={'result': hasEnoughResource}, status=status.HTTP_200_OK)
        except VimDriverNewtonException as e:
            self._logger.error("Plugin exception> status:%s,error:%s"
                                  % (e.status_code, e.content))
            return Response(data={'result': hasEnoughResource,'error': e.content}, status=e.status_code)
        except HttpError as e:
            self._logger.error("HttpError: status:%s, response:%s" % (e.http_status, e.response.json()))
            resp = e.response.json()
            resp.update({'result': hasEnoughResource})
            return Response(data=e.response.json(), status=e.http_status)
        except Exception as e:
            self._logger.error(traceback.format_exc())
            return Response(data={'result': hasEnoughResource, 'error': str(e)},
                            status=status.HTTP_500_INTERNAL_SERVER_ERROR)