2 from invirt.common import *
3 from os.path import getmtime
5 default_src_path = '/etc/invirt/master.yaml'
6 default_cache_path = '/var/lib/invirt/cache.json'
8 def load(src_path = default_src_path,
9 cache_path = default_cache_path,
10 force_refresh = False):
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.
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
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
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
34 @with_lock_file('/var/lib/invirt/cache.lock')
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
46 structs = dicts2struct(dicts)