blob: 7e16b907fe28f14875f9c1c5998db9f349049381 [file] [log] [blame]
alex_sh9d980ce2017-08-23 17:30:56 -04001"""client to talk to consul at the standard port 8500"""
2
3# org.onap.dcae
4# ================================================================================
5# Copyright (c) 2017 AT&T Intellectual Property. All rights reserved.
6# ================================================================================
7# Licensed under the Apache License, Version 2.0 (the "License");
8# you may not use this file except in compliance with the License.
9# You may obtain a copy of the License at
10#
11# http://www.apache.org/licenses/LICENSE-2.0
12#
13# Unless required by applicable law or agreed to in writing, software
14# distributed under the License is distributed on an "AS IS" BASIS,
15# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16# See the License for the specific language governing permissions and
17# limitations under the License.
18# ============LICENSE_END=========================================================
19#
20# ECOMP is a trademark and service mark of AT&T Intellectual Property.
21
22import logging
23import json
24import base64
25import requests
26
27class DiscoveryClient(object):
28 """talking to consul at http://consul:8500
29
30 relies on proper --add-host "consul:<consul-agent ip>" in
31 docker run command that runs along the consul-agent:
32
33 docker run --name ${APPNAME} -d
34 -e HOSTNAME
35 --add-host "consul:<consul-agent ip>"
36 -v ${BASEDIR}/logs:${TARGETDIR}/logs
37 -v ${BASEDIR}/etc:${TARGETDIR}/etc
38 -p <outport>:<innerport>
39 ${APPNAME}:latest
40 """
41 CONSUL_SERVICE_MASK = "http://consul:8500/v1/catalog/service/{0}"
42 CONSUL_KV_MASK = "http://consul:8500/v1/kv/{0}"
43 SERVICE_MASK = "http://{0}:{1}"
44 _logger = logging.getLogger("policy_handler.discovery")
45
46
47 @staticmethod
48 def get_service_url(service_name):
49 """find the service record in consul"""
50 service_path = DiscoveryClient.CONSUL_SERVICE_MASK.format(service_name)
51 DiscoveryClient._logger.info("discover %s", service_path)
52 response = requests.get(service_path)
53 response.raise_for_status()
54 service = response.json()[0]
55 return DiscoveryClient.SERVICE_MASK.format( \
56 service["ServiceAddress"], service["ServicePort"])
57
58 @staticmethod
59 def get_value(key):
60 """get the value for the key from consul-kv"""
61 response = requests.get(DiscoveryClient.CONSUL_KV_MASK.format(key))
62 response.raise_for_status()
63 data = response.json()[0]
64 value = base64.b64decode(data["Value"]).decode("utf-8")
65 DiscoveryClient._logger.info("consul-kv key=%s data=%s value(%s)", \
66 key, json.dumps(data), value)
67 return json.loads(value)
68
69 @staticmethod
70 def put_kv(key, value):
71 """put the value under the key in consul-kv"""
72 response = requests.put(DiscoveryClient.CONSUL_KV_MASK.format(key), data=value)
73 response.raise_for_status()