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 try: default_loader = yaml.CSafeLoader
9 except: default_loader = yaml.SafeLoader
11 def load(src_path = default_src_path,
12 cache_path = default_cache_path,
13 force_refresh = False):
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.
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
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
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
37 @with_lock_file('/var/lib/invirt/cache.lock')
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)