1
"Interactions with the Juju environment"
2
# Copyright 2013 Canonical Ltd.
5
# Charm Helpers Developers <juju@lists.ubuntu.com>
13
from subprocess import CalledProcessError
26
"""Cache return values for multiple executions of func + args
31
def unit_get(attribute):
36
will cache the result of unit_get + 'test' for future calls.
38
def wrapper(*args, **kwargs):
40
key = str((func, args, kwargs))
44
res = func(*args, **kwargs)
51
"""Flushes any entries from function cache where the
52
key is found in the function+args """
56
flush_list.append(item)
57
for item in flush_list:
61
def log(message, level=None):
62
"""Write a message to the juju log"""
63
command = ['juju-log']
65
command += ['-l', level]
67
subprocess.call(command)
70
class Serializable(UserDict.IterableUserDict):
71
"""Wrapper, an object that can be serialized to yaml or json"""
73
def __init__(self, obj):
75
UserDict.IterableUserDict.__init__(self)
78
def __getattr__(self, attr):
79
# See if this object has attribute.
80
if attr in ("json", "yaml", "data"):
81
return self.__dict__[attr]
82
# Check for attribute in wrapped object.
83
got = getattr(self.data, attr, MARKER)
86
# Proxy to the wrapped object via dict interface.
88
return self.data[attr]
90
raise AttributeError(attr)
92
def __getstate__(self):
93
# Pickle as a standard dictionary.
96
def __setstate__(self, state):
97
# Unpickle into our wrapper.
101
"""Serialize the object to json"""
102
return json.dumps(self.data)
105
"""Serialize the object to yaml"""
106
return yaml.dump(self.data)
109
def execution_environment():
110
"""A convenient bundling of the current execution context"""
112
context['conf'] = config()
114
context['reltype'] = relation_type()
115
context['relid'] = relation_id()
116
context['rel'] = relation_get()
117
context['unit'] = local_unit()
118
context['rels'] = relations()
119
context['env'] = os.environ
123
def in_relation_hook():
124
"""Determine whether we're running in a relation hook"""
125
return 'JUJU_RELATION' in os.environ
129
"""The scope for the current relation hook"""
130
return os.environ.get('JUJU_RELATION', None)
134
"""The relation ID for the current relation hook"""
135
return os.environ.get('JUJU_RELATION_ID', None)
140
return os.environ['JUJU_UNIT_NAME']
144
"""The remote unit for the current relation hook"""
145
return os.environ['JUJU_REMOTE_UNIT']
149
"""The name service group this unit belongs to"""
150
return local_unit().split('/')[0]
154
"""The name of the currently executing hook"""
155
return os.path.basename(sys.argv[0])
159
"""A dictionary representation of the charm's config.yaml, with some
162
- See which values in the dictionary have changed since the previous hook.
163
- For values that have changed, see what the previous value was.
164
- Store arbitrary data for use in a later hook.
166
NOTE: Do not instantiate this object directly - instead call
167
``hookenv.config()``, which will return an instance of :class:`Config`.
172
>>> from charmhelpers.core import hookenv
173
>>> config = hookenv.config()
176
>>> # store a new key/value for later use
177
>>> config['mykey'] = 'myval'
180
>>> # user runs `juju set mycharm foo=baz`
181
>>> # now we're inside subsequent config-changed hook
182
>>> config = hookenv.config()
185
>>> # test to see if this val has changed since last hook
186
>>> config.changed('foo')
188
>>> # what was the previous value?
189
>>> config.previous('foo')
191
>>> # keys/values that we add are preserved across hooks
196
CONFIG_FILE_NAME = '.juju-persistent-config'
198
def __init__(self, *args, **kw):
199
super(Config, self).__init__(*args, **kw)
200
self.implicit_save = True
201
self._prev_dict = None
202
self.path = os.path.join(charm_dir(), Config.CONFIG_FILE_NAME)
203
if os.path.exists(self.path):
206
def __getitem__(self, key):
207
"""For regular dict lookups, check the current juju config first,
208
then the previous (saved) copy. This ensures that user-saved values
209
will be returned by a dict lookup.
213
return dict.__getitem__(self, key)
215
return (self._prev_dict or {})[key]
217
def load_previous(self, path=None):
218
"""Load previous copy of config from disk.
220
In normal usage you don't need to call this method directly - it
221
is called automatically at object initialization.
225
File path from which to load the previous config. If `None`,
226
config is loaded from the default location. If `path` is
227
specified, subsequent `save()` calls will write to the same
231
self.path = path or self.path
232
with open(self.path) as f:
233
self._prev_dict = json.load(f)
235
def changed(self, key):
236
"""Return True if the current value for this key is different from
240
if self._prev_dict is None:
242
return self.previous(key) != self.get(key)
244
def previous(self, key):
245
"""Return previous value for this key, or None if there
246
is no previous value.
250
return self._prev_dict.get(key)
254
"""Save this config to disk.
256
If the charm is using the :mod:`Services Framework <services.base>`
257
or :meth:'@hook <Hooks.hook>' decorator, this
258
is called automatically at the end of successful hook execution.
259
Otherwise, it should be called directly by user code.
261
To disable automatic saves, set ``implicit_save=False`` on this
266
for k, v in self._prev_dict.iteritems():
269
with open(self.path, 'w') as f:
274
def config(scope=None):
275
"""Juju charm configuration"""
276
config_cmd_line = ['config-get']
277
if scope is not None:
278
config_cmd_line.append(scope)
279
config_cmd_line.append('--format=json')
281
config_data = json.loads(subprocess.check_output(config_cmd_line))
282
if scope is not None:
284
return Config(config_data)
290
def relation_get(attribute=None, unit=None, rid=None):
291
"""Get relation information"""
292
_args = ['relation-get', '--format=json']
296
_args.append(attribute or '-')
300
return json.loads(subprocess.check_output(_args))
303
except CalledProcessError, e:
304
if e.returncode == 2:
309
def relation_set(relation_id=None, relation_settings=None, **kwargs):
310
"""Set relation information for the current unit"""
311
relation_settings = relation_settings if relation_settings else {}
312
relation_cmd_line = ['relation-set']
313
if relation_id is not None:
314
relation_cmd_line.extend(('-r', relation_id))
315
for k, v in (relation_settings.items() + kwargs.items()):
317
relation_cmd_line.append('{}='.format(k))
319
relation_cmd_line.append('{}={}'.format(k, v))
320
subprocess.check_call(relation_cmd_line)
321
# Flush cache of any relation-gets for local unit
326
def relation_ids(reltype=None):
327
"""A list of relation_ids"""
328
reltype = reltype or relation_type()
329
relid_cmd_line = ['relation-ids', '--format=json']
330
if reltype is not None:
331
relid_cmd_line.append(reltype)
332
return json.loads(subprocess.check_output(relid_cmd_line)) or []
337
def related_units(relid=None):
338
"""A list of related units"""
339
relid = relid or relation_id()
340
units_cmd_line = ['relation-list', '--format=json']
341
if relid is not None:
342
units_cmd_line.extend(('-r', relid))
343
return json.loads(subprocess.check_output(units_cmd_line)) or []
347
def relation_for_unit(unit=None, rid=None):
348
"""Get the json represenation of a unit's relation"""
349
unit = unit or remote_unit()
350
relation = relation_get(unit=unit, rid=rid)
352
if key.endswith('-list'):
353
relation[key] = relation[key].split()
354
relation['__unit__'] = unit
359
def relations_for_id(relid=None):
360
"""Get relations of a specific relation ID"""
362
relid = relid or relation_ids()
363
for unit in related_units(relid):
364
unit_data = relation_for_unit(unit, relid)
365
unit_data['__relid__'] = relid
366
relation_data.append(unit_data)
371
def relations_of_type(reltype=None):
372
"""Get relations of a specific type"""
374
reltype = reltype or relation_type()
375
for relid in relation_ids(reltype):
376
for relation in relations_for_id(relid):
377
relation['__relid__'] = relid
378
relation_data.append(relation)
383
def relation_types():
384
"""Get a list of relation types supported by this charm"""
385
charmdir = os.environ.get('CHARM_DIR', '')
386
mdf = open(os.path.join(charmdir, 'metadata.yaml'))
387
md = yaml.safe_load(mdf)
389
for key in ('provides', 'requires', 'peers'):
390
section = md.get(key)
392
rel_types.extend(section.keys())
399
"""Get a nested dictionary of relation data for all related units"""
401
for reltype in relation_types():
403
for relid in relation_ids(reltype):
404
units = {local_unit(): relation_get(unit=local_unit(), rid=relid)}
405
for unit in related_units(relid):
406
reldata = relation_get(unit=unit, rid=relid)
407
units[unit] = reldata
408
relids[relid] = units
409
rels[reltype] = relids
414
def is_relation_made(relation, keys='private-address'):
416
Determine whether a relation is established by checking for
417
presence of key(s). If a list of keys is provided, they
418
must all be present for the relation to be identified as made
420
if isinstance(keys, str):
422
for r_id in relation_ids(relation):
423
for unit in related_units(r_id):
426
context[k] = relation_get(k, rid=r_id,
428
if None not in context.values():
433
def open_port(port, protocol="TCP"):
434
"""Open a service network port"""
435
_args = ['open-port']
436
_args.append('{}/{}'.format(port, protocol))
437
subprocess.check_call(_args)
440
def close_port(port, protocol="TCP"):
441
"""Close a service network port"""
442
_args = ['close-port']
443
_args.append('{}/{}'.format(port, protocol))
444
subprocess.check_call(_args)
448
def unit_get(attribute):
449
"""Get the unit ID for the remote unit"""
450
_args = ['unit-get', '--format=json', attribute]
452
return json.loads(subprocess.check_output(_args))
457
def unit_private_ip():
458
"""Get this unit's private IP address"""
459
return unit_get('private-address')
462
class UnregisteredHookError(Exception):
463
"""Raised when an undefined hook is called"""
468
"""A convenient handler for hook functions.
474
# register a hook, taking its name from the function name
477
pass # your code here
479
# register a hook, providing a custom hook name
480
@hooks.hook("config-changed")
481
def config_changed():
482
pass # your code here
484
if __name__ == "__main__":
485
# execute a hook based on the name the program is called by
486
hooks.execute(sys.argv)
490
super(Hooks, self).__init__()
493
def register(self, name, function):
494
"""Register a hook"""
495
self._hooks[name] = function
497
def execute(self, args):
498
"""Execute a registered hook based on args[0]"""
499
hook_name = os.path.basename(args[0])
500
if hook_name in self._hooks:
501
self._hooks[hook_name]()
503
if cfg.implicit_save:
506
raise UnregisteredHookError(hook_name)
508
def hook(self, *hook_names):
509
"""Decorator, registering them as hooks"""
510
def wrapper(decorated):
511
for hook_name in hook_names:
512
self.register(hook_name, decorated)
514
self.register(decorated.__name__, decorated)
515
if '_' in decorated.__name__:
517
decorated.__name__.replace('_', '-'), decorated)
523
"""Return the root directory of the current charm"""
524
return os.environ.get('CHARM_DIR')