~ahasenack/charms/precise/apache2/apache2-no-failing-juju-log

« back to all changes in this revision

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

  • Committer: Marco Ceppi
  • Date: 2013-10-17 03:21:15 UTC
  • mfrom: (27.2.55 master)
  • Revision ID: marco@ceppi.net-20131017032115-iwu78y9cgqwi3a5s
[sidnei] Greatly improved test coverage. Support for 'all_services' set from haproxy relation. Improved documentation.

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 UserDict
 
12
 
 
13
CRITICAL = "CRITICAL"
 
14
ERROR = "ERROR"
 
15
WARNING = "WARNING"
 
16
INFO = "INFO"
 
17
DEBUG = "DEBUG"
 
18
MARKER = object()
 
19
 
 
20
cache = {}
 
21
 
 
22
 
 
23
def cached(func):
 
24
    ''' Cache return values for multiple executions of func + args
 
25
 
 
26
    For example:
 
27
 
 
28
        @cached
 
29
        def unit_get(attribute):
 
30
            pass
 
31
 
 
32
        unit_get('test')
 
33
 
 
34
    will cache the result of unit_get + 'test' for future calls.
 
35
    '''
 
36
    def wrapper(*args, **kwargs):
 
37
        global cache
 
38
        key = str((func, args, kwargs))
 
39
        try:
 
40
            return cache[key]
 
41
        except KeyError:
 
42
            res = func(*args, **kwargs)
 
43
            cache[key] = res
 
44
            return res
 
45
    return wrapper
 
46
 
 
47
 
 
48
def flush(key):
 
49
    ''' Flushes any entries from function cache where the
 
50
    key is found in the function+args '''
 
51
    flush_list = []
 
52
    for item in cache:
 
53
        if key in item:
 
54
            flush_list.append(item)
 
55
    for item in flush_list:
 
56
        del cache[item]
 
57
 
 
58
 
 
59
def log(message, level=None):
 
60
    "Write a message to the juju log"
 
61
    command = ['juju-log']
 
62
    if level:
 
63
        command += ['-l', level]
 
64
    command += [message]
 
65
    subprocess.call(command)
 
66
 
 
67
 
 
68
class Serializable(UserDict.IterableUserDict):
 
69
    "Wrapper, an object that can be serialized to yaml or json"
 
70
 
 
71
    def __init__(self, obj):
 
72
        # wrap the object
 
73
        UserDict.IterableUserDict.__init__(self)
 
74
        self.data = obj
 
75
 
 
76
    def __getattr__(self, attr):
 
77
        # See if this object has attribute.
 
78
        if attr in ("json", "yaml", "data"):
 
79
            return self.__dict__[attr]
 
80
        # Check for attribute in wrapped object.
 
81
        got = getattr(self.data, attr, MARKER)
 
82
        if got is not MARKER:
 
83
            return got
 
84
        # Proxy to the wrapped object via dict interface.
 
85
        try:
 
86
            return self.data[attr]
 
87
        except KeyError:
 
88
            raise AttributeError(attr)
 
89
 
 
90
    def __getstate__(self):
 
91
        # Pickle as a standard dictionary.
 
92
        return self.data
 
93
 
 
94
    def __setstate__(self, state):
 
95
        # Unpickle into our wrapper.
 
96
        self.data = state
 
97
 
 
98
    def json(self):
 
99
        "Serialize the object to json"
 
100
        return json.dumps(self.data)
 
101
 
 
102
    def yaml(self):
 
103
        "Serialize the object to yaml"
 
104
        return yaml.dump(self.data)
 
105
 
 
106
 
 
107
def execution_environment():
 
108
    """A convenient bundling of the current execution context"""
 
109
    context = {}
 
110
    context['conf'] = config()
 
111
    if relation_id():
 
112
        context['reltype'] = relation_type()
 
113
        context['relid'] = relation_id()
 
114
        context['rel'] = relation_get()
 
115
    context['unit'] = local_unit()
 
116
    context['rels'] = relations()
 
