1 # ============LICENSE_START=======================================================
3 # ================================================================================
4 # Copyright (c) 2017-2020 AT&T Intellectual Property. All rights reserved.
5 # Copyright (c) 2019 Pantheon.tech. 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
11 # http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
22 from urllib.parse import urlparse
24 from urlparse import urlparse
29 class DiscoveryError(RuntimeError):
32 def _create_rel_key(service_component_name):
33 return "{0}:rel".format(service_component_name)
35 def _parse_host(host):
39 Tuple of the hostname and port to use to connect to Consul
41 def parse_urlparse_result(pr):
43 raise DiscoveryError("Invalid Consul host provided: {0}".format(host))
46 # Port 8500 is the Consul default
47 return (pr.hostname, pr.port if pr.port else 8500)
48 except ValueError as e:
49 # Something bad happened with port
50 raise DiscoveryError("Invalid Consul host provided: {0}".format(host))
54 # urlparse requires scheme to be set in order to be useful
55 if pr.scheme and pr.netloc:
56 return parse_urlparse_result(pr)
58 return parse_urlparse_result(urlparse("http://{0}".format(host)))
61 def create_kv_conn(host):
62 """Create connection to key-value store
64 Returns a Consul client to the specified Consul host
66 (hostname, port) = _parse_host(host)
67 return consul.Consul(host=hostname, port=port)
69 def store_relationship(kv_conn, source_name, target_name):
70 # TODO: Rel entry may already exist in a one-to-many situation. Need to
72 rel_key = _create_rel_key(source_name)
73 rel_value = [target_name] if target_name else []
75 kv_conn.kv.put(rel_key, json.dumps(rel_value))
76 print("Added relationship for {0}".format(rel_key))
78 def delete_relationship(kv_conn, service_component_name):
79 rel_key = _create_rel_key(service_component_name)
80 index, rels = kv_conn.kv.get(rel_key)
83 rels = json.loads(rels["Value"].decode("utf-8"))
84 kv_conn.kv.delete(rel_key)