~evarlast/charms/trusty/elasticsearch/add-logs-relation

« back to all changes in this revision

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

  • Committer: Michael Nelson
  • Date: 2014-11-06 02:48:04 UTC
  • mfrom: (35.1.8 firewall_optional)
  • Revision ID: michael.nelson@canonical.com-20141106024804-uxduhm2huet147vi
[r=simondavy][bugs=1386664,1376396] Bug fix for firewall on ec2 and enable firewall to be configured off (as well as update of tests and charmhelpers).

Show diffs side-by-side

added added

removed removed

Lines of Context:
25
25
def cached(func):
26
26
    """Cache return values for multiple executions of func + args
27
27
 
28
 
    For example:
 
28
    For example::
29
29
 
30
30
        @cached
31
31
        def unit_get(attribute):
155
155
    return os.path.basename(sys.argv[0])
156
156
 
157
157
 
 
158
class Config(dict):
 
159
    """A dictionary representation of the charm's config.yaml, with some
 
160
    extra features:
 
161
 
 
162
    - See which values in the dictionary have changed since the previous hook.
 
163
    - For values that have changed, see what the previous value was.
 
164
    - Store arbitrary data for use in a later hook.
 
165
 
 
166
    NOTE: Do not instantiate this object directly - instead call
 
167
    ``hookenv.config()``, which will return an instance of :class:`Config`.
 
168
 
 
169
    Example usage::
 
170
 
 
171
        >>> # inside a hook
 
172
        >>> from charmhelpers.core import hookenv
 
173
        >>> config = hookenv.config()
 
174
        >>> config['foo']
 
175
        'bar'
 
176
        >>> # store a new key/value for later use
 
177
        >>> config['mykey'] = 'myval'
 
178
 
 
179
 
 
180
        >>> # user runs `juju set mycharm foo=baz`
 
181
        >>> # now we're inside subsequent config-changed hook
 
182
        >>> config = hookenv.config()
 
183
        >>> config['foo']
 
184
        'baz'
 
185
        >>> # test to see if this val has changed since last hook
 
186
        >>> config.changed('foo')
 
187
        True
 
188
        >>> # what was the previous value?
 
189
        >>> config.previous('foo')
 
190
        'bar'
 
191
        >>> # keys/values that we add are preserved across hooks
 
192
        >>> config['mykey']
 
193
        'myval'
 
194
 
 
195
    """
 
196
    CONFIG_FILE_NAME = '.juju-persistent-config'
 
197
 
 
198
    def __init__(self, *args, **kw):
 
199
        super(Config, self).__init__(*args, **kw)
 
200
        self.implicit_save = True
 
201
        self._prev_dict = None
 
202
        self.path = os.path.join(charm_dir(), Config.CONFIG_FILE_NAME)
 
203
        if os.path.exists(self.path):
 
204
            self.load_previous()
 
205
 
 
206
    def __getitem__(self, key):
 
207
        """For regular dict lookups, check the current juju config first,
 
208
        then the previous (saved) copy. This ensures that user-saved values
 
209
        will be returned by a dict lookup.
 
210
 
 
211
        """
 
212
        try:
 
213
            return dict.__getitem__(self, key)
 
214
        except KeyError:
 
215
            return (self._prev_dict or {})[key]
 
216
 
 
217
    def keys(self):
 
218
        prev_keys = []
 
219
        if self._prev_dict is not None:
 
220
            prev_keys = self._prev_dict.keys()
 
221
        return list(set(prev_keys + dict.keys(self)))
 
222
 
 
223
    def load_previous(self, path=None):
 
224
        """Load previous copy of config from disk.
 
225
 
 
226
        In normal usage you don't need to call this method directly - it
 
227
        is called automatically at object initialization.
 
228
 
 
229
        :param path:
 
230
 
 
231
            File path from which to load the previous config. If `None`,
 
232
            config is loaded from the default location. If `path` is
 
233
            specified, subsequent `save()` calls will write to the same
 
