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

Last change on this file since 784 was 784, checked in by y_z, 16 years ago

lazily import yaml for faster module load times

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