| 1 |
#!/usr/bin/env python3 |
| 2 |
|
| 3 |
# Copyright (C) 2017 |
| 4 |
|
| 5 |
import collections.abc |
| 6 |
import logging |
| 7 |
import os # requires posix |
| 8 |
|
| 9 |
from augeas import Augeas |
| 10 |
|
| 11 |
AUGEAS_LOAD_PATH = '/augeas/load/' |
| 12 |
AUGEAS_FILES_PATH = '/files/' |
| 13 |
AUGEAS_ERROR_PATH = '//error' |
| 14 |
|
| 15 |
log = logging.getLogger('augeas') |
| 16 |
|
| 17 |
|
| 18 |
def join(*paths): |
| 19 |
""" |
| 20 |
join two Augeas tree paths |
| 21 |
|
| 22 |
FIXME: Beware: // is normalized to / |
| 23 |
""" |
| 24 |
norm_paths = [os.path.normpath(path) for path in paths] |
| 25 |
# first path must be absolute |
| 26 |
assert norm_paths[0][0] == '/' |
| 27 |
new_paths = [norm_paths[0]] |
| 28 |
# relativize all other paths so join works as expected |
| 29 |
for path in norm_paths[1:]: |
| 30 |
if path.startswith('/'): |
| 31 |
path = path[1:] |
| 32 |
new_paths.append(path) |
| 33 |
new_path = os.path.join(*new_paths) |
| 34 |
log.debug("join: new_path %s", new_path) |
| 35 |
return os.path.normpath(new_path) |
| 36 |
|
| 37 |
|
| 38 |
class AugeasWrapper: |
| 39 |
"""python-augeas higher-level wrapper. |
| 40 |
|
| 41 |
Load single augeas lens and configuration file. |
| 42 |
Exposes configuration file as AugeasNode object with dict-like interface. |
| 43 |
|
| 44 |
AugeasWrapper can be used in with statement in the same way as file does. |
| 45 |
""" |
| 46 |
|
| 47 |
def __init__(self, confpath, lens, root=None, loadpath=None, |
| 48 |
flags=Augeas.NO_MODL_AUTOLOAD | Augeas.NO_LOAD | Augeas.ENABLE_SPAN): |
| 49 |
"""Parse configuration file using given lens. |
| 50 |
|
| 51 |
Params: |
| 52 |
confpath (str): Absolute path to the configuration file |
| 53 |
lens (str): Name of module containing Augeas lens |
| 54 |
root: passed down to original Augeas |
| 55 |
flags: passed down to original Augeas |
| 56 |
loadpath: passed down to original Augeas |
| 57 |
flags: passed down to original Augeas |
| 58 |
""" |
| 59 |
log.debug('loadpath: %s', loadpath) |
| 60 |
log.debug('confpath: %s', confpath) |
| 61 |
self._aug = Augeas(root=root, loadpath=loadpath, flags=flags) |
| 62 |
|
| 63 |
# /augeas/load/{lens} |
| 64 |
aug_load_path = join(AUGEAS_LOAD_PATH, lens) |
| 65 |
# /augeas/load/{lens}/lens = {lens}.lns |
| 66 |
self._aug.set(join(aug_load_path, 'lens'), f'{lens}.lns') |
| 67 |
# /augeas/load/{lens}/incl[0] = {confpath} |
| 68 |
self._aug.set(join(aug_load_path, 'incl[0]'), confpath) |
| 69 |
self._aug.load() |
| 70 |
|
| 71 |
errors = self._aug.match(AUGEAS_ERROR_PATH) |
| 72 |
if errors: |
| 73 |
err_msg = '\n'.join( |
| 74 |
[f"{e}: {self._aug.get(e)}" for e in errors] |
| 75 |
) |
| 76 |
raise RuntimeError(err_msg) |
| 77 |
|
| 78 |
path = join(AUGEAS_FILES_PATH, confpath) |
| 79 |
paths = self._aug.match(path) |
| 80 |
if len(paths) != 1: |
| 81 |
raise ValueError(f'path {path} did not match exactly once') |
| 82 |
self.tree = AugeasNode(self._aug, path) |
| 83 |
self._loaded = True |
| 84 |
|
| 85 |
def __enter__(self): |
| 86 |
return self |
| 87 |
|
| 88 |
def __exit__(self, exc_type, exc_value, traceback): |
| 89 |
self.save() |
| 90 |
self.close() |
| 91 |
|
| 92 |
def save(self): |
| 93 |
"""Save Augeas tree to its original file.""" |
| 94 |
assert self._loaded |
| 95 |
try: |
| 96 |
self._aug.save() |
| 97 |
except IOError as exc: |
| 98 |
log.exception(exc) |
| 99 |
for err_path in self._aug.match('//error'): |
| 100 |
log.error('%s: %s', err_path, |
| 101 |
self._aug.get(os.path.join(err_path, 'message'))) |
| 102 |
raise |
| 103 |
|
| 104 |
def close(self): |
| 105 |
""" |
| 106 |
close Augeas library |
| 107 |
|
| 108 |
After calling close() the object must not be used anymore. |
| 109 |
""" |
| 110 |
assert self._loaded |
| 111 |
self._aug.close() |
| 112 |
del self._aug |
| 113 |
self._loaded = False |
| 114 |
|
| 115 |
def match(self, path): |
| 116 |
"""Yield AugeasNodes matching given expression.""" |
| 117 |
assert self._loaded |
| 118 |
assert path |
| 119 |
log.debug('tree match %s', path) |
| 120 |
for matched_path in self._aug.match(path): |
| 121 |
yield AugeasNode(self._aug, matched_path) |
| 122 |
|
| 123 |
|
| 124 |
class AugeasNode(collections.abc.MutableMapping): |
| 125 |
"""One Augeas tree node with dict-like interface.""" |
| 126 |
|
| 127 |
def __init__(self, aug, path): |
| 128 |
""" |
| 129 |
Args: |
| 130 |
aug (AugeasWrapper or Augeas): Augeas library instance |
| 131 |
path (str): absolute path in Augeas tree matching single node |
| 132 |
|
| 133 |
BEWARE: There are no sanity checks of given path for performance reasons. |
| 134 |
""" |
| 135 |
assert aug |
| 136 |
assert path |
| 137 |
assert path.startswith('/') |
| 138 |
self._aug = aug |
| 139 |
self._path = path |
| 140 |
self._span = None |
| 141 |
|
| 142 |
@property |
| 143 |
def path(self): |
| 144 |
"""canonical path in Augeas tree, read-only""" |
| 145 |
return self._path |
| 146 |
|
| 147 |
@property |
| 148 |
def value(self): |
| 149 |
""" |
| 150 |
get value of this node in Augeas tree |
| 151 |
""" |
| 152 |
value = self._aug.get(self._path) |
| 153 |
log.debug('tree get: %s = %s', self._path, value) |
| 154 |
return value |
| 155 |
|
| 156 |
@value.setter |
| 157 |
def value(self, value): |
| 158 |
""" |
| 159 |
set value of this node in Augeas tree |
| 160 |
""" |
| 161 |
log.debug('tree set: %s = %s', self._path, value) |
| 162 |
self._aug.set(self._path, value) |
| 163 |
|
| 164 |
@property |
| 165 |
def span(self): |
| 166 |
if self._span is None: |
| 167 |
self._span = f"char position {self.char}" |
| 168 |
return self._span |
| 169 |
|
| 170 |
@property |
| 171 |
def char(self): |
| 172 |
return self._aug.span(self._path)[5] |
| 173 |
|
| 174 |
def __len__(self): |
| 175 |
""" |
| 176 |
number of items matching this path |
| 177 |
|
| 178 |
It is always 1 after __init__() but it may change |
| 179 |
as Augeas tree changes. |
| 180 |
""" |
| 181 |
return len(self._aug.match(self._path)) |
| 182 |
|
| 183 |
def __getitem__(self, key): |
| 184 |
if isinstance(key, int): |
| 185 |
# int is a shortcut to write [int] |
| 186 |
target_path = f'{self._path}[{key}]' |
| 187 |
else: |
| 188 |
target_path = self._path + key |
| 189 |
log.debug('tree getitem: target_path %s', target_path) |
| 190 |
paths = self._aug.match(target_path) |
| 191 |
if len(paths) != 1: |
| 192 |
raise KeyError(f'path {target_path} did not match exactly once') |
| 193 |
return AugeasNode(self._aug, target_path) |
| 194 |
|
| 195 |
def __delitem__(self, key): |
| 196 |
log.debug('tree delitem: %s + %s', self._path, key) |
| 197 |
target_path = self._path + key |
| 198 |
log.debug('tree delitem: target_path %s', target_path) |
| 199 |
self._aug.remove(target_path) |
| 200 |
|
| 201 |
def __setitem__(self, key, value): |
| 202 |
assert isinstance(value, AugeasNode) |
| 203 |
target_path = self.path + key |
| 204 |
self._aug.copy(value.path, target_path) |
| 205 |
|
| 206 |
def __iter__(self): |
| 207 |
self_path_len = len(self._path) |
| 208 |
assert self_path_len > 0 |
| 209 |
|
| 210 |
log.debug('tree iter: %s', self._path) |
| 211 |
for new_path in self._aug.match(self._path): |
| 212 |
if len(new_path) == self_path_len: |
| 213 |
yield '' |
| 214 |
else: |
| 215 |
yield new_path[self_path_len - 1:] |
| 216 |
|
| 217 |
def match(self, subpath): |
| 218 |
"""Yield AugeasNodes matching given sub-expression.""" |
| 219 |
assert subpath.startswith("/") |
| 220 |
match_path = f"{self._path}{subpath}" |
| 221 |
log.debug('tree match %s: %s', match_path, self._path) |
| 222 |
for matched_path in self._aug.match(match_path): |
| 223 |
yield AugeasNode(self._aug, matched_path) |
| 224 |
|
| 225 |
def __repr__(self): |
| 226 |
return f'AugeasNode({self._path})' |