kubernetes-client-Kubernetes-helm.py

v1

from kubernetes import client, config
import requests
from requests.packages.urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
import socket
import paramiko
import re
 
import socket
import paramiko
 
class SSHConnection(object):
    def __init__(self,host='10.6.0.50',port=22,username='ubuntu',pwd='bktencent', pkey='/home/ubuntu/.ssh/id_rsa'):
        if pkey is None and pwd is None:
            raise Exception('私钥或者密码必须有一个不为空')
        self.host = host
        self.port = port
        self.username = username
        self.pwd = pwd
        self.key = paramiko.RSAKey.from_private_key_file(pkey)
        self._k = None
 
    def close(self):
        ssh.close()
        pass
 
    def cmd(self,command):
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh.connect(self.host, self.port, username=self.username, pkey=self.key)
        # ssh._transport = self.__transport
        command = 'set -e\n' + command
        stdin,stdout,stderr = ssh.exec_command(command)
        result = stdout.read()
        out = result.decode(encoding="utf-8")
        return out
 
# client_ssh  = SSHConnection()
# cmd = 'ls'
# r1 = client_ssh.cmd(cmd)
# print(r1)
 
 
class Pingcode(object):
    def __init__(self, app_name=['flow','box','example','gantt','todo','charm','goals','jira-importer','pingcode','portal','alarm','atlas','charm-sky','daedalus','hulk','ladon','preview','prophet','admin','agile','devops','githubapp','gitlab','hydra','iris','marketplace','open','pipeline','plan','pontus','testhub','tracking','typhon','wiki-gaea','wiki-sky','wiki-agile','wiki-okr','siren','tartarus','teams-hydra-admin','teams-hydra-h5','worktile-com','worktile-com-test' ]):
        pass
 
 
