updated changelog
[invirt/packages/invirt-base.git] / files / usr / share / python-support / sipb-xen-base / invirt / config.py
1 import json, yaml
2 from invirt.common import *
3 from os.path import getmtime
4
5 default_src_path   = '/etc/invirt/master.yaml'
6 default_cache_path = '/var/lib/invirt/cache.json'
7
8 try:    default_loader = yaml.CSafeLoader
9 except: default_loader = yaml.SafeLoader
10
11 def 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             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
45 dicts = load()
46 structs = dicts2struct(dicts)
47
48 # vim:et:sw=4:ts=4