1
from charmhelpers.core.hookenv import (
9
This helper provides functions to support use of a peer relation
10
for basic key/value storage, with the added benefit that all storage
11
can be replicated across peer units, so this is really useful for
12
services that issue usernames/passwords to remote services.
14
def shared_db_changed()
15
# Only the lead unit should create passwords
18
username = relation_get('username')
19
key = '{}.password'.format(username)
20
# Attempt to retrieve any existing password for this user
21
password = peer_retrieve(key)
23
# New user, create password and store
24
password = pwgen(length=64)
25
peer_store(key, password)
26
create_access(username, password)
27
relation_set(password=password)
31
# Echo any relation data other that *-address
32
# back onto the peer relation so all units have
33
# all *.password keys stored on their local relation
34
# for later retrieval.
40
def peer_retrieve(key, relation_name='cluster'):
41
""" Retrieve a named key from peer relation relation_name """
42
cluster_rels = relation_ids(relation_name)
43
if len(cluster_rels) > 0:
44
cluster_rid = cluster_rels[0]
45
return relation_get(attribute=key, rid=cluster_rid,
48
raise ValueError('Unable to detect'
49
'peer relation {}'.format(relation_name))
52
def peer_store(key, value, relation_name='cluster'):
53
""" Store the key/value pair on the named peer relation relation_name """
54
cluster_rels = relation_ids(relation_name)
55
if len(cluster_rels) > 0:
56
cluster_rid = cluster_rels[0]
57
relation_set(relation_id=cluster_rid,
58
relation_settings={key: value})
60
raise ValueError('Unable to detect '
61
'peer relation {}'.format(relation_name))
64
def peer_echo(includes=None):
65
"""Echo filtered attributes back onto the same relation for storage
67
Note that this helper must only be called within a peer relation
70
rdata = relation_get()
73
echo_data = rdata.copy()
74
for ex in ['private-address', 'public-address']:
78
for attribute, value in rdata.iteritems():
79
for include in includes:
80
if include in attribute:
81
echo_data[attribute] = value
82
if len(echo_data) > 0:
83
relation_set(relation_settings=echo_data)