class Python_helm(Pingcode):
    """
    # 获取证书有效token : kubectl describe secret/$(kubectl get secret -nkube-system |grep admin|awk '{print $1}') -nkube-system
    """
    def __init__(self, host="10.6.0.50", port=6443, ssl=False, token = "eyJhbGciOiJSUzI1NiIsImtpZCI6Imloc0IyLVptV2J4VU5NRDJSUWk2cjVsNmtfMU5LcDhaRnY2VDcteDd1NDQifQ.eyJpc3MiOiJrdWJlcm5ldGVzL3NlcnZpY2VhY2NvdW50Iiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9uYW1lc3BhY2UiOiJrdWJlLXN5c3RlbSIsImt1YmVybmV0ZXMuaW8vc2VydmljZWFjY291bnQvc2VjcmV0Lm5hbWUiOiJ0aWxsZXItdG9rZW4tOW5rZHgiLCJrdWJlcm5ldGVzLmlvL3NlcnZpY2VhY2NvdW50L3NlcnZpY2UtYWNjb3VudC5uYW1lIjoidGlsbGVyIiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9zZXJ2aWNlLWFjY291bnQudWlkIjoiMGQxOGI1ZGEtYzExNS00YTY0LWFhYTEtNDhiMTVmNjdiMmNjIiwic3ViIjoic3lzdGVtOnNlcnZpY2VhY2NvdW50Omt1YmUtc3lzdGVtOnRpbGxlciJ9.uijhor3I0W381bQPxVBDqK297-sMWmfZYyS_hZvfdBJktqf4ZuoMJCaR3-wHu29aXqQdjazX3-j0qlopSyfndBjJRg4ajLNa_TTNz6QB3IUkjeH10MmdJDr8W7HPw3WI3-GFFUBG7dCo6YsHHe5aC43972zS7w79JI2IjsTtDsK79gfg1II5CG9tHc00o_zV6SuI2nM8j_R_BByPHuoMYU_d5l1oYwCnb7Bhb2mkwcyA4QqlvY5kbEiWrNbvxE3Jz8wPsRFkVxuMA1-N-43DGEDzoq2Gqd1GjXrnZNmblmm15hxwSQrpH2lMbHziUk9yGMuQ6JEevYzHs31Bpu6lbQ"):
            self.host = host
            self.token = token
            self.port = port
            self.ssl = ssl
 
    def telnet(self):
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        try:
            s.connect((self.host, self.port))
            s.shutdown(2)
            # print('%s:%d is used' % (self.host,self.port))
            return True
        except Exception as e:
            # print('%s:%d is unused' % (self.host, self.port))
            return False
 
 
    def login(self):
        if Python_helm().telnet():
            client_ip = "https://" + str(self.host) + ":" + str(self.port)
            configuration = client.Configuration()
            configuration.host = client_ip
            configuration.verify_ssl = False # self.ssl
            configuration.api_key = {"authorization": "Bearer " + self.token}
            client.Configuration.set_default(configuration)
            core_api = client.CoreV1Api()
            # print(core_api.list_namespace())
            return core_api
 
 
    # @property
    # def show_login(self):
    #     pass
 
 
    def show_namespace(self):
        date = []
        core_api = Python_helm().login()
        for ns in core_api.list_namespace().items:
            name = ns.metadata.name
            labels = ns.metadata.labels
            create_time = ns.metadata.creation_timestamp
            namespace = {'name': name, 'labels': labels, 'create_time': create_time}
            date.append(name)
            # print(name)
        return date
 
 
    def show_release(self, namespace='default'):
        # core_api = Python_helm().login()
        if namespace in Python_helm().show_namespace():
            print('{} -> namespace is Exits'.format(namespace))
            data = []
            deplpyment_name = []
            core_api = client.AppsV1Api()
            for dp in core_api.list_namespaced_deployment(namespace=namespace).items:
                name = dp.metadata.name
                namespace = dp.metadata.namespace
                replicas = dp.spec.replicas
                available_replicas = ( 0 if dp.status.available_replicas is None else dp.status.available_replicas)
                labels = dp.metadata.labels
                selector = dp.spec.selector.match_labels
                if len(dp.spec.template.spec.containers) > 1:
                    images = ""
                    n = 1
                    for c in dp.spec.template.spec.containers:
                        status = ("运行中" if dp.status.conditions[0].status == "True" else "异常")
                        image = c.image
                        images += "[%s]: %s / %s" % (n, image, status)
                        images += "<br>"
                        n += 1
                else:
                    status = (
                        "运行中" if dp.status.conditions[0].status == "True" else "异常")
                    image = dp.spec.template.spec.containers[0].image
                    images = "%s / %s" % (image, status)
 
                create_time = dp.metadata.creation_timestamp
                dp = {"name": name, "namespace": namespace, "replicas":replicas,
                             "available_replicas":available_replicas , "labels":labels, "selector":selector,
                             "images":images, "create_time": create_time}
                data.append(dp)
                deplpyment_name.append(name)
            #print(deplpyment_name)
            return deplpyment_name
 
 
    @staticmethod
    def rollback_release(search_release, namespace='default'):
        """
        pipe 上面的应用名称就是 : deployment名称也是helm release名称
        """
        # dp = Python_helm().show_release(namespace=namespace)
        # print(dp, '0000000000' * 10)
        ssh = SSHConnection()
        cmd_helm_name = "sudo /yc/bin/helm/helm list --namespace={}".format(namespace) + " | awk '{}'".format('NR>1') + "| awk '{print $1}'"
        cmd_helm_version = "sudo /yc/bin/helm/helm list --namespace={}".format(namespace) + " | awk '{}'".format('NR>1') + "| awk '{print $1}'"
        # command = f'/root/Kubernetes-study/kubernetes_configure/heml/linux-amd64/helm list -n {}'
 
        try:
            release = []
            # user_save = str(search_release) + "-" +  str(namespace)
            # print(user_save)
            # search = search_release.split('-')
            # print(search)
            # if "agile" in search:
            r1 = ssh.cmd(cmd_helm_name)
 
            release.append(r1.replace("\n",","))
            release_list = release[0].split(",")
            # print(release_list)
 
            a = Pingcode()
            a.app(release_name=release_list, search_release=search_release)
 
        except Exception as e:
            print(e)
 
from collections import Counter
 
