# coding: utf-8
from kazoo.client import KazooClient, NoNodeError
zk = KazooClient(hosts="192.168.1.1:2181")
zk.start()
node_path_tpl = "/test1/resources/rsip@{ip}/rsport@{port}"
# 从文件读取信息
# ip:port
# with open("ip.list", "r") as f:
# node_list = f.readlines()
# 直接从zk获取信息
node_list = []
rsip_list = zk.get_children("/test1/resources")
for rsip in rsip_list:
_, host = rsip.split("@")
rsport_list = zk.get_children("/test1/resources" + "/" + rsip)
for rsport in rsport_list:
_, port = rsport.split("@")
node_list.append("{}:{}".format(host, port))
for item in node_list:
sub_node_list = []
ip, port = item.replace("\n", "").split(":")
node_path = node_path_tpl.format(ip=ip, port=port)
print(node_path)
# 获取所有子节点
# 方法1: 直接返回异常
# try:
# if zk.exists(node_path):
# sub_node_list = zk.get_children(node_path)
# else:
# print("(ne){}".format(node_path))
# except NoNodeError:
# continue
# 方法2: 通过zstat获取
if zk.exists(node_path):
_, state = zk.get(node_path)
if state.numChildren != 0:
sub_node_list = zk.get_children(node_path)
else:
zk.ensure_path(node_path)
# 子节点不为空,删除所有子节点
for sub_item in sub_node_list:
sub_node_path = node_path + "/" + sub_item
print("\t" + sub_node_path)
# zk.delete(sub_node_path, recursive=True)
zk.stop()
zk.close()