117
    context['env'] = os.environ
 
118
    return context
 
119
 
 
120
 
 
121
def in_relation_hook():
 
122
    "Determine whether we're running in a relation hook"
 
123
    return 'JUJU_RELATION' in os.environ
 
124
 
 
125
 
 
126
def relation_type():
 
127
    "The scope for the current relation hook"
 
128
    return os.environ.get('JUJU_RELATION', None)
 
129
 
 
130
 
 
131
def relation_id():
 
132
    "The relation ID for the current relation hook"
 
133
    return os.environ.get('JUJU_RELATION_ID', None)
 
134
 
 
135
 
 
136
def local_unit():
 
137
    "Local unit ID"
 
138
    return os.environ['JUJU_UNIT_NAME']
 
139
 
 
140
 
 
141
def remote_unit():
 
142
    "The remote unit for the current relation hook"
 
143
    return os.environ['JUJU_REMOTE_UNIT']
 
144
 
 
145
 
 
146
def service_name():
 
147
    "The name service group this unit belongs to"
 
148
    return local_unit().split('/')[0]
 
149
 
 
150
 
 
151
@cached
 
152
def config(scope=None):
 
153
    "Juju charm configuration"
 
154
    config_cmd_line = ['config-get']
 
155
    if scope is not None:
 
156
        config_cmd_line.append(scope)
 
157
    config_cmd_line.append('--format=json')
 
158
    try:
 
159
        return json.loads(subprocess.check_output(config_cmd_line))
 
160
    except ValueError:
 
161
        return None
 
162
 
 
163
 
 
164
@cached
 
165
def relation_get(attribute=None, unit=None, rid=None):
 
166
    _args = ['relation-get', '--format=json']
 
167
    if rid:
 
168
        _args.append('-r')
 
169
        _args.append(rid)
 
170
    _args.append(attribute or '-')
 
171
    if unit:
 
172
        _args.append(unit)
 
173
    try:
 
174
        return json.loads(subprocess.check_output(_args))
 
175
    except ValueError:
 
176
        return None
 
177
 
 
178
 
 
179
def relation_set(relation_id=None, relation_settings={}, **kwargs):
 
180
    relation_cmd_line = ['relation-set']
 
181
    if relation_id is not None:
 
182
        relation_cmd_line.extend(('-r', relation_id))
 
183
    for k, v in (relation_settings.items() + kwargs.items()):
 
184
        if v is None:
 
185
            relation_cmd_line.append('{}='.format(k))
 
186
        else:
 
187
            relation_cmd_line.append('{}={}'.format(k, v))
 
188
    subprocess.check_call(relation_cmd_line)
 
189
    # Flush cache of any relation-gets for local unit
 
190
    flush(local_unit())
 
191
 
 
192
 
 
193
@cached
 
194
def relation_ids(reltype=None):
 
195
    "A list of relation_ids"
 
196
    reltype = reltype or relation_type()
 
197
    relid_cmd_line = ['relation-ids', '--format=json']
 
198
    if reltype is not None:
 
199
        relid_cmd_line.append(reltype)
 
200
        return json.loads(subprocess.check_output(relid_cmd_line)) or []
 
201
    return []
 
202
 
 
203
 
 
204
@cached
 
205
def related_units(relid=None):
 
206
    "A list of related units"
 
207
    relid = relid or relation_id()
 
208
    units_cmd_line = ['relation-list', '--format=json']
 
209
    if relid is not None:
 
210
        units_cmd_line.extend(('-r', relid))
 
211
    return json.loads(subprocess.check_output(units_cmd_line)) or []
 
212
 
 
213
 
 
214
@cached
 
215
def relation_for_unit(unit=None, rid=None):
 
216
    "Get the json represenation of a unit's relation"
 
217
    unit = unit or remote_unit()
 
218
    relation = relation_get(unit=unit, rid=rid)
 
219
    for key in relation:
 
220
        if key.endswith('-list'):
 
221
            relation[key] = relation[key].split()
 
