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
Line 
1import json
2from invirt.common import *
3from os.path import getmtime
4
5default_src_path   = '/etc/invirt/master.yaml'
6default_cache_path = '/var/lib/invirt/cache.json'
7
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
25    if not do_refresh:
26        # try reading from the cache first
27        try: cfg = with_closing(file(cache_path))(lambda f: json.read(f.read()))
28        except: do_refresh = True
29
30    if do_refresh:
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():
36            import yaml
37            try:    default_loader = yaml.CSafeLoader
38            except: default_loader = yaml.SafeLoader
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
43    return cfg
44
45dicts = load()
46structs = dicts2struct(dicts)
47
48# vim:et:sw=4:ts=4
Note: See TracBrowser for help on using the repository browser.