3
# Copyright 2014 Canonical Ltd.
5
# This program is free software: you can redistribute it and/or modify it
6
# under the terms of the GNU Affero General Public License version 3, as
7
# published by the Free Software Foundation.
9
# This program is distributed in the hope that it will be useful, but
10
# WITHOUT ANY WARRANTY; without even the implied warranties of
11
# MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR
12
# PURPOSE. See the GNU Affero General Public License for more details.
14
# You should have received a copy of the GNU Affero General Public License
15
# along with this program. If not, see <http://www.gnu.org/licenses/>.
20
from charmhelpers.core import hookenv
22
hooks = hookenv.Hooks()
26
def get_service_dir():
27
unit_name = hookenv.local_unit()
28
sanitized_unit_name = unit_name.split('/')[0]
29
return os.path.join('/srv', sanitized_unit_name)
32
@hooks.hook('intercom-relation-changed')
33
@hooks.hook('intercom-relation-joined')
34
def update_intercom(remove=False):
35
"""Update the inter-components map.
37
It maintains a map of <unit> -> (<hostname>, <port>) components
38
that may exchange data directly.
40
It consumes 'http' (hostname:port) interface.
42
The inter-components map is saved as 'intercom.json' in the
43
application DIR in JSON format.
45
intercom_path = os.path.join(get_service_dir(), 'intercom.json')
47
if os.path.exists(intercom_path):
48
registry = json.load(open(intercom_path))
52
relation_id = hookenv.relation_id()
53
unit = hookenv.remote_unit()
54
hostname = hookenv.relation_get('hostname')
55
port = hookenv.relation_get('port')
58
log('Intercom unit \'{}\' ({}) departed.'.format(unit, hostname))
59
if registry.get(relation_id) is not None:
60
del registry[relation_id]
62
log('Intercom unit \'{}\' ({}) joined.'.format(unit, hostname))
63
registry[relation_id] = {
69
with open(intercom_path, 'w') as fd:
70
json.dump(registry, fd)
74
def intercom_relation_broken():
75
update_intercom(remove=True)
78
if __name__ == "__main__":
79
hooks.execute(sys.argv)