~arosales/charms/trusty/openstack-dashboard/add-default-key

« back to all changes in this revision

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

  • Committer: Edward Hope-Morley
  • Date: 2014-02-20 18:25:58 UTC
  • mfrom: (23.2.8 openstack-dashboard)
  • Revision ID: edward.hope-morley@canonical.com-20140220182558-v7pxp37bt3ofgklw
[yolanda] sync charmhelpers and add syslog support

Show diffs side-by-side

added added

removed removed

Lines of Context:
8
8
import json
9
9
import yaml
10
10
import subprocess
 
11
import sys
11
12
import UserDict
 
13
from subprocess import CalledProcessError
12
14
 
13
15
CRITICAL = "CRITICAL"
14
16
ERROR = "ERROR"
21
23
 
22
24
 
23
25
def cached(func):
24
 
    ''' Cache return values for multiple executions of func + args
 
26
    """Cache return values for multiple executions of func + args
25
27
 
26
28
    For example:
27
29
 
32
34
        unit_get('test')
33
35
 
34
36
    will cache the result of unit_get + 'test' for future calls.
35
 
    '''
 
37
    """
36
38
    def wrapper(*args, **kwargs):
37
39
        global cache
38
40
        key = str((func, args, kwargs))
46
48
 
47
49
 
48
50
def flush(key):
49
 
    ''' Flushes any entries from function cache where the
50
 
    key is found in the function+args '''
 
51
    """Flushes any entries from function cache where the
 
52
    key is found in the function+args """
51
53
    flush_list = []
52
54
    for item in cache:
53
55
        if key in item:
57
59
 
58
60
 
59
61
def log(message, level=None):
60
 
    "Write a message to the juju log"
 
62
    """Write a message to the juju log"""
61
63
    command = ['juju-log']
62
64
    if level:
63
65
        command += ['-l', level]
66
68
 
67
69
 
68
70
class Serializable(UserDict.IterableUserDict):
69
 
    "Wrapper, an object that can be serialized to yaml or json"
 
71
    """Wrapper, an object that can be serialized to yaml or json"""
70
72
 
71
73
    def __init__(self, obj):
72
74
        # wrap the object
96
98
        self.data = state
97
99
 
98
100
    def json(self):
99
 
        "Serialize the object to json"
 
101
        """Serialize the object to json"""
100
102
        return json.dumps(self.data)
101
103
 
102
104
    def yaml(self):
103
 
        "Serialize the object to yaml"
 
105
        """Serialize the object to yaml"""
104
106
        return yaml.dump(self.data)
105
107
 
106
108
 
119
121
 
120
122
 
121
123
def in_relation_hook():
122
 
    "Determine whether we're running in a relation hook"
 
124
    """Determine whether we're running in a relation hook"""
123
125
    return 'JUJU_RELATION' in os.environ
124
126
 
125
127
 
126
128
def relation_type():
127
 
    "The scope for the current relation hook"
 
129
    """The scope for the current relation hook"""
128
130
    return os.environ.get('JUJU_RELATION', None)
129
131
 
130
132
 
131
133
def relation_id():
132
 
    "The relation ID for the current relation hook"
 
134
    """The relation ID for the current relation hook"""
133
135
    return os.environ.get('JUJU_RELATION_ID', None)
134
136
 
135
137
 
136
138
def local_unit():
137
 
    "Local unit ID"
 
139
    """Local unit ID"""
138
140
    return os.environ['JUJU_UNIT_NAME']
139
141
 
140
142
 
141
143
def remote_unit():
142
 
    "The remote unit for the current relation hook"
 
144
    """The remote unit for the current relation hook"""
143
145
    return os.environ['JUJU_REMOTE_UNIT']
144
146
 
145
147
 
146
148
def service_name():
147
 
    "The name service group this unit belongs to"
 
149
    """The name service group this unit belongs to"""
148
150
    return local_unit().split('/')[0]
149
151
 
150
152
 
 
153
def hook_name():
 
154
    """The name of the currently executing hook"""
 
155
    return os.path.basename(sys.argv[0])
 
156
 
 
157
 
151
158
@cached
152
159
def config(scope=None):
153
 
    "Juju charm configuration"
 
160
    """Juju charm configuration"""
154
161
    config_cmd_line = ['config-get']
155
162
    if scope is not None:
156
163
        config_cmd_line.append(scope)
163
170
 
164
171
@cached
165
172
def relation_get(attribute=None, unit=None, rid=None):
 
173
    """Get relation information"""
166
174
    _args = ['relation-get', '--format=json']
167
175
    if rid:
168
176
        _args.append('-r')
174
182
        return json.loads(subprocess.check_output(_args))
175
183
    except ValueError:
176
184
        return None
 
185
    except CalledProcessError, e:
 
186
        if e.returncode == 2:
 
187
            return None
 
188
        raise
177
189
 
178
190
 
179
191
def relation_set(relation_id=None, relation_settings={}, **kwargs):
 
192
    """Set relation information for the current unit"""
180
193
    relation_cmd_line = ['relation-set']
181
194
    if relation_id is not None:
182
195
        relation_cmd_line.extend(('-r', relation_id))
192
205
 
193
206
@cached
194
207
def relation_ids(reltype=None):
195
 
    "A list of relation_ids"
 
208
    """A list of relation_ids"""
196
209
    reltype = reltype or relation_type()
197
210
    relid_cmd_line = ['relation-ids', '--format=json']
