121
146
def in_relation_hook():
122
"Determine whether we're running in a relation hook"
147
"""Determine whether we're running in a relation hook"""
123
148
return 'JUJU_RELATION' in os.environ
126
151
def relation_type():
127
"The scope for the current relation hook"
152
"""The scope for the current relation hook"""
128
153
return os.environ.get('JUJU_RELATION', None)
131
156
def relation_id():
132
"The relation ID for the current relation hook"
157
"""The relation ID for the current relation hook"""
133
158
return os.environ.get('JUJU_RELATION_ID', None)
136
161
def local_unit():
138
163
return os.environ['JUJU_UNIT_NAME']
141
166
def remote_unit():
142
"The remote unit for the current relation hook"
167
"""The remote unit for the current relation hook"""
143
168
return os.environ['JUJU_REMOTE_UNIT']
146
171
def service_name():
147
"The name service group this unit belongs to"
172
"""The name service group this unit belongs to"""
148
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:
152
303
def config(scope=None):
153
"Juju charm configuration"
304
"""Juju charm configuration"""
154
305
config_cmd_line = ['config-get']
155
306
if scope is not None:
156
307
config_cmd_line.append(scope)
157
308
config_cmd_line.append('--format=json')
159
return json.loads(subprocess.check_output(config_cmd_line))
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)
160
315
except ValueError:
165
320
def relation_get(attribute=None, unit=None, rid=None):
321
"""Get relation information"""
166
322
_args = ['relation-get', '--format=json']
168
324
_args.append('-r')
172
328
_args.append(unit)
174
return json.loads(subprocess.check_output(_args))
330
return json.loads(subprocess.check_output(_args).decode('UTF-8'))
175
331
except ValueError:
179
def relation_set(relation_id=None, relation_settings={}, **kwargs):
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 {}
180
342
relation_cmd_line = ['relation-set']
181
343
if relation_id is not None:
182
344
relation_cmd_line.extend(('-r', relation_id))
183
for k, v in (relation_settings.items() + kwargs.items()):
345
for k, v in (list(relation_settings.items()) + list(kwargs.items())):
185
347
relation_cmd_line.append('{}='.format(k))
194
356
def relation_ids(reltype=None):
195
"A list of relation_ids"
357
"""A list of relation_ids"""
196
358
reltype = reltype or relation_type()
197
359
relid_cmd_line = ['relation-ids', '--format=json']
198
360
if reltype is not None:
199
361
relid_cmd_line.append(reltype)
200
return json.loads(subprocess.check_output(relid_cmd_line)) or []
363
subprocess.check_output(relid_cmd_line).decode('UTF-8')) or []
205
368
def related_units(relid=None):
206
"A list of related units"
369
"""A list of related units"""
207
370
relid = relid or relation_id()
208
371
units_cmd_line = ['relation-list', '--format=json']
209
372
if relid is not None:
210
373
units_cmd_line.extend(('-r', relid))
211
return json.loads(subprocess.check_output(units_cmd_line)) or []
375
subprocess.check_output(units_cmd_line).decode('UTF-8')) or []
215
379
def relation_for_unit(unit=None, rid=None):
216
"Get the json represenation of a unit's relation"
380
"""Get the json represenation of a unit's relation"""
217
381
unit = unit or remote_unit()
218
382
relation = relation_get(unit=unit, rid=rid)
219
383
for key in relation:
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():
280
475
def open_port(port, protocol="TCP"):
281
"Open a service network port"
476
"""Open a service network port"""
282
477
_args = ['open-port']
283
478
_args.append('{}/{}'.format(port, protocol))
284
479
subprocess.check_call(_args)
287
482
def close_port(port, protocol="TCP"):
288
"Close a service network port"
483
"""Close a service network port"""
289
484
_args = ['close-port']
290
485
_args.append('{}/{}'.format(port, protocol))
291
486
subprocess.check_call(_args)
295
490
def unit_get(attribute):
491
"""Get the unit ID for the remote unit"""
296
492
_args = ['unit-get', '--format=json', attribute]
298
return json.loads(subprocess.check_output(_args))
494
return json.loads(subprocess.check_output(_args).decode('UTF-8'))
299
495
except ValueError:
303
499
def unit_private_ip():
500
"""Get this unit's private IP address"""
304
501
return unit_get('private-address')
307
504
class UnregisteredHookError(Exception):
505
"""Raised when an undefined hook is called"""
311
509
class Hooks(object):
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):
313
532
super(Hooks, self).__init__()
534
self._config_save = config_save
316
536
def register(self, name, function):
537
"""Register a hook"""
317
538
self._hooks[name] = function
319
540
def execute(self, args):
541
"""Execute a registered hook based on args[0]"""
320
542
hook_name = os.path.basename(args[0])
321
543
if hook_name in self._hooks:
322
544
self._hooks[hook_name]()
545
if self._config_save:
547
if cfg.implicit_save:
324
550
raise UnregisteredHookError(hook_name)
326
552
def hook(self, *hook_names):
553
"""Decorator, registering them as hooks"""
327
554
def wrapper(decorated):
328
555
for hook_name in hook_names:
329
556
self.register(hook_name, decorated)