blob: c424e7fe8262099f99c6b8fe9a47f2dee24e2a12 [file] [log] [blame]
khenb95fe9a2016-10-05 11:15:25 -07001#
2# Copyright 2016 the original author or authors.
3#
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
21import os
22from structlog import get_logger
23import sys
24from consul import Consul
25from random import randint
26
27log = get_logger()
28
29def get_endpoint_from_consul(consul_endpoint, service_name):
30 """Look up, from consul, the service name specified by service-name
31 """
32 log.debug('Retrieving endpoint {} from consul {}'.format(service_name,
33 consul_endpoint))
34 host = consul_endpoint.split(':')[0].strip()
35 port = int(consul_endpoint.split(':')[1].strip())
36
37 consul = Consul(host=host, port=port)
38 _, services = consul.catalog.service(service_name)
39
40 if len(services) == 0:
41 raise Exception('Cannot find service {} in consul'.format(service_name))
42
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
50 print endpoint
51 return endpoint
52
53
54if __name__ == '__main__':
55 get_endpoint_from_consul('10.100.198.220:8500', 'kafka')