blob: 1d2b88f3e6f8fdcf21cf43e0d08067e45e7d82a3 [file] [log] [blame]
khenb95fe9a2016-10-05 11:15:25 -07001#
Zsolt Haraszti3eb27a52017-01-03 21:56:48 -08002# Copyright 2017 the original author or authors.
khenb95fe9a2016-10-05 11:15:25 -07003#
4# Licensed under the Apache License, Version 2.0 (the "License");
5# you may not use this file except in compliance with the License.
6# You may obtain a copy of the License at
7#
8# http://www.apache.org/licenses/LICENSE-2.0
9#
10# Unless required by applicable law or agreed to in writing, software
11# distributed under the License is distributed on an "AS IS" BASIS,
12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13# See the License for the specific language governing permissions and
14# limitations under the License.
15#
16
17"""
18Some consul related convenience functions
19"""
20
khenb95fe9a2016-10-05 11:15:25 -070021from structlog import get_logger
khenb95fe9a2016-10-05 11:15:25 -070022from consul import Consul
23from random import randint
24
25log = get_logger()
26
Khen Nursimulu441dedd2016-10-05 14:44:26 -070027
khenb95fe9a2016-10-05 11:15:25 -070028def get_endpoint_from_consul(consul_endpoint, service_name):
29 """Look up, from consul, the service name specified by service-name
30 """
31 log.debug('Retrieving endpoint {} from consul {}'.format(service_name,
Khen Nursimulu441dedd2016-10-05 14:44:26 -070032 consul_endpoint))
khenb95fe9a2016-10-05 11:15:25 -070033 host = consul_endpoint.split(':')[0].strip()
34 port = int(consul_endpoint.split(':')[1].strip())
35
36 consul = Consul(host=host, port=port)
37 _, services = consul.catalog.service(service_name)
38
39 if len(services) == 0:
Khen Nursimulu441dedd2016-10-05 14:44:26 -070040 raise Exception(
41 'Cannot find service {} in consul'.format(service_name))
khenb95fe9a2016-10-05 11:15:25 -070042
43 # pick a random entry
44 # TODO should we prefer local IP addresses? Probably.
45
46 service = services[randint(0, len(services) - 1)]
47 endpoint = '{}:{}'.format(service['ServiceAddress'],
48 service['ServicePort'])
49
khenb95fe9a2016-10-05 11:15:25 -070050 return endpoint
51
52
53if __name__ == '__main__':
54 get_endpoint_from_consul('10.100.198.220:8500', 'kafka')