Remove __future__ imports
[invirt/packages/invirt-base.git] / python / invirt / config.py
1 import json
2 from invirt.common import *
3 import os
4 from os import rename
5 from os.path import getmtime
6 from contextlib import closing
7 import yaml
8 import re
9
10 try:    loader = yaml.CSafeLoader
11 except: loader = yaml.SafeLoader
12
13 src_path    = '/etc/invirt/master.yaml'
14 src_dirpath = '/etc/invirt/conf.d'
15 cache_path  = '/var/lib/invirt/cache.json'
16 lock_path   = '/var/lib/invirt/cache.lock'
17
18 def augment(d1, d2):
19     """Splice dict-tree d2 into d1.  Return d1.
20
21     d2 may be None for an empty dict-tree, because yaml.load produces that.
22
23     Example:
24     >>> d = {'a': {'b': 1}, 'c': 2}
25     >>> augment(d, {'a': {'d': 3}})
26     {'a': {'b', 1, 'd': 3}, 'c': 2}
27     >>> d
28     {'a': {'b', 1, 'd': 3}, 'c': 2}
29     """
30     if d2 is None:
31         return d1
32     for k in d2:
33         if k in d1 and isinstance(d1[k], dict):
34             augment(d1[k], d2[k])
35         else:
36             d1[k] = d2[k]
37     return d1
38
39 def run_parts_list(dirname):
40     """Reimplements Debian's run-parts --list.
41
42     One difference from run-parts's behavior: run-parts --list /foo/
43     will give output like /foo//bar, but run_parts_list('/foo/') gives
44     /foo/bar in deference to Python conventions.
45
46     Matches documented behavior of run-parts in debianutils v2.28.2, dated 2007.
47     """
48     # From run-parts(8).
49     lanana_re   = re.compile('^[a-z0-9]+$')
50     lsb_re      = re.compile('^_?([a-z0-9_.]+-)+[a-z0-9]+$')
51     deb_cron_re = re.compile('^[a-z0-9][a-z0-9-]*$')
52     for name in os.listdir(dirname):
53         if lanana_re.match(name) or lsb_re.match(name) or deb_cron_re.match(name):
54             yield os.path.join(dirname, name)
55
56 def list_files():
57     yield src_path
58     for name in run_parts_list(src_dirpath):
59         yield name
60
61 def load_master():
62     config = dict()
63     for filename in list_files():
64         with closing(open(filename)) as f:
65             augment(config, yaml.load(f, loader))
66     return config
67
68 def get_src_mtime():
69     return max(max(getmtime(filename) for filename in list_files()),
70                getmtime(src_dirpath))
71
72 def load(force_refresh = False):
73     """
74     Try loading the configuration from the faster-to-load JSON cache at
75     cache_path.  If it doesn't exist or is outdated, load the configuration
76     instead from the original YAML file at src_path and regenerate the cache.
77     I assume I have the permissions to write to the cache directory.
78     """
79
80     # Namespace container for state variables, so that they can be updated by
81     # closures.
82     ns = struct()
83
84     if force_refresh:
85         do_refresh = True
86     else:
87         src_mtime = get_src_mtime()
88         try:            cache_mtime = getmtime(cache_path)
89         except OSError: do_refresh  = True
90         else:           do_refresh  = src_mtime + 1 >= cache_mtime
91
92         # We chose not to simply say
93         #
94         #   do_refresh = src_mtime >= cache_time
95         #
96         # because between the getmtime(src_path) and the time the cache is
97         # rewritten, the master configuration may have been updated, so future
98         # checks here would find a cache with a newer mtime than the master
99         # (and thus treat the cache as containing the latest version of the
100         # master).  The +1 means that for at least a full second following the
101         # update to the master, this function will refresh the cache, giving us
102         # 1 second to write the cache.  Note that if it takes longer than 1
103         # second to write the cache, then this situation could still arise.
104         #
105         # The getmtime calls should logically be part of the same transaction
106         # as the rest of this function (cache read + conditional cache
107         # refresh), but to wrap everything in an flock would cause the
108         # following cache read to be less streamlined.
109
110     if not do_refresh:
111         # Try reading from the cache first.  This must be transactionally
112         # isolated from concurrent writes to prevent reading an incomplete
113         # (changing) version of the data (but the transaction can share the
114         # lock with other concurrent reads).  This isolation is accomplished
115         # using an atomic filesystem rename in the refreshing stage.
116         try: 
117             with closing(open(cache_path)) as f:
118                 ns.cfg = json.read(f.read())
119         except: do_refresh = True
120
121     if do_refresh:
122         # Atomically reload the source and regenerate the cache.  The read and
123         # write must be a single transaction, or a stale version may be
124         # written (if another read/write of a more recent configuration
125         # is interleaved).  The final atomic rename is to keep this
126         # transactionally isolated from the above cache read.  If we fail to
127         # acquire the lock, just try to load the master configuration.
128         try:
129             with lock_file(lock_path):
130                 ns.cfg = load_master()
131                 try: 
132                     with closing(open(cache_path + '.tmp', 'w')) as f:
133                         f.write(json.write(ns.cfg))
134                 except: pass # silent failure
135                 else: rename(cache_path + '.tmp', cache_path)
136         except IOError:
137             ns.cfg = load_master()
138     return ns.cfg
139
140 dicts = load()
141 structs = dicts2struct(dicts, '')
142 safestructs = dicts2struct(dicts, '', '')