198
211
    if reltype is not None:
203
216
 
204
217
@cached
205
218
def related_units(relid=None):
206
 
    "A list of related units"
 
219
    """A list of related units"""
207
220
    relid = relid or relation_id()
208
221
    units_cmd_line = ['relation-list', '--format=json']
209
222
    if relid is not None:
213
226
 
214
227
@cached
215
228
def relation_for_unit(unit=None, rid=None):
216
 
    "Get the json represenation of a unit's relation"
 
229
    """Get the json represenation of a unit's relation"""
217
230
    unit = unit or remote_unit()
218
231
    relation = relation_get(unit=unit, rid=rid)
219
232
    for key in relation:
225
238
 
226
239
@cached
227
240
def relations_for_id(relid=None):
228
 
    "Get relations of a specific relation ID"
 
241
    """Get relations of a specific relation ID"""
229
242
    relation_data = []
230
243
    relid = relid or relation_ids()
231
244
    for unit in related_units(relid):
237
250
 
238
251
@cached
239
252
def relations_of_type(reltype=None):
240
 
    "Get relations of a specific type"
 
253
    """Get relations of a specific type"""
241
254
    relation_data = []
242
255
    reltype = reltype or relation_type()
243
256
    for relid in relation_ids(reltype):
249
262
 
250
263
@cached
251
264
def relation_types():
252
 
    "Get a list of relation types supported by this charm"
 
265
    """Get a list of relation types supported by this charm"""
253
266
    charmdir = os.environ.get('CHARM_DIR', '')
254
267
    mdf = open(os.path.join(charmdir, 'metadata.yaml'))
255
268
    md = yaml.safe_load(mdf)
264
277
 
265
278
@cached
266
279
def relations():
 
280
    """Get a nested dictionary of relation data for all related units"""
267
281
    rels = {}
268
282
    for reltype in relation_types():
269
283
        relids = {}
277
291
    return rels
278
292
 
279
293
 
 
294
@cached
 
295
def is_relation_made(relation, keys='private-address'):
 
296
    '''
 
297
    Determine whether a relation is established by checking for
 
298
    presence of key(s).  If a list of keys is provided, they
 
299
    must all be present for the relation to be identified as made
 
300
    '''
 
301
    if isinstance(keys, str):
 
302
        keys = [keys]
 
303
    for r_id in relation_ids(relation):
 
304
        for unit in related_units(r_id):
 
305
            context = {}
 
306
            for k in keys:
 
307
                context[k] = relation_get(k, rid=r_id,
 
308
                                          unit=unit)
 
309
            if None not in context.values():
 
310
                return True
 
311
    return False
 
312
 
 
313
 
280
314
def open_port(port, protocol="TCP"):
281
 
    "Open a service network port"
 
315
    """Open a service network port"""
282
316
    _args = ['open-port']
283
317
    _args.append('{}/{}'.format(port, protocol))
284
318
    subprocess.check_call(_args)
285
319
 
286
320
 
287
321
def close_port(port, protocol="TCP"):
288
 
    "Close a service network port"
 
322
    """Close a service network port"""
289
323
    _args = ['close-port']
290
324
    _args.append('{}/{}'.format(port, protocol))
291
325
    subprocess.check_call(_args)
293
327
 
294
328
@cached
295
329
def unit_get(attribute):
 
330
    """Get the unit ID for the remote unit"""
296
331
    _args = ['unit-get', '--format=json', attribute]
297
332
    try:
298
333
        return json.loads(subprocess.check_output(_args))
301
336
 
302
337
 
303
338
def unit_private_ip():
 
339
    """Get this unit's private IP address"""
304
340
    return unit_get('private-address')
305
341
 
306
342
 
307
343
class UnregisteredHookError(Exception):
 
344
    """Raised when an undefined hook is called"""
308
345
    pass
309
346
 
310
347
 
311
348
class Hooks(object):
 
349
    """A convenient handler for hook functions.
 
350
 
 
351
    Example:
 
352
        hooks = Hooks()
 
353
 
 
354
        # register a hook, taking its name from the function name
 
355
        @hooks.hook()
 
356
        def install():
 
357
            ...
 
358
 
 
359
        # register a hook, providing a custom hook name
 
360
        @hooks.hook("config-changed")
 
361
        def config_changed():
 
362
            ...
 
363
 
 
364
        if __name__ == "__main__":
 
365
            # execute a hook based on the name the program is called by
 
366
            hooks.execute(sys.argv)
 
367
    """
 
368
 
312
369
    def __init__(self):
313
370
        super(Hooks, self).__init__()
314
371
        self._hooks = {}
315
372
 
316
373
    def register(self, name, function):
 
374
        """Register a hook"""
317
375
        self._hooks[name] = function
318
376
 
319
377
    def execute(self, args):
 
378
        """Execute a registered hook based on args[0]"""
320
379
        hook_name = os.path.basename(args[0])
321
380
        if hook_name in self._hooks:
322
381
            self._hooks[hook_name]()
324
383
            raise UnregisteredHookError(hook_name)
325
384
 
326
385
    def hook(self, *hook_names):
 
386
        """Decorator, registering them as hooks"""
327
387
        def wrapper(decorated):
328
388
            for hook_name in hook_names:
329
389
                self.register(hook_name, decorated)
337
397
 
338
398
 
339
399
def charm_dir():
 
400
    """Return the root directory of the current charm"""
340
401
    return os.environ.get('CHARM_DIR')