234
            path.
 
235
 
 
236
        """
 
237
        self.path = path or self.path
 
238
        with open(self.path) as f:
 
239
            self._prev_dict = json.load(f)
 
240
 
 
241
    def changed(self, key):
 
242
        """Return True if the current value for this key is different from
 
243
        the previous value.
 
244
 
 
245
        """
 
246
        if self._prev_dict is None:
 
247
            return True
 
248
        return self.previous(key) != self.get(key)
 
249
 
 
250
    def previous(self, key):
 
251
        """Return previous value for this key, or None if there
 
252
        is no previous value.
 
253
 
 
254
        """
 
255
        if self._prev_dict:
 
256
            return self._prev_dict.get(key)
 
257
        return None
 
258
 
 
259
    def save(self):
 
260
        """Save this config to disk.
 
261
 
 
262
        If the charm is using the :mod:`Services Framework <services.base>`
 
263
        or :meth:'@hook <Hooks.hook>' decorator, this
 
264
        is called automatically at the end of successful hook execution.
 
265
        Otherwise, it should be called directly by user code.
 
266
 
 
267
        To disable automatic saves, set ``implicit_save=False`` on this
 
268
        instance.
 
269
 
 
270
        """
 
271
        if self._prev_dict:
 
272
            for k, v in self._prev_dict.iteritems():
 
273
                if k not in self:
 
274
                    self[k] = v
 
275
        with open(self.path, 'w') as f:
 
276
            json.dump(self, f)
 
277
 
 
278
 
158
279
@cached
159
280
def config(scope=None):
160
281
    """Juju charm configuration"""
163
284
        config_cmd_line.append(scope)
164
285
    config_cmd_line.append('--format=json')
165
286
    try:
166
 
        return json.loads(subprocess.check_output(config_cmd_line))
 
287
        config_data = json.loads(subprocess.check_output(config_cmd_line))
 
288
        if scope is not None:
 
289
            return config_data
 
290
        return Config(config_data)
167
291
    except ValueError:
168
292
        return None
169
293
 
188
312
        raise
189
313
 
190
314
 
191
 
def relation_set(relation_id=None, relation_settings={}, **kwargs):
 
315
def relation_set(relation_id=None, relation_settings=None, **kwargs):
192
316
    """Set relation information for the current unit"""
 
317
    relation_settings = relation_settings if relation_settings else {}
193
318
    relation_cmd_line = ['relation-set']
194
319
    if relation_id is not None:
195
320
        relation_cmd_line.extend(('-r', relation_id))
348
473
class Hooks(object):
349
474
    """A convenient handler for hook functions.
350
475
 
351
 
    Example:
 
476
    Example::
 
477
 
352
478
        hooks = Hooks()
353
479
 
354
480
        # register a hook, taking its name from the function name
355
481
        @hooks.hook()
356
482
        def install():
357
 
            ...
 
483
            pass  # your code here
358
484
 
359
485
        # register a hook, providing a custom hook name
360
486
        @hooks.hook("config-changed")
361
487
        def config_changed():
362
 
            ...
 
488
            pass  # your code here
363
489
 
364
490
        if __name__ == "__main__":
365
491
            # execute a hook based on the name the program is called by
366
492
            hooks.execute(sys.argv)
367
493
    """
368
494
 
369
 
    def __init__(self):
 
495
    def __init__(self, config_save=True):
370
496
        super(Hooks, self).__init__()
371
497
        self._hooks = {}
 
498
        self._config_save = config_save
372
499
 
373
500
    def register(self, name, function):
374
501
        """Register a hook"""
379
506
        hook_name = os.path.basename(args[0])
380
507
        if hook_name in self._hooks:
381
508
            self._hooks[hook_name]()
 
509
            if self._config_save:
 
510
                cfg = config()
 
511
                if cfg.implicit_save:
 
512
                    cfg.save()
382
513
        else:
383
514
            raise UnregisteredHookError(hook_name)
384
515