summaryrefslogtreecommitdiffstats
path: root/share/newton_base/util.py
blob: b06529bb49d1abb5da815b90e00aa9adc9db7bde (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
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
# 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

from django.conf import settings
from django.core.cache import cache
from keystoneauth1.identity import v2 as keystone_v2
from keystoneauth1.identity import v3 as keystone_v3
from keystoneauth1 import session

from common.msapi import extsys

# profiler decoration
import cProfile
import pstats
import os

logger = logging.getLogger(__name__)


class VimDriverUtils(object):
    @staticmethod
    def get_vim_info(vimid):
        """
        Retrieve VIM information.

        :param vimid: VIM Identifier
        :return: VIM information
        """
        # TODO: get vim info from local cache firstly later from ESR
        return extsys.get_vim_by_id(vimid)

    @staticmethod
    def delete_vim_info(vimid):
        return extsys.delete_vim_by_id(vimid)

    @staticmethod
    def get_query_part(request):
        query = ""
        full_path = request.get_full_path()
        if '?' in full_path:
            _, query = full_path.split('?')
        return query

    @staticmethod
    def get_session(
            vim, tenant_id=None, tenant_name=None, auth_state=None):
        """
        get session object and optionally preload auth_state
        """
        auth = None

        params = {
            "auth_url": vim["url"],
            "username": vim["userName"],
            "password": vim["password"],
        }

        # tenantid takes precedence over tenantname
        if tenant_id:
            params["tenant_id"] = tenant_id
        else:
            # input tenant name takes precedence over the default one
            # from AAI data store
            params["tenant_name"] = (tenant_name if tenant_name
                                     else vim['tenant'])

        if '/v2' in params["auth_url"]:
            auth = keystone_v2.Password(**params)
        else:
            params["user_domain_name"] = vim["domain"]
            params["project_domain_name"] = vim["domain"]

            if 'tenant_id' in params:
                params["project_id"] = params.pop("tenant_id")
            if 'tenant_name' in params:
                params["project_name"] = params.pop("tenant_name")
            if '/v3' not in params["auth_url"]:
                params["auth_url"] = params["auth_url"] + "/v3",
            auth = keystone_v3.Password(**params)

        #preload auth_state which was acquired in last requests
        if auth_state:
           auth.set_auth_state(auth_state)

        return session.Session(auth=auth, verify=(vim['insecure']==False))

    @staticmethod
    def get_auth_state(session_obj):
        """
        Retrieve the authorization state
        :param session: OpenStack Session object
        :return: return a string dump of json object with token and
        resp_data of authentication request
        """
        auth = session_obj._auth_required(None, 'fetch a token')
        if auth:
            #trigger the authenticate request
            session_obj.get_auth_headers(auth)

            # norm_expires = utils.normalize_time(auth.expires)
            return auth.get_auth_state()

    @staticmethod
    def get_token_cache(token):
        """
        get auth_state and metadata fromm cache
        :param token:
        :return:
        """
        return cache.get(token), cache.get("meta_%s" % token)

    @staticmethod
    def update_token_cache(token, auth_state, metadata):
        """
        Stores into the cache the auth_state and metadata_catalog
        information.

        :param token: Base token to be used as an identifier
        :param auth_state: Authorization information
        :param metadata: Metadata Catalog information
        """
        if metadata and not cache.get(token):
            cache.set(
                token, auth_state, settings.CACHE_EXPIRATION_TIME)
            cache.set(
                "meta_%s" % token, metadata,
                settings.CACHE_EXPIRATION_TIME)

    @staticmethod
    def _replace_a_key(dict_obj, key_pair, reverse):
        old_key = key_pair[1] if reverse else key_pair[0]
        new_key = key_pair[0] if reverse else key_pair[1]

        old_value = dict_obj.pop(old_key, None)
        if old_value:
            dict_obj[new_key] = old_value

    @staticmethod
    def replace_key_by_mapping(dict_obj, mapping, reverse=False):
        for k in mapping:
            VimDriverUtils._replace_a_key(dict_obj, k, reverse)

    # profiler decoration
    @staticmethod
    def do_cprofile(filename):
        """
        Decorator for function profiling.
        """
        def wrapper(func):
            def profiled_func(*args, **kwargs):
                # Flag for do profiling or not.
                DO_PROF = True # os.getenv("PROFILING")
                if DO_PROF:
                    profile = cProfile.Profile()
                    profile.enable()
                    result = func(*args, **kwargs)
                    profile.disable()
                    # Sort stat by internal time.
                    sortby = "tottime"
                    ps = pstats.Stats(profile).sort_stats(sortby)
                    ps.dump_stats(filename)
                else:
                    result = func(*args, **kwargs)
                return result
            return profiled_func
        return wrapper


    @staticmethod
    def check_k8s_cluster(viminfo):
        """
        check if cloud region is k8s cluster
        """
        software_version = viminfo.get("cloud_extra_info_json", {})\
        .get("isystem", {}).get("software_version")

        is_k8s_cluster = False
        if software_version == "19.12":
            is_k8s_cluster = True
        elif software_version == "19.10":
            is_k8s_cluster = True

        return is_k8s_cluster