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

Last change on this file since 771 was 771, checked in by y_z, 16 years ago
  • added timestamp-based JSON caching of configuration for faster loading
  • exposed (more) options to command-line frontend
  • improved error messages/handling/help
  • removed all python 2.5-isms
  • reformatted to fit project style conventions
File size: 1.4 KB
Line 
1import json, yaml
2from os import error, makedirs
3from os.path import dirname, getmtime
4
5default_src_path   = '/etc/invirt/master.yaml'
6default_cache_path = '/var/lib/invirt/invirt.json'
7
8try:    default_loader = yaml.CSafeLoader
9except: default_loader = yaml.SafeLoader
10
11def wrap(rsrc, func):
12    "Utility to that emulates with Python 2.5's `with closing(rsrc)`."
13    try: return func(rsrc)
14    finally: rsrc.close()
15
16def load(src_path = default_src_path,
17         cache_path = default_cache_path,
18         force_refresh = False):
19    """
20    Try loading the configuration from the faster-to-load JSON cache at
21    cache_path.  If it doesn't exist or is outdated, load the configuration
22    instead from the original YAML file at src_path and regenerate the cache.
23    I assume I have the permissions to write to the cache directory.
24    """
25    if force_refresh:
26        do_refresh = True
27    else:
28        src_mtime = getmtime(src_path)
29        try:            cache_mtime = getmtime(cache_path)
30        except OSError: do_refresh  = True
31        else:           do_refresh  = src_mtime > cache_mtime
32
33    if do_refresh:
34        # reload the source and regenerate the cache
35        cfg = wrap(file(src_path), lambda f: yaml.load(f, default_loader))
36        wrap(file(cache_path, 'w'), lambda f: f.write(json.write(cfg)))
37    else:
38        cfg = wrap(file(cache_path), lambda f: json.read(f.read()))
39    return cfg
40
41# vim:et:sw=4:ts=4
Note: See TracBrowser for help on using the repository browser.