python获取k8s中指定pod添加至consul

自动获取k8s某个名称空间中的pod添加至consul

#!/usr/bin/python
# -*- coding: utf-8 -*-
# @Time      :   2022/7/8 15:27
# @Author    :   fishking
# @Role      :


import requests,json
from kubernetes import client,config


registerapi = 'http://10.10.10.10:8500/v1/agent/service/register'

headers = {
    "X-Consul-Token": 'www.xsery.net'
}

def getConsulHost():
    url = 'http://10.10.10.10:8500/v1/agent/checks'
    result = json.loads(requests.get(url,headers=headers).text)
    hosts = []
    if result:
        for host in result:
            if 'game' in host or 'match' in host or 'guild' in host:
                hosts.append(host[8:])
        return hosts
    else:
        exit(1)

def getData(name,ip,port):
    data = {
        "ID": "%s"%name,
        "Name":"node-exporter",
        "Address": "%s" %ip,
        "Port": port,
        "Meta": {"moudle":"node-exporter","project": "nova","instance": "%s"%name,'engine': 'k8s'},
        "Check": {"HTTP": "http://%s:%s/metrics"%(ip,port),"Interval": "15s"}
    }
    return data

def push(api,headers,data):
    print(requests.put(api,headers=headers,data=data).text)

def delete(name):
    print(requests.put('http://10.10.10.10:8500/v1/agent/service/deregister/%s'%name,headers=headers))

def getK8sHosts():
    global infos
	# config 文件为k8smaster的keubeconfig 文件 一般为/root/.kube/config 
    config.kube_config.load_kube_config(config_file="/root/config")
    v1 = client.CoreV1Api()
    pods = v1.list_namespaced_pod('nova')
    infos = []
    hosts = []
    for pod in pods.items:
        pod_ip = pod.status.pod_ip
        pod_name = pod.metadata.name
        url = ''
        port = 22
        if 'game' in pod_name:
            port = 9010
            url = 'http://' + str(pod_ip) + ':9010' + '/metrics'
        elif 'guild' in pod_name and 'search' not in pod_name:
            port = 9011
            url = 'http://' + str(pod_ip) + ':9011' + '/metrics'
        elif 'match' in pod_name:
            port = 9012
            url = 'http://' + str(pod_ip) + ':9012' + '/metrics'
        try:
            if url:
                infos.append({"name": pod_name,"ip": pod_ip,"port": port})
                status_code = requests.get(url).status_code
                if status_code == 200:
                    hosts.append(pod_name)
        except Exception as e:
            pass
    return hosts

if __name__ == '__main__':
    k8s_pod  = getK8sHosts()
    consul_host = getConsulHost()

    #k8s里边有,consul里边没有的 添加至consul
    inster_list = list(set(k8s_pod).difference(set(consul_host)))

    #consul里边有, k8s里边没有, 从consul中删除
    delete_host = list(set(consul_host).difference(set(k8s_pod)))

    #添加consul
    for host in inster_list:
        for info in infos:
            if host == info['name']:
                ip = info['ip']
                port = info['port']
                data = getData(host,ip,port)
                push(registerapi,headers=headers,data=json.dumps(data))

    #删除consul
    for host in delete_host:
        delete(host)

给TA打赏
共{{data.count}}人
人已打赏
运维文档

logstash重复消费写入两次es问题

2022-6-25 15:45:20

运维文档

logstash重复消费写入两次es问题

2022-6-25 15:45:20

0 条回复 A文章作者 M管理员
    暂无讨论,说说你的看法吧
个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索