~jamesj/charms/trusty/haproxy/xenial-support

« back to all changes in this revision

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

  • Committer: Christopher Glass
  • Date: 2015-02-20 09:42:24 UTC
  • mfrom: (86.2.15 ssl-crt-support)
  • Revision ID: christopher.glass@canonical.com-20150220094224-az770sf2ny2jnkax
Merge lp:~free.ekanayaka/charms/trusty/haproxy/ssl-crt-support [a=free.ekanayaka, r=tribaal]

This branch adds support for SSL termination if the installed HAproxy version
supports it.

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
 
1
17
"Interactions with the Juju environment"
2
18
# Copyright 2013 Canonical Ltd.
3
19
#
8
24
import json
9
25
import yaml
10
26
import subprocess
11
 
import UserDict
 
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
12
35
 
13
36
CRITICAL = "CRITICAL"
14
37
ERROR = "ERROR"
21
44
 
22
45
 
23
46
def cached(func):
24
 
    ''' Cache return values for multiple executions of func + args
 
47
    """Cache return values for multiple executions of func + args
25
48
 
26
 
    For example:
 
49
    For example::
27
50
 
28
51
        @cached
29
52
        def unit_get(attribute):
32
55
        unit_get('test')
33
56
 
34
57
    will cache the result of unit_get + 'test' for future calls.
35
 
    '''
 
58
    """
36
59
    def wrapper(*args, **kwargs):
37
60
        global cache
38
61
        key = str((func, args, kwargs))
46
69
 
47
70
 
48
71
def flush(key):
49
 
    ''' Flushes any entries from function cache where the
50
 
    key is found in the function+args '''
 
72
    """Flushes any entries from function cache where the
 
