~free.ekanayaka/landscape-charm/run-schema-script

« back to all changes in this revision

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

  • Committer: Free Ekanayaka
  • Date: 2015-01-28 11:53:32 UTC
  • mfrom: (222.1.5 testable-install-hook)
  • Revision ID: free.ekanayaka@canonical.com-20150128115332-4fjkh28z3lqf136x
MergeĀ fromĀ testable-install-hook

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright 2014-2015 Canonical Limited.
 
2
#
 
3
# This file is part of charm-helpers.
 
4
#
 
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.
 
8
#
 
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.
 
13
#
 
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/>.
 
16
 
 
17
"Interactions with the Juju environment"
 
18
# Copyright 2013 Canonical Ltd.
 
19
#
 
20
# Authors:
 
21
#  Charm Helpers Developers <juju@lists.ubuntu.com>
 
22
 
 
23
import os
 
24
import json
 
25
import yaml
 
26
import subprocess
 
27
import sys
 
28
from subprocess import CalledProcessError
 
29
 
 
30
import six
 
31
if not six.PY3:
 
32
    from UserDict import UserDict
 
33
else:
 
34
    from collections import UserDict
 
35
 
 
36
CRITICAL = "CRITICAL"
 
37
ERROR = "ERROR"
 
38
WARNING = "WARNING"
 
39
INFO = "INFO"
 
40
DEBUG = "DEBUG"
 
41
MARKER = object()
 
42
 
 
43
cache = {}
 
44
 
 
45
 
 
46
def cached(func):
 
47
    """Cache return values for multiple executions of func + args
 
48
 
 
49
    For example::
 
50
 
 
51
        @cached
 
52
        def unit_get(attribute):
 
53
            pass
 
54
 
 
55
        unit_get('test')
 
56
 
 
57
    will cache the result of unit_get + 'test' for future calls.
 
58
    """
 
59
    def wrapper(*args, **kwargs):
 
60
        global cache
 
61
        key = str((func, args, kwargs))
 
62
        try:
 
63
            return cache[key]
 
64
        except KeyError:
 
65
            res = func(*args, **kwargs)
 
66
            cache[key] = res
 
67
            return res
 
68
    return wrapper
 
69
 
 
70
 
 
71
def flush(key):
 
72
    """Flushes any entries from function cache where the
 
73
    key is found in the function+args """
 
74
    flush_list = []
 
75
    for item in cache:
 
76
        if key in item:
 
77
            flush_list.append(item)
 
78
    for item in flush_list:
 
79
        del cache[item]
 
80
 
 
81
 
 
82
def log(message, level=None):
 
83
    """Write a message to the juju log"""
 
84
    command = ['juju-log']
 
85
    if level:
 
86
        command += ['-l', level]
 
87
    if not isinstance(message, six.string_types):
 
88
        message = repr(message)
 
89
    command += [message]
 
90
    subprocess.call(command)
 
91
 
 
92
 
 
93
class Serializable(UserDict):
 
94
    """Wrapper, an object that can be serialized to yaml or json"""
 
95
 
 
96
    def __init__(self, obj):
 
97
        # wrap the object
 
98
        UserDict.__init__(self)
 
99
        self.data = obj
 
100
 
 
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:
 
108
            return got
 
109
        # Proxy to the wrapped object via dict interface.
 
110
        try:
 
111
            return self.data[attr]
 
112
        except KeyError:
 
113
            raise AttributeError(attr)
 
114
 
 
115
    def __getstate__(self):
 
116
        # Pickle as a standard dictionary.
 
117
        return self.data
 
118
 
 
119
    def __setstate__(self, state):
 
120
        # Unpickle into our wrapper.
 
121
        self.data = state
 
122
 
 
123
    def json(self):
 
124
        """Serialize the object to json"""
 
125
        return json.dumps(self.data)
 
126
 
 
127
    def yaml(self):
 
128
        """Serialize the object to yaml"""
 
129
        return yaml.dump(self.data)
 
130
 
 
131
 
 
132
def execution_environment():
 
133
    """A convenient bundling of the current execution context"""
 
134
    context = {}
 
135
    context['conf'] = config()
 
136
    if relation_id():
 
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
 
143
    return context
 
144
 
 
145
 
 
146
def in_relation_hook():
 
147
    """Determine whether we're running in a relation hook"""
 
148
    return 'JUJU_RELATION' in os.environ
 
149
 
 
150
 
 
151
def relation_type():
 
152
    """The scope for the current relation hook"""
 
153
    return os.environ.get('JUJU_RELATION', None)
 
154
 
 
155
 
 
156
def relation_id():
 
157
    """The relation ID for the current relation hook"""
 
158
    return os.environ.get('JUJU_RELATION_ID', None)
 
159
 
 
160
 
 
161
def local_unit():
 
162
    """Local unit ID"""
 
163
    return os.environ['JUJU_UNIT_NAME']
 
164
 
 
165
 
 
166
def remote_unit():
 
167
    """The remote unit for the current relation hook"""
 
