fad48fe397c6754e8a2dc550b89cb0b33a43ec98
[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 import error, makedirs
4 from os.path import dirname, getmtime
5
6 default_src_path   = '/etc/invirt/master.yaml'
7 default_cache_path = '/var/lib/invirt/invirt.json'
8
9 try:    default_loader = yaml.CSafeLoader
10 except: default_loader = yaml.SafeLoader
11
12 def load(src_path = default_src_path,
13          cache_path = default_cache_path,
14          force_refresh = False):
15     """
16     Try loading the configuration from the faster-to-load JSON cache at
17     cache_path.  If it doesn't exist or is outdated, load the configuration
18     instead from the original YAML file at src_path and regenerate the cache.
19     I assume I have the permissions to write to the cache directory.
20     """
21     if force_refresh:
22         do_refresh = True
23     else:
24         src_mtime = getmtime(src_path)
25         try:            cache_mtime = getmtime(cache_path)
26         except OSError: do_refresh  = True
27         else:           do_refresh  = src_mtime > cache_mtime
28
29     if not do_refresh:
30         # try reading from the cache first
31         try: cfg = wrap(file(cache_path), lambda f: json.read(f.read()))
32         except: do_refresh = True
33
34     if do_refresh:
35         # reload the source and regenerate the cache
36         cfg = wrap(file(src_path), lambda f: yaml.load(f, default_loader))
37         try: wrap(file(cache_path, 'w'), lambda f: f.write(json.write(cfg)))
38         except: pass # silent failure
39     return cfg
40
41 dicts = load()
42 structs = dicts2struct(dicts)
43
44 # vim:et:sw=4:ts=4