~nobuto/charms/trusty/ceph/workaround-multinics

« back to all changes in this revision

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

  • Committer: James Page
  • Date: 2013-11-18 12:20:21 UTC
  • mfrom: (64.1.6 ceph)
  • Revision ID: james.page@canonical.com-20131118122021-m7xwu38zg0g1vij6
[james-page] Manage ceph.conf using alternatives

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
 
 
147
def service_name():
 
148
    """The name service group this unit belongs to"""
 
149
    return local_unit().split('/')[0]
 
150
 
 
151
 
146
152
@cached
147
153
def config(scope=None):
148
 
    "Juju charm configuration"
 
154
    """Juju charm configuration"""
149
155
    config_cmd_line = ['config-get']
150
156
    if scope is not None:
151
157
        config_cmd_line.append(scope)
158
164
 
159
165
@cached
160
166
def relation_get(attribute=None, unit=None, rid=None):
 
167
    """Get relation information"""
161
168
    _args = ['relation-get', '--format=json']
162
169
    if rid:
163
170
        _args.append('-r')
169
176
        return json.loads(subprocess.check_output(_args))
170
177
    except ValueError:
171
178
        return None
 
179
    except CalledProcessError, e:
 
180
        if e.returncode == 2:
 
181
            return None
 
182
        raise
172
183
 
173
184
 
174
185
def relation_set(relation_id=None, relation_settings={}, **kwargs):
 
186
    """Set relation information for the current unit"""
175
187
    relation_cmd_line = ['relation-set']
176
188
    if relation_id is not None:
177
189
        relation_cmd_line.extend(('-r', relation_id))
187
199
 
188
200
@cached
189
201
def relation_ids(reltype=None):
190
 
    "A list of relation_ids"
 
202
    """A list of relation_ids"""
191
203
    reltype = reltype or relation_type()
192
204
    relid_cmd_line = ['relation-ids', '--format=json']
193
205
    if reltype is not None:
194
206
        relid_cmd_line.append(reltype)
195
 
        return json.loads(subprocess.check_output(relid_cmd_line))
 
207
        return json.loads(subprocess.check_output(relid_cmd_line)) or []
196
208
    return []
197
209
 
198
210
 
199
211
@cached
200
212
def related_units(relid=None):
201
 
    "A list of related units"
 
213
    """A list of related units"""
202
214
    relid = relid or relation_id()
203
215
    units_cmd_line = ['relation-list', '--format=json']
204
216
    if relid is not None:
205
217
        units_cmd_line.extend(('-r', relid))
206
 
    return json.loads(subprocess.check_output(units_cmd_line))
 
218
    return json.loads(subprocess.check_output(units_cmd_line)) or []
207
219
 
208
220
 
209
221
@cached
210
222
def relation_for_unit(unit=None, rid=None):
211
 
    "Get the json represenation of a unit's relation"
 
223
    """Get the json represenation of a unit's relation"""
212
224
    unit = unit or remote_unit()
213
225
    relation = relation_get(unit=unit, rid=rid)
214
226
    for key in relation:
220
232
 
221
233
@cached
222
234
def relations_for_id(relid=None):
223
 
    "Get relations of a specific relation ID"
 
235
    """Get relations of a specific relation ID"""
224
236
    relation_data = []
225
237
    relid = relid or relation_ids()
226
238
    for unit in related_units(relid):
232
244
 
233
245
@cached
234
246
def relations_of_type(reltype=None):
235
 
    "Get relations of a specific type"
 
247
    """Get relations of a specific type"""
236
248
    relation_data = []
237
249
    reltype = reltype or relation_type()
238
250
    for relid in relation_ids(reltype):
244
256
 
245
257
@cached
246
258
def relation_types():
247
 
    "Get a list of relation types supported by this charm"
 
259
    """Get a list of relation types supported by this charm"""
248
260
    charmdir = os.environ.get('CHARM_DIR', '')
249
261
    mdf = open(os.path.join(charmdir, 'metadata.yaml'))
250
262
    md = yaml.safe_load(mdf)
259
271
 
260
272
@cached
261
273
def relations():
 
274
    """Get a nested dictionary of relation data for all related units"""
262
275
    rels = {}
263
276
    for reltype in relation_types():
264
277
        relids = {}
272
285
    return rels
273
286
 
274
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
 
275
308
def open_port(port, protocol="TCP"):
276
 
    "Open a service network port"
 
309
    """Open a service network port"""
277
310
    _args = ['open-port']
278
311
    _args.append('{}/{}'.format(port, protocol))
279
312
    subprocess.check_call(_args)
280
313
 
281
314
 
282
315
def close_port(port, protocol="TCP"):
283
 
    "Close a service network port"
 
316
    """Close a service network port"""
284
317
    _args = ['close-port']
285
318
    _args.append('{}/{}'.format(port, protocol))
286
319
    subprocess.check_call(_args)
288
321
 
289
322
@cached
290
323
def unit_get(attribute):
 
324
    """Get the unit ID for the remote unit"""
291
325
    _args = ['unit-get', '--format=json', attribute]
292
326
    try:
293
327
        return json.loads(subprocess.check_output(_args))
296
330
 
297
331
 
298
332
def unit_private_ip():
 
333
    """Get this unit's private IP address"""
299
334
    return unit_get('private-address')
300
335
 
301
336
 
302
337
class UnregisteredHookError(Exception):
 
338
    """Raised when an undefined hook is called"""
303
339
    pass
304
340
 
305
341
 
306
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
 
307
363
    def __init__(self):
308
364
        super(Hooks, self).__init__()
309
365
        self._hooks = {}
310
366
 
311
367
    def register(self, name, function):
 
368
        """Register a hook"""
312
369
        self._hooks[name] = function
313
370
 
314
371
    def execute(self, args):
 
372
        """Execute a registered hook based on args[0]"""
315
373
        hook_name = os.path.basename(args[0])
316
374
        if hook_name in self._hooks:
317
375
            self._hooks[hook_name]()
319
377
            raise UnregisteredHookError(hook_name)
320
378
 
321
379
    def hook(self, *hook_names):
 
380
        """Decorator, registering them as hooks"""
322
381
        def wrapper(decorated):
323
382
            for hook_name in hook_names:
324
383
                self.register(hook_name, decorated)
330
389
            return decorated
331
390
        return wrapper
332
391
 
 
392
 
333
393
def charm_dir():
 
394
    """Return the root directory of the current charm"""
334
395
    return os.environ.get('CHARM_DIR')