1
# Copyright 2014-2015 Canonical Limited.
3
# This file is part of charm-helpers.
5
# charm-helpers is free software: you can redistribute it and/or modify
6
# it under the terms of the GNU Lesser General Public License version 3 as
7
# published by the Free Software Foundation.
9
# charm-helpers is distributed in the hope that it will be useful,
10
# but WITHOUT ANY WARRANTY; without even the implied warranty of
11
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12
# GNU Lesser General Public License for more details.
14
# You should have received a copy of the GNU Lesser General Public License
15
# along with charm-helpers. If not, see <http://www.gnu.org/licenses/>.
17
"Interactions with the Juju environment"
18
# Copyright 2013 Canonical Ltd.
21
# Charm Helpers Developers <juju@lists.ubuntu.com>
28
from subprocess import CalledProcessError
32
from UserDict import UserDict
34
from collections import UserDict
47
"""Cache return values for multiple executions of func + args
52
def unit_get(attribute):
57
will cache the result of unit_get + 'test' for future calls.
59
def wrapper(*args, **kwargs):
61
key = str((func, args, kwargs))
65
res = func(*args, **kwargs)
72
"""Flushes any entries from function cache where the
73
key is found in the function+args """
77
flush_list.append(item)
78
for item in flush_list:
82
def log(message, level=None):
83
"""Write a message to the juju log"""
84
command = ['juju-log']
86
command += ['-l', level]
87
if not isinstance(message, six.string_types):
88
message = repr(message)
90
subprocess.call(command)
93
class Serializable(UserDict):
94
"""Wrapper, an object that can be serialized to yaml or json"""
96
def __init__(self, obj):
98
UserDict.__init__(self)
101
def __getattr__(self, attr):
102
# See if this object has attribute.
103
if attr in ("json", "yaml", "data"):
104
return self.__dict__[attr]
105
# Check for attribute in wrapped object.
106
got = getattr(self.data, attr, MARKER)
107
if got is not MARKER:
109
# Proxy to the wrapped object via dict interface.
111
return self.data[attr]
113
raise AttributeError(attr)
115
def __getstate__(self):
116
# Pickle as a standard dictionary.
119
def __setstate__(self, state):
120
# Unpickle into our wrapper.
124
"""Serialize the object to json"""
125
return json.dumps(self.data)
128
"""Serialize the object to yaml"""
129
return yaml.dump(self.data)
132
def execution_environment():
133
"""A convenient bundling of the current execution context"""
135
context['conf'] = config()
137
context['reltype'] = relation_type()
138
context['relid'] = relation_id()
139
context['rel'] = relation_get()
140
context['unit'] = local_unit()
141
context['rels'] = relations()
142
context['env'] = os.environ
146
def in_relation_hook():
147
"""Determine whether we're running in a relation hook"""
148
return 'JUJU_RELATION' in os.environ
152
"""The scope for the current relation hook"""
153
return os.environ.get('JUJU_RELATION', None)
157
"""The relation ID for the current relation hook"""
158
return os.environ.get('JUJU_RELATION_ID', None)
163
return os.environ['JUJU_UNIT_NAME']
167
"""The remote unit for the current relation hook"""
168
return os.environ['JUJU_REMOTE_UNIT']
172
"""The name service group this unit belongs to"""
173
return local_unit().split('/')[0]
177
"""The name of the currently executing hook"""
178
return os.path.basename(sys.argv[0])
182
"""A dictionary representation of the charm's config.yaml, with some
185
- See which values in the dictionary have changed since the previous hook.
186
- For values that have changed, see what the previous value was.
187
- Store arbitrary data for use in a later hook.
189
NOTE: Do not instantiate this object directly - instead call
190
``hookenv.config()``, which will return an instance of :class:`Config`.
195
>>> from charmhelpers.core import hookenv
196
>>> config = hookenv.config()
199
>>> # store a new key/value for later use
200
>>> config['mykey'] = 'myval'
203
>>> # user runs `juju set mycharm foo=baz`
204
>>> # now we're inside subsequent config-changed hook
205
>>> config = hookenv.config()
208
>>> # test to see if this val has changed since last hook
209
>>> config.changed('foo')
211
>>> # what was the previous value?
212
>>> config.previous('foo')
214
>>> # keys/values that we add are preserved across hooks
219
CONFIG_FILE_NAME = '.juju-persistent-config'
221
def __init__(self, *args, **kw):
222
super(Config, self).__init__(*args, **kw)
223
self.implicit_save = True
224
self._prev_dict = None
225
self.path = os.path.join(charm_dir(), Config.CONFIG_FILE_NAME)
226
if os.path.exists(self.path):
229
def __getitem__(self, key):
230
"""For regular dict lookups, check the current juju config first,
231
then the previous (saved) copy. This ensures that user-saved values
232
will be returned by a dict lookup.
236
return dict.__getitem__(self, key)
238
return (self._prev_dict or {})[key]
242
if self._prev_dict is not None:
243
prev_keys = self._prev_dict.keys()
244
return list(set(prev_keys + list(dict.keys(self))))
246
def load_previous(self, path=None):
247
"""Load previous copy of config from disk.
249
In normal usage you don't need to call this method directly - it
250
is called automatically at object initialization.
254
File path from which to load the previous config. If `None`,
255
config is loaded from the default location. If `path` is
256
specified, subsequent `save()` calls will write to the same
260
self.path = path or self.path
261
with open(self.path) as f:
262
self._prev_dict = json.load(f)
264
def changed(self, key):
265
"""Return True if the current value for this key is different from
269
if self._prev_dict is None:
271
return self.previous(key) != self.get(key)
273
def previous(self, key):
274
"""Return previous value for this key, or None if there
275
is no previous value.
279
return self._prev_dict.get(key)
283
"""Save this config to disk.
285
If the charm is using the :mod:`Services Framework <services.base>`
286
or :meth:'@hook <Hooks.hook>' decorator, this
287
is called automatically at the end of successful hook execution.
288
Otherwise, it should be called directly by user code.
290
To disable automatic saves, set ``implicit_save=False`` on this
295
for k, v in six.iteritems(self._prev_dict):
298
with open(self.path, 'w') as f:
303
def config(scope=None):
304
"""Juju charm configuration"""
305
config_cmd_line = ['config-get']
306
if scope is not None:
307
config_cmd_line.append(scope)
308
config_cmd_line.append('--format=json')
310
config_data = json.loads(
311
subprocess.check_output(config_cmd_line).decode('UTF-8'))
312
if scope is not None:
314
return Config(config_data)
320
def relation_get(attribute=None, unit=None, rid=None):
321
"""Get relation information"""
322
_args = ['relation-get', '--format=json']
326
_args.append(attribute or '-')
330
return json.loads(subprocess.check_output(_args).decode('UTF-8'))
333
except CalledProcessError as e:
334
if e.returncode == 2:
339
def relation_set(relation_id=None, relation_settings=None, **kwargs):
340
"""Set relation information for the current unit"""
341
relation_settings = relation_settings if relation_settings else {}
342
relation_cmd_line = ['relation-set']
343
if relation_id is not None:
344
relation_cmd_line.extend(('-r', relation_id))
345
for k, v in (list(relation_settings.items()) + list(kwargs.items())):
347
relation_cmd_line.append('{}='.format(k))
349
relation_cmd_line.append('{}={}'.format(k, v))
350
subprocess.check_call(relation_cmd_line)
351
# Flush cache of any relation-gets for local unit
356
def relation_ids(reltype=None):
357
"""A list of relation_ids"""
358
reltype = reltype or relation_type()
359
relid_cmd_line = ['relation-ids', '--format=json']
360
if reltype is not None:
361
relid_cmd_line.append(reltype)
363
subprocess.check_output(relid_cmd_line).decode('UTF-8')) or []
368
def related_units(relid=None):
369
"""A list of related units"""
370
relid = relid or relation_id()
371
units_cmd_line = ['relation-list', '--format=json']
372
if relid is not None:
373
units_cmd_line.extend(('-r', relid))
375
subprocess.check_output(units_cmd_line).decode('UTF-8')) or []
379
def relation_for_unit(unit=None, rid=None):
380
"""Get the json represenation of a unit's relation"""
381
unit = unit or remote_unit()
382
relation = relation_get(unit=unit, rid=rid)
384
if key.endswith('-list'):
385
relation[key] = relation[key].split()
386
relation['__unit__'] = unit
391
def relations_for_id(relid=None):
392
"""Get relations of a specific relation ID"""
394
relid = relid or relation_ids()
395
for unit in related_units(relid):
396
unit_data = relation_for_unit(unit, relid)
397
unit_data['__relid__'] = relid
398
relation_data.append(unit_data)
403
def relations_of_type(reltype=None):
404
"""Get relations of a specific type"""
406
reltype = reltype or relation_type()
407
for relid in relation_ids(reltype):
408
for relation in relations_for_id(relid):
409
relation['__relid__'] = relid
410
relation_data.append(relation)
416
"""Get the current charm metadata.yaml contents as a python object"""
417
with open(os.path.join(charm_dir(), 'metadata.yaml')) as md:
418
return yaml.safe_load(md)
422
def relation_types():
423
"""Get a list of relation types supported by this charm"""
426
for key in ('provides', 'requires', 'peers'):
427
section = md.get(key)
429
rel_types.extend(section.keys())
435
"""Get the name of the current charm as is specified on metadata.yaml"""
436
return metadata().get('name')
441
"""Get a nested dictionary of relation data for all related units"""
443
for reltype in relation_types():
445
for relid in relation_ids(reltype):
446
units = {local_unit(): relation_get(unit=local_unit(), rid=relid)}
447
for unit in related_units(relid):
448
reldata = relation_get(unit=unit, rid=relid)
449
units[unit] = reldata
450
relids[relid] = units
451
rels[reltype] = relids
456
def is_relation_made(relation, keys='private-address'):
458
Determine whether a relation is established by checking for
459
presence of key(s). If a list of keys is provided, they
460
must all be present for the relation to be identified as made
462
if isinstance(keys, str):
464
for r_id in relation_ids(relation):
465
for unit in related_units(r_id):
468
context[k] = relation_get(k, rid=r_id,
470
if None not in context.values():
475
def open_port(port, protocol="TCP"):
476
"""Open a service network port"""
477
_args = ['open-port']
478
_args.append('{}/{}'.format(port, protocol))
479
subprocess.check_call(_args)
482
def close_port(port, protocol="TCP"):
483
"""Close a service network port"""
484
_args = ['close-port']
485
_args.append('{}/{}'.format(port, protocol))
486
subprocess.check_call(_args)
490
def unit_get(attribute):
491
"""Get the unit ID for the remote unit"""
492
_args = ['unit-get', '--format=json', attribute]
494
return json.loads(subprocess.check_output(_args).decode('UTF-8'))
499
def unit_private_ip():
500
"""Get this unit's private IP address"""
501
return unit_get('private-address')
504
class UnregisteredHookError(Exception):
505
"""Raised when an undefined hook is called"""
510
"""A convenient handler for hook functions.
516
# register a hook, taking its name from the function name
519
pass # your code here
521
# register a hook, providing a custom hook name
522
@hooks.hook("config-changed")
523
def config_changed():
524
pass # your code here
526
if __name__ == "__main__":
527
# execute a hook based on the name the program is called by
528
hooks.execute(sys.argv)
531
def __init__(self, config_save=True):
532
super(Hooks, self).__init__()
534
self._config_save = config_save
536
def register(self, name, function):
537
"""Register a hook"""
538
self._hooks[name] = function
540
def execute(self, args):
541
"""Execute a registered hook based on args[0]"""
542
hook_name = os.path.basename(args[0])
543
if hook_name in self._hooks:
544
self._hooks[hook_name]()
545
if self._config_save:
547
if cfg.implicit_save:
550
raise UnregisteredHookError(hook_name)
552
def hook(self, *hook_names):
553
"""Decorator, registering them as hooks"""
554
def wrapper(decorated):
555
for hook_name in hook_names:
556
self.register(hook_name, decorated)
558
self.register(decorated.__name__, decorated)
559
if '_' in decorated.__name__:
561
decorated.__name__.replace('_', '-'), decorated)
567
"""Return the root directory of the current charm"""
568
return os.environ.get('CHARM_DIR')