~robert-ayres/charms/trusty/contrail-configuration/trunk

« back to all changes in this revision

Viewing changes to hooks/charmhelpers/core/hookenv.py

  • Committer: Robert Ayres
  • Date: 2014-09-10 14:03:02 UTC
  • Revision ID: robert.ayres@canonical.com-20140910140302-bqu0wb61an4nhgfa
Initial charm

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
"Interactions with the Juju environment"
 
2
# Copyright 2013 Canonical Ltd.
 
3
#
 
4
# Authors:
 
5
#  Charm Helpers Developers <juju@lists.ubuntu.com>
 
6
 
 
7
import os
 
8
import json
 
9
import yaml
 
10
import subprocess
 
11
import sys
 
12
import UserDict
 
13
from subprocess import CalledProcessError
 
14
 
 
15
CRITICAL = "CRITICAL"
 
16
ERROR = "ERROR"
 
17
WARNING = "WARNING"
 
18
INFO = "INFO"
 
19
DEBUG = "DEBUG"
 
20
MARKER = object()
 
21
 
 
22
cache = {}
 
23
 
 
24
 
 
25
def cached(func):
 
26
    """Cache return values for multiple executions of func + args
 
27
 
 
28
    For example::
 
29
 
 
30
        @cached
 
31
        def unit_get(attribute):
 
32
            pass
 
33
 
 
34
        unit_get('test')
 
35
 
 
36
    will cache the result of unit_get + 'test' for future calls.
 
37
    """
 
38
    def wrapper(*args, **kwargs):
 
39
        global cache
 
40
        key = str((func, args, kwargs))
 
41
        try:
 
42
            return cache[key]
 
43
        except KeyError:
 
44
            res = func(*args, **kwargs)
 
45
            cache[key] = res
 
46
            return res
 
47
    return wrapper
 
48
 
 
49
 
 
50
def flush(key):
 
51
    """Flushes any entries from function cache where the
 
52
    key is found in the function+args """
 
53
    flush_list = []
 
54
    for item in cache:
 
55
        if key in item:
 
56
            flush_list.append(item)
 
57
    for item in flush_list:
 
58
        del cache[item]
 
59
 
 
60
 
 
61
def log(message, level=None):
 
62
    """Write a message to the juju log"""
 
63
    command = ['juju-log']
 
64
    if level:
 
65
        command += ['-l', level]
 
66
    command += [message]
 
67
    subprocess.call(command)
 
68
 
 
69
 
 
70
class Serializable(UserDict.IterableUserDict):
 
71
    """Wrapper, an object that can be serialized to yaml or json"""
 
72
 
 
73
    def __init__(self, obj):
 
74
        # wrap the object
 
75
        UserDict.IterableUserDict.__init__(self)
 
76
        self.data = obj
 
77
 
 
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)
 
84
        if got is not MARKER:
 
85
            return got
 
86
        # Proxy to the wrapped object via dict interface.
 
87
        try:
 
88
            return self.data[attr]
 
89
        except KeyError:
 
90
            raise AttributeError(attr)
 
91
 
 
92
    def __getstate__(self):
 
93
        # Pickle as a standard dictionary.
 
94
        return self.data
 
95
 
 
96
    def __setstate__(self, state):
 
97
        # Unpickle into our wrapper.
 
98
        self.data = state
 
99
 
 
100
    def json(self):
 
101
        """Serialize the object to json"""
 
102
        return json.dumps(self.data)
 
103
 
 
104
    def yaml(self):
 
105
        """Serialize the object to yaml"""
 
106
        return yaml.dump(self.data)
 
107
 
 
108
 
 
109
def execution_environment():
 
110
    """A convenient bundling of the current execution context"""
 
111
    context = {}
 
112
    context['conf'] = config()
 
113
    if relation_id():
 
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
 
120
    return context
 
121
 
 
122
 
 
123
def in_relation_hook():
 
124
    """Determine whether we're running in a relation hook"""
 
125
    return 'JUJU_RELATION' in os.environ
 
126
 
 
127
 
 
128
def relation_type():
 
129
    """The scope for the current relation hook"""
 
130
    return os.environ.get('JUJU_RELATION', None)
 
131
 
 
132
 
 
133
def relation_id():
 
134
    """The relation ID for the current relation hook"""
 
135
    return os.environ.get('JUJU_RELATION_ID', None)
 
136
 
 
137
 
 
138
def local_unit():
 
139
    """Local unit ID"""
 
140
    return os.environ['JUJU_UNIT_NAME']
 
141
 
 
142
 
 
143
def remote_unit():
 
