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