168
    return os.environ['JUJU_REMOTE_UNIT']
 
169
 
 
170
 
 
171
def service_name():
 
172
    """The name service group this unit belongs to"""
 
173
    return local_unit().split('/')[0]
 
174
 
 
175
 
 
176
def hook_name():
 
177
    """The name of the currently executing hook"""
 
178
    return os.path.basename(sys.argv[0])
 
179
 
 
180
 
 
181
class Config(dict):
 
182
    """A dictionary representation of the charm's config.yaml, with some
 
183
    extra features:
 
184
 
 
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.
 
188
 
 
189
    NOTE: Do not instantiate this object directly - instead call
 
190
    ``hookenv.config()``, which will return an instance of :class:`Config`.
 
191
 
 
192
    Example usage::
 
193
 
 
194
        >>> # inside a hook
 
195
        >>> from charmhelpers.core import hookenv
 
196
        >>> config = hookenv.config()
 
197
        >>> config['foo']
 
198
        'bar'
 
199
        >>> # store a new key/value for later use
 
200
        >>> config['mykey'] = 'myval'
 
201
 
 
202
 
 
203
        >>> # user runs `juju set mycharm foo=baz`
 
204
        >>> # now we're inside subsequent config-changed hook
 
205
        >>> config = hookenv.config()
 
206
        >>> config['foo']
 
207
        'baz'
 
208
        >>> # test to see if this val has changed since last hook
 
209
        >>> config.changed('foo')
 
210
        True
 
211
        >>> # what was the previous value?
 
212
        >>> config.previous('foo')
 
213
        'bar'
 
214
        >>> # keys/values that we add are preserved across hooks
 
215
        >>> config['mykey']
 
216
        'myval'
 
217
 
 
218
    """
 
219
    CONFIG_FILE_NAME = '.juju-persistent-config'
 
220
 
 
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):
 
227
            self.load_previous()
 
228
 
 
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.
 
233
 
 
234
        """
 
235
        try:
 
236
            return dict.__getitem__(self, key)
 
237
        except KeyError:
 
238
            return (self._prev_dict or {})[key]
 
239
 
 
240
    def keys(self):
 
241
        prev_keys = []
 
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))))
 
245
 
 
246
    def load_previous(self, path=None):
 
247
        """Load previous copy of config from disk.
 
248
 
 
249
        In normal usage you don't need to call this method directly - it
 
250
        is called automatically at object initialization.
 
251
 
 
252
        :param path:
 
253
 
 
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
 
257
            path.
 
258
 
 
259
        """
 
260
        self.path = path or self.path
 
261
        with open(self.path) as f:
 
262
            self._prev_dict = json.load(f)
 
263
 
 
264
    def changed(self, key):
 
265
        """Return True if the current value for this key is different from
 
266
        the previous value.
 
267
 
 
268
        """
 
269
        if self._prev_dict is None:
 
270
            return True
 
271
        return self.previous(key) != self.get(key)
 
272
 
 
273
    def previous(self, key):
 
274
        """Return previous value for this key, or None if there
 
275
        is no previous value.
 
276
 
 
277
        """
 
278
        if self._prev_dict:
 
279
            return self._prev_dict.get(key)
 
280
        return None
 
281
 
 
282
    def save(self):
 
283
        """Save this config to disk.
 
284
 
 
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.
 
289
 
 
290
        To disable automatic saves, set ``implicit_save=False`` on this
 
291
        instance.
 
