source: trunk/packages/sipb-xen-base/files/usr/share/python-support/sipb-xen-base/invirt/config.py @ 792

Last change on this file since 792 was 792, checked in by price, 16 years ago

fix bug in late-import of yaml in invirt.config

File size: 1.7 KB
RevLine 
[784]1import json
[778]2from invirt.common import *
[781]3from os.path import getmtime
[726]4
[771]5default_src_path   = '/etc/invirt/master.yaml'
[781]6default_cache_path = '/var/lib/invirt/cache.json'
[726]7
[771]8def load(src_path = default_src_path,
9         cache_path = default_cache_path,
10         force_refresh = False):
11    """
12    Try loading the configuration from the faster-to-load JSON cache at
13    cache_path.  If it doesn't exist or is outdated, load the configuration
14    instead from the original YAML file at src_path and regenerate the cache.
15    I assume I have the permissions to write to the cache directory.
16    """
17    if force_refresh:
18        do_refresh = True
19    else:
20        src_mtime = getmtime(src_path)
21        try:            cache_mtime = getmtime(cache_path)
22        except OSError: do_refresh  = True
23        else:           do_refresh  = src_mtime > cache_mtime
24
[778]25    if not do_refresh:
26        # try reading from the cache first
[781]27        try: cfg = with_closing(file(cache_path))(lambda f: json.read(f.read()))
[778]28        except: do_refresh = True
29
[771]30    if do_refresh:
[781]31        # Atomically reload the source and regenerate the cache.  The read and
32        # write must be a single transaction, or a stale version may be
33        # written.
34        @with_lock_file('/var/lib/invirt/cache.lock')
35        def cfg():
[784]36            import yaml
[792]37            try:    default_loader = yaml.CSafeLoader
38            except: default_loader = yaml.SafeLoader
[781]39            cfg = with_closing(file(src_path))(lambda f: yaml.load(f, default_loader))
40            try: with_closing(file(cache_path, 'w'))(lambda f: f.write(json.write(cfg)))
41            except: pass # silent failure
42            return cfg
[771]43    return cfg
44
[778]45dicts = load()
46structs = dicts2struct(dicts)
47
[726]48# vim:et:sw=4:ts=4
Note: See TracBrowser for help on using the repository browser.