144
    """The remote unit for the current relation hook"""
 
145
    return os.environ['JUJU_REMOTE_UNIT']
 
146
 
 
147
 
 
148
def service_name():
 
149
    """The name service group this unit belongs to"""
 
150
    return local_unit().split('/')[0]
 
151
 
 
152
 
 
153
def hook_name():
 
154
    """The name of the currently executing hook"""
 
155
    return os.path.basename(sys.argv[0])
 
156
 
 
157
 
 
158
class Config(dict):
 
159
    """A dictionary representation of the charm's config.yaml, with some
 
160
    extra features:
 
161
 
 
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.
 
165
 
 
166
    NOTE: Do not instantiate this object directly - instead call
 
167
    ``hookenv.config()``, which will return an instance of :class:`Config`.
 
168
 
 
169
    Example usage::
 
170
 
 
171
        >>> # inside a hook
 
172
        >>> from charmhelpers.core import hookenv
 
173
        >>> config = hookenv.config()
 
174
        >>> config['foo']
 
175
        'bar'
 
176
        >>> # store a new key/value for later use
 
177
        >>> config['mykey'] = 'myval'
 
178
 
 
179
 
 
180
        >>> # user runs `juju set mycharm foo=baz`
 
181
        >>> # now we're inside subsequent config-changed hook
 
182
        >>> config = hookenv.config()
 
183
        >>> config['foo']
 
184
        'baz'
 
185
        >>> # test to see if this val has changed since last hook
 
186
        >>> config.changed('foo')
 
187
        True
 
188
        >>> # what was the previous value?
 
189
        >>> config.previous('foo')
 
190
        'bar'
 
191
        >>> # keys/values that we add are preserved across hooks
 
192
        >>> config['mykey']
 
193
        'myval'
 
194
 
 
195
    """
 
196
    CONFIG_FILE_NAME = '.juju-persistent-config'
 
197
 
 
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):
 
204
            self.load_previous()
 
205
 
 
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.
 
210
 
 
211
        """
 
212
        try:
 
213
            return dict.__getitem__(self, key)
 
214
        except KeyError:
 
215
            return (self._prev_dict or {})[key]
 
216
 
 
217
    def load_previous(self, path=None):
 
218
        """Load previous copy of config from disk.
 
219
 
 
220
        In normal usage you don't need to call this method directly - it
 
221
        is called automatically at object initialization.
 
222
 
 
223
        :param path:
 
224
 
 
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
 
228
            path.
 
229
 
 
230
        """
 
231
        self.path = path or self.path
 
232
        with open(self.path) as f:
 
233
            self._prev_dict = json.load(f)
 
234
 
 
235
    def changed(self, key):
 
236
        """Return True if the current value for this key is different from
 
237
        the previous value.
 
238
 
 
239
        """
 
240
        if self._prev_dict is None:
 
241
            return True
 
242
        return self.previous(key) != self.get(key)
 
243
 
 
244
    def previous(self, key):
 
245
        """Return previous value for this key, or None if there
 
246
        is no previous value.
 
247
 
 
248
        """
 
249
        if self._prev_dict:
 
250
            return self._prev_dict.get(key)
 
251
        return None
 
252
 
 
253
    def save(self):
 
254
        """Save this config to disk.
 
255
 
 
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.
 
260
 
 
261
        To disable automatic saves, set ``implicit_save=False`` on this
 
262
        instance.
 
