[771] | 1 | import json, yaml |
---|
[778] | 2 | from invirt.common import * |
---|
[771] | 3 | from os import error, makedirs |
---|
| 4 | from os.path import dirname, getmtime |
---|
[726] | 5 | |
---|
[771] | 6 | default_src_path = '/etc/invirt/master.yaml' |
---|
| 7 | default_cache_path = '/var/lib/invirt/invirt.json' |
---|
[726] | 8 | |
---|
[733] | 9 | try: default_loader = yaml.CSafeLoader |
---|
| 10 | except: default_loader = yaml.SafeLoader |
---|
| 11 | |
---|
[771] | 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 | |
---|
[778] | 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 | |
---|
[771] | 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)) |
---|
[778] | 37 | try: wrap(file(cache_path, 'w'), lambda f: f.write(json.write(cfg))) |
---|
| 38 | except: pass # silent failure |
---|
[771] | 39 | return cfg |
---|
| 40 | |
---|
[778] | 41 | dicts = load() |
---|
| 42 | structs = dicts2struct(dicts) |
---|
| 43 | |
---|
[726] | 44 | # vim:et:sw=4:ts=4 |
---|