-
Notifications
You must be signed in to change notification settings - Fork 5
/
kube2pyconsul.py
161 lines (129 loc) · 6.05 KB
/
kube2pyconsul.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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
"""kube2pyconsul.
Usage:
kube2pyconsul.py [-v <loglevel>] [--verify-ssl=<value>] [--consul-agent=<consul-uri>] [--kube-master=<kubeapi-uri>] [--consul-auth=<user,pass>] [--kube-auth=<user,pass>]
kube2pyconsul.py (-h | --help)
Options:
-h --help Show this screen.
-v <loglevel> Set logging level [default: INFO]
--consul-agent=<consul-uri> Consul agent location [default: https://127.0.0.1:8500].
--kube-master=<kubeapi-uri> Kubeapi location [default: https://127.0.0.1:6443]
--consul-auth=<user,pass> Consul http auth credentials [default: None]
--kube-auth=<user,pass> Kubernetes http auth credentials [default: None]
--verify-ssl=<value> Option to enable or disable SSL certificate validation [default: False]
"""
from docopt import docopt
import sys
import json
import time
import logging
import requests
import traceback
import multiprocessing
from multiprocessing import Queue
from multiprocessing import Process
args = docopt(__doc__, version='kube2pyconsul 1.0')
logging.basicConfig()
log = multiprocessing.log_to_stderr()
level = logging.getLevelName(args['-v'])
log.setLevel(level)
consul_uri = args['--consul-agent']
consul_auth = tuple(args['--consul-auth'].split(',')) if args['--consul-auth'] != 'None' else None
kubeapi_uri = args['--kube-master']
kube_auth = tuple(args['--kube-auth'].split(',')) if args['--kube-auth'] != 'None' else None
verify_ssl = args['--verify-ssl']
log.info("Starting with: consul={0}, kubeapi={1}".format(consul_uri, kubeapi_uri))
def getservice(event, ports):
return {"Name": event['object']['metadata']['name'],
"ID": '{}-{}'.format(event['object']['metadata']['name'], ports['port']),
"Address": event['object']['spec']['clusterIP'],
"Port": ports['port']}
def services_monitor(queue):
while True:
try:
r = requests.get('{base}/api/v1/services?watch=true'.format(base=kubeapi_uri),
stream=True, verify=verify_ssl, auth=kube_auth)
for line in r.iter_lines():
if line:
event = json.loads(line)
queue.put(('service', event))
except Exception as e:
log.debug(traceback.format_exc())
log.error(e)
log.error("Sleeping and restarting afresh.")
time.sleep(10)
def pods_monitor(queue):
while True:
try:
r = requests.get('{base}/api/v1/pods?watch=true'.format(base=kubeapi_uri),
stream=True, verify=verify_ssl, auth=kube_auth)
for line in r.iter_lines():
if line:
event = json.loads(line)
queue.put(('pod', event))
except Exception as e:
log.debug(traceback.format_exc())
log.error(e)
log.error("Sleeping and restarting afresh.")
time.sleep(10)
def registration(queue):
while True:
context, event = queue.get(block=True)
if context == 'service':
if event['type'] == 'ADDED':
for ports in event['object']['spec']['ports']:
service = getservice(event, ports)
r = ''
while True:
try:
r = requests.put('{base}/v1/agent/service/register'.format(base=consul_uri),
json=service, auth=consul_auth, verify=verify_ssl)
break
except Exception as e:
log.debug(traceback.format_exc())
log.error(e)
log.error("Sleeping and retrying.")
time.sleep(10)
if r.status_code == 200:
log.info("ADDED service {service} to Consul's catalog".format(service=service))
else:
log.error("Consul returned non-200 request status code. Could not register service {service}. Continuing on to the next service...".format())
sys.stdout.flush()
elif event['type'] == 'DELETED':
for ports in event['object']['spec']['ports']:
service = getservice(event, ports)
r = ''
while True:
try:
r = requests.put('{base}/v1/agent/service/deregister/{name}-{port}'.format(base=consul_uri, name=service['name'], port=service['port']),
auth=consul_auth, verify=verify_ssl)
break
except Exception as e:
log.debug(traceback.format_exc())
log.error(e)
log.error("Sleeping and retrying.")
time.sleep(10)
if r.status_code == 200:
log.info("DELETED service {service} from Consul's catalog".format(service=service))
else:
log.error("Consul returned non-200 request status code. Could not deregister service {service}. Continuing on to the next service...".format())
sys.stdout.flush()
elif context == 'pod':
pass
def run():
q = Queue()
services_watch = Process(target=services_monitor, args=(q,), name='kube2pyconsul/services')
pods_watch = Process(target=pods_monitor, args=(q,), name='kube2pyconsul/pods')
consul_desk = Process(target=registration, args=(q,), name='kube2pyconsul/registration')
services_watch.start()
pods_watch.start()
consul_desk.start()
try:
while True:
time.sleep(10)
except KeyboardInterrupt:
services_watch.terminate()
pods_watch.terminate()
consul_desk.terminate()
exit()
if __name__ == '__main__':
run()