khen | b95fe9a | 2016-10-05 11:15:25 -0700 | [diff] [blame] | 1 | # |
Zsolt Haraszti | 3eb27a5 | 2017-01-03 21:56:48 -0800 | [diff] [blame] | 2 | # Copyright 2017 the original author or authors. |
khen | b95fe9a | 2016-10-05 11:15:25 -0700 | [diff] [blame] | 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 | """ |
| 18 | Some consul related convenience functions |
| 19 | """ |
| 20 | |
khen | b95fe9a | 2016-10-05 11:15:25 -0700 | [diff] [blame] | 21 | from structlog import get_logger |
khen | b95fe9a | 2016-10-05 11:15:25 -0700 | [diff] [blame] | 22 | from consul import Consul |
| 23 | from random import randint |
| 24 | |
| 25 | log = get_logger() |
| 26 | |
Khen Nursimulu | 441dedd | 2016-10-05 14:44:26 -0700 | [diff] [blame] | 27 | |
khen | b95fe9a | 2016-10-05 11:15:25 -0700 | [diff] [blame] | 28 | def get_endpoint_from_consul(consul_endpoint, service_name): |
| 29 | """Look up, from consul, the service name specified by service-name |
| 30 | """ |
Khen Nursimulu | 90fc35d | 2017-01-09 08:42:04 -0500 | [diff] [blame] | 31 | log.debug('getting-service-endpoint', consul=consul_endpoint, |
| 32 | service=service_name) |
| 33 | |
khen | b95fe9a | 2016-10-05 11:15:25 -0700 | [diff] [blame] | 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: |
Khen Nursimulu | 441dedd | 2016-10-05 14:44:26 -0700 | [diff] [blame] | 41 | raise Exception( |
| 42 | 'Cannot find service {} in consul'.format(service_name)) |
alshabib | b634d90 | 2017-01-16 13:10:17 -0600 | [diff] [blame] | 43 | os.exit(1) |
khen | b95fe9a | 2016-10-05 11:15:25 -0700 | [diff] [blame] | 44 | |
| 45 | # pick a random entry |
| 46 | # TODO should we prefer local IP addresses? Probably. |
| 47 | |
| 48 | service = services[randint(0, len(services) - 1)] |
| 49 | endpoint = '{}:{}'.format(service['ServiceAddress'], |
| 50 | service['ServicePort']) |
| 51 | |
khen | b95fe9a | 2016-10-05 11:15:25 -0700 | [diff] [blame] | 52 | return endpoint |
| 53 | |
| 54 | |
| 55 | if __name__ == '__main__': |
Khen Nursimulu | 9b9f1ad | 2017-01-10 15:43:32 -0500 | [diff] [blame] | 56 | print get_endpoint_from_consul('10.100.198.220:8500', 'kafka') |