73
    key is found in the function+args """
51
74
    flush_list = []
52
75
    for item in cache:
53
76
        if key in item:
57
80
 
58
81
 
59
82
def log(message, level=None):
60
 
    "Write a message to the juju log"
 
83
    """Write a message to the juju log"""
61
84
    command = ['juju-log']
62
85
    if level:
63
86
        command += ['-l', level]
 
87
    if not isinstance(message, six.string_types):
 
88
        message = repr(message)
64
89
    command += [message]
65
90
    subprocess.call(command)
66
91
 
67
92
 
68
 
class Serializable(UserDict.IterableUserDict):
69
 
    "Wrapper, an object that can be serialized to yaml or json"
 
93
class Serializable(UserDict):
 
94
    """Wrapper, an object that can be serialized to yaml or json"""
70
95
 
71
96
    def __init__(self, obj):
72
97
        # wrap the object
73
 
        UserDict.IterableUserDict.__init__(self)
 
98
        UserDict.__init__(self)
74
99
        self.data = obj
75
100
 
76
101
    def __getattr__(self, attr):
96
121
        self.data = state
97
122
 
98
123
    def json(self):
99
 
        "Serialize the object to json"
 
124
        """Serialize the object to json"""
100
125
        return json.dumps(self.data)
101
126
 
102
127
    def yaml(self):
103
 
        "Serialize the object to yaml"
 
128
        """Serialize the object to yaml"""
104
129
        return yaml.dump(self.data)
105
130
 
106
131
 
119
144
 
120
145
 
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
124
149
 
125
150
 
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)
129
154
 
130
155
 
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)
134
159
 
135
160
 
136
161
def local_unit():
137
 
    "Local unit ID"
 
162
    """Local unit ID"""
138
163
    return os.environ['JUJU_UNIT_NAME']
139
164
 
140
165
 
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']
144
169
 
145
170
 
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]
149
174
 
150
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
 
151
302
@cached
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')
158
309
    try:
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:
 
313
            return config_data
 
314
        return Config(config_data)
160
315
    except ValueError:
161
316
        return None
162
317
 
163
318
 
164
319
@cached
165
320
def relation_get(attribute=None, unit=None, rid=None):
 
321
    """Get relation information"""
166
322
    _args = ['relation-get', '--format=json']
167
323
    if rid:
168
324
        _args.append('-r')
171
327
    if unit:
172
328
        _args.append(unit)
173
329
    try:
174
 
        return json.loads(subprocess.check_output(_args))
 
330
        return json.loads(subprocess.check_output(_args).decode('UTF-8'))
175
331
    except ValueError:
176
332
        return None
177
 
 
178
 
 
179
 
def relation_set(relation_id=None, relation_settings={}, **kwargs):
 
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 {}
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())):
184
346
        if v is None:
185
347
            relation_cmd_line.append('{}='.format(k))
186
348
        else:
192
354
 
193
355
@cached
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 []
 
362
        return json.loads(
 
363
            subprocess.check_output(relid_cmd_line).decode('UTF-8')) or []
201
364
    return []
202
365
 
203
366
 
204
367
@cached
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 []
 
374
    return json.loads(
 
375
        subprocess.check_output(units_cmd_line).decode('UTF-8')) or []
212
376
 
213
377
 
214
378
@cached
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:
225
389
 
226
390
@cached
227
391
def relations_for_id(relid=None):
228
 
    "Get relations of a specific relation ID"
 
392
    """Get relations of a specific relation ID"""
229
393
    relation_data = []
230
394
    relid = relid or relation_ids()
231
395
    for unit in related_units(relid):
237
401
 
238
402
@cached
239
403
def relations_of_type(reltype=None):
240
 
    "Get relations of a specific type"
 
404
    """Get relations of a specific type"""
241
405
    relation_data = []
242
406
    reltype = reltype or relation_type()
243
407
    for relid in relation_ids(reltype):
248
412
 
249
413
 
250
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
251
422
def relation_types():
252
 
    "Get a list of relation types supported by this charm"
253
 
    charmdir = os.environ.get('CHARM_DIR', '')
254
 
    mdf = open(os.path.join(charmdir, 'metadata.yaml'))
255
 
    md = yaml.safe_load(mdf)
 
423
    """Get a list of relation types supported by this charm"""
256
424
    rel_types = []
 
425
    md = metadata()
257
426
    for key in ('provides', 'requires', 'peers'):
258
427
        section = md.get(key)
259
428
        if section:
260
429
            rel_types.extend(section.keys())
261
 
    mdf.close()
262
430
    return rel_types
263
431
 
264
432
 
265
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
266
440
def relations():
 
441
    """Get a nested dictionary of relation data for all related units"""
267
442
    rels = {}
268
443
    for reltype in relation_types():
269
444
        relids = {}
277
452
    return rels
278
453
 
279
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
 
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)
285
480
 
286
481
 
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)
293
488
 
294
489
@cached
295
490
def unit_get(attribute):
 
491
    """Get the unit ID for the remote unit"""
296
492
    _args = ['unit-get', '--format=json', attribute]
297
493
    try:
298
 
        return json.loads(subprocess.check_output(_args))
 
494
        return json.loads(subprocess.check_output(_args).decode('UTF-8'))
299
495
    except ValueError:
300
496
        return None
301
497
 
302
498
 
303
499
def unit_private_ip():
 
500
    """Get this unit's private IP address"""
304
501
    return unit_get('private-address')
305
502
 
306
503
 
307
504
class UnregisteredHookError(Exception):
 
505
    """Raised when an undefined hook is called"""
308
506
    pass
309
507
 
310
508
 
311
509
class Hooks(object):
312
 
    def __init__(self):
 
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):
313
532
        super(Hooks, self).__init__()
314
533
        self._hooks = {}
 
534
        self._config_save = config_save
315
535
 
316
536
    def register(self, name, function):
 
537
        """Register a hook"""
317
538
        self._hooks[name] = function
318
539
 
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:
 
546
                cfg = config()
 
547
                if cfg.implicit_save:
 
548
                    cfg.save()
323
549
        else:
324
550
            raise UnregisteredHookError(hook_name)
325
551
 
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)
337
564
 
338
565
 
339
566
def charm_dir():
 
567
    """Return the root directory of the current charm"""
340
568
    return os.environ.get('CHARM_DIR')