-
Notifications
You must be signed in to change notification settings - Fork 0
/
zkGenServers.py
executable file
·75 lines (62 loc) · 1.97 KB
/
zkGenServers.py
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
#! /usr/bin/env python
import argparse
import json
import os
import re
import requests
def myid(node):
if 'ServiceTags' not in node:
return None
r = re.compile('^myid=(\d+)$')
res = list(filter(r.match, node['ServiceTags']))
if len(res) == 0:
return None
return r.search(res[0]).group(1)
def has_myid(node):
return not myid(node) is None
def is_valid_zookeeper(zookeeper):
return (
'ID' in zookeeper
and
'Address' in zookeeper
and
'ClientPort' in zookeeper
and
'ServerPort' in zookeeper
and
'ElectionPort' in zookeeper
)
parser = argparse.ArgumentParser(description='Generates ZooKeeper\'s servers configuration by querying Consul.')
parser.add_argument('myid', help='myid')
args = parser.parse_args()
consul_http_addr = os.getenv('CONSUL_HTTP_ADDR', 'consul:8500')
r = requests.get(f"http://{consul_http_addr}/v1/catalog/service/zookeeper-2181")
res = r.json()
if len(res) == 0:
print('[]')
exit(0)
zookeepers = {}
for node in filter(has_myid, res):
id = myid(node)
zookeepers[id] = {
'ID': id,
'Address': '0.0.0.0' if id == args.myid else node['ServiceAddress'],
'ClientPort': os.getenv('ZOO_PORT', '2181') if id == args.myid else node['ServicePort'],
}
r = requests.get(f"http://{consul_http_addr}/v1/catalog/service/zookeeper-2888")
res = r.json()
for node in filter(has_myid, res):
id = myid(node)
if id not in zookeepers:
continue
zookeepers[id]['ServerPort'] = '2888' if id == args.myid else node['ServicePort']
r = requests.get(f"http://{consul_http_addr}/v1/catalog/service/zookeeper-3888")
res = r.json()
for node in filter(has_myid, res):
id = myid(node)
if id not in zookeepers:
continue
zookeepers[id]['ElectionPort'] = '3888' if id == args.myid else node['ServicePort']
valid_zookeepers = list(filter(is_valid_zookeeper, zookeepers.values()))
print(json.dumps(valid_zookeepers))
exit(0)