1 # ============LICENSE_START=======================================================
3 # ================================================================================
4 # Copyright (c) 2017 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=========================================================
20 # ECOMP is a trademark and service mark of AT&T Intellectual Property.
23 from urllib.parse import urlparse
25 from urlparse import urlparse
30 class DiscoveryError(RuntimeError):
33 def _create_rel_key(service_component_name):
34 return "{0}:rel".format(service_component_name)
36 def _parse_host(host):
40 Tuple of the hostname and port to use to connect to Consul
42 def parse_urlparse_result(pr):
44 raise DiscoveryError("Invalid Consul host provided: {0}".format(host))
47 # Port 8500 is the Consul default
48 return (pr.hostname, pr.port if pr.port else 8500)
49 except ValueError as e:
50 # Something bad happened with port
51 raise DiscoveryError("Invalid Consul host provided: {0}".format(host))
55 # urlparse requires scheme to be set in order to be useful
56 if pr.scheme and pr.netloc:
57 return parse_urlparse_result(pr)
59 return parse_urlparse_result(urlparse("http://{0}".format(host)))
62 def create_kv_conn(host):
63 """Create connection to key-value store
65 Returns a Consul client to the specified Consul host
67 (hostname, port) = _parse_host(host)
68 return consul.Consul(host=hostname, port=port)
70 def store_relationship(kv_conn, source_name, target_name):
71 # TODO: Rel entry may already exist in a one-to-many situation. Need to
73 rel_key = _create_rel_key(source_name)
74 rel_value = [target_name] if target_name else []
76 kv_conn.kv.put(rel_key, json.dumps(rel_value))
77 print("Added relationship for {0}".format(rel_key))
79 def delete_relationship(kv_conn, service_component_name):
80 rel_key = _create_rel_key(service_component_name)
81 index, rels = kv_conn.kv.get(rel_key)
84 rels = json.loads(rels["Value"].decode("utf-8"))
85 kv_conn.kv.delete(rel_key)