~hazmat/charms/precise/quantum-gateway/ssl-everywhere

« back to all changes in this revision

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

  • Committer: James Page
  • Date: 2013-11-17 21:53:21 UTC
  • mfrom: (37.1.5 quantum-gateway)
  • Revision ID: james.page@canonical.com-20131117215321-o4o6uje3itj2e4se
[gandelman-a][james-page] NVP support

Show diffs side-by-side

added added

removed removed

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