cuk_cluster_info.py 8.09 KB
Newer Older
qunfeng qiu's avatar
qunfeng qiu committed
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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
@Descripttion: CUK集群信息查询
@Author: guohb65
@Email: guohb65@chinaunicom.cn
@Date: 22022/7/11 10:21
@LastEditors: guohb65
@LastEditTime: 2022/7/11 10:21
'''
import json
import os

import requests
import urllib3

from cucc_common_pkg.util_pkg.common_func import CommonFunc
from cucc_common_pkg.util_pkg.const import RequestMethod, ConstGen, ResponseCode

CUK_DOMAIN = "CUK_DOMAIN"
CUK_SVC_TIMEOUT = "CUK_SVC_TIMEOUT"
ACCESS_TOKEN = "accessToken"
CUK_URL_REGIONS = "/regions/"
CUK_URL_CLUSTER_URL = "/k8s/clusters"
CUK_URL_VERSION = "/v1"
CUK_URL_PREFIX = "/cuk"
CUK_URL_ADMIN_TOKEN = "adminToken"
CUK_KEY_API_SERVER = "apiserver"
CUK_KEY_NETWORK = "network"
CUK_KEY_VPC = "vpc"
CUK_KEY_ADMIN_TOKEN = "AdminToken"


class CukClusterInfo(object):

    def __init__(self, login_cookie=None):
        env_dist = os.environ
        common_mount_path = env_dist.get(ConstGen.COMMON_MOUNT_PATH)
        common_conf_file = open(common_mount_path, 'r')
        common_data_json = json.loads(common_conf_file.read())
        common_conf_file.close()
        self.cuk_domain = common_data_json.get(CUK_DOMAIN)
        if CUK_SVC_TIMEOUT in common_data_json:
            self.cuk_svc_timeout = int(common_data_json.get(CUK_SVC_TIMEOUT))
        else:
            self.cuk_svc_timeout = 3
        self.login_cookie = login_cookie

    def get_cuk_list(self, regions):
        request_url = self.cuk_domain + CUK_URL_PREFIX + CUK_URL_REGIONS + regions + CUK_URL_CLUSTER_URL
        urllib3.disable_warnings()
        try:
            resp = requests.request(RequestMethod.GET.value, request_url, cookies=self.login_cookie,
                                    timeout=self.cuk_svc_timeout, verify=False)
        except Exception as e:
            print("CUK请求异常:" + e.__str__())
            ret_data = {ConstGen.CODE: ResponseCode.SysError.value, ConstGen.MESSAGE: "CUK访问异常"}
            return False, json.dumps(ret_data, ensure_ascii=False)
        resp_code = resp.status_code
        if resp_code == 200:
            if ConstGen.CONTENT_TYPE_JSON in resp.headers.get(ConstGen.CONTENT_TYPE) and resp.text is not None:
                resp_json = json.loads(resp.text)
                if resp_json[ConstGen.CODE] == ResponseCode.OK.value:
                    cluster_list = resp_json["data"]
                    cluster_data = []
                    for cluster in cluster_list:
                        # apiservers = cluster.get(CUK_KEY_API_SERVER)
                        # apiserver_list = apiservers.split(";")
                        # apiserver = apiserver_list[0]
                        # if apiserver is not "":
                        #     apiserver_tuple = apiserver.split(":")
                        #     cluster_ip = apiserver_tuple[1][2:]
                        #     cluster_port = apiserver_tuple[2]
                        post_handle_cluster = {"cluster_name": cluster.get("name"), "cluster_ip": "",
                                               "cluster_port": "", "cluster_type": "CUK",
                                               "cluster_apiserver": "", "cluster_apiservers": ""}
                        cluster_data.append(post_handle_cluster)
                    return True, cluster_data
                else:
                    return False, resp.text
        else:
            ret_data = {ConstGen.CODE: ResponseCode.SysError.value, ConstGen.MESSAGE: resp.text}
            return False, json.dumps(ret_data, ensure_ascii=False)

    def list_cuk_cluster(self, regions):
        ret_tuple = self.get_cuk_list(regions)
        if ret_tuple[0]:
            return CommonFunc().fabricate_response_data(ConstGen.SUCCESS_CODE, ResponseCode.OK.value,
                                                        ConstGen.SUCCESS_STR, None, ret_tuple[1])
        else:
            return CommonFunc().fabricate_response_data(ConstGen.FAIL_CODE, ResponseCode.Failure.value, ret_tuple[1])

    def get_cuk_info(self, region_id, cluster_name):
        cluster_type = "CUK"
        cuk_info = self.get_cuk_rest_info(region_id, cluster_name)
        token = self.get_cuk_token(region_id, cluster_name)
        if cuk_info is not None and token is not None:
            api_servers = json.loads(cuk_info).get(CUK_KEY_API_SERVER)
            apiserver_list = api_servers.split(";")
            api_server = apiserver_list[0]
            network = json.loads(cuk_info).get(CUK_KEY_NETWORK)
            vpc = json.loads(cuk_info).get(CUK_KEY_VPC)
            if type(api_server) is str and type(token) is str:
                apiserver = api_server.split(":")
                cluster_ip = apiserver[1][2:]
                cluster_port = apiserver[2]
                cluster_info = {"cluster_type": cluster_type, "cluster_ip": cluster_ip, "cluster_port": cluster_port,
                                "cluster_token": token, "cluster_apiserver": api_server,
                                "cluster_apiservers": apiserver_list}
                if type(network) is str:
                    cluster_info["cluster_network"] = network
                if type(vpc) is str:
                    cluster_info["cluster_vpc"] = vpc
            else:
                cluster_info = {}
        else:
            cluster_info = {}
        print(cluster_info)
        return cluster_info

    def get_cuk_apiserver(self, regions, cluster_name):
        request_url = self.cuk_domain + CUK_URL_PREFIX + CUK_URL_REGIONS + regions + CUK_URL_CLUSTER_URL + "/" + cluster_name
        print(request_url)
        urllib3.disable_warnings()
        try:
            resp = requests.request(RequestMethod.GET.value, request_url, cookies=self.login_cookie, verify=False)
        except Exception as e:
            print("cuk请求异常:" + e.__str__())
            return e.__str__()
        resp_code = resp.status_code
        if resp_code == 200:
            if ConstGen.CONTENT_TYPE_JSON in resp.headers.get(ConstGen.CONTENT_TYPE) and resp.text is not None:
                resp_json = json.loads(resp.text)
                apiservers = resp_json.get(CUK_KEY_API_SERVER)
                apiserver_list = apiservers.split(";")
                return apiserver_list[0]
            else:
                return None
        else:
            return None

    def get_cuk_rest_info(self, regions, cluster_name):
        if self.login_cookie is not None:
            request_url = self.cuk_domain + CUK_URL_PREFIX + CUK_URL_REGIONS + regions + CUK_URL_CLUSTER_URL + "/" + cluster_name
            print(request_url)
            urllib3.disable_warnings()
            try:
                resp = requests.request(RequestMethod.GET.value, request_url, cookies=self.login_cookie, verify=False)
                print(resp.text)
            except Exception as e:
                print("cuk请求异常:" + e.__str__())
                return None
            resp_code = resp.status_code
            if resp_code == 200:
                if ConstGen.CONTENT_TYPE_JSON in resp.headers.get(ConstGen.CONTENT_TYPE) and resp.text is not None:
                    return resp.text
                else:
                    return None
            else:
                return None
        else:
            return None

    def get_cuk_token(self, regions, cluster_name):
        if self.login_cookie is not None:
            request_url = self.cuk_domain + CUK_URL_PREFIX + CUK_URL_REGIONS + regions + CUK_URL_CLUSTER_URL + "/" + cluster_name \
                          + "/" + CUK_URL_ADMIN_TOKEN
            urllib3.disable_warnings()
            try:
                resp = requests.request(RequestMethod.GET.value, request_url, cookies=self.login_cookie, verify=False)

            except Exception as e:
                print("cuk请求异常:" + e.__str__())
                return None
            resp_code = resp.status_code
            if resp_code == 200:
                if ConstGen.CONTENT_TYPE_JSON in resp.headers.get(ConstGen.CONTENT_TYPE) and resp.text is not None:
                    resp_json = json.loads(resp.text)
                    return resp_json.get(CUK_KEY_ADMIN_TOKEN)
                else:
                    return None
            else:
                return None
        else:
            return None