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

Last change on this file since 778 was 778, checked in by y_z, 16 years ago
  • moved more generic code into common package
  • silently fail if cache fails
  • load the configuration on module load
  • produce a struct-based representation of the configuration
  • allowing full exception messages for OSErrors (default behavior)
  • added some dependencies specs
File size: 1.5 KB
Line 
1import json, yaml
2from invirt.common import *
3from os import error, makedirs
4from os.path import dirname, getmtime
5
6default_src_path   = '/etc/invirt/master.yaml'
7default_cache_path = '/var/lib/invirt/invirt.json'
8
9try:    default_loader = yaml.CSafeLoader
10except: default_loader = yaml.SafeLoader
11
12def load(src_path = default_src_path,
13         cache_path = default_cache_path,
14         force_refresh = False):
15    """
16    Try loading the configuration from the faster-to-load JSON cache at
17    cache_path.  If it doesn't exist or is outdated, load the configuration
18    instead from the original YAML file at src_path and regenerate the cache.
19    I assume I have the permissions to write to the cache directory.
20    """
21    if force_refresh:
22        do_refresh = True
23    else:
24        src_mtime = getmtime(src_path)
25        try:            cache_mtime = getmtime(cache_path)
26        except OSError: do_refresh  = True
27        else:           do_refresh  = src_mtime > cache_mtime
28
29    if not do_refresh:
30        # try reading from the cache first
31        try: cfg = wrap(file(cache_path), lambda f: json.read(f.read()))
32        except: do_refresh = True
33
34    if do_refresh:
35        # reload the source and regenerate the cache
36        cfg = wrap(file(src_path), lambda f: yaml.load(f, default_loader))
37        try: wrap(file(cache_path, 'w'), lambda f: f.write(json.write(cfg)))
38        except: pass # silent failure
39    return cfg
40
41dicts = load()
42structs = dicts2struct(dicts)
43
44# vim:et:sw=4:ts=4
Note: See TracBrowser for help on using the repository browser.