配置文件
CONSUL_HOST = "10.9.xx.xx"
CONSUL_PORT = "8500"
CONSUL_TOKEN = "cd76a0f7-5535-40cc-8696-xxxxxxxx"
Consul API
import consul
from django.conf import settings
from common.utils import get_logger
logger = get_logger(__file__)
class ConsulHandle(object):
ENV_DICT = {
'SIT环境': 'sit',
'开发环境': 'dev',
'测试环境': 'test',
'生产环境': 'product',
'预发布环境': 'uat',
'NULL': 'null',
}
def __init__(self, consul_host=None, consul_port=None,token=None):
self.host = consul_host or settings.CONSUL_HOST
self.port = consul_port or settings.CONSUL_PORT
self.token = token
if not token: self.token = settings.CONSUL_TOKEN
self.consul_client = consul.Consul(self.host, self.port, token=self.token)
# self.consul_client = consul.Consul(self.host,self.port)
# 注册服务
def register(self, server_name,server_id, ip, port, tags=[], meta={}):
# c = consul.Consul() # 连接consul 服务器,默认是127.0.0.1,可用host参数指定host
check = consul.Check.tcp(ip, port, "30s") # 健康检查的ip,端口,检查时间
result = self.consul_client.agent.service.register(server_name, server_id, address=ip, port=port, check=check, tags=tags, meta=meta) # 注册服务部分
return result
# 注销服务
def deregister(self, server_id):
result = self.consul_client.agent.service.deregister(server_id)
return result
# 获取服务
def get_service(self, service_id):
services = self.consul_client.agent.services()
service = services.get(service_id)
return service
# 添加更新 键值对
def put_kv(self,key, value):
result = self.consul_client.kv.put(key, value)
return result
# 删除键
def del_kv(self, key):
result = self.consul_client.kv.delete(key)
return result
# 获取键值对
def get_kv(self, key):
value = ""
result = self.consul_client.kv.get(key)
if result[1]:
value = str(result[1].get("Value"), encoding="utf8")
return value
# 获取某目录下所有键值对
def get_kvs(self, _key):
logger.info("get all keys ......")
result = self.consul_client.kv.get(_key, recurse=True)
try:
return result[1]
except:
return []
def sync_instance(self, instance, action):
'''
同步资产信息到consul
node_exporter端口配置
linux
9100 'SIT环境': 'sit',
'开发环境': 'dev',
'测试环境': 'test',
'NULL': 'null',
29100 '生产环境': 'product',
'预发布环境': 'uat',
win os "win"
9182
:param instance: 资产obj
:param action: create/update/delete
:return:
'''
if action == "delete":
self.deregister(str(instance.id))
return True
env_name = self.ENV_DICT.get(instance.get_environment, '') if instance.get_environment else ''
port, type = None, None
if "esxi" in str(instance.os).lower():
return
elif "win" in str(instance.os).lower():
port = 9182
type = "window"
else:
type = "linux"
if env_name in ["sit", "dev", "test", "null"]:
port = 9100
elif env_name in ["product", "uat"]:
port = 29100
network_obj = instance.ipAddress.all().first()
if network_obj:
network = instance.ipAddress.all().first().segment.segment
network = ".".join(network.split(".")[:3])
else:
network = ""
meta = {
"ipAddress": instance.get_ipAddress or '',
"instance": instance.get_ipAddress or '',
"idrac_ip": instance.idrac_ip or '',
"asset_type": instance.get_asset_type or '',
"env": env_name,
"model": instance.model or '',
"os": instance.os or '',
"network": network,
"vendor": instance.vendor or '',
"type": type,
"job": "node_exporter"
}
try:
self.register(env_name, str(instance.id), instance.get_ipAddress, port, meta=meta)
except Exception as e:
logger.warning('同步consul报错 {}'.format(e))