| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
"""Implementation classes for config.""" |
| 18 |
|
| 19 |
__all__ = [ |
| 20 |
"Config", |
| 21 |
"ConfigData", |
| 22 |
"ConfigSchema", |
| 23 |
"ImplicitTypeSchema", |
| 24 |
"ImplicitTypeSection", |
| 25 |
"Section", |
| 26 |
"SectionSchema", |
| 27 |
"as_boolean", |
| 28 |
"as_host_port", |
| 29 |
"as_log_level", |
| 30 |
"as_timedelta", |
| 31 |
"as_username_groupname", |
| 32 |
] |
| 33 |
|
| 34 |
|
| 35 |
import datetime |
| 36 |
import grp |
| 37 |
import logging |
| 38 |
import os |
| 39 |
import pwd |
| 40 |
import re |
| 41 |
from os.path import abspath, basename, dirname |
| 42 |
from textwrap import dedent |
| 43 |
|
| 44 |
try: |
| 45 |
from configparser import NoSectionError, RawConfigParser |
| 46 |
from io import StringIO |
| 47 |
|
| 48 |
def _parser_read_file(parser, f, source=None): |
| 49 |
parser.read_file(f, source) |
| 50 |
|
| 51 |
except ImportError: |
| 52 |
|
| 53 |
from ConfigParser import NoSectionError, RawConfigParser |
| 54 |
from StringIO import StringIO |
| 55 |
|
| 56 |
def _parser_read_file(parser, f, source=None): |
| 57 |
parser.readfp(f, source) |
| 58 |
|
| 59 |
|
| 60 |
from lazr.delegates import delegate_to |
| 61 |
from zope.interface import implementer |
| 62 |
|
| 63 |
from lazr.config.interfaces import ( |
| 64 |
ConfigErrors, |
| 65 |
ICategory, |
| 66 |
IConfigData, |
| 67 |
IConfigLoader, |
| 68 |
IConfigSchema, |
| 69 |
InvalidSectionNameError, |
| 70 |
ISection, |
| 71 |
ISectionSchema, |
| 72 |
IStackableConfig, |
| 73 |
NoCategoryError, |
| 74 |
NoConfigError, |
| 75 |
RedefinedSectionError, |
| 76 |
UnknownKeyError, |
| 77 |
UnknownSectionError, |
| 78 |
) |
| 79 |
|
| 80 |
_missing = object() |
| 81 |
|
| 82 |
|
| 83 |
def read_content(filename): |
| 84 |
"""Return the content of a file at filename as a string.""" |
| 85 |
with open(filename) as fp: |
| 86 |
return fp.read() |
| 87 |
|
| 88 |
|
| 89 |
@implementer(ISectionSchema) |
| 90 |
class SectionSchema: |
| 91 |
"""See `ISectionSchema`.""" |
| 92 |
|
| 93 |
def __init__(self, name, options, is_optional=False, is_master=False): |
| 94 |
"""Create an `ISectionSchema` from the name and options. |
| 95 |
|
| 96 |
:param name: A string. The name of the ISectionSchema. |
| 97 |
:param options: A dict of the key-value pairs in the ISectionSchema. |
| 98 |
:param is_optional: A boolean. Is this section schema optional? |
| 99 |
:raise `RedefinedKeyError`: if a keys is redefined in SectionSchema. |
| 100 |
""" |
| 101 |
|
| 102 |
|
| 103 |
self.name = name |
| 104 |
self._options = options |
| 105 |
self.optional = is_optional |
| 106 |
self.master = is_master |
| 107 |
|
| 108 |
def __iter__(self): |
| 109 |
"""See `ISectionSchema`""" |
| 110 |
yield from self._options.keys() |
| 111 |
|
| 112 |
def __contains__(self, name): |
| 113 |
"""See `ISectionSchema`""" |
| 114 |
return name in self._options |
| 115 |
|
| 116 |
def __getitem__(self, key): |
| 117 |
"""See `ISectionSchema`""" |
| 118 |
return self._options[key] |
| 119 |
|
| 120 |
@property |
| 121 |
def category_and_section_names(self): |
| 122 |
"""See `ISectionSchema`.""" |
| 123 |
if "." in self.name: |
| 124 |
return tuple(self.name.split(".")) |
| 125 |
else: |
| 126 |
return (None, self.name) |
| 127 |
|
| 128 |
def clone(self): |
| 129 |
"""Return a copy of this section schema.""" |
| 130 |
return self.__class__( |
| 131 |
self.name, self._options.copy(), self.optional, self.master |
| 132 |
) |
| 133 |
|
| 134 |
|
| 135 |
@delegate_to(ISectionSchema, context="schema") |
| 136 |
@implementer(ISection) |
| 137 |
class Section: |
| 138 |
"""See `ISection`.""" |
| 139 |
|
| 140 |
def __init__(self, schema, _options=None): |
| 141 |
"""Create an `ISection` from schema. |
| 142 |
|
| 143 |
:param schema: The ISectionSchema that defines this ISection. |
| 144 |
""" |
| 145 |
|
| 146 |
self.__dict__["schema"] = schema |
| 147 |
if _options is None: |
| 148 |
_options = {key: schema[key] for key in schema} |
| 149 |
self.__dict__["_options"] = _options |
| 150 |
|
| 151 |
def __getitem__(self, key): |
| 152 |
"""See `ISection`""" |
| 153 |
return self._options[key] |
| 154 |
|
| 155 |
def __getattr__(self, name): |
| 156 |
"""See `ISection`.""" |
| 157 |
if name in self._options: |
| 158 |
return self._options[name] |
| 159 |
else: |
| 160 |
raise AttributeError("No section key named %s." % name) |
| 161 |
|
| 162 |
def __setattr__(self, name, value): |
| 163 |
"""Callsites cannot mutate the config by direct manipulation.""" |
| 164 |
raise AttributeError("Config options cannot be set directly.") |
| 165 |
|
| 166 |
@property |
| 167 |
def category_and_section_names(self): |
| 168 |
"""See `ISection`.""" |
| 169 |
return self.schema.category_and_section_names |
| 170 |
|
| 171 |
def update(self, items): |
| 172 |
"""Update the keys with new values. |
| 173 |
|
| 174 |
:return: A list of `UnknownKeyError`s if the section does not have |
| 175 |
the key. An empty list is returned if there are no errors. |
| 176 |
""" |
| 177 |
errors = [] |
| 178 |
for key, value in items: |
| 179 |
if key in self._options: |
| 180 |
self._options[key] = value |
| 181 |
else: |
| 182 |
msg = "{} does not have a {} key.".format(self.name, key) |
| 183 |
errors.append(UnknownKeyError(msg)) |
| 184 |
return errors |
| 185 |
|
| 186 |
def clone(self): |
| 187 |
"""Return a copy of this section. |
| 188 |
|
| 189 |
The extension mechanism requires a copy of a section to prevent |
| 190 |
mutation. |
| 191 |
""" |
| 192 |
return self.__class__(self.schema, self._options.copy()) |
| 193 |
|
| 194 |
|
| 195 |
class ImplicitTypeSection(Section): |
| 196 |
"""See `ISection`. |
| 197 |
|
| 198 |
ImplicitTypeSection supports implicit conversion of key values to |
| 199 |
simple datatypes. It accepts the same section data as Section; the |
| 200 |
datatype information is not embedded in the schema or the config file. |
| 201 |
""" |
| 202 |
|
| 203 |
re_types = re.compile( |
| 204 |
r""" |
| 205 |
(?P<false> ^false$) | |
| 206 |
(?P<true> ^true$) | |
| 207 |
(?P<none> ^none$) | |
| 208 |
(?P<int> ^[+-]?\d+$) | |
| 209 |
(?P<str> ^.*) |
| 210 |
""", |
| 211 |
re.IGNORECASE | re.VERBOSE, |
| 212 |
) |
| 213 |
|
| 214 |
def _convert(self, value): |
| 215 |
"""Return the value as the datatype the str appears to be. |
| 216 |
|
| 217 |
Conversion rules: |
| 218 |
* bool: a single word, 'true' or 'false', case insensitive. |
| 219 |
* int: a single word that is a number. Signed is supported, |
| 220 |
hex and octal numbers are not. |
| 221 |
* str: anything else. |
| 222 |
""" |
| 223 |
match = self.re_types.match(value) |
| 224 |
if match.group("false"): |
| 225 |
return False |
| 226 |
elif match.group("true"): |
| 227 |
return True |
| 228 |
elif match.group("none"): |
| 229 |
return None |
| 230 |
elif match.group("int"): |
| 231 |
return int(value) |
| 232 |
else: |
| 233 |
|
| 234 |
return value.strip() |
| 235 |
|
| 236 |
def __getitem__(self, key): |
| 237 |
"""See `ISection`.""" |
| 238 |
value = super().__getitem__(key) |
| 239 |
return self._convert(value) |
| 240 |
|
| 241 |
def __getattr__(self, name): |
| 242 |
"""See `ISection`.""" |
| 243 |
value = super().__getattr__(name) |
| 244 |
return self._convert(value) |
| 245 |
|
| 246 |
|
| 247 |
@implementer(IConfigSchema, IConfigLoader) |
| 248 |
class ConfigSchema: |
| 249 |
"""See `IConfigSchema`.""" |
| 250 |
|
| 251 |
_section_factory = Section |
| 252 |
|
| 253 |
def __init__(self, filename, file_object=None): |
| 254 |
"""Load a configuration schema from the provided filename. |
| 255 |
|
| 256 |
:param filename: The name of the file to load from, or if |
| 257 |
`file_object` is given, to pretend to load from. |
| 258 |
:type filename: string |
| 259 |
:param file_object: If given, optional file-like object to read from |
| 260 |
instead of actually opening the named file. |
| 261 |
:type file_object: An object with a readline() method. |
| 262 |
:raise `UnicodeDecodeError`: if the string contains non-ascii |
| 263 |
characters. |
| 264 |
:raise `RedefinedSectionError`: if a SectionSchema name is redefined. |
| 265 |
:raise `InvalidSectionNameError`: if a SectionSchema name is |
| 266 |
ill-formed. |
| 267 |
""" |
| 268 |
|
| 269 |
|
| 270 |
|
| 271 |
self.filename = filename |
| 272 |
self.name = basename(filename) |
| 273 |
self._section_schemas = {} |
| 274 |
self._category_names = [] |
| 275 |
if file_object is None: |
| 276 |
raw_schema = self._getRawSchema(filename) |
| 277 |
else: |
| 278 |
raw_schema = file_object |
| 279 |
parser = RawConfigParser() |
| 280 |
_parser_read_file(parser, raw_schema, filename) |
| 281 |
self._setSectionSchemasAndCategoryNames(parser) |
| 282 |
|
| 283 |
def _getRawSchema(self, filename): |
| 284 |
"""Return the contents of the schema at filename as a StringIO. |
| 285 |
|
| 286 |
This method verifies that the file is ascii encoded and that no |
| 287 |
section name is redefined. |
| 288 |
""" |
| 289 |
raw_schema = read_content(filename) |
| 290 |
|
| 291 |
raw_schema.encode("ascii", "strict") |
| 292 |
|
| 293 |
section_names = [] |
| 294 |
for section_name in re.findall(r"^\s*\[[^\]]+\]", raw_schema, re.M): |
| 295 |
if section_name in section_names: |
| 296 |
raise RedefinedSectionError(section_name) |
| 297 |
else: |
| 298 |
section_names.append(section_name) |
| 299 |
return StringIO(raw_schema) |
| 300 |
|
| 301 |
def _setSectionSchemasAndCategoryNames(self, parser): |
| 302 |
"""Set the SectionSchemas and category_names from the config.""" |
| 303 |
category_names = set() |
| 304 |
templates = {} |
| 305 |
|
| 306 |
|
| 307 |
for name in parser.sections(): |
| 308 |
( |
| 309 |
section_name, |
| 310 |
category_name, |
| 311 |
is_template, |
| 312 |
is_optional, |
| 313 |
is_master, |
| 314 |
) = self._parseSectionName(name) |
| 315 |
if is_template or is_master: |
| 316 |
templates[category_name] = dict(parser.items(name)) |
| 317 |
for name in parser.sections(): |
| 318 |
( |
| 319 |
section_name, |
| 320 |
category_name, |
| 321 |
is_template, |
| 322 |
is_optional, |
| 323 |
is_master, |
| 324 |
) = self._parseSectionName(name) |
| 325 |
if is_template: |
| 326 |
continue |
| 327 |
options = dict(templates.get(category_name, {})) |
| 328 |
options.update(parser.items(name)) |
| 329 |
self._section_schemas[section_name] = SectionSchema( |
| 330 |
section_name, options, is_optional, is_master |
| 331 |
) |
| 332 |
if category_name is not None: |
| 333 |
category_names.add(category_name) |
| 334 |
self._category_names = sorted(category_names) |
| 335 |
|
| 336 |
_section_name_pattern = re.compile(r"\w[\w.-]+\w") |
| 337 |
|
| 338 |
def _parseSectionName(self, name): |
| 339 |
"""Return a tuple of names and kinds embedded in the name. |
| 340 |
|
| 341 |
:return: (section_name, category_name, is_template, is_optional). |
| 342 |
section_name is always a string. category_name is a string or |
| 343 |
None if there is no prefix. is_template and is_optional |
| 344 |
are False by default, but will be true if the name's suffix |
| 345 |
ends in '.template' or '.optional'. |
| 346 |
""" |
| 347 |
name_parts = name.split(".") |
| 348 |
is_template = name_parts[-1] == "template" |
| 349 |
is_optional = name_parts[-1] == "optional" |
| 350 |
is_master = name_parts[-1] == "master" |
| 351 |
if is_template or is_optional: |
| 352 |
|
| 353 |
|
| 354 |
del name_parts[-1] |
| 355 |
count = len(name_parts) |
| 356 |
if count == 1 and is_template: |
| 357 |
|
| 358 |
category_name = name_parts[0] |
| 359 |
section_name = name_parts[0] |
| 360 |
elif count == 1: |
| 361 |
|
| 362 |
category_name = None |
| 363 |
section_name = name_parts[0] |
| 364 |
elif count == 2: |
| 365 |
|
| 366 |
category_name = name_parts[0] |
| 367 |
section_name = ".".join(name_parts) |
| 368 |
else: |
| 369 |
raise InvalidSectionNameError("[%s] has too many parts." % name) |
| 370 |
if self._section_name_pattern.match(section_name) is None: |
| 371 |
raise InvalidSectionNameError( |
| 372 |
r"[%s] name does not match [\w.-]+." % name |
| 373 |
) |
| 374 |
return ( |
| 375 |
section_name, |
| 376 |
category_name, |
| 377 |
is_template, |
| 378 |
is_optional, |
| 379 |
is_master, |
| 380 |
) |
| 381 |
|
| 382 |
@property |
| 383 |
def section_factory(self): |
| 384 |
"""See `IConfigSchema`.""" |
| 385 |
return self._section_factory |
| 386 |
|
| 387 |
@property |
| 388 |
def category_names(self): |
| 389 |
"""See `IConfigSchema`.""" |
| 390 |
return self._category_names |
| 391 |
|
| 392 |
def __iter__(self): |
| 393 |
"""See `IConfigSchema`.""" |
| 394 |
yield from self._section_schemas.values() |
| 395 |
|
| 396 |
def __contains__(self, name): |
| 397 |
"""See `IConfigSchema`.""" |
| 398 |
return name in self._section_schemas.keys() |
| 399 |
|
| 400 |
def __getitem__(self, name): |
| 401 |
"""See `IConfigSchema`.""" |
| 402 |
try: |
| 403 |
return self._section_schemas[name] |
| 404 |
except KeyError: |
| 405 |
raise NoSectionError(name) |
| 406 |
|
| 407 |
def getByCategory(self, name, default=_missing): |
| 408 |
"""See `IConfigSchema`.""" |
| 409 |
if name not in self.category_names: |
| 410 |
if default is _missing: |
| 411 |
raise NoCategoryError(name) |
| 412 |
return default |
| 413 |
section_schemas = [] |
| 414 |
for key in self._section_schemas: |
| 415 |
section = self._section_schemas[key] |
| 416 |
category, _ = section.category_and_section_names |
| 417 |
if name == category: |
| 418 |
section_schemas.append(section) |
| 419 |
return section_schemas |
| 420 |
|
| 421 |
def _getRequiredSections(self): |
| 422 |
"""return a dict of `Section`s from the required `SectionSchemas`.""" |
| 423 |
sections = {} |
| 424 |
for section_schema in self: |
| 425 |
if not section_schema.optional: |
| 426 |
sections[section_schema.name] = self.section_factory( |
| 427 |
section_schema |
| 428 |
) |
| 429 |
return sections |
| 430 |
|
| 431 |
def load(self, filename): |
| 432 |
"""See `IConfigLoader`.""" |
| 433 |
conf_data = read_content(filename) |
| 434 |
return self._load(filename, conf_data) |
| 435 |
|
| 436 |
def loadFile(self, source_file, filename=None): |
| 437 |
"""See `IConfigLoader`.""" |
| 438 |
conf_data = source_file.read() |
| 439 |
if filename is None: |
| 440 |
filename = getattr(source_file, "name") |
| 441 |
assert filename is not None, ( |
| 442 |
"filename must be provided if the file-like object " |
| 443 |
"does not have a name attribute." |
| 444 |
) |
| 445 |
return self._load(filename, conf_data) |
| 446 |
|
| 447 |
def _load(self, filename, conf_data): |
| 448 |
"""Return a Config parsed from conf_data.""" |
| 449 |
config = Config(self) |
| 450 |
config.push(filename, conf_data) |
| 451 |
return config |
| 452 |
|
| 453 |
|
| 454 |
class ImplicitTypeSchema(ConfigSchema): |
| 455 |
"""See `IConfigSchema`. |
| 456 |
|
| 457 |
ImplicitTypeSchema creates a config that supports implicit datatyping |
| 458 |
of section key values. |
| 459 |
""" |
| 460 |
|
| 461 |
_section_factory = ImplicitTypeSection |
| 462 |
|
| 463 |
|
| 464 |
@implementer(IConfigData) |
| 465 |
class ConfigData: |
| 466 |
"""See `IConfigData`.""" |
| 467 |
|
| 468 |
def __init__(self, filename, sections, extends=None, errors=None): |
| 469 |
"""Set the configuration data.""" |
| 470 |
self.filename = filename |
| 471 |
self.name = basename(filename) |
| 472 |
self._sections = sections |
| 473 |
self._category_names = self._getCategoryNames() |
| 474 |
self._extends = extends |
| 475 |
if errors is None: |
| 476 |
self._errors = [] |
| 477 |
else: |
| 478 |
self._errors = errors |
| 479 |
|
| 480 |
def _getCategoryNames(self): |
| 481 |
"""Return a tuple of category names that the `Section`s belong to.""" |
| 482 |
category_names = set() |
| 483 |
for section_name in self._sections: |
| 484 |
section = self._sections[section_name] |
| 485 |
category, _ = section.category_and_section_names |
| 486 |
if category is not None: |
| 487 |
category_names.add(category) |
| 488 |
return tuple(category_names) |
| 489 |
|
| 490 |
@property |
| 491 |
def category_names(self): |
| 492 |
"""See `IConfigData`.""" |
| 493 |
return self._category_names |
| 494 |
|
| 495 |
def __iter__(self): |
| 496 |
"""See `IConfigData`.""" |
| 497 |
yield from self._sections.values() |
| 498 |
|
| 499 |
def __contains__(self, name): |
| 500 |
"""See `IConfigData`.""" |
| 501 |
return name in self._sections.keys() |
| 502 |
|
| 503 |
def __getitem__(self, name): |
| 504 |
"""See `IConfigData`.""" |
| 505 |
try: |
| 506 |
return self._sections[name] |
| 507 |
except KeyError: |
| 508 |
raise NoSectionError(name) |
| 509 |
|
| 510 |
def getByCategory(self, name, default=_missing): |
| 511 |
"""See `IConfigData`.""" |
| 512 |
if name not in self.category_names: |
| 513 |
if default is _missing: |
| 514 |
raise NoCategoryError(name) |
| 515 |
return default |
| 516 |
sections = [] |
| 517 |
for key in self._sections: |
| 518 |
section = self._sections[key] |
| 519 |
category, _ = section.category_and_section_names |
| 520 |
if name == category: |
| 521 |
sections.append(section) |
| 522 |
return sections |
| 523 |
|
| 524 |
|
| 525 |
@delegate_to(IConfigData, context="data") |
| 526 |
@implementer(IStackableConfig) |
| 527 |
class Config: |
| 528 |
"""See `IStackableConfig`.""" |
| 529 |
|
| 530 |
|
| 531 |
|
| 532 |
|
| 533 |
def __init__(self, schema): |
| 534 |
"""Set the schema and configuration.""" |
| 535 |
self._overlays = ( |
| 536 |
ConfigData(schema.filename, schema._getRequiredSections()), |
| 537 |
) |
| 538 |
self.schema = schema |
| 539 |
|
| 540 |
def __getattr__(self, name): |
| 541 |
"""See `IStackableConfig`.""" |
| 542 |
if name in self.data._sections: |
| 543 |
return self.data._sections[name] |
| 544 |
elif name in self.data._category_names: |
| 545 |
return Category(name, self.data.getByCategory(name)) |
| 546 |
raise AttributeError("No section or category named %s." % name) |
| 547 |
|
| 548 |
@property |
| 549 |
def data(self): |
| 550 |
"""See `IStackableConfig`.""" |
| 551 |
return self.overlays[0] |
| 552 |
|
| 553 |
@property |
| 554 |
def extends(self): |
| 555 |
"""See `IStackableConfig`.""" |
| 556 |
if len(self.overlays) == 1: |
| 557 |
|
| 558 |
return None |
| 559 |
else: |
| 560 |
return self.overlays[1] |
| 561 |
|
| 562 |
@property |
| 563 |
def overlays(self): |
| 564 |
"""See `IStackableConfig`.""" |
| 565 |
return self._overlays |
| 566 |
|
| 567 |
def validate(self): |
| 568 |
"""See `IConfigData`.""" |
| 569 |
if len(self.data._errors) > 0: |
| 570 |
message = "%s is not valid." % self.name |
| 571 |
raise ConfigErrors(message, errors=self.data._errors) |
| 572 |
return True |
| 573 |
|
| 574 |
def push(self, conf_name, conf_data): |
| 575 |
"""See `IStackableConfig`. |
| 576 |
|
| 577 |
Create a new ConfigData object from the raw conf_data, and |
| 578 |
place it on top of the overlay stack. If the conf_data extends |
| 579 |
another conf, a ConfigData object will be created for that first. |
| 580 |
""" |
| 581 |
conf_data = dedent(conf_data) |
| 582 |
confs = self._getExtendedConfs(conf_name, conf_data) |
| 583 |
confs.reverse() |
| 584 |
for conf_name, parser, encoding_errors in confs: |
| 585 |
if self.data.filename == self.schema.filename == conf_name: |
| 586 |
|
| 587 |
continue |
| 588 |
config_data = self._createConfigData( |
| 589 |
conf_name, parser, encoding_errors |
| 590 |
) |
| 591 |
self._overlays = (config_data,) + self._overlays |
| 592 |
|
| 593 |
def _getExtendedConfs(self, conf_filename, conf_data, confs=None): |
| 594 |
"""Return a list of tuple (conf_name, parser, encoding_errors). |
| 595 |
|
| 596 |
:param conf_filename: The path and name of the conf file. |
| 597 |
:param conf_data: Unparsed config data. |
| 598 |
:param confs: A list of confs that extend filename. |
| 599 |
:return: A list of confs ordered from extender to extendee. |
| 600 |
:raises IOError: If filename cannot be read. |
| 601 |
|
| 602 |
This method parses the config data and checks for encoding errors. |
| 603 |
It checks parsed config data for the extends key in the meta section. |
| 604 |
It reads the unparsed config_data from the extended filename. |
| 605 |
It passes filename, data, and the working list to itself. |
| 606 |
""" |
| 607 |
if confs is None: |
| 608 |
confs = [] |
| 609 |
encoding_errors = self._verifyEncoding(conf_data) |
| 610 |
|
| 611 |
|
| 612 |
|
| 613 |
|
| 614 |
parser = RawConfigParser(strict=False) |
| 615 |
_parser_read_file(parser, StringIO(conf_data), conf_filename) |
| 616 |
confs.append((conf_filename, parser, encoding_errors)) |
| 617 |
if parser.has_option("meta", "extends"): |
| 618 |
base_path = dirname(conf_filename) |
| 619 |
extends_name = parser.get("meta", "extends") |
| 620 |
extends_filename = abspath("{}/{}".format(base_path, extends_name)) |
| 621 |
extends_data = read_content(extends_filename) |
| 622 |
self._getExtendedConfs(extends_filename, extends_data, confs) |
| 623 |
return confs |
| 624 |
|
| 625 |
def _createConfigData(self, conf_name, parser, encoding_errors): |
| 626 |
"""Return a new ConfigData object created from a parsed conf file. |
| 627 |
|
| 628 |
:param conf_name: the full name of the config file, may be a filepath. |
| 629 |
:param parser: the parsed config file; an instance of ConfigParser. |
| 630 |
:param encoding_errors: a list of encoding error in the config file. |
| 631 |
:return: a new ConfigData object. |
| 632 |
|
| 633 |
This method extracts the sections, keys, and values from the parser |
| 634 |
to construct a new ConfigData object. The list of encoding errors are |
| 635 |
incorporated into the the list of data-related errors for the |
| 636 |
ConfigData. |
| 637 |
""" |
| 638 |
sections = {} |
| 639 |
for section in self.data: |
| 640 |
sections[section.name] = section.clone() |
| 641 |
errors = list(self.data._errors) |
| 642 |
errors.extend(encoding_errors) |
| 643 |
extends = None |
| 644 |
masters = set() |
| 645 |
for section_name in parser.sections(): |
| 646 |
if section_name == "meta": |
| 647 |
extends, meta_errors = self._loadMetaData(parser) |
| 648 |
errors.extend(meta_errors) |
| 649 |
continue |
| 650 |
if ( |
| 651 |
section_name.endswith(".template") |
| 652 |
or section_name.endswith(".optional") |
| 653 |
or section_name.endswith(".master") |
| 654 |
): |
| 655 |
|
| 656 |
continue |
| 657 |
|
| 658 |
|
| 659 |
if "." in section_name: |
| 660 |
category, section = section_name.split(".") |
| 661 |
master_name = category + ".master" |
| 662 |
else: |
| 663 |
master_name = None |
| 664 |
if ( |
| 665 |
section_name not in self.schema |
| 666 |
and master_name not in self.schema |
| 667 |
): |
| 668 |
|
| 669 |
msg = "{} does not have a {} section.".format( |
| 670 |
self.schema.name, |
| 671 |
section_name, |
| 672 |
) |
| 673 |
errors.append(UnknownSectionError(msg)) |
| 674 |
continue |
| 675 |
if section_name not in self.data: |
| 676 |
|
| 677 |
try: |
| 678 |
section_schema = self.schema[master_name] |
| 679 |
except NoSectionError: |
| 680 |
|
| 681 |
|
| 682 |
pass |
| 683 |
else: |
| 684 |
assert section_schema.master, ".master is not a master?" |
| 685 |
schema = section_schema.clone() |
| 686 |
schema.name = section_name |
| 687 |
section = self.schema.section_factory(schema) |
| 688 |
section.update(parser.items(section_name)) |
| 689 |
sections[section_name] = section |
| 690 |
masters.add(master_name) |
| 691 |
continue |
| 692 |
|
| 693 |
section_schema = self.schema[section_name] |
| 694 |
sections[section_name] = self.schema.section_factory( |
| 695 |
section_schema |
| 696 |
) |
| 697 |
|
| 698 |
items = parser.items(section_name) |
| 699 |
section_errors = sections[section_name].update(items) |
| 700 |
errors.extend(section_errors) |
| 701 |
|
| 702 |
|
| 703 |
for master in masters: |
| 704 |
sections.pop(master, None) |
| 705 |
return ConfigData(conf_name, sections, extends, errors) |
| 706 |
|
| 707 |
def _verifyEncoding(self, config_data): |
| 708 |
"""Verify that the data is ASCII encoded. |
| 709 |
|
| 710 |
:return: a list of UnicodeDecodeError errors. If there are no |
| 711 |
errors, return an empty list. |
| 712 |
""" |
| 713 |
errors = [] |
| 714 |
try: |
| 715 |
if isinstance(config_data, bytes): |
| 716 |
config_data.decode("ascii", "strict") |
| 717 |
else: |
| 718 |
config_data.encode("ascii", "strict") |
| 719 |
except UnicodeError as error: |
| 720 |
errors.append(error) |
| 721 |
return errors |
| 722 |
|
| 723 |
def _loadMetaData(self, parser): |
| 724 |
"""Load the config meta data from the ConfigParser. |
| 725 |
|
| 726 |
The meta section is reserved for the LAZR config parser. |
| 727 |
|
| 728 |
:return: a list of errors if there are errors, or an empty list. |
| 729 |
""" |
| 730 |
extends = None |
| 731 |
errors = [] |
| 732 |
for key in parser.options("meta"): |
| 733 |
if key == "extends": |
| 734 |
extends = parser.get("meta", "extends") |
| 735 |
else: |
| 736 |
|
| 737 |
msg = "The meta section does not have a %s key." % key |
| 738 |
errors.append(UnknownKeyError(msg)) |
| 739 |
return (extends, errors) |
| 740 |
|
| 741 |
def pop(self, conf_name): |
| 742 |
"""See `IStackableConfig`.""" |
| 743 |
index = self._getIndexOfOverlay(conf_name) |
| 744 |
removed_overlays = self.overlays[:index] |
| 745 |
self._overlays = self.overlays[index:] |
| 746 |
return removed_overlays |
| 747 |
|
| 748 |
def _getIndexOfOverlay(self, conf_name): |
| 749 |
"""Return the index of the config named conf_name. |
| 750 |
|
| 751 |
The bottom of the stack cannot never be returned because it was |
| 752 |
made from the schema. |
| 753 |
""" |
| 754 |
schema_index = len(self.overlays) - 1 |
| 755 |
for index, config_data in enumerate(self.overlays): |
| 756 |
if index == schema_index and config_data.name == conf_name: |
| 757 |
raise NoConfigError("Cannot pop the schema's default config.") |
| 758 |
if config_data.name == conf_name: |
| 759 |
return index + 1 |
| 760 |
|
| 761 |
raise NoConfigError("No config with name: %s." % conf_name) |
| 762 |
|
| 763 |
|
| 764 |
@implementer(ICategory) |
| 765 |
class Category: |
| 766 |
"""See `ICategory`.""" |
| 767 |
|
| 768 |
def __init__(self, name, sections): |
| 769 |
"""Initialize the Category its name and a list of sections.""" |
| 770 |
self.name = name |
| 771 |
self._sections = {} |
| 772 |
for section in sections: |
| 773 |
self._sections[section.name] = section |
| 774 |
|
| 775 |
def __getattr__(self, name): |
| 776 |
"""See `ICategory`.""" |
| 777 |
full_name = "{}.{}".format(self.name, name) |
| 778 |
if full_name in self._sections: |
| 779 |
return self._sections[full_name] |
| 780 |
raise AttributeError("No section named %s." % name) |
| 781 |
|
| 782 |
|
| 783 |
def as_boolean(value): |
| 784 |
"""Turn a string into a boolean. |
| 785 |
|
| 786 |
:param value: A string with one of the following values |
| 787 |
(case-insensitive): true, yes, 1, on, enable, enabled (for True), or |
| 788 |
false, no, 0, off, disable, disabled (for False). Everything else is |
| 789 |
an error. |
| 790 |
:type value: string |
| 791 |
:return: True or False. |
| 792 |
:rtype: boolean |
| 793 |
""" |
| 794 |
value = value.lower() |
| 795 |
if value in ("true", "yes", "1", "on", "enabled", "enable"): |
| 796 |
return True |
| 797 |
if value in ("false", "no", "0", "off", "disabled", "disable"): |
| 798 |
return False |
| 799 |
raise ValueError("Invalid boolean value: %s" % value) |
| 800 |
|
| 801 |
|
| 802 |
def as_host_port(value, default_host="localhost", default_port=25): |
| 803 |
"""Return a 2-tuple of (host, port) from a value like 'host:port'. |
| 804 |
|
| 805 |
:param value: The configuration value. |
| 806 |
:type value: string |
| 807 |
:param default_host: Optional host name to use if the configuration value |
| 808 |
is missing the host name. |
| 809 |
:type default_host: string |
| 810 |
:param default_port: Optional port number to use if the configuration |
| 811 |
value is missing the port number. |
| 812 |
:type default_port: integer |
| 813 |
:return: a 2-tuple of the form (host, port) |
| 814 |
:rtype: 2-tuple of (string, integer) |
| 815 |
""" |
| 816 |
if ":" in value: |
| 817 |
host, port = value.split(":") |
| 818 |
if host == "": |
| 819 |
host = default_host |
| 820 |
port = int(port) |
| 821 |
else: |
| 822 |
host = value |
| 823 |
port = default_port |
| 824 |
return host, port |
| 825 |
|
| 826 |
|
| 827 |
def as_username_groupname(value=None): |
| 828 |
"""Turn a string of the form user:group into the user and group names. |
| 829 |
|
| 830 |
:param value: The configuration value. |
| 831 |
:type value: a string containing exactly one colon, or None |
| 832 |
:return: a 2-tuple of (username, groupname). If `value` was None, then |
| 833 |
the current user and group names are returned. |
| 834 |
:rtype: 2-tuple of type (string, string) |
| 835 |
""" |
| 836 |
if value: |
| 837 |
user, group = value.split(":", 1) |
| 838 |
else: |
| 839 |
user = pwd.getpwuid(os.getuid()).pw_name |
| 840 |
group = grp.getgrgid(os.getgid()).gr_name |
| 841 |
return user, group |
| 842 |
|
| 843 |
|
| 844 |
def _sortkey(item): |
| 845 |
"""Return a value that sorted(..., key=_sortkey) can use.""" |
| 846 |
order = dict( |
| 847 |
w=0, |
| 848 |
d=1, |
| 849 |
h=2, |
| 850 |
m=3, |
| 851 |
s=4, |
| 852 |
) |
| 853 |
return order.get(item[-1]) |
| 854 |
|
| 855 |
|
| 856 |
def as_timedelta(value): |
| 857 |
"""Convert a value string to the equivalent timedeta.""" |
| 858 |
|
| 859 |
|
| 860 |
|
| 861 |
components = sorted(re.findall(r"([\d.]+[smhdw])", value), key=_sortkey) |
| 862 |
|
| 863 |
if "".join(components) != value: |
| 864 |
raise ValueError |
| 865 |
keywords = { |
| 866 |
interval[0].lower(): interval |
| 867 |
for interval in ("weeks", "days", "hours", "minutes", "seconds") |
| 868 |
} |
| 869 |
keyword_arguments = {} |
| 870 |
for interval in components: |
| 871 |
if len(interval) == 0: |
| 872 |
raise ValueError |
| 873 |
keyword = keywords.get(interval[-1].lower()) |
| 874 |
if keyword is None: |
| 875 |
raise ValueError |
| 876 |
if keyword in keyword_arguments: |
| 877 |
raise ValueError |
| 878 |
if "." in interval[:-1]: |
| 879 |
converted = float(interval[:-1]) |
| 880 |
else: |
| 881 |
converted = int(interval[:-1]) |
| 882 |
keyword_arguments[keyword] = converted |
| 883 |
if len(keyword_arguments) == 0: |
| 884 |
raise ValueError |
| 885 |
return datetime.timedelta(**keyword_arguments) |
| 886 |
|
| 887 |
|
| 888 |
def as_log_level(value): |
| 889 |
"""Turn a string into a log level. |
| 890 |
|
| 891 |
:param value: A string with a value (case-insensitive) equal to one of the |
| 892 |
symbolic logging levels. |
| 893 |
:type value: string |
| 894 |
:return: A logging level constant. |
| 895 |
:rtype: int |
| 896 |
""" |
| 897 |
value = value.upper() |
| 898 |
return getattr(logging, value) |