| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
|
| 22 |
""" |
| 23 |
Cluster nodes utility module |
| 24 |
|
| 25 |
The NodeUtils module is a ClusterShell helper module that provides |
| 26 |
supplementary services to manage nodes in a cluster. It is primarily |
| 27 |
designed to enhance the NodeSet module providing some binding support |
| 28 |
to external node groups sources in separate namespaces (example of |
| 29 |
group sources are: files, jobs scheduler, custom scripts, etc.). |
| 30 |
""" |
| 31 |
|
| 32 |
try: |
| 33 |
from configparser import ConfigParser, NoOptionError, NoSectionError |
| 34 |
except ImportError: |
| 35 |
|
| 36 |
from ConfigParser import ConfigParser, NoOptionError, NoSectionError |
| 37 |
|
| 38 |
import errno |
| 39 |
from functools import wraps |
| 40 |
import glob |
| 41 |
import logging |
| 42 |
import os |
| 43 |
import shlex |
| 44 |
import time |
| 45 |
import warnings |
| 46 |
|
| 47 |
from string import Template |
| 48 |
from subprocess import Popen, PIPE |
| 49 |
|
| 50 |
|
| 51 |
try: |
| 52 |
from subprocess import DEVNULL |
| 53 |
except ImportError: |
| 54 |
DEVNULL = open(os.devnull, 'r') |
| 55 |
|
| 56 |
|
| 57 |
try: |
| 58 |
basestring |
| 59 |
except NameError: |
| 60 |
basestring = str |
| 61 |
|
| 62 |
|
| 63 |
LOGGER = logging.getLogger(__name__) |
| 64 |
|
| 65 |
|
| 66 |
class GroupSourceError(Exception): |
| 67 |
"""Base GroupSource error exception""" |
| 68 |
def __init__(self, message, group_source): |
| 69 |
Exception.__init__(self, message) |
| 70 |
self.group_source = group_source |
| 71 |
|
| 72 |
class GroupSourceNoUpcall(GroupSourceError): |
| 73 |
"""Raised when upcall or method is not available""" |
| 74 |
|
| 75 |
class GroupSourceQueryFailed(GroupSourceError): |
| 76 |
"""Raised when a query failed (eg. no group found)""" |
| 77 |
|
| 78 |
class GroupResolverError(Exception): |
| 79 |
"""Base GroupResolver error""" |
| 80 |
|
| 81 |
class GroupResolverSourceError(GroupResolverError): |
| 82 |
"""Raised when upcall is not available""" |
| 83 |
|
| 84 |
class GroupResolverIllegalCharError(GroupResolverError): |
| 85 |
"""Raised when an illegal group character is encountered""" |
| 86 |
|
| 87 |
class GroupResolverConfigError(GroupResolverError): |
| 88 |
"""Raised when a configuration error is encountered""" |
| 89 |
|
| 90 |
|
| 91 |
_DEFAULT_CACHE_TIME = 3600 |
| 92 |
|
| 93 |
|
| 94 |
class GroupSource(object): |
| 95 |
"""ClusterShell Group Source class. |
| 96 |
|
| 97 |
A Group Source object defines resolv_map, resolv_list, resolv_all and |
| 98 |
optional resolv_reverse methods for node group resolution. It is |
| 99 |
constituting a group resolution namespace. |
| 100 |
""" |
| 101 |
|
| 102 |
def __init__(self, name, groups=None, allgroups=None): |
| 103 |
"""Initialize GroupSource |
| 104 |
|
| 105 |
:param name: group source name |
| 106 |
:param groups: group to nodes dict |
| 107 |
:param allgroups: optional "all groups" result (string) |
| 108 |
""" |
| 109 |
self.name = name |
| 110 |
self.groups = groups or {} |
| 111 |
self.allgroups = allgroups |
| 112 |
self.has_reverse = False |
| 113 |
|
| 114 |
def resolv_map(self, group): |
| 115 |
"""Get nodes from group `group`""" |
| 116 |
return self.groups.get(group, '') |
| 117 |
|
| 118 |
def resolv_list(self): |
| 119 |
"""Return a list of all group names for this group source""" |
| 120 |
return list(self.groups) |
| 121 |
|
| 122 |
def resolv_all(self): |
| 123 |
"""Return the content of all groups as defined by this GroupSource""" |
| 124 |
if self.allgroups is None: |
| 125 |
raise GroupSourceNoUpcall("All groups info not available", self) |
| 126 |
return self.allgroups |
| 127 |
|
| 128 |
def resolv_reverse(self, node): |
| 129 |
""" |
| 130 |
Return the group name matching the provided node. |
| 131 |
""" |
| 132 |
raise GroupSourceNoUpcall("Not implemented", self) |
| 133 |
|
| 134 |
|
| 135 |
class FileGroupSource(GroupSource): |
| 136 |
"""File-based Group Source using loader for file format and cache expiry.""" |
| 137 |
|
| 138 |
def __init__(self, name, loader): |
| 139 |
""" |
| 140 |
Initialize FileGroupSource object. |
| 141 |
|
| 142 |
:param name: group source name (eg. key name of yaml root dict) |
| 143 |
:param loader: associated content loader (eg. YAMLGroupLoader object) |
| 144 |
""" |
| 145 |
|
| 146 |
self.name = name |
| 147 |
self.loader = loader |
| 148 |
self.has_reverse = False |
| 149 |
|
| 150 |
@property |
| 151 |
def groups(self): |
| 152 |
"""groups property (dict)""" |
| 153 |
return self.loader.groups(self.name) |
| 154 |
|
| 155 |
@property |
| 156 |
def allgroups(self): |
| 157 |
"""allgroups property (string)""" |
| 158 |
|
| 159 |
return self.groups.get('all') |
| 160 |
|
| 161 |
|
| 162 |
class UpcallGroupSource(GroupSource): |
| 163 |
""" |
| 164 |
GroupSource class managing external calls for nodegroup support. |
| 165 |
|
| 166 |
Upcall results are cached for a customizable amount of time. This is |
| 167 |
controlled by `cache_time` attribute. Default is 3600 seconds. |
| 168 |
|
| 169 |
The optional 'mapall' upcall returns all group-to-nodes mappings in a |
| 170 |
single call and is then used to serve both 'map' and 'list' queries |
| 171 |
from the cache. |
| 172 |
""" |
| 173 |
|
| 174 |
def __init__(self, name, map_upcall=None, all_upcall=None, |
| 175 |
list_upcall=None, reverse_upcall=None, cfgdir=None, |
| 176 |
cache_time=None, mapall_upcall=None): |
| 177 |
GroupSource.__init__(self, name) |
| 178 |
self.verbosity = 0 |
| 179 |
self.cfgdir = cfgdir |
| 180 |
self.logger = logging.getLogger(__name__) |
| 181 |
|
| 182 |
|
| 183 |
self.upcalls = {} |
| 184 |
if map_upcall: |
| 185 |
self.upcalls['map'] = map_upcall |
| 186 |
if all_upcall: |
| 187 |
self.upcalls['all'] = all_upcall |
| 188 |
if list_upcall: |
| 189 |
self.upcalls['list'] = list_upcall |
| 190 |
if reverse_upcall: |
| 191 |
self.upcalls['reverse'] = reverse_upcall |
| 192 |
self.has_reverse = True |
| 193 |
if mapall_upcall: |
| 194 |
self.upcalls['mapall'] = mapall_upcall |
| 195 |
|
| 196 |
|
| 197 |
if cache_time is None: |
| 198 |
self.cache_time = _DEFAULT_CACHE_TIME |
| 199 |
else: |
| 200 |
self.cache_time = cache_time |
| 201 |
self._cache = {} |
| 202 |
self.clear_cache() |
| 203 |
|
| 204 |
def clear_cache(self): |
| 205 |
""" |
| 206 |
Remove all previously cached upcall results whatever their lifetime is. |
| 207 |
""" |
| 208 |
self._cache = { |
| 209 |
'map': {}, |
| 210 |
'reverse': {} |
| 211 |
} |
| 212 |
|
| 213 |
def _upcall_read(self, cmdtpl, args=dict()): |
| 214 |
""" |
| 215 |
Invoke the specified upcall command, raise an Exception if |
| 216 |
something goes wrong and return the command output otherwise. |
| 217 |
""" |
| 218 |
cmdline = Template(self.upcalls[cmdtpl]).safe_substitute(args) |
| 219 |
self.logger.debug("EXEC '%s'", cmdline) |
| 220 |
proc = Popen(cmdline, stdin=DEVNULL, stdout=PIPE, shell=True, |
| 221 |
cwd=self.cfgdir, universal_newlines=True) |
| 222 |
output = proc.communicate()[0].strip() |
| 223 |
self.logger.debug("READ '%s'", output) |
| 224 |
if proc.returncode != 0: |
| 225 |
self.logger.debug("ERROR '%s' returned %d", cmdline, |
| 226 |
proc.returncode) |
| 227 |
raise GroupSourceQueryFailed(cmdline, self) |
| 228 |
return output |
| 229 |
|
| 230 |
def _upcall_cache(self, upcall, cache, key, **args): |
| 231 |
""" |
| 232 |
Look for `key' in provided `cache'. If not found, call the |
| 233 |
corresponding `upcall'. |
| 234 |
|
| 235 |
If `key' is missing, it is added to provided `cache'. Each entry in a |
| 236 |
cache is kept only for a limited time equal to self.cache_time . |
| 237 |
""" |
| 238 |
|
| 239 |
if key in cache and cache[key][1] < time.time(): |
| 240 |
self.logger.debug("PURGE EXPIRED (%d)'%s'", cache[key][1], key) |
| 241 |
del cache[key] |
| 242 |
|
| 243 |
|
| 244 |
if key not in cache: |
| 245 |
if not self.upcalls.get(upcall): |
| 246 |
raise GroupSourceNoUpcall(upcall, self) |
| 247 |
|
| 248 |
cache_expiry = time.time() + self.cache_time |
| 249 |
|
| 250 |
args['CFGDIR'] = self.cfgdir |
| 251 |
args['SOURCE'] = self.name |
| 252 |
cache[key] = (self._upcall_read(upcall, args), cache_expiry) |
| 253 |
|
| 254 |
return cache[key][0] |
| 255 |
|
| 256 |
def _populate_from_mapall(self): |
| 257 |
""" |
| 258 |
Run the optional 'mapall' upcall and fill the map and list caches |
| 259 |
from its output. No-op if 'mapall' is not defined or its last |
| 260 |
result is still fresh. |
| 261 |
""" |
| 262 |
if 'mapall' not in self.upcalls: |
| 263 |
return |
| 264 |
cached = self._cache.get('mapall') |
| 265 |
if cached is not None and cached[1] >= time.time(): |
| 266 |
return |
| 267 |
|
| 268 |
content = self._upcall_cache('mapall', self._cache, 'mapall') |
| 269 |
cache_expiry = self._cache['mapall'][1] |
| 270 |
new_map = {} |
| 271 |
try: |
| 272 |
for line in content.splitlines(): |
| 273 |
line = line.strip() |
| 274 |
if not line: |
| 275 |
continue |
| 276 |
group, sep, nodes = line.partition(':') |
| 277 |
group = group.strip() |
| 278 |
if not sep or not group or len(group.split()) > 1: |
| 279 |
raise GroupSourceQueryFailed( |
| 280 |
"mapall: invalid line %r (expected 'group: nodes')" |
| 281 |
% line, self) |
| 282 |
nodes = nodes.strip() |
| 283 |
if group in new_map: |
| 284 |
|
| 285 |
nodes = ','.join(n for n in (new_map[group][0], nodes) if n) |
| 286 |
new_map[group] = (nodes, cache_expiry) |
| 287 |
except GroupSourceQueryFailed: |
| 288 |
del self._cache['mapall'] |
| 289 |
raise |
| 290 |
self._cache['map'] = new_map |
| 291 |
self._cache['list'] = (' '.join(new_map), cache_expiry) |
| 292 |
|
| 293 |
def resolv_map(self, group): |
| 294 |
""" |
| 295 |
Get nodes from group 'group', using the cached value if |
| 296 |
available. |
| 297 |
""" |
| 298 |
self._populate_from_mapall() |
| 299 |
if 'map' not in self.upcalls and 'mapall' in self.upcalls: |
| 300 |
|
| 301 |
return self._cache['map'].get(group, ('',))[0] |
| 302 |
return self._upcall_cache('map', self._cache['map'], group, GROUP=group) |
| 303 |
|
| 304 |
def resolv_list(self): |
| 305 |
""" |
| 306 |
Return a list of all group names for this group source, using |
| 307 |
the cached value if available. |
| 308 |
""" |
| 309 |
self._populate_from_mapall() |
| 310 |
if 'list' not in self.upcalls and 'mapall' in self.upcalls: |
| 311 |
|
| 312 |
return self._cache['list'][0] |
| 313 |
return self._upcall_cache('list', self._cache, 'list') |
| 314 |
|
| 315 |
def resolv_all(self): |
| 316 |
""" |
| 317 |
Return the content of special group ALL, using the cached value |
| 318 |
if available. |
| 319 |
""" |
| 320 |
return self._upcall_cache('all', self._cache, 'all') |
| 321 |
|
| 322 |
def resolv_reverse(self, node): |
| 323 |
""" |
| 324 |
Return the group name matching the provided node, using the |
| 325 |
cached value if available. |
| 326 |
""" |
| 327 |
|
| 328 |
node_str = str(node) |
| 329 |
return self._upcall_cache('reverse', self._cache['reverse'], node_str, |
| 330 |
NODE=node_str) |
| 331 |
|
| 332 |
|
| 333 |
class YAMLGroupLoader(object): |
| 334 |
""" |
| 335 |
YAML group file loader/reloader. |
| 336 |
|
| 337 |
Load or reload a YAML multi group sources file: |
| 338 |
|
| 339 |
- create GroupSource objects |
| 340 |
- gather groups dict content on load |
| 341 |
- reload the file once cache_time has expired |
| 342 |
""" |
| 343 |
|
| 344 |
def __init__(self, filename, cache_time=None): |
| 345 |
""" |
| 346 |
Initialize YAMLGroupLoader and load file. |
| 347 |
|
| 348 |
:param filename: YAML file path |
| 349 |
:param cache_time: cache time (seconds) |
| 350 |
""" |
| 351 |
if cache_time is None: |
| 352 |
self.cache_time = _DEFAULT_CACHE_TIME |
| 353 |
else: |
| 354 |
self.cache_time = cache_time |
| 355 |
self.cache_expiry = 0 |
| 356 |
self.filename = filename |
| 357 |
self.sources = {} |
| 358 |
self._groups = {} |
| 359 |
|
| 360 |
self._load() |
| 361 |
|
| 362 |
def _load(self): |
| 363 |
"""Load or reload YAML group file to create GroupSource objects.""" |
| 364 |
with open(self.filename) as yamlfile: |
| 365 |
try: |
| 366 |
import yaml |
| 367 |
sources = yaml.safe_load(yamlfile) |
| 368 |
except ImportError as exc: |
| 369 |
msg = "Disable autodir or install PyYAML!" |
| 370 |
raise GroupResolverConfigError("%s (%s)" % (str(exc), msg)) |
| 371 |
except yaml.YAMLError as exc: |
| 372 |
raise GroupResolverConfigError("%s: %s" % (self.filename, exc)) |
| 373 |
|
| 374 |
|
| 375 |
if not isinstance(sources, dict): |
| 376 |
fmt = "%s: invalid content (base is not a dict)" |
| 377 |
raise GroupResolverConfigError(fmt % self.filename) |
| 378 |
|
| 379 |
first = not self.sources |
| 380 |
|
| 381 |
for srcname, groups in sources.items(): |
| 382 |
|
| 383 |
|
| 384 |
if not isinstance(srcname, basestring): |
| 385 |
fmt = '%s: group source %s not a string (add quotes?)' |
| 386 |
raise GroupResolverConfigError(fmt % (self.filename, srcname)) |
| 387 |
|
| 388 |
if not isinstance(groups, dict): |
| 389 |
fmt = "%s: invalid content (group source '%s' is not a dict)" |
| 390 |
raise GroupResolverConfigError(fmt % (self.filename, srcname)) |
| 391 |
|
| 392 |
for grp, grpnodes in groups.items(): |
| 393 |
if not isinstance(grp, basestring): |
| 394 |
fmt = '%s: %s: group name %s not a string (add quotes?)' |
| 395 |
raise GroupResolverConfigError(fmt % (self.filename, |
| 396 |
srcname, grp)) |
| 397 |
|
| 398 |
if grpnodes is None: |
| 399 |
groups[grp] = '' |
| 400 |
|
| 401 |
if first: |
| 402 |
self._groups[srcname] = groups |
| 403 |
self.sources[srcname] = FileGroupSource(srcname, self) |
| 404 |
elif srcname in self.sources: |
| 405 |
|
| 406 |
self._groups[srcname] = groups |
| 407 |
|
| 408 |
|
| 409 |
|
| 410 |
self.cache_expiry = time.time() + self.cache_time |
| 411 |
|
| 412 |
def __iter__(self): |
| 413 |
"""Iterate over GroupSource objects.""" |
| 414 |
|
| 415 |
return iter(self.sources.values()) |
| 416 |
|
| 417 |
def groups(self, sourcename): |
| 418 |
""" |
| 419 |
Groups dict accessor for sourcename. |
| 420 |
|
| 421 |
This method is called by associated FileGroupSource objects and simply |
| 422 |
returns dict content, after reloading file if cache_time has expired. |
| 423 |
""" |
| 424 |
if self.cache_expiry < time.time(): |
| 425 |
|
| 426 |
self._load() |
| 427 |
|
| 428 |
return self._groups[sourcename] |
| 429 |
|
| 430 |
|
| 431 |
class GroupResolver(object): |
| 432 |
""" |
| 433 |
Base class GroupResolver that aims to provide node/group resolution |
| 434 |
from multiple GroupSources. |
| 435 |
|
| 436 |
A GroupResolver object might be initialized with a default |
| 437 |
GroupSource object, that is later used when group resolution is |
| 438 |
requested with no source information. As of version 1.7, a set of |
| 439 |
illegal group characters may also be provided for sanity check |
| 440 |
(raising GroupResolverIllegalCharError when found). |
| 441 |
""" |
| 442 |
|
| 443 |
def __init__(self, default_source=None, illegal_chars=None): |
| 444 |
"""Lazy initialization of a new GroupResolver object.""" |
| 445 |
self._sources = {} |
| 446 |
self._default_source = default_source |
| 447 |
self._initialized = False |
| 448 |
self.illegal_chars = illegal_chars or set() |
| 449 |
|
| 450 |
def _late_init(self): |
| 451 |
"""Override method to initialize object just before it is needed.""" |
| 452 |
if self._default_source: |
| 453 |
self._sources[self._default_source.name] = self._default_source |
| 454 |
self._initialized = True |
| 455 |
|
| 456 |
def init(func): |
| 457 |
@wraps(func) |
| 458 |
def wrapper(self, *args): |
| 459 |
if not self._initialized: |
| 460 |
self._late_init() |
| 461 |
return func(self, *args) |
| 462 |
return wrapper |
| 463 |
|
| 464 |
@init |
| 465 |
def set_verbosity(self, value): |
| 466 |
"""Set debugging verbosity value (DEPRECATED: use logging.DEBUG).""" |
| 467 |
warnings.warn("set_verbosity() is deprecated; use logging instead", |
| 468 |
DeprecationWarning, stacklevel=2) |
| 469 |
for source in self._sources.values(): |
| 470 |
source.verbosity = value |
| 471 |
|
| 472 |
@init |
| 473 |
def add_source(self, group_source): |
| 474 |
"""Add a GroupSource to this resolver.""" |
| 475 |
if group_source.name in self._sources: |
| 476 |
raise ValueError("GroupSource '%s': name collision" % \ |
| 477 |
group_source.name) |
| 478 |
self._sources[group_source.name] = group_source |
| 479 |
|
| 480 |
@init |
| 481 |
def sources(self): |
| 482 |
"""Get the list of all resolver source names. """ |
| 483 |
srcs = list(self._sources) |
| 484 |
if srcs and srcs[0] is not self._default_source: |
| 485 |
srcs.remove(self._default_source.name) |
| 486 |
srcs.insert(0, self._default_source.name) |
| 487 |
return srcs |
| 488 |
|
| 489 |
@init |
| 490 |
def _get_default_source_name(self): |
| 491 |
"""Get default source name of resolver.""" |
| 492 |
if self._default_source is None: |
| 493 |
return None |
| 494 |
return self._default_source.name |
| 495 |
|
| 496 |
@init |
| 497 |
def _set_default_source_name(self, sourcename): |
| 498 |
"""Set default source of resolver (by name).""" |
| 499 |
try: |
| 500 |
self._default_source = self._sources[sourcename] |
| 501 |
except KeyError: |
| 502 |
raise GroupResolverSourceError(sourcename) |
| 503 |
|
| 504 |
default_source_name = property(_get_default_source_name, |
| 505 |
_set_default_source_name) |
| 506 |
|
| 507 |
def _list_nodes(self, source, what, *args): |
| 508 |
"""Helper method that returns a list of results (nodes) when |
| 509 |
the source is defined.""" |
| 510 |
result = [] |
| 511 |
assert source |
| 512 |
raw = getattr(source, 'resolv_%s' % what)(*args) |
| 513 |
if isinstance(raw, list): |
| 514 |
raw = ','.join(raw) |
| 515 |
for line in raw.splitlines(): |
| 516 |
[result.append(x) for x in line.strip().split()] |
| 517 |
return result |
| 518 |
|
| 519 |
def _list_groups(self, source, what, *args): |
| 520 |
"""Helper method that returns a list of results (groups) when |
| 521 |
the source is defined.""" |
| 522 |
result = [] |
| 523 |
assert source |
| 524 |
raw = getattr(source, 'resolv_%s' % what)(*args) |
| 525 |
|
| 526 |
try: |
| 527 |
grpiter = raw.splitlines() |
| 528 |
except AttributeError: |
| 529 |
grpiter = raw |
| 530 |
|
| 531 |
for line in grpiter: |
| 532 |
for grpstr in line.strip().split(): |
| 533 |
if self.illegal_chars.intersection(grpstr): |
| 534 |
errmsg = ' '.join(self.illegal_chars.intersection(grpstr)) |
| 535 |
raise GroupResolverIllegalCharError(errmsg) |
| 536 |
result.append(grpstr) |
| 537 |
return result |
| 538 |
|
| 539 |
@init |
| 540 |
def _source(self, namespace): |
| 541 |
"""Helper method that returns the source by namespace name.""" |
| 542 |
if not namespace: |
| 543 |
source = self._default_source |
| 544 |
else: |
| 545 |
source = self._sources.get(namespace) |
| 546 |
if not source: |
| 547 |
raise GroupResolverSourceError(namespace or "<default>") |
| 548 |
return source |
| 549 |
|
| 550 |
def group_nodes(self, group, namespace=None): |
| 551 |
""" |
| 552 |
Find nodes for specified group name and optional namespace. |
| 553 |
""" |
| 554 |
source = self._source(namespace) |
| 555 |
return self._list_nodes(source, 'map', group) |
| 556 |
|
| 557 |
def all_nodes(self, namespace=None): |
| 558 |
""" |
| 559 |
Find all nodes. You may specify an optional namespace. |
| 560 |
""" |
| 561 |
source = self._source(namespace) |
| 562 |
return self._list_nodes(source, 'all') |
| 563 |
|
| 564 |
def grouplist(self, namespace=None): |
| 565 |
""" |
| 566 |
Get full group list. You may specify an optional |
| 567 |
namespace. |
| 568 |
""" |
| 569 |
source = self._source(namespace) |
| 570 |
return self._list_groups(source, 'list') |
| 571 |
|
| 572 |
def has_node_groups(self, namespace=None): |
| 573 |
""" |
| 574 |
Return whether finding group list for a specified node is |
| 575 |
supported by the resolver (in optional namespace). |
| 576 |
""" |
| 577 |
try: |
| 578 |
return self._source(namespace).has_reverse |
| 579 |
except GroupResolverSourceError: |
| 580 |
return False |
| 581 |
|
| 582 |
def node_groups(self, node, namespace=None): |
| 583 |
""" |
| 584 |
Find group list for specified node and optional namespace. |
| 585 |
""" |
| 586 |
source = self._source(namespace) |
| 587 |
return self._list_groups(source, 'reverse', node) |
| 588 |
|
| 589 |
|
| 590 |
class GroupResolverConfig(GroupResolver): |
| 591 |
""" |
| 592 |
GroupResolver class that is able to automatically setup its |
| 593 |
GroupSource's from a configuration file. This is the default |
| 594 |
resolver for NodeSet. |
| 595 |
""" |
| 596 |
SECTION_MAIN = 'Main' |
| 597 |
|
| 598 |
def __init__(self, filenames, illegal_chars=None): |
| 599 |
""" |
| 600 |
Lazy init GroupResolverConfig object from filenames. |
| 601 |
""" |
| 602 |
GroupResolver.__init__(self, illegal_chars=illegal_chars) |
| 603 |
|
| 604 |
self.filenames = filenames |
| 605 |
self.config = None |
| 606 |
|
| 607 |
def _late_init(self): |
| 608 |
""" |
| 609 |
Initialize object when needed. Only the first accessible config |
| 610 |
filename is loaded. |
| 611 |
""" |
| 612 |
GroupResolver._late_init(self) |
| 613 |
|
| 614 |
|
| 615 |
self.config = ConfigParser() |
| 616 |
parsed = self.config.read(self.filenames) |
| 617 |
|
| 618 |
|
| 619 |
|
| 620 |
if parsed: |
| 621 |
|
| 622 |
self._parse_config(os.path.dirname(parsed[-1])) |
| 623 |
|
| 624 |
def _parse_config(self, cfg_dirname): |
| 625 |
"""parse config using relative dir cfg_dirname""" |
| 626 |
|
| 627 |
try: |
| 628 |
if self.config.has_option(self.SECTION_MAIN, 'groupsdir'): |
| 629 |
opt_confdir = 'groupsdir' |
| 630 |
else: |
| 631 |
opt_confdir = 'confdir' |
| 632 |
|
| 633 |
|
| 634 |
loaded_confdirs = set() |
| 635 |
|
| 636 |
confdirstr = self.config.get(self.SECTION_MAIN, opt_confdir) |
| 637 |
for confdir in shlex.split(confdirstr): |
| 638 |
|
| 639 |
|
| 640 |
confdir = Template(confdir).safe_substitute(CFGDIR=cfg_dirname) |
| 641 |
confdir = os.path.normpath(confdir) |
| 642 |
if confdir in loaded_confdirs: |
| 643 |
continue |
| 644 |
loaded_confdirs.add(confdir) |
| 645 |
if not os.path.isdir(confdir): |
| 646 |
if not os.path.exists(confdir): |
| 647 |
continue |
| 648 |
raise GroupResolverConfigError("Defined confdir %s is not" |
| 649 |
" a directory" % confdir) |
| 650 |
|
| 651 |
for groupsfn in sorted(glob.glob('%s/*.conf' % confdir)): |
| 652 |
grpcfg = ConfigParser() |
| 653 |
grpcfg.read(groupsfn) |
| 654 |
self._sources_from_cfg(grpcfg, confdir) |
| 655 |
except (NoSectionError, NoOptionError): |
| 656 |
pass |
| 657 |
|
| 658 |
|
| 659 |
try: |
| 660 |
|
| 661 |
loaded_autodirs = set() |
| 662 |
|
| 663 |
autodirstr = self.config.get(self.SECTION_MAIN, 'autodir') |
| 664 |
for autodir in shlex.split(autodirstr): |
| 665 |
|
| 666 |
|
| 667 |
autodir = Template(autodir).safe_substitute(CFGDIR=cfg_dirname) |
| 668 |
autodir = os.path.normpath(autodir) |
| 669 |
if autodir in loaded_autodirs: |
| 670 |
continue |
| 671 |
loaded_autodirs.add(autodir) |
| 672 |
if not os.path.isdir(autodir): |
| 673 |
if not os.path.exists(autodir): |
| 674 |
continue |
| 675 |
raise GroupResolverConfigError("Defined autodir %s is not" |
| 676 |
" a directory" % autodir) |
| 677 |
|
| 678 |
for autosfn in sorted(glob.glob('%s/*.yaml' % autodir)): |
| 679 |
try: |
| 680 |
self._sources_from_yaml(autosfn) |
| 681 |
except IOError as exc: |
| 682 |
|
| 683 |
if exc.errno in (errno.EACCES, errno.EPERM): |
| 684 |
|
| 685 |
LOGGER.debug(exc) |
| 686 |
continue |
| 687 |
except (NoSectionError, NoOptionError): |
| 688 |
pass |
| 689 |
|
| 690 |
|
| 691 |
self._sources_from_cfg(self.config, cfg_dirname) |
| 692 |
|
| 693 |
|
| 694 |
try: |
| 695 |
def_sourcename = self.config.get('Main', 'default') |
| 696 |
|
| 697 |
self.default_source_name = def_sourcename |
| 698 |
except (NoSectionError, NoOptionError): |
| 699 |
pass |
| 700 |
except GroupResolverSourceError: |
| 701 |
if def_sourcename: |
| 702 |
fmt = 'Default group source not found: "%s"' |
| 703 |
raise GroupResolverConfigError(fmt % self.config.get('Main', |
| 704 |
'default')) |
| 705 |
|
| 706 |
if not self.default_source_name and self._sources: |
| 707 |
self.default_source_name = list(self._sources)[0] |
| 708 |
|
| 709 |
def _sources_from_cfg(self, cfg, cfgdir): |
| 710 |
""" |
| 711 |
Instantiate as many UpcallGroupSources needed from cfg object, |
| 712 |
cfgdir (CWD for callbacks) and cfg filename. |
| 713 |
""" |
| 714 |
try: |
| 715 |
for section in cfg.sections(): |
| 716 |
|
| 717 |
for srcname in section.split(','): |
| 718 |
if srcname != self.SECTION_MAIN: |
| 719 |
|
| 720 |
if not cfg.has_option(section, 'map') and \ |
| 721 |
not cfg.has_option(section, 'mapall'): |
| 722 |
raise GroupResolverConfigError( |
| 723 |
"No option 'map' or 'mapall' in section: %r" |
| 724 |
% section) |
| 725 |
|
| 726 |
map_upcall = mapall_upcall = None |
| 727 |
all_upcall = list_upcall = reverse_upcall = ctime = None |
| 728 |
if cfg.has_option(section, 'map'): |
| 729 |
map_upcall = cfg.get(section, 'map', raw=True) |
| 730 |
if cfg.has_option(section, 'mapall'): |
| 731 |
mapall_upcall = cfg.get(section, 'mapall', |
| 732 |
raw=True) |
| 733 |
if cfg.has_option(section, 'all'): |
| 734 |
all_upcall = cfg.get(section, 'all', raw=True) |
| 735 |
if cfg.has_option(section, 'list'): |
| 736 |
list_upcall = cfg.get(section, 'list', raw=True) |
| 737 |
if cfg.has_option(section, 'reverse'): |
| 738 |
reverse_upcall = cfg.get(section, 'reverse', |
| 739 |
raw=True) |
| 740 |
if cfg.has_option(section, 'cache_time'): |
| 741 |
ctime = float(cfg.get(section, 'cache_time', |
| 742 |
raw=True)) |
| 743 |
|
| 744 |
self.add_source(UpcallGroupSource( |
| 745 |
srcname, map_upcall, all_upcall, list_upcall, |
| 746 |
reverse_upcall, cfgdir, ctime, |
| 747 |
mapall_upcall=mapall_upcall)) |
| 748 |
except (NoSectionError, NoOptionError, ValueError) as exc: |
| 749 |
raise GroupResolverConfigError(str(exc)) |
| 750 |
|
| 751 |
def _sources_from_yaml(self, filepath): |
| 752 |
"""Load source(s) from YAML file.""" |
| 753 |
for source in YAMLGroupLoader(filepath): |
| 754 |
self.add_source(source) |