~xianghui/charms/trusty/hacluster/support-ipv6

« back to all changes in this revision

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

  • Committer: Hui Xiang
  • Date: 2014-08-19 07:06:29 UTC
  • Revision ID: hui.xiang@canonical.com-20140819070629-pheqt6jch26p84l5
Support hacluster for IPv6.

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 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
 
158
252
@cached
159
253
def config(scope=None):
160
254
    """Juju charm configuration"""
163
257
        config_cmd_line.append(scope)
164
258
    config_cmd_line.append('--format=json')
165
259
    try:
166
 
        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)
167
264
    except ValueError:
168
265
        return None
169
266
 
348
445
class Hooks(object):
349
446
    """A convenient handler for hook functions.
350
447
 
351
 
    Example:
 
448
    Example::
 
449
 
352
450
        hooks = Hooks()
353
451
 
354
452
        # register a hook, taking its name from the function name
355
453
        @hooks.hook()
356
454
        def install():
357
 
            ...
 
455
            pass  # your code here
358
456
 
359
457
        # register a hook, providing a custom hook name
360
458
        @hooks.hook("config-changed")
361
459
        def config_changed():
362
 
            ...
 
460
            pass  # your code here
363
461
 
364
462
        if __name__ == "__main__":
365
463
            # execute a hook based on the name the program is called by