263
 
 
264
        """
 
265
        if self._prev_dict:
 
266
            for k, v in self._prev_dict.iteritems():
 
267
                if k not in self:
 
268
                    self[k] = v
 
269
        with open(self.path, 'w') as f:
 
270
            json.dump(self, f)
 
271
 
 
272
 
 
273
@cached
 
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')
 
280
    try:
 
281
        config_data = json.loads(subprocess.check_output(config_cmd_line))
 
282
        if scope is not None:
 
283
            return config_data
 
284
        return Config(config_data)
 
285
    except ValueError:
 
286
        return None
 
287
 
 
288
 
 
289
@cached
 
290
def relation_get(attribute=None, unit=None, rid=None):
 
291
    """Get relation information"""
 
292
    _args = ['relation-get', '--format=json']
 
293
    if rid:
 
294
        _args.append('-r')
 
295
        _args.append(rid)
 
296
    _args.append(attribute or '-')
 
297
    if unit:
 
298
        _args.append(unit)
 
299
    try:
 
300
        return json.loads(subprocess.check_output(_args))
 
301
    except ValueError:
 
302
        return None
 
303
    except CalledProcessError, e:
 
304
        if e.returncode == 2:
 
305
            return None
 
306
        raise
 
307
 
 
308
 
 
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()):
 
316
        if v is None:
 
317
            relation_cmd_line.append('{}='.format(k))
 
318
        else:
 
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
 
322
    flush(local_unit())
 
323
 
 
324
 
 
325
@cached
 
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 []
 
333
    return []
 
334
 
 
335
 
 
336
@cached
 
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 []
 
344
 
 
345
 
 
346
@cached
 
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)
 
351
    for key in relation:
 
352
        if key.endswith('-list'):
 
353
            relation[key] = relation[key].split()
 
354
    relation['__unit__'] = unit
 
355
    return relation
 
356
 
 
357
 
 
358
@cached
 
359
def relations_for_id(relid=None):
 
360
    """Get relations of a specific relation ID"""
 
361
    relation_data = []
 
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)
 
367
    return relation_data
 
368
 
 
369
 
 
370
@cached
 
371
def relations_of_type(reltype=None):
 
372
    """Get relations of a specific type"""
 
373
    relation_data = []
 
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)
 
379
    return relation_data
 
380
 
 
381
 
 
382
@cached
 
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)
 
388
    rel_types = []
 
389
    for key in ('provides', 'requires', 'peers'):
 
390
        section = md.get(key)
 
391
        if section:
 
392
            rel_types.extend(section.keys())
 
393
    mdf.close()
 
394
    return rel_types
 
395
 
 
396
 
 
397
@cached
 
398
def relations():
 
399
    """Get a nested dictionary of relation data for all related units"""
 
400
    rels = {}
 
401
    for reltype in relation_types():
 
402
        relids = {}
 
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
 
410
    return rels
 
411
 
 
412
 
 
413
@cached
 
414
def is_relation_made(relation, keys='private-address'):
 
415
    '''
 
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
 
419
    '''
 
420
    if isinstance(keys, str):
 
421
        keys = [keys]
 
422
    for r_id in relation_ids(relation):
 
423
        for unit in related_units(r_id):
 
424
            context = {}
 
425
            for k in keys:
 
426
                context[k] = relation_get(k, rid=r_id,
 
427
                                          unit=unit)
 
428
            if None not in context.values():
 
429
                return True
 
430
    return False
 
431
 
 
432
 
 
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)
 
438
 
 
439
 
 
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)
 
445
 
 
446
 
 
447
@cached
 
448
def unit_get(attribute):
 
449
    """Get the unit ID for the remote unit"""
 
450
    _args = ['unit-get', '--format=json', attribute]
 
451
    try:
 
452
        return json.loads(subprocess.check_output(_args))
 
453
    except ValueError:
 
454
        return None
 
455
 
 
456
 
 
457
def unit_private_ip():
 
458
    """Get this unit's private IP address"""
 
459
    return unit_get('private-address')
 
460
 
 
461
 
 
462
class UnregisteredHookError(Exception):
 
463
    """Raised when an undefined hook is called"""
 
464
    pass
 
465
 
 
466
 
 
467
class Hooks(object):
 
468
    """A convenient handler for hook functions.
 
469
 
 
470
    Example::
 
471
 
 
472
        hooks = Hooks()
 
473
 
 
474
        # register a hook, taking its name from the function name
 
475
        @hooks.hook()
 
476
        def install():
 
477
            pass  # your code here
 
478
 
 
479
        # register a hook, providing a custom hook name
 
480
        @hooks.hook("config-changed")
 
481
        def config_changed():
 
482
            pass  # your code here
 
483
 
 
484
        if __name__ == "__main__":
 
485
            # execute a hook based on the name the program is called by
 
486
            hooks.execute(sys.argv)
 
487
    """
 
488
 
 
489
    def __init__(self):
 
490
        super(Hooks, self).__init__()
 
491
        self._hooks = {}
 
492
 
 
493
    def register(self, name, function):
 
494
        """Register a hook"""
 
495
        self._hooks[name] = function
 
496
 
 
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]()
 
502
            cfg = config()
 
503
            if cfg.implicit_save:
 
504
                cfg.save()
 
505
        else:
 
506
            raise UnregisteredHookError(hook_name)
 
507
 
 
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)
 
513
            else:
 
514
                self.register(decorated.__name__, decorated)
 
515
                if '_' in decorated.__name__:
 
516
                    self.register(
 
517
                        decorated.__name__.replace('_', '-'), decorated)
 
518
            return decorated
 
519
        return wrapper
 
520
 
 
521
 
 
522
def charm_dir():
 
523
    """Return the root directory of the current charm"""
 
524
    return os.environ.get('CHARM_DIR')