class Pingcode(object):
 
    @staticmethod
    def app(release_name:list, search_release:str):
        app_name = ['flow', 'box', 'example', 'gantt', 'todo', 'charm', 'goals', 'jira', 'pingcode', 'portal',
                    'alarm', 'atlas', 'charm-sky', 'daedalus', 'hulk', 'ladon', 'preview', 'prophet', 'admin', 'agile',
                    'devops', 'githubapp', 'gitlab', 'hydra', 'iris', 'marketplace', 'open', 'pipeline', 'plan',
                    'pontus', 'testhub', 'tracking', 'typhon', 'wiki-gaea', 'wiki-sky', 'wiki-agile', 'wiki-okr',
                    'siren', 'tartarus', 'teams-hydra-admin', 'teams-hydra-h5', 'worktile-com', 'worktile-com-test']
 
        try:
            # 将应用名称转换成列表元素
            if isinstance(search_release, str):
                search = search_release.split('-')
                number = len(search)
                # print(search, number)
 
 
            # if isinstance(release_name, (str, list)):
            #     # for i in range(0, number):
            #     #     print(search[i])
            #     #     if app_name[str(search[i])]:
            #     #         print(app_name[str(search[i])])
            #     #     break
            #     pass
 
            newli = list(set(search)) + list(set(app_name))
            count = Counter(newli)
            same, diff = [], []
            for i in count.keys():
                if (count.get(i) >= 2):
                    same.append(i)
                else:
                    diff.append(i)
            print(same)
 
            # print("same is {},diff is {}".format(same, diff))
            for i in release_name:
                result = re.findall(str(same[0]), i)
                if result:
                    print(i)
        except Exception as e:
            print(e, '回滚失败,可能是应用名称与原名称列表未对应')
 
 
# a = A()
# search_release = 'pc-goals-sky-test'
# a.app(release_name=release_list, search_release=search_release)
 
 
a = Python_helm(host="10.6.0.50", port=6443, ssl=False, token = "eyJhbGciOiJSUzI1NiIsImtpZCI6Imloc0IyLVptV2J4VU5NRDJSUWk2cjVsNmtfMU5LcDhaRnY2VDcteDd1NDQifQ.eyJpc3MiOiJrdWJlcm5ldGVzL3NlcnZpY2VhY2NvdW50Iiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9uYW1lc3BhY2UiOiJrdWJlLXN5c3RlbSIsImt1YmVybmV0ZXMuaW8vc2VydmljZWFjY291bnQvc2VjcmV0Lm5hbWUiOiJ0aWxsZXItdG9rZW4tOW5rZHgiLCJrdWJlcm5ldGVzLmlvL3NlcnZpY2VhY2NvdW50L3NlcnZpY2UtYWNjb3VudC5uYW1lIjoidGlsbGVyIiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9zZXJ2aWNlLWFjY291bnQudWlkIjoiMGQxOGI1ZGEtYzExNS00YTY0LWFhYTEtNDhiMTVmNjdiMmNjIiwic3ViIjoic3lzdGVtOnNlcnZpY2VhY2NvdW50Omt1YmUtc3lzdGVtOnRpbGxlciJ9.uijhor3I0W381bQPxVBDqK297-sMWmfZYyS_hZvfdBJktqf4ZuoMJCaR3-wHu29aXqQdjazX3-j0qlopSyfndBjJRg4ajLNa_TTNz6QB3IUkjeH10MmdJDr8W7HPw3WI3-GFFUBG7dCo6YsHHe5aC43972zS7w79JI2IjsTtDsK79gfg1II5CG9tHc00o_zV6SuI2nM8j_R_BByPHuoMYU_d5l1oYwCnb7Bhb2mkwcyA4QqlvY5kbEiWrNbvxE3Jz8wPsRFkVxuMA1-N-43DGEDzoq2Gqd1GjXrnZNmblmm15hxwSQrpH2lMbHziUk9yGMuQ6JEevYzHs31Bpu6lbQ")
a = Python_helm()
a.show_namespace()
# a.show_release(namespace='kube-system')
 
# namespace         -> 环境名称
# search_release    -> 申请部署的应用
# app_version       -> 部署环境
 
a.rollback_release(search_release='wt-rd-APP-gaea', namespace='test')
posted @ 2021-05-30 15:17  SRE运维充电站  阅读(93)  评论(0编辑  收藏  举报