fix bug in late-import of yaml in invirt.config
[invirt/packages/invirt-base.git] / files / usr / share / python-support / sipb-xen-base / invirt / config.py
1 import json
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 def 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
45 dicts = load()
46 structs = dicts2struct(dicts)
47
48 # vim:et:sw=4:ts=4