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'
7 lock_file = '/var/lib/invirt/cache.lock'
9 def load(src_path = default_src_path,
10 cache_path = default_cache_path,
11 force_refresh = False):
13 Try loading the configuration from the faster-to-load JSON cache at
14 cache_path. If it doesn't exist or is outdated, load the configuration
15 instead from the original YAML file at src_path and regenerate the cache.
16 I assume I have the permissions to write to the cache directory.
19 # Namespace container for various state variables, so that they can be
20 # updated by closures.
26 src_mtime = getmtime(src_path)
27 try: cache_mtime = getmtime(cache_path)
28 except OSError: do_refresh = True
29 else: do_refresh = src_mtime > cache_mtime
32 # Try reading from the cache first. This must be transactionally
33 # isolated from concurrent writes to prevent reading an incomplete
34 # (changing) version of the data (but the transaction can share the
35 # lock with other concurrent reads). This isolation is accomplished
36 # using an atomic filesystem rename in the refreshing stage.
37 try: ns.cfg = with_closing(file(cache_path)) (
38 lambda f: json.read(f.read()))
39 except: do_refresh = True
42 # Atomically reload the source and regenerate the cache. The read and
43 # write must be a single transaction, or a stale version may be
44 # written (if another read/write of a more recent configuration
45 # is interleaved). The final atomic rename is to keep this
46 # transactionally isolated from the above cache read. If we fail to
47 # acquire the lock, just try to load the master configuration.
49 try: loader = yaml.CSafeLoader
50 except: loader = yaml.SafeLoader
52 @with_lock_file(lock_file)
54 ns.cfg = with_closing(file(src_path)) (
55 lambda f: yaml.load(f, loader))
56 try: with_closing(file(cache_path + '.tmp', 'w')) (
57 lambda f: f.write(json.write(ns.cfg)))
58 except: pass # silent failure
59 else: os.rename(cache_path + '.tmp', cache_path)
61 ns.cfg = with_closing(file(src_path)) (
62 lambda f: yaml.load(f, loader))
66 structs = dicts2struct(dicts)