~tvansteenburgh/charms/precise/nvp-transport-node/fix-proof

« back to all changes in this revision

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

  • Committer: Liam Young
  • Date: 2014-07-30 13:08:44 UTC
  • mfrom: (46.1.2 nvp-transport-node)
  • Revision ID: liam.young@canonical.com-20140730130844-ljfr29rwh62vsfid
[jamespage, r=gnuoy] Add support for using tarball from object storage

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
12
13
from subprocess import CalledProcessError
13
14
 
149
150
    return local_unit().split('/')[0]
150
151
 
151
152
 
 
153
def hook_name():
 
154
    """The name of the currently executing hook"""
 
155
    return os.path.basename(sys.argv[0])
 
156
 
 
157
 
 
158
class Config(dict):
 
159
    """A Juju charm config dictionary that can write itself to
 
160
    disk (as json) and track which values have changed since
 
161
    the previous hook invocation.
 
162
 
 
163
    Do not instantiate this object directly - instead call
 
164
    ``hookenv.config()``
 
165
 
 
166
    Example usage::
 
167
 
 
168
        >>> # inside a hook
 
169
        >>> from charmhelpers.core import hookenv
 
170
        >>> config = hookenv.config()
 
171
        >>> config['foo']
 
172
        'bar'
 
173
        >>> config['mykey'] = 'myval'
 
174
        >>> config.save()
 
175
 
 
176
 
 
177
        >>> # user runs `juju set mycharm foo=baz`
 
178
        >>> # now we're inside subsequent config-changed hook
 
179
        >>> config = hookenv.config()
 
180
        >>> config['foo']
 
181
        'baz'
 
182
        >>> # test to see if this val has changed since last hook
 
183
        >>> config.changed('foo')
 
184
        True
 
185
        >>> # what was the previous value?
 
186
        >>> config.previous('foo')
 
187
        'bar'
 
188
        >>> # keys/values that we add are preserved across hooks
 
189
        >>> config['mykey']
 
190
        'myval'
 
191
        >>> # don't forget to save at the end of hook!
 
192
        >>> config.save()
 
193
 
 
194
    """
 
195
    CONFIG_FILE_NAME = '.juju-persistent-config'
 
196
 
 
197
    def __init__(self, *args, **kw):
 
198
        super(Config, self).__init__(*args, **kw)
 
199
        self._prev_dict = None
 
200
        self.path = os.path.join(charm_dir(), Config.CONFIG_FILE_NAME)
 
201
        if os.path.exists(self.path):
 
202
            self.load_previous()
 
203
 
 
204
    def load_previous(self, path=None):
 
205
        """Load previous copy of config from disk so that current values
 
206
        can be compared to previous values.
 
207
 
 
208
        :param path:
 
209
 
 
210
            File path from which to load the previous config. If `None`,
 
211
            config is loaded from the default location. If `path` is
 
212
            specified, subsequent `save()` calls will write to the same
 
213
            path.
 
214
 
 
215
        """
 
216
        self.path = path or self.path
 
217
        with open(self.path) as f:
 
218
            self._prev_dict = json.load(f)
 
219
 
 
220
    def changed(self, key):
 
221
        """Return true if the value for this key has changed since
 
222
        the last save.
 
223
 
 
224
        """
 
225
        if self._prev_dict is None:
 
226
            return True
 
227
        return self.previous(key) != self.get(key)
 
228
 
 
229
    def previous(self, key):
 
230
        """Return previous value for this key, or None if there
 
231
        is no "previous" value.
 
232
 
 
233
        """
 
234
        if self._prev_dict:
 
235
            return self._prev_dict.get(key)
 
236
        return None
 
237
 
 
238
    def save(self):
 
239
        """Save this config to disk.
 
240
 
 
241
        Preserves items in _prev_dict that do not exist in self.
 
242
 
 
243
        """
 
244
        if self._prev_dict:
 
245
            for k, v in self._prev_dict.iteritems():
 
246
                if k not in self:
 
247
                    self[k] = v
 
248
        with open(self.path, 'w') as f:
 
249
            json.dump(self, f)
 
250
 
 
251
 
152
252
@cached
153
253
def config(scope=None):
154
254
    """Juju charm configuration"""
157
257
        config_cmd_line.append(scope)
158
258
    config_cmd_line.append('--format=json')
159
259
    try:
160
 
        return json.loads(subprocess.check_output(config_cmd_line))
 
260
        config_data = json.loads(subprocess.check_output(config_cmd_line))
 
261
        if scope is not None:
 
262
            return config_data
 
263
        return Config(config_data)
161
264
    except ValueError:
162
265
        return None
163
266
 
285
388
    return rels
286
389
 
287
390
 
 
391
@cached
 
392
def is_relation_made(relation, keys='private-address'):
 
393
    '''
 
394
    Determine whether a relation is established by checking for
 
395
    presence of key(s).  If a list of keys is provided, they
 
396
    must all be present for the relation to be identified as made
 
397
    '''
 
398
    if isinstance(keys, str):
 
399
        keys = [keys]
 
400
    for r_id in relation_ids(relation):
 
401
        for unit in related_units(r_id):
 
402
            context = {}
 
403
            for k in keys:
 
404
                context[k] = relation_get(k, rid=r_id,
 
405
                                          unit=unit)
 
406
            if None not in context.values():
 
407
                return True
 
408
    return False
 
409
 
 
410
 
288
411
def open_port(port, protocol="TCP"):
289
412
    """Open a service network port"""
290
413
    _args = ['open-port']