292
 
 
293
        """
 
294
        if self._prev_dict:
 
295
            for k, v in six.iteritems(self._prev_dict):
 
296
                if k not in self:
 
297
                    self[k] = v
 
298
        with open(self.path, 'w') as f:
 
299
            json.dump(self, f)
 
300
 
 
301
 
 
302
@cached
 
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')
 
309
    try:
 
310
        config_data = json.loads(
 
311
            subprocess.check_output(config_cmd_line).decode('UTF-8'))
 
312
        if scope is not None:
 
313
            return config_data
 
314
        return Config(config_data)
 
315
    except ValueError:
 
316
        return None
 
317
 
 
318
 
 
319
@cached
 
320
def relation_get(attribute=None, unit=None, rid=None):
 
321
    """Get relation information"""
 
322
    _args = ['relation-get', '--format=json']
 
323
    if rid:
 
324
        _args.append('-r')
 
325
        _args.append(rid)
 
326
    _args.append(attribute or '-')
 
327
    if unit:
 
328
        _args.append(unit)
 
329
    try:
 
330
        return json.loads(subprocess.check_output(_args).decode('UTF-8'))
 
331
    except ValueError:
 
332
        return None
 
333
    except CalledProcessError as e:
 
334
        if e.returncode == 2:
 
335
            return None
 
336
        raise
 
337
 
 
338
 
 
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())):
 
346
        if v is None:
 
347
            relation_cmd_line.append('{}='.format(k))
 
348
        else:
 
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
 
352
    flush(local_unit())
 
353
 
 
354
 
 
355
@cached
 
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)
 
362
        return json.loads(
 
363
            subprocess.check_output(relid_cmd_line).decode('UTF-8')) or []
 
364
    return []
 
365
 
 
366
 
 
367
@cached
 
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))
 
374
    return json.loads(
 
375
        subprocess.check_output(units_cmd_line).decode('UTF-8')) or []
 
376
 
 
377
 
 
378
@cached
 
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)
 
383
    for key in relation:
 
384
        if key.endswith('-list'):
 
385
            relation[key] = relation[key].split()
 
386
    relation['__unit__'] = unit
 
387
    return relation
 
388
 
 
389
 
 
390
@cached
 
391
def relations_for_id(relid=None):
 
392
    """Get relations of a specific relation ID"""
 
393
    relation_data = []
 
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)
 
399
    return relation_data
 
400
 
 
401
 
 
402
@cached
 
403
def relations_of_type(reltype=None):
 
404
    """Get relations of a specific type"""
 
405
    relation_data = []
 
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)
 
411
    return relation_data
 
412
 
 
413
 
 
414
@cached
 
415
def metadata():
 
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)
 
419
 
 
420
 
 
421
@cached
 
422
def relation_types():
 
423
    """Get a list of relation types supported by this charm"""
 
424
    rel_types = []
 
425
    md = metadata()
 
426
    for key in ('provides', 'requires', 'peers'):
 
427
        section = md.get(key)
 
428
        if section:
 
429
            rel_types.extend(section.keys())
 
430
    return rel_types
 
431
 
 
432
 
 
433
@cached
 
434
def charm_name():
 
435
    """Get the name of the current charm as is specified on metadata.yaml"""
 
436
    return metadata().get('name')
 
437
 
 
438
 
 
439
@cached
 
440
def relations():
 
441
    """Get a nested dictionary of relation data for all related units"""
 
442
    rels = {}
 
443
    for reltype in relation_types():
 
444
        relids = {}
 
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
 
452
    return rels
 
453
 
 
454
 
 
455
@cached
 
456
def is_relation_made(relation, keys='private-address'):
 
457
    '''
 
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
 
461
    '''
 
462
    if isinstance(keys, str):
 
463
        keys = [keys]
 
464
    for r_id in relation_ids(relation):
 
465
        for unit in related_units(r_id):
 
466
            context = {}
 
467
            for k in keys:
 
468
                context[k] = relation_get(k, rid=r_id,
 
469
                                          unit=unit)
 
470
            if None not in context.values():
 
471
                return True
 
472
    return False
 
473
 
 
474
 
 
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)
 
480
 
 
481
 
 
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)
 
487
 
 
488
 
 
489
@cached
 
490
def unit_get(attribute):
 
491
    """Get the unit ID for the remote unit"""
 
492
    _args = ['unit-get', '--format=json', attribute]
 
493
    try:
 
494
        return json.loads(subprocess.check_output(_args).decode('UTF-8'))
 
495
    except ValueError:
 
496
        return None
 
497
 
 
498
 
 
499
def unit_private_ip():
 
500
    """Get this unit's private IP address"""
 
501
    return unit_get('private-address')
 
502
 
 
503
 
 
504
class UnregisteredHookError(Exception):
 
505
    """Raised when an undefined hook is called"""
 
506
    pass
 
507
 
 
508
 
 
509
class Hooks(object):
 
510
    """A convenient handler for hook functions.
 
511
 
 
512
    Example::
 
513
 
 
514
        hooks = Hooks()
 
515
 
 
516
        # register a hook, taking its name from the function name
 
517
        @hooks.hook()
 
518
        def install():
 
519
            pass  # your code here
 
520
 
 
521
        # register a hook, providing a custom hook name
 
522
        @hooks.hook("config-changed")
 
523
        def config_changed():
 
524
            pass  # your code here
 
525
 
 
526
        if __name__ == "__main__":
 
527
            # execute a hook based on the name the program is called by
 
528
            hooks.execute(sys.argv)
 
529
    """
 
530
 
 
531
    def __init__(self, config_save=True):
 
532
        super(Hooks, self).__init__()
 
533
        self._hooks = {}
 
534
        self._config_save = config_save
 
535
 
 
536
    def register(self, name, function):
 
537
        """Register a hook"""
 
538
        self._hooks[name] = function
 
539
 
 
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:
 
546
                cfg = config()
 
547
                if cfg.implicit_save:
 
548
                    cfg.save()
 
549
        else:
 
550
            raise UnregisteredHookError(hook_name)
 
551
 
 
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)
 
557
            else:
 
558
                self.register(decorated.__name__, decorated)
 
559
                if '_' in decorated.__name__:
 
560
                    self.register(
 
561
                        decorated.__name__.replace('_', '-'), decorated)
 
562
            return decorated
 
563
        return wrapper
 
564
 
 
565
 
 
566
def charm_dir():
 
567
    """Return the root directory of the current charm"""
 
568
    return os.environ.get('CHARM_DIR')