222
    relation['__unit__'] = unit
 
223
    return relation
 
224
 
 
225
 
 
226
@cached
 
227
def relations_for_id(relid=None):
 
228
    "Get relations of a specific relation ID"
 
229
    relation_data = []
 
230
    relid = relid or relation_ids()
 
231
    for unit in related_units(relid):
 
232
        unit_data = relation_for_unit(unit, relid)
 
233
        unit_data['__relid__'] = relid
 
234
        relation_data.append(unit_data)
 
235
    return relation_data
 
236
 
 
237
 
 
238
@cached
 
239
def relations_of_type(reltype=None):
 
240
    "Get relations of a specific type"
 
241
    relation_data = []
 
242
    reltype = reltype or relation_type()
 
243
    for relid in relation_ids(reltype):
 
244
        for relation in relations_for_id(relid):
 
245
            relation['__relid__'] = relid
 
246
            relation_data.append(relation)
 
247
    return relation_data
 
248
 
 
249
 
 
250
@cached
 
251
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)
 
256
    rel_types = []
 
257
    for key in ('provides', 'requires', 'peers'):
 
258
        section = md.get(key)
 
259
        if section:
 
260
            rel_types.extend(section.keys())
 
261
    mdf.close()
 
262
    return rel_types
 
263
 
 
264
 
 
265
@cached
 
266
def relations():
 
267
    rels = {}
 
268
    for reltype in relation_types():
 
269
        relids = {}
 
270
        for relid in relation_ids(reltype):
 
271
            units = {local_unit(): relation_get(unit=local_unit(), rid=relid)}
 
272
            for unit in related_units(relid):
 
273
                reldata = relation_get(unit=unit, rid=relid)
 
274
                units[unit] = reldata
 
275
            relids[relid] = units
 
276
        rels[reltype] = relids
 
277
    return rels
 
278
 
 
279
 
 
280
def open_port(port, protocol="TCP"):
 
281
    "Open a service network port"
 
282
    _args = ['open-port']
 
283
    _args.append('{}/{}'.format(port, protocol))
 
284
    subprocess.check_call(_args)
 
285
 
 
286
 
 
287
def close_port(port, protocol="TCP"):
 
288
    "Close a service network port"
 
289
    _args = ['close-port']
 
290
    _args.append('{}/{}'.format(port, protocol))
 
291
    subprocess.check_call(_args)
 
292
 
 
293
 
 
294
@cached
 
295
def unit_get(attribute):
 
296
    _args = ['unit-get', '--format=json', attribute]
 
297
    try:
 
298
        return json.loads(subprocess.check_output(_args))
 
299
    except ValueError:
 
300
        return None
 
301
 
 
302
 
 
303
def unit_private_ip():
 
304
    return unit_get('private-address')
 
305
 
 
306
 
 
307
class UnregisteredHookError(Exception):
 
308
    pass
 
309
 
 
310
 
 
311
class Hooks(object):
 
312
    def __init__(self):
 
313
        super(Hooks, self).__init__()
 
314
        self._hooks = {}
 
315
 
 
316
    def register(self, name, function):
 
317
        self._hooks[name] = function
 
318
 
 
319
    def execute(self, args):
 
320
        hook_name = os.path.basename(args[0])
 
321
        if hook_name in self._hooks:
 
322
            self._hooks[hook_name]()
 
323
        else:
 
324
            raise UnregisteredHookError(hook_name)
 
325
 
 
326
    def hook(self, *hook_names):
 
327
        def wrapper(decorated):
 
328
            for hook_name in hook_names:
 
329
                self.register(hook_name, decorated)
 
330
            else:
 
331
                self.register(decorated.__name__, decorated)
 
332
                if '_' in decorated.__name__:
 
333
                    self.register(
 
334
                        decorated.__name__.replace('_', '-'), decorated)
 
335
            return decorated
 
336
        return wrapper
 
337
 
 
338
 
 
339
def charm_dir():
 
340
    return os.environ.get('CHARM_DIR')