1
# Copyright 2015-2016 Canonical Ltd.
3
# This file is part of the Leadership Layer for Juju.
5
# This program is free software: you can redistribute it and/or modify
6
# it under the terms of the GNU 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 General Public License for more details.
14
# You should have received a copy of the GNU General Public License
15
# along with this program. If not, see <http://www.gnu.org/licenses/>.
17
from charmhelpers.core import hookenv
18
from charmhelpers.core import unitdata
20
from charms import reactive
21
from charms.leadership import leader_get, leader_set
24
__all__ = ['leader_get', 'leader_set'] # Backwards compatibility
27
def initialize_leadership_state():
28
'''Initialize leadership.* states from the hook environment.
30
Invoked by hookenv.atstart() so states are available in
31
@hook decorated handlers.
33
is_leader = hookenv.is_leader()
35
hookenv.log('Initializing Leadership Layer (is leader)')
37
hookenv.log('Initializing Leadership Layer (is follower)')
39
reactive.helpers.toggle_state('leadership.is_leader', is_leader)
41
previous = unitdata.kv().getrange('leadership.settings.', strip=True)
42
current = hookenv.leader_get()
45
for key in set(previous.keys()) - set(current.keys()):
49
for key, value in current.items():
50
reactive.helpers.toggle_state('leadership.changed.{}'.format(key),
51
value != previous.get(key))
52
if value != previous.get(key):
54
reactive.helpers.toggle_state('leadership.set.{}'.format(key),
56
reactive.helpers.toggle_state('leadership.changed', any_changed)
58
unitdata.kv().update(current, prefix='leadership.settings.')
61
# Per https://github.com/juju-solutions/charms.reactive/issues/33,
62
# this module may be imported multiple times so ensure the
63
# initialization hook is only registered once. I have to piggy back
64
# onto the namespace of a module imported before reactive discovery
66
if not hasattr(reactive, '_leadership_registered'):
67
hookenv.atstart(initialize_leadership_state)
68
reactive._leadership_registered = True