| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
|
| 22 |
""" |
| 23 |
Cluster node set module. |
| 24 |
|
| 25 |
A module to efficiently deal with node sets and node groups. |
| 26 |
Instances of NodeSet provide similar operations than the builtin set() type, |
| 27 |
see http://www.python.org/doc/lib/set-objects.html |
| 28 |
|
| 29 |
Usage example |
| 30 |
============= |
| 31 |
>>> # Import NodeSet class |
| 32 |
... from ClusterShell.NodeSet import NodeSet |
| 33 |
>>> |
| 34 |
>>> # Create a new nodeset from string |
| 35 |
... nodeset = NodeSet("cluster[1-30]") |
| 36 |
>>> # Add cluster32 to nodeset |
| 37 |
... nodeset.update("cluster32") |
| 38 |
>>> # Remove from nodeset |
| 39 |
... nodeset.difference_update("cluster[2-5,8-31]") |
| 40 |
>>> # Print nodeset as a pdsh-like pattern |
| 41 |
... print(nodeset) |
| 42 |
cluster[1,6-7,32] |
| 43 |
>>> # Iterate over node names in nodeset |
| 44 |
... for node in nodeset: |
| 45 |
... print(node) |
| 46 |
cluster1 |
| 47 |
cluster6 |
| 48 |
cluster7 |
| 49 |
cluster32 |
| 50 |
""" |
| 51 |
|
| 52 |
import fnmatch |
| 53 |
import re |
| 54 |
import string |
| 55 |
import sys |
| 56 |
|
| 57 |
from ClusterShell.Defaults import config_paths, DEFAULTS |
| 58 |
import ClusterShell.NodeUtils as NodeUtils |
| 59 |
|
| 60 |
|
| 61 |
from ClusterShell.RangeSet import RangeSet, RangeSetND, AUTOSTEP_DISABLED |
| 62 |
from ClusterShell.RangeSet import RangeSetParseError |
| 63 |
|
| 64 |
|
| 65 |
|
| 66 |
try: |
| 67 |
basestring |
| 68 |
except NameError: |
| 69 |
basestring = str |
| 70 |
|
| 71 |
|
| 72 |
DEF_GROUPS_CONFIGS = config_paths('groups.conf') |
| 73 |
ILLEGAL_GROUP_CHARS = set("@,!&^*") |
| 74 |
_DEF_RESOLVER_STD_GROUP = NodeUtils.GroupResolverConfig(DEF_GROUPS_CONFIGS, |
| 75 |
ILLEGAL_GROUP_CHARS) |
| 76 |
|
| 77 |
RESOLVER_STD_GROUP = _DEF_RESOLVER_STD_GROUP |
| 78 |
|
| 79 |
|
| 80 |
|
| 81 |
RESOLVER_NOGROUP = -1 |
| 82 |
RESOLVER_NOINIT = -2 |
| 83 |
|
| 84 |
STD_GROUP_RESOLVER = RESOLVER_STD_GROUP |
| 85 |
NOGROUP_RESOLVER = RESOLVER_NOGROUP |
| 86 |
|
| 87 |
|
| 88 |
class NodeSetException(Exception): |
| 89 |
"""Base NodeSet exception class.""" |
| 90 |
|
| 91 |
class NodeSetError(NodeSetException): |
| 92 |
"""Raised when an error is encountered.""" |
| 93 |
|
| 94 |
class NodeSetParseError(NodeSetError): |
| 95 |
"""Raised when NodeSet parsing cannot be done properly.""" |
| 96 |
def __init__(self, part, msg): |
| 97 |
if part: |
| 98 |
msg = "%s: \"%s\"" % (msg, part) |
| 99 |
NodeSetError.__init__(self, msg) |
| 100 |
|
| 101 |
self.part = part |
| 102 |
|
| 103 |
class NodeSetParseRangeError(NodeSetParseError): |
| 104 |
"""Raised when bad range is encountered during NodeSet parsing.""" |
| 105 |
def __init__(self, rset_exc): |
| 106 |
NodeSetParseError.__init__(self, str(rset_exc), "bad range") |
| 107 |
|
| 108 |
class NodeSetExternalError(NodeSetError): |
| 109 |
"""Raised when an external error is encountered.""" |
| 110 |
|
| 111 |
|
| 112 |
class NodeSetBase(object): |
| 113 |
""" |
| 114 |
Base class for NodeSet. |
| 115 |
|
| 116 |
This class allows node set base object creation from specified string |
| 117 |
pattern and rangeset object. If optional copy_rangeset boolean flag is |
| 118 |
set to True (default), provided rangeset object is copied (if needed), |
| 119 |
otherwise it may be referenced (should be seen as an ownership transfer |
| 120 |
upon creation). |
| 121 |
|
| 122 |
This class implements core node set arithmetic (no string parsing here). |
| 123 |
|
| 124 |
Example: |
| 125 |
>>> nsb = NodeSetBase('node%s-ipmi', RangeSet('1-5,7'), False) |
| 126 |
>>> str(nsb) |
| 127 |
'node[1-5,7]-ipmi' |
| 128 |
>>> nsb = NodeSetBase('node%s-ib%s', RangeSetND([['1-5,7', '1-2']]), False) |
| 129 |
>>> str(nsb) |
| 130 |
'node[1-5,7]-ib[1-2]' |
| 131 |
""" |
| 132 |
def __init__(self, pattern=None, rangeset=None, copy_rangeset=True, |
| 133 |
autostep=None, fold_axis=None): |
| 134 |
"""New NodeSetBase object initializer""" |
| 135 |
self._autostep = autostep |
| 136 |
self._length = 0 |
| 137 |
self._patterns = {} |
| 138 |
self.fold_axis = fold_axis |
| 139 |
if self.fold_axis is None and DEFAULTS.fold_axis: |
| 140 |
self.fold_axis = DEFAULTS.fold_axis |
| 141 |
if pattern: |
| 142 |
self._add(pattern, rangeset, copy_rangeset) |
| 143 |
elif rangeset: |
| 144 |
raise ValueError("missing pattern") |
| 145 |
|
| 146 |
def get_autostep(self): |
| 147 |
"""Get autostep value (property)""" |
| 148 |
return self._autostep |
| 149 |
|
| 150 |
def set_autostep(self, val): |
| 151 |
"""Set autostep value (property)""" |
| 152 |
if val is None: |
| 153 |
self._autostep = None |
| 154 |
else: |
| 155 |
|
| 156 |
self._autostep = min(int(val), AUTOSTEP_DISABLED) |
| 157 |
|
| 158 |
|
| 159 |
for pat, rset in self._patterns.items(): |
| 160 |
if rset: |
| 161 |
rset.autostep = self._autostep |
| 162 |
|
| 163 |
autostep = property(get_autostep, set_autostep) |
| 164 |
|
| 165 |
def _iter(self): |
| 166 |
"""Iterator on internal item tuples |
| 167 |
(pattern, indexes, autostep).""" |
| 168 |
for pat, rset in sorted(self._patterns.items()): |
| 169 |
if rset: |
| 170 |
autostep = rset.autostep |
| 171 |
if rset.dim() == 1: |
| 172 |
assert isinstance(rset, RangeSet) |
| 173 |
for idx in rset: |
| 174 |
yield pat, (idx,), autostep |
| 175 |
else: |
| 176 |
for rvec in rset: |
| 177 |
yield pat, rvec, autostep |
| 178 |
else: |
| 179 |
yield pat, None, None |
| 180 |
|
| 181 |
def _iterbase(self): |
| 182 |
"""Iterator on single, one-item NodeSetBase objects.""" |
| 183 |
for pat, ivec, autostep in self._iter(): |
| 184 |
rset = None |
| 185 |
if ivec is not None: |
| 186 |
assert len(ivec) > 0 |
| 187 |
if len(ivec) == 1: |
| 188 |
rset = RangeSet.fromone(ivec[0], autostep) |
| 189 |
else: |
| 190 |
rset = RangeSetND([ivec], autostep) |
| 191 |
yield NodeSetBase(pat, rset) |
| 192 |
|
| 193 |
def __iter__(self): |
| 194 |
"""Iterator on single nodes as string.""" |
| 195 |
|
| 196 |
for pat, ivec, _ in self._iter(): |
| 197 |
if ivec is not None: |
| 198 |
yield pat % ivec |
| 199 |
else: |
| 200 |
yield pat % () |
| 201 |
|
| 202 |
|
| 203 |
striter = __iter__ |
| 204 |
|
| 205 |
|
| 206 |
|
| 207 |
|
| 208 |
def nsiter(self): |
| 209 |
"""Object-based NodeSet iterator on single nodes.""" |
| 210 |
for pat, ivec, autostep in self._iter(): |
| 211 |
nodeset = self.__class__() |
| 212 |
if ivec is not None: |
| 213 |
if len(ivec) == 1: |
| 214 |
nodeset._add_new(pat, RangeSet.fromone(ivec[0])) |
| 215 |
else: |
| 216 |
nodeset._add_new(pat, RangeSetND([ivec], autostep)) |
| 217 |
else: |
| 218 |
nodeset._add_new(pat, None) |
| 219 |
yield nodeset |
| 220 |
|
| 221 |
def contiguous(self): |
| 222 |
"""Object-based NodeSet iterator on contiguous node sets. |
| 223 |
|
| 224 |
Contiguous node set contains nodes with same pattern name and a |
| 225 |
contiguous range of indexes, like foobar[1-100].""" |
| 226 |
for pat, rangeset in sorted(self._patterns.items()): |
| 227 |
if rangeset: |
| 228 |
for cont_rset in rangeset.contiguous(): |
| 229 |
nodeset = self.__class__() |
| 230 |
nodeset._add_new(pat, cont_rset) |
| 231 |
yield nodeset |
| 232 |
else: |
| 233 |
nodeset = self.__class__() |
| 234 |
nodeset._add_new(pat, None) |
| 235 |
yield nodeset |
| 236 |
|
| 237 |
def __len__(self): |
| 238 |
"""Get the number of nodes in NodeSet.""" |
| 239 |
cnt = 0 |
| 240 |
for rangeset in self._patterns.values(): |
| 241 |
if rangeset: |
| 242 |
cnt += len(rangeset) |
| 243 |
else: |
| 244 |
cnt += 1 |
| 245 |
return cnt |
| 246 |
|
| 247 |
def _iter_nd_pat(self, pat, rset): |
| 248 |
""" |
| 249 |
Take a pattern and a RangeSetND object and iterate over nD computed |
| 250 |
nodeset strings while following fold_axis constraints. |
| 251 |
""" |
| 252 |
try: |
| 253 |
dimcnt = rset.dim() |
| 254 |
if self.fold_axis is None: |
| 255 |
|
| 256 |
fold_axis = range(dimcnt) |
| 257 |
else: |
| 258 |
|
| 259 |
fold_axis = [int(x) % dimcnt for x in self.fold_axis |
| 260 |
if -dimcnt <= int(x) < dimcnt] |
| 261 |
except (TypeError, ValueError) as exc: |
| 262 |
raise NodeSetParseError("fold_axis=%s" % self.fold_axis, exc) |
| 263 |
|
| 264 |
for rgvec in rset.vectors(): |
| 265 |
rgnargs = [] |
| 266 |
for axis, rangeset in enumerate(rgvec): |
| 267 |
|
| 268 |
if len(rangeset) > 1: |
| 269 |
if axis not in fold_axis: |
| 270 |
rgstrit = rangeset.striter() |
| 271 |
else: |
| 272 |
rgstrit = ["[%s]" % rangeset] |
| 273 |
else: |
| 274 |
rgstrit = [str(rangeset)] |
| 275 |
|
| 276 |
|
| 277 |
t_rgnargs = [] |
| 278 |
for rgstr in rgstrit: |
| 279 |
if not rgnargs: |
| 280 |
t_rgnargs.append([rgstr]) |
| 281 |
else: |
| 282 |
for rga in rgnargs: |
| 283 |
t_rgnargs.append(rga + [rgstr]) |
| 284 |
rgnargs = t_rgnargs |
| 285 |
|
| 286 |
|
| 287 |
for rgargs in rgnargs: |
| 288 |
yield pat % tuple(rgargs) |
| 289 |
|
| 290 |
def __str__(self): |
| 291 |
"""Get ranges-based pattern of node list.""" |
| 292 |
results = [] |
| 293 |
try: |
| 294 |
for pat, rset in sorted(self._patterns.items()): |
| 295 |
if not rset: |
| 296 |
results.append(pat % ()) |
| 297 |
elif rset.dim() == 1: |
| 298 |
|
| 299 |
if self.fold_axis is None or \ |
| 300 |
list(x for x in self.fold_axis if -1 <= int(x) < 1): |
| 301 |
rgs = str(rset) |
| 302 |
cnt = len(rset) |
| 303 |
if cnt > 1: |
| 304 |
rgs = "[%s]" % rgs |
| 305 |
results.append(pat % rgs) |
| 306 |
else: |
| 307 |
results.extend((pat % rgs for rgs in rset.striter())) |
| 308 |
elif rset.dim() > 1: |
| 309 |
results.extend(self._iter_nd_pat(pat, rset)) |
| 310 |
except TypeError: |
| 311 |
raise NodeSetParseError(pat, "Internal error: node pattern and " |
| 312 |
"ranges mismatch") |
| 313 |
return ",".join(results) |
| 314 |
|
| 315 |
def copy(self): |
| 316 |
"""Return a shallow copy.""" |
| 317 |
cpy = self.__class__() |
| 318 |
cpy.fold_axis = self.fold_axis |
| 319 |
cpy._autostep = self._autostep |
| 320 |
cpy._length = self._length |
| 321 |
dic = {} |
| 322 |
for pat, rangeset in self._patterns.items(): |
| 323 |
if rangeset is None: |
| 324 |
dic[pat] = None |
| 325 |
else: |
| 326 |
dic[pat] = rangeset.copy() |
| 327 |
cpy._patterns = dic |
| 328 |
return cpy |
| 329 |
|
| 330 |
def __contains__(self, other): |
| 331 |
"""Is node contained in NodeSet ?""" |
| 332 |
return self.issuperset(other) |
| 333 |
|
| 334 |
def _binary_sanity_check(self, other): |
| 335 |
|
| 336 |
|
| 337 |
if not isinstance(other, NodeSetBase): |
| 338 |
raise TypeError("Binary operation only permitted between " |
| 339 |
"NodeSetBase") |
| 340 |
|
| 341 |
def issubset(self, other): |
| 342 |
"""Report whether another nodeset contains this nodeset.""" |
| 343 |
self._binary_sanity_check(other) |
| 344 |
return other.issuperset(self) |
| 345 |
|
| 346 |
def issuperset(self, other): |
| 347 |
"""Report whether this nodeset contains another nodeset.""" |
| 348 |
self._binary_sanity_check(other) |
| 349 |
status = True |
| 350 |
for pat, erangeset in other._patterns.items(): |
| 351 |
rangeset = self._patterns.get(pat) |
| 352 |
if rangeset: |
| 353 |
status = rangeset.issuperset(erangeset) |
| 354 |
else: |
| 355 |
|
| 356 |
status = pat in self._patterns |
| 357 |
if not status: |
| 358 |
break |
| 359 |
return status |
| 360 |
|
| 361 |
def __eq__(self, other): |
| 362 |
"""NodeSet equality comparison.""" |
| 363 |
|
| 364 |
if not isinstance(other, NodeSetBase): |
| 365 |
return NotImplemented |
| 366 |
return len(self) == len(other) and self.issuperset(other) |
| 367 |
|
| 368 |
|
| 369 |
__le__ = issubset |
| 370 |
__ge__ = issuperset |
| 371 |
|
| 372 |
def __lt__(self, other): |
| 373 |
"""x.__lt__(y) <==> x<y""" |
| 374 |
self._binary_sanity_check(other) |
| 375 |
return len(self) < len(other) and self.issubset(other) |
| 376 |
|
| 377 |
def __gt__(self, other): |
| 378 |
"""x.__gt__(y) <==> x>y""" |
| 379 |
self._binary_sanity_check(other) |
| 380 |
return len(self) > len(other) and self.issuperset(other) |
| 381 |
|
| 382 |
def _extractslice(self, index): |
| 383 |
"""Private utility function: extract slice parameters from slice object |
| 384 |
`index` for an list-like object of size `length`.""" |
| 385 |
length = len(self) |
| 386 |
if index.start is None: |
| 387 |
sl_start = 0 |
| 388 |
elif index.start < 0: |
| 389 |
sl_start = max(0, length + index.start) |
| 390 |
else: |
| 391 |
sl_start = index.start |
| 392 |
if index.stop is None: |
| 393 |
sl_stop = sys.maxsize |
| 394 |
elif index.stop < 0: |
| 395 |
sl_stop = max(0, length + index.stop) |
| 396 |
else: |
| 397 |
sl_stop = index.stop |
| 398 |
if index.step is None: |
| 399 |
sl_step = 1 |
| 400 |
elif index.step < 0: |
| 401 |
|
| 402 |
if index.start is not None or index.stop is not None: |
| 403 |
raise IndexError("illegal start and stop when negative step " |
| 404 |
"is used") |
| 405 |
|
| 406 |
|
| 407 |
stepmod = (length + -index.step - 1) % -index.step |
| 408 |
if stepmod > 0: |
| 409 |
sl_start += stepmod |
| 410 |
sl_step = -index.step |
| 411 |
else: |
| 412 |
sl_step = index.step |
| 413 |
if not isinstance(sl_start, int) or not isinstance(sl_stop, int) \ |
| 414 |
or not isinstance(sl_step, int): |
| 415 |
raise TypeError("slice indices must be integers") |
| 416 |
return sl_start, sl_stop, sl_step |
| 417 |
|
| 418 |
def __getitem__(self, index): |
| 419 |
"""Return the node at specified index or a subnodeset when a slice is |
| 420 |
specified.""" |
| 421 |
if isinstance(index, slice): |
| 422 |
inst = NodeSetBase() |
| 423 |
sl_start, sl_stop, sl_step = self._extractslice(index) |
| 424 |
sl_next = sl_start |
| 425 |
if sl_stop <= sl_next: |
| 426 |
return inst |
| 427 |
length = 0 |
| 428 |
for pat, rangeset in sorted(self._patterns.items()): |
| 429 |
if rangeset: |
| 430 |
cnt = len(rangeset) |
| 431 |
offset = sl_next - length |
| 432 |
if offset < cnt: |
| 433 |
num = min(sl_stop - sl_next, cnt - offset) |
| 434 |
inst._add(pat, rangeset[offset:offset + num:sl_step]) |
| 435 |
else: |
| 436 |
|
| 437 |
length += cnt |
| 438 |
continue |
| 439 |
else: |
| 440 |
cnt = num = 1 |
| 441 |
if sl_next > length: |
| 442 |
length += cnt |
| 443 |
continue |
| 444 |
inst._add(pat, None) |
| 445 |
|
| 446 |
sl_next += num |
| 447 |
if (sl_next - sl_start) % sl_step: |
| 448 |
sl_next = sl_start + \ |
| 449 |
((sl_next - sl_start)//sl_step + 1) * sl_step |
| 450 |
if sl_next >= sl_stop: |
| 451 |
break |
| 452 |
length += cnt |
| 453 |
return inst |
| 454 |
elif isinstance(index, int): |
| 455 |
if index < 0: |
| 456 |
length = len(self) |
| 457 |
if index >= -length: |
| 458 |
index = length + index |
| 459 |
else: |
| 460 |
raise IndexError("%d out of range" % index) |
| 461 |
length = 0 |
| 462 |
for pat, rangeset in sorted(self._patterns.items()): |
| 463 |
if rangeset: |
| 464 |
cnt = len(rangeset) |
| 465 |
if index < length + cnt: |
| 466 |
|
| 467 |
if rangeset.dim() == 1: |
| 468 |
return pat % rangeset[index-length:index-length+1] |
| 469 |
else: |
| 470 |
sub = rangeset[index-length:index-length+1] |
| 471 |
for rgvec in sub.vectors(): |
| 472 |
return pat % (tuple(rgvec)) |
| 473 |
else: |
| 474 |
cnt = 1 |
| 475 |
if index == length: |
| 476 |
return pat |
| 477 |
length += cnt |
| 478 |
raise IndexError("%d out of range" % index) |
| 479 |
else: |
| 480 |
raise TypeError("NodeSet indices must be integers") |
| 481 |
|
| 482 |
def _rangeset_index(self, rangeset, orangeset): |
| 483 |
"""Return the position of the single index held by `orangeset` |
| 484 |
within `rangeset`, following the same order as iteration, or None |
| 485 |
if the index is not contained in `rangeset`. |
| 486 |
|
| 487 |
Both arguments are the RangeSet/RangeSetND/None objects respectively |
| 488 |
associated to the same pattern in this nodeset and in the searched |
| 489 |
single node. |
| 490 |
""" |
| 491 |
|
| 492 |
if rangeset is None or orangeset is None: |
| 493 |
return 0 if rangeset is None and orangeset is None else None |
| 494 |
|
| 495 |
try: |
| 496 |
if isinstance(orangeset, RangeSetND): |
| 497 |
|
| 498 |
return rangeset.index(next(iter(orangeset))) |
| 499 |
|
| 500 |
return rangeset.index(next(orangeset.striter())) |
| 501 |
except ValueError: |
| 502 |
return None |
| 503 |
|
| 504 |
def index(self, other, start=0, stop=None): |
| 505 |
"""Return the zero-based index in the nodeset of the node `other`. |
| 506 |
|
| 507 |
This behaves like the ``index()`` method of the ``list`` type: it |
| 508 |
returns the position of the node when iterating over the nodeset and |
| 509 |
raises a :class:`ValueError` if the node is not present. The optional |
| 510 |
`start` and `stop` arguments restrict the search to the matching |
| 511 |
subsequence, and may be negative (counted from the end). |
| 512 |
|
| 513 |
Unlike a naive linear search, this implementation does not expand the |
| 514 |
whole nodeset: it only sums the size of the patterns that precede the |
| 515 |
searched node and locates it within its own pattern. |
| 516 |
|
| 517 |
Example: |
| 518 |
>>> NodeSetBase('node%s', RangeSet('0-9,20')).index( |
| 519 |
... NodeSetBase('node%s', RangeSet('20'))) |
| 520 |
10 |
| 521 |
""" |
| 522 |
self._binary_sanity_check(other) |
| 523 |
if len(other) != 1: |
| 524 |
raise ValueError("index() argument must be a single node") |
| 525 |
|
| 526 |
|
| 527 |
opat, orangeset = list(other._patterns.items())[0] |
| 528 |
|
| 529 |
|
| 530 |
|
| 531 |
found = None |
| 532 |
base = 0 |
| 533 |
for pat, rangeset in sorted(self._patterns.items()): |
| 534 |
if pat == opat: |
| 535 |
offset = self._rangeset_index(rangeset, orangeset) |
| 536 |
if offset is not None: |
| 537 |
found = base + offset |
| 538 |
break |
| 539 |
if rangeset: |
| 540 |
base += len(rangeset) |
| 541 |
else: |
| 542 |
base += 1 |
| 543 |
|
| 544 |
if found is None: |
| 545 |
raise ValueError("'%s' is not in nodeset" % other) |
| 546 |
|
| 547 |
|
| 548 |
if start != 0 or stop is not None: |
| 549 |
length = len(self) |
| 550 |
if start < 0: |
| 551 |
start = max(0, length + start) |
| 552 |
if stop is None: |
| 553 |
stop = length |
| 554 |
elif stop < 0: |
| 555 |
stop = max(0, length + stop) |
| 556 |
if not start <= found < stop: |
| 557 |
raise ValueError("'%s' is not in nodeset" % other) |
| 558 |
|
| 559 |
return found |
| 560 |
|
| 561 |
def _add_new(self, pat, rangeset): |
| 562 |
"""Add nodes from a (pat, rangeset) tuple. |
| 563 |
Predicate: pattern does not exist in current set. RangeSet object is |
| 564 |
referenced (not copied).""" |
| 565 |
assert pat not in self._patterns |
| 566 |
self._patterns[pat] = rangeset |
| 567 |
|
| 568 |
def _add(self, pat, rangeset, copy_rangeset=True): |
| 569 |
"""Add nodes from a (pat, rangeset) tuple. |
| 570 |
`pat' may be an existing pattern and `rangeset' may be None. |
| 571 |
RangeSet or RangeSetND objects are copied if re-used internally |
| 572 |
when provided and if copy_rangeset flag is set. |
| 573 |
""" |
| 574 |
if pat in self._patterns: |
| 575 |
|
| 576 |
pat_e = self._patterns[pat] |
| 577 |
|
| 578 |
if (pat_e is None) is not (rangeset is None): |
| 579 |
raise NodeSetError("Invalid operation") |
| 580 |
|
| 581 |
if pat_e: |
| 582 |
pat_e.update(rangeset) |
| 583 |
else: |
| 584 |
|
| 585 |
if rangeset and copy_rangeset: |
| 586 |
|
| 587 |
rangeset = rangeset.copy() |
| 588 |
|
| 589 |
if self._autostep is not None: |
| 590 |
|
| 591 |
rangeset.autostep = self._autostep |
| 592 |
self._add_new(pat, rangeset) |
| 593 |
|
| 594 |
def union(self, other): |
| 595 |
""" |
| 596 |
s.union(t) returns a new set with elements from both s and t. |
| 597 |
""" |
| 598 |
self_copy = self.copy() |
| 599 |
self_copy.update(other) |
| 600 |
return self_copy |
| 601 |
|
| 602 |
def __or__(self, other): |
| 603 |
""" |
| 604 |
Implements the | operator. So s | t returns a new nodeset with |
| 605 |
elements from both s and t. |
| 606 |
""" |
| 607 |
if not isinstance(other, NodeSetBase): |
| 608 |
return NotImplemented |
| 609 |
return self.union(other) |
| 610 |
|
| 611 |
def add(self, other): |
| 612 |
""" |
| 613 |
Add node to NodeSet. |
| 614 |
""" |
| 615 |
self.update(other) |
| 616 |
|
| 617 |
def update(self, other): |
| 618 |
""" |
| 619 |
s.update(t) updates nodeset s with elements added from t. |
| 620 |
""" |
| 621 |
for pat, rangeset in other._patterns.items(): |
| 622 |
self._add(pat, rangeset) |
| 623 |
|
| 624 |
def updaten(self, others): |
| 625 |
""" |
| 626 |
s.updaten(list) updates nodeset s with elements added from given list. |
| 627 |
""" |
| 628 |
for other in others: |
| 629 |
self.update(other) |
| 630 |
|
| 631 |
def clear(self): |
| 632 |
""" |
| 633 |
Remove all nodes from this nodeset. |
| 634 |
""" |
| 635 |
self._patterns.clear() |
| 636 |
|
| 637 |
def __ior__(self, other): |
| 638 |
""" |
| 639 |
Implements the ``|=`` operator. So ``s |= t`` returns nodeset s |
| 640 |
with elements added from t. (Python version 2.5+ required) |
| 641 |
""" |
| 642 |
self._binary_sanity_check(other) |
| 643 |
self.update(other) |
| 644 |
return self |
| 645 |
|
| 646 |
def intersection(self, other): |
| 647 |
""" |
| 648 |
s.intersection(t) returns a new set with elements common to s |
| 649 |
and t. |
| 650 |
""" |
| 651 |
self_copy = self.copy() |
| 652 |
self_copy.intersection_update(other) |
| 653 |
return self_copy |
| 654 |
|
| 655 |
def __and__(self, other): |
| 656 |
""" |
| 657 |
Implements the & operator. So ``s & t`` returns a new nodeset with |
| 658 |
elements common to s and t. |
| 659 |
""" |
| 660 |
if not isinstance(other, NodeSet): |
| 661 |
return NotImplemented |
| 662 |
return self.intersection(other) |
| 663 |
|
| 664 |
def intersection_update(self, other): |
| 665 |
""" |
| 666 |
``s.intersection_update(t)`` updates nodeset s keeping only |
| 667 |
elements also found in t. |
| 668 |
""" |
| 669 |
if other is self: |
| 670 |
return |
| 671 |
|
| 672 |
tmp_ns = NodeSetBase() |
| 673 |
|
| 674 |
for pat, irangeset in other._patterns.items(): |
| 675 |
rangeset = self._patterns.get(pat) |
| 676 |
if rangeset: |
| 677 |
irset = rangeset.intersection(irangeset) |
| 678 |
|
| 679 |
if len(irset) > 0: |
| 680 |
tmp_ns._add(pat, irset, copy_rangeset=False) |
| 681 |
elif not irangeset and pat in self._patterns: |
| 682 |
|
| 683 |
tmp_ns._add(pat, None) |
| 684 |
|
| 685 |
|
| 686 |
self._patterns = tmp_ns._patterns |
| 687 |
|
| 688 |
def __iand__(self, other): |
| 689 |
""" |
| 690 |
Implements the &= operator. So ``s &= t`` returns nodeset s keeping |
| 691 |
only elements also found in t. (Python version 2.5+ required) |
| 692 |
""" |
| 693 |
self._binary_sanity_check(other) |
| 694 |
self.intersection_update(other) |
| 695 |
return self |
| 696 |
|
| 697 |
def difference(self, other): |
| 698 |
""" |
| 699 |
``s.difference(t)`` returns a new NodeSet with elements in s but not |
| 700 |
in t. |
| 701 |
""" |
| 702 |
self_copy = self.copy() |
| 703 |
self_copy.difference_update(other) |
| 704 |
return self_copy |
| 705 |
|
| 706 |
def __sub__(self, other): |
| 707 |
""" |
| 708 |
Implement the - operator. So ``s - t`` returns a new nodeset with |
| 709 |
elements in s but not in t. |
| 710 |
""" |
| 711 |
if not isinstance(other, NodeSetBase): |
| 712 |
return NotImplemented |
| 713 |
return self.difference(other) |
| 714 |
|
| 715 |
def difference_update(self, other, strict=False): |
| 716 |
""" |
| 717 |
``s.difference_update(t)`` removes from s all the elements found in t. |
| 718 |
|
| 719 |
:raises KeyError: an element cannot be removed (only if strict is |
| 720 |
True) |
| 721 |
""" |
| 722 |
|
| 723 |
purge_patterns = [] |
| 724 |
|
| 725 |
|
| 726 |
for pat, erangeset in other._patterns.items(): |
| 727 |
|
| 728 |
rangeset = self._patterns.get(pat) |
| 729 |
if rangeset: |
| 730 |
|
| 731 |
rangeset.difference_update(erangeset, strict) |
| 732 |
|
| 733 |
|
| 734 |
if len(rangeset) == 0: |
| 735 |
purge_patterns.append(pat) |
| 736 |
else: |
| 737 |
|
| 738 |
if pat in self._patterns: |
| 739 |
purge_patterns.append(pat) |
| 740 |
elif strict: |
| 741 |
raise KeyError(pat) |
| 742 |
|
| 743 |
for pat in purge_patterns: |
| 744 |
del self._patterns[pat] |
| 745 |
|
| 746 |
def __isub__(self, other): |
| 747 |
""" |
| 748 |
Implement the -= operator. So ``s -= t`` returns nodeset s after |
| 749 |
removing elements found in t. (Python version 2.5+ required) |
| 750 |
""" |
| 751 |
self._binary_sanity_check(other) |
| 752 |
self.difference_update(other) |
| 753 |
return self |
| 754 |
|
| 755 |
def remove(self, elem): |
| 756 |
""" |
| 757 |
Remove element elem from the nodeset. Raise KeyError if elem |
| 758 |
is not contained in the nodeset. |
| 759 |
|
| 760 |
:raises KeyError: elem is not contained in the nodeset |
| 761 |
""" |
| 762 |
self.difference_update(elem, True) |
| 763 |
|
| 764 |
def symmetric_difference(self, other): |
| 765 |
""" |
| 766 |
``s.symmetric_difference(t)`` returns the symmetric difference of |
| 767 |
two nodesets as a new NodeSet. |
| 768 |
|
| 769 |
(ie. all nodes that are in exactly one of the nodesets.) |
| 770 |
""" |
| 771 |
self_copy = self.copy() |
| 772 |
self_copy.symmetric_difference_update(other) |
| 773 |
return self_copy |
| 774 |
|
| 775 |
def __xor__(self, other): |
| 776 |
""" |
| 777 |
Implement the ^ operator. So ``s ^ t`` returns a new NodeSet with |
| 778 |
nodes that are in exactly one of the nodesets. |
| 779 |
""" |
| 780 |
if not isinstance(other, NodeSet): |
| 781 |
return NotImplemented |
| 782 |
return self.symmetric_difference(other) |
| 783 |
|
| 784 |
def symmetric_difference_update(self, other): |
| 785 |
""" |
| 786 |
``s.symmetric_difference_update(t)`` updates nodeset s keeping all |
| 787 |
nodes that are in exactly one of the nodesets. |
| 788 |
""" |
| 789 |
purge_patterns = [] |
| 790 |
|
| 791 |
|
| 792 |
for pat, rangeset in self._patterns.items(): |
| 793 |
brangeset = other._patterns.get(pat) |
| 794 |
if brangeset: |
| 795 |
rangeset.symmetric_difference_update(brangeset) |
| 796 |
else: |
| 797 |
if pat in other._patterns: |
| 798 |
purge_patterns.append(pat) |
| 799 |
|
| 800 |
|
| 801 |
for pat, brangeset in other._patterns.items(): |
| 802 |
rangeset = self._patterns.get(pat) |
| 803 |
if not rangeset and not pat in self._patterns: |
| 804 |
self._add(pat, brangeset) |
| 805 |
|
| 806 |
|
| 807 |
for pat, rangeset in self._patterns.items(): |
| 808 |
if rangeset is not None and len(rangeset) == 0: |
| 809 |
purge_patterns.append(pat) |
| 810 |
|
| 811 |
|
| 812 |
for pat in purge_patterns: |
| 813 |
del self._patterns[pat] |
| 814 |
|
| 815 |
def __ixor__(self, other): |
| 816 |
""" |
| 817 |
Implement the ^= operator. So ``s ^= t`` returns nodeset s after |
| 818 |
keeping all nodes that are in exactly one of the nodesets. |
| 819 |
(Python version 2.5+ required) |
| 820 |
""" |
| 821 |
self._binary_sanity_check(other) |
| 822 |
self.symmetric_difference_update(other) |
| 823 |
return self |
| 824 |
|
| 825 |
|
| 826 |
def _strip_escape(nsstr): |
| 827 |
""" |
| 828 |
Helper to prepare a nodeset string for parsing: trim boundary |
| 829 |
whitespaces and escape special characters. |
| 830 |
""" |
| 831 |
return nsstr.strip().replace('%', '%%') |
| 832 |
|
| 833 |
def _rsets4nsb(rsets, autostep): |
| 834 |
""" |
| 835 |
Helper to convert a list of RangeSet objects into the proper object |
| 836 |
for NodeSetBase: RangeSet, RangeSetND or None (no node index). |
| 837 |
""" |
| 838 |
if len(rsets) > 1: |
| 839 |
return RangeSetND([rsets], None, autostep, copy_rangeset=False) |
| 840 |
elif len(rsets) == 1: |
| 841 |
return rsets[0] |
| 842 |
|
| 843 |
|
| 844 |
class ParsingEngine(object): |
| 845 |
""" |
| 846 |
Class that is able to transform a source into a NodeSetBase. |
| 847 |
""" |
| 848 |
|
| 849 |
OP_CODES = {',': 'update', |
| 850 |
'!': 'difference_update', |
| 851 |
'&': 'intersection_update', |
| 852 |
'^': 'symmetric_difference_update'} |
| 853 |
|
| 854 |
OP_CODES_PAT = '[%s]' % re.escape(''.join(OP_CODES.keys())) |
| 855 |
|
| 856 |
BRACKET_OPEN = '[' |
| 857 |
BRACKET_CLOSE = ']' |
| 858 |
|
| 859 |
def __init__(self, group_resolver, node_wildcard_enable=True): |
| 860 |
""" |
| 861 |
Initialize Parsing Engine. |
| 862 |
""" |
| 863 |
self.group_resolver = group_resolver |
| 864 |
self.base_node_re = re.compile(r"(\D*)(\d*)") |
| 865 |
self.node_wc = node_wildcard_enable |
| 866 |
|
| 867 |
def parse(self, nsobj, autostep): |
| 868 |
""" |
| 869 |
Parse provided object if possible and return a NodeSetBase object. |
| 870 |
""" |
| 871 |
|
| 872 |
if nsobj is None: |
| 873 |
return NodeSetBase() |
| 874 |
|
| 875 |
|
| 876 |
if isinstance(nsobj, NodeSetBase): |
| 877 |
return nsobj |
| 878 |
|
| 879 |
|
| 880 |
if isinstance(nsobj, basestring): |
| 881 |
try: |
| 882 |
return self.parse_string(str(nsobj), autostep) |
| 883 |
except (NodeUtils.GroupSourceQueryFailed, RuntimeError) as exc: |
| 884 |
raise NodeSetParseError(nsobj, str(exc)) |
| 885 |
|
| 886 |
raise TypeError("Unsupported NodeSet input %s" % type(nsobj)) |
| 887 |
|
| 888 |
def parse_string(self, nsstr, autostep, namespace=None): |
| 889 |
"""Parse provided string in optional namespace. |
| 890 |
|
| 891 |
This method parses string, resolves all node groups, and |
| 892 |
computes set operations. |
| 893 |
|
| 894 |
Return a NodeSetBase object. |
| 895 |
""" |
| 896 |
alln_cache = None |
| 897 |
nodeset = NodeSetBase() |
| 898 |
nsstr = _strip_escape(nsstr) |
| 899 |
|
| 900 |
for opc, pat, rgnd in self._scan_string(nsstr, autostep): |
| 901 |
|
| 902 |
|
| 903 |
if self.group_resolver and pat[0] == '@': |
| 904 |
ns_group = NodeSetBase() |
| 905 |
for nodegroup in NodeSetBase(pat, rgnd): |
| 906 |
|
| 907 |
ns_str_ext, ns_nsp_ext = self.parse_group_string(nodegroup, |
| 908 |
namespace) |
| 909 |
if ns_str_ext: |
| 910 |
|
| 911 |
ns_group.update(self.parse_string(ns_str_ext, |
| 912 |
autostep, |
| 913 |
ns_nsp_ext)) |
| 914 |
|
| 915 |
getattr(nodeset, opc)(ns_group) |
| 916 |
|
| 917 |
elif self.group_resolver and self.node_wc and ('*' in pat or |
| 918 |
'?' in pat): |
| 919 |
|
| 920 |
|
| 921 |
wcmasks = (str(wcn) for wcn in NodeSetBase(pat, rgnd, False)) |
| 922 |
|
| 923 |
|
| 924 |
|
| 925 |
if alln_cache is None: |
| 926 |
self.node_wc = False |
| 927 |
try: |
| 928 |
nsb = NodeSetBase() |
| 929 |
for res in self.all_nodes(namespace): |
| 930 |
nsb.update(self.parse_string(res, autostep, |
| 931 |
namespace)) |
| 932 |
alln_cache = set(str(node) for node in nsb) |
| 933 |
finally: |
| 934 |
self.node_wc = True |
| 935 |
|
| 936 |
alln = alln_cache.copy() |
| 937 |
|
| 938 |
|
| 939 |
|
| 940 |
|
| 941 |
|
| 942 |
wcns = NodeSetBase() |
| 943 |
for wcmask in wcmasks: |
| 944 |
|
| 945 |
for node in fnmatch.filter(alln, wcmask): |
| 946 |
alln.remove(node) |
| 947 |
wcp, wcr = self._scan_string_single(node, autostep) |
| 948 |
wcrgnd = _rsets4nsb(wcr, autostep) |
| 949 |
wcns.update(NodeSetBase(wcp, wcrgnd, False)) |
| 950 |
getattr(nodeset, opc)(wcns) |
| 951 |
|
| 952 |
else: |
| 953 |
getattr(nodeset, opc)(NodeSetBase(pat, rgnd, False)) |
| 954 |
|
| 955 |
return nodeset |
| 956 |
|
| 957 |
def parse_string_single(self, nsstr, autostep): |
| 958 |
"""Parse provided string and return a NodeSetBase object.""" |
| 959 |
pat, rangesets = self._scan_string_single(_strip_escape(nsstr), |
| 960 |
autostep) |
| 961 |
if len(rangesets) > 1: |
| 962 |
rgobj = RangeSetND([rangesets], None, autostep, copy_rangeset=False) |
| 963 |
elif len(rangesets) == 1: |
| 964 |
rgobj = rangesets[0] |
| 965 |
else: |
| 966 |
rgobj = None |
| 967 |
return NodeSetBase(pat, rgobj, False) |
| 968 |
|
| 969 |
def parse_group(self, group, namespace=None, autostep=None): |
| 970 |
"""Parse provided single group name (without @ prefix).""" |
| 971 |
assert self.group_resolver is not None |
| 972 |
nodestr = self.group_resolver.group_nodes(group, namespace) |
| 973 |
return self.parse(",".join(nodestr), autostep) |
| 974 |
|
| 975 |
def parse_group_string(self, nodegroup, namespace=None): |
| 976 |
"""Parse provided raw nodegroup string in optional namespace. |
| 977 |
|
| 978 |
Warning: 1 pass only, may still return groups. |
| 979 |
|
| 980 |
Return a tuple (grp_resolved_string, namespace). |
| 981 |
""" |
| 982 |
assert nodegroup[0] == '@' |
| 983 |
assert self.group_resolver is not None |
| 984 |
grpstr = group = nodegroup[1:] |
| 985 |
if grpstr.find(':') >= 0: |
| 986 |
|
| 987 |
namespace, group = grpstr.split(':', 1) |
| 988 |
if group == '*': |
| 989 |
reslist = self.all_nodes(namespace) |
| 990 |
elif group.startswith('@'): |
| 991 |
reslist = self.grouplist(grpstr[1:]) |
| 992 |
else: |
| 993 |
reslist = self.group_resolver.group_nodes(group, namespace) |
| 994 |
return ','.join(reslist), namespace |
| 995 |
|
| 996 |
def grouplist(self, namespace=None): |
| 997 |
""" |
| 998 |
Return a sorted list of groups from current resolver (in optional |
| 999 |
group source / namespace). |
| 1000 |
""" |
| 1001 |
grpset = NodeSetBase() |
| 1002 |
for grpstr in self.group_resolver.grouplist(namespace): |
| 1003 |
|
| 1004 |
grpstr = _strip_escape(grpstr) |
| 1005 |
for opc, pat, rgnd in self._scan_string(grpstr, None): |
| 1006 |
getattr(grpset, opc)(NodeSetBase(pat, rgnd, False)) |
| 1007 |
return list(grpset) |
| 1008 |
|
| 1009 |
def all_nodes(self, namespace=None): |
| 1010 |
"""Get all nodes from group resolver as a list of strings.""" |
| 1011 |
|
| 1012 |
assert self.group_resolver is not None |
| 1013 |
alln = [] |
| 1014 |
try: |
| 1015 |
|
| 1016 |
alln = self.group_resolver.all_nodes(namespace) |
| 1017 |
except NodeUtils.GroupSourceNoUpcall: |
| 1018 |
try: |
| 1019 |
|
| 1020 |
|
| 1021 |
for grp in self.grouplist(namespace): |
| 1022 |
alln += self.group_resolver.group_nodes(grp, namespace) |
| 1023 |
except NodeUtils.GroupSourceNoUpcall: |
| 1024 |
|
| 1025 |
msg = "Not enough working methods (all or map + list) to " \ |
| 1026 |
"get all nodes" |
| 1027 |
raise NodeSetExternalError(msg) |
| 1028 |
except NodeUtils.GroupSourceQueryFailed as exc: |
| 1029 |
raise NodeSetExternalError("Failed to get all nodes: %s" % exc) |
| 1030 |
return alln |
| 1031 |
|
| 1032 |
def _next_op(self, pat): |
| 1033 |
"""Opcode parsing subroutine.""" |
| 1034 |
mobj = re.search(ParsingEngine.OP_CODES_PAT, pat) |
| 1035 |
if mobj: |
| 1036 |
return mobj.span()[0], mobj.group() |
| 1037 |
else: |
| 1038 |
return -1, None |
| 1039 |
|
| 1040 |
def _scan_string_single(self, nsstr, autostep): |
| 1041 |
"""Single node scan, returns (pat, list of rangesets)""" |
| 1042 |
|
| 1043 |
pfx_nd = [mobj.groups() for mobj in self.base_node_re.finditer(nsstr)] |
| 1044 |
pfx_nd = pfx_nd[:-1] |
| 1045 |
if not pfx_nd: |
| 1046 |
raise NodeSetParseError(nsstr, "parse error") |
| 1047 |
|
| 1048 |
pat = "" |
| 1049 |
rangesets = [] |
| 1050 |
for pfx, idx in pfx_nd: |
| 1051 |
if idx: |
| 1052 |
|
| 1053 |
pad = 0 |
| 1054 |
if int(idx) != 0: |
| 1055 |
idxs = idx.lstrip("0") |
| 1056 |
if len(idx) - len(idxs) > 0: |
| 1057 |
pad = len(idx) |
| 1058 |
idxint = int(idxs) |
| 1059 |
else: |
| 1060 |
if len(idx) > 1: |
| 1061 |
pad = len(idx) |
| 1062 |
idxint = 0 |
| 1063 |
if idxint > 1e100: |
| 1064 |
raise NodeSetParseRangeError( \ |
| 1065 |
RangeSetParseError(idx, "invalid rangeset index")) |
| 1066 |
|
| 1067 |
pat += "%s%%s" % pfx |
| 1068 |
rangesets.append(RangeSet.fromone(idxint, pad, autostep)) |
| 1069 |
else: |
| 1070 |
|
| 1071 |
pat += pfx |
| 1072 |
return pat, rangesets |
| 1073 |
|
| 1074 |
def _scan_string(self, nsstr, autostep): |
| 1075 |
"""Parsing engine's string scanner method (iterator).""" |
| 1076 |
next_op_code = ',' |
| 1077 |
while nsstr: |
| 1078 |
|
| 1079 |
nsstr = nsstr.lstrip() |
| 1080 |
|
| 1081 |
rsets = [] |
| 1082 |
op_code = next_op_code |
| 1083 |
|
| 1084 |
op_idx, next_op_code = self._next_op(nsstr) |
| 1085 |
bracket_idx = nsstr.find(self.BRACKET_OPEN) |
| 1086 |
|
| 1087 |
|
| 1088 |
|
| 1089 |
if bracket_idx >= 0 and (op_idx > bracket_idx or op_idx < 0): |
| 1090 |
|
| 1091 |
|
| 1092 |
|
| 1093 |
|
| 1094 |
newpat = "" |
| 1095 |
sfx = nsstr |
| 1096 |
while bracket_idx >= 0 and (op_idx > bracket_idx or op_idx < 0): |
| 1097 |
pfx, sfx = sfx.split(self.BRACKET_OPEN, 1) |
| 1098 |
try: |
| 1099 |
rng, sfx = sfx.split(self.BRACKET_CLOSE, 1) |
| 1100 |
except ValueError: |
| 1101 |
raise NodeSetParseError(nsstr, "missing bracket") |
| 1102 |
|
| 1103 |
|
| 1104 |
if pfx.find(self.BRACKET_CLOSE) > -1: |
| 1105 |
raise NodeSetParseError(pfx, "illegal closing bracket") |
| 1106 |
|
| 1107 |
if len(sfx) > 0: |
| 1108 |
bra_end = sfx.find(self.BRACKET_CLOSE) |
| 1109 |
bra_start = sfx.find(self.BRACKET_OPEN) |
| 1110 |
if bra_start == -1: |
| 1111 |
bra_start = bra_end + 1 |
| 1112 |
if bra_end >= 0 and bra_end < bra_start: |
| 1113 |
msg = "illegal closing bracket" |
| 1114 |
raise NodeSetParseError(sfx, msg) |
| 1115 |
|
| 1116 |
pfxlen, sfxlen = len(pfx), len(sfx) |
| 1117 |
|
| 1118 |
if sfxlen > 0: |
| 1119 |
try: |
| 1120 |
|
| 1121 |
sfx, rng = self._amend_trailing_digits(sfx, rng) |
| 1122 |
except RangeSetParseError as ex: |
| 1123 |
raise NodeSetParseRangeError(ex) |
| 1124 |
|
| 1125 |
if pfxlen > 0: |
| 1126 |
try: |
| 1127 |
|
| 1128 |
pfx, rng = self._amend_leading_digits(pfx, rng) |
| 1129 |
except RangeSetParseError as ex: |
| 1130 |
raise NodeSetParseRangeError(ex) |
| 1131 |
if pfx: |
| 1132 |
|
| 1133 |
pfx, pfxrvec = self._scan_string_single(pfx, autostep) |
| 1134 |
rsets += pfxrvec |
| 1135 |
|
| 1136 |
|
| 1137 |
bracket_idx = sfx.find(self.BRACKET_OPEN, |
| 1138 |
bracket_idx - pfxlen) |
| 1139 |
op_idx, next_op_code = self._next_op(sfx) |
| 1140 |
|
| 1141 |
if len(sfx) > 0 and sfx[0] == '[': |
| 1142 |
msg = "illegal reopening bracket" |
| 1143 |
raise NodeSetParseError(sfx, msg) |
| 1144 |
|
| 1145 |
newpat += "%s%%s" % pfx |
| 1146 |
try: |
| 1147 |
rsets.append(RangeSet(rng, autostep)) |
| 1148 |
except RangeSetParseError as ex: |
| 1149 |
raise NodeSetParseRangeError(ex) |
| 1150 |
|
| 1151 |
|
| 1152 |
op_idx, next_op_code = self._next_op(sfx) |
| 1153 |
if op_idx < 0: |
| 1154 |
nsstr = None |
| 1155 |
else: |
| 1156 |
sfx, nsstr = sfx.split(next_op_code, 1) |
| 1157 |
|
| 1158 |
if not nsstr: |
| 1159 |
msg = "missing nodeset operand with '%s' " \ |
| 1160 |
"operator" % next_op_code |
| 1161 |
raise NodeSetParseError(None, msg) |
| 1162 |
|
| 1163 |
|
| 1164 |
sfx = sfx.rstrip() |
| 1165 |
if sfx: |
| 1166 |
sfx, sfxrvec = self._scan_string_single(sfx, autostep) |
| 1167 |
newpat += sfx |
| 1168 |
rsets += sfxrvec |
| 1169 |
else: |
| 1170 |
|
| 1171 |
|
| 1172 |
|
| 1173 |
if op_idx < 0: |
| 1174 |
node = nsstr |
| 1175 |
nsstr = None |
| 1176 |
else: |
| 1177 |
node, nsstr = nsstr.split(next_op_code, 1) |
| 1178 |
|
| 1179 |
if not node or not nsstr: |
| 1180 |
msg = "missing nodeset operand with '%s' " \ |
| 1181 |
"operator" % next_op_code |
| 1182 |
raise NodeSetParseError(node or nsstr, msg) |
| 1183 |
|
| 1184 |
|
| 1185 |
if node.find(self.BRACKET_CLOSE) > -1: |
| 1186 |
raise NodeSetParseError(node, "illegal closing bracket") |
| 1187 |
|
| 1188 |
|
| 1189 |
node = node.rstrip() |
| 1190 |
newpat, rsets = self._scan_string_single(node, autostep) |
| 1191 |
|
| 1192 |
op = ParsingEngine.OP_CODES[op_code] |
| 1193 |
yield op, newpat, _rsets4nsb(rsets, autostep) |
| 1194 |
|
| 1195 |
def _amend_leading_digits(self, outer, inner): |
| 1196 |
"""Helper to get rid of leading bracket digits. |
| 1197 |
|
| 1198 |
Take a bracket outer prefix string and an inner range set string and |
| 1199 |
return amended strings. |
| 1200 |
""" |
| 1201 |
outerstrip = outer.rstrip(string.digits) |
| 1202 |
outerlen, outerstriplen = len(outer), len(outerstrip) |
| 1203 |
if outerstriplen < outerlen: |
| 1204 |
|
| 1205 |
outerdigits = outer[outerstriplen:] |
| 1206 |
inner = ','.join( |
| 1207 |
'-'.join(outerdigits + bound for bound in elem.split('-')) |
| 1208 |
for elem in (str(subrng) |
| 1209 |
for subrng in RangeSet(inner).contiguous())) |
| 1210 |
return outerstrip, inner |
| 1211 |
|
| 1212 |
def _amend_trailing_digits(self, outer, inner): |
| 1213 |
"""Helper to get rid of trailing bracket digits. |
| 1214 |
|
| 1215 |
Take a bracket outer suffix string and an inner range set string and |
| 1216 |
return amended strings. |
| 1217 |
""" |
| 1218 |
outerstrip = outer.lstrip(string.digits) |
| 1219 |
outerlen, outerstriplen = len(outer), len(outerstrip) |
| 1220 |
if outerstriplen < outerlen: |
| 1221 |
|
| 1222 |
if '/' in inner: |
| 1223 |
msg = "illegal trailing digits after range with steps" |
| 1224 |
raise NodeSetParseError(outer, msg) |
| 1225 |
|
| 1226 |
outerdigits = outer[0:outerlen-outerstriplen] |
| 1227 |
outlen = len(outerdigits) |
| 1228 |
def shiftstep(orig, power): |
| 1229 |
"""Add needed step after shifting range indexes""" |
| 1230 |
if '-' in orig: |
| 1231 |
return orig + '/1' + '0' * power |
| 1232 |
return orig |
| 1233 |
inner = ','.join(shiftstep(s, outlen) for s in |
| 1234 |
('-'.join(bound + outerdigits |
| 1235 |
for bound in elem.split('-')) |
| 1236 |
for elem in inner.split(','))) |
| 1237 |
return outerstrip, inner |
| 1238 |
|
| 1239 |
|
| 1240 |
class NodeSet(NodeSetBase): |
| 1241 |
""" |
| 1242 |
Iterable class of nodes with node ranges support. |
| 1243 |
|
| 1244 |
NodeSet creation examples: |
| 1245 |
|
| 1246 |
>>> nodeset = NodeSet() # empty NodeSet |
| 1247 |
>>> nodeset = NodeSet("cluster3") # contains only cluster3 |
| 1248 |
>>> nodeset = NodeSet("cluster[5,10-42]") |
| 1249 |
>>> nodeset = NodeSet("cluster[0-10/2]") |
| 1250 |
>>> nodeset = NodeSet("cluster[0-10/2],othername[7-9,120-300]") |
| 1251 |
|
| 1252 |
NodeSet provides methods like update(), intersection_update() or |
| 1253 |
difference_update() methods, which conform to the Python Set API. |
| 1254 |
However, unlike RangeSet or standard Set, NodeSet is somewhat not |
| 1255 |
so strict for convenience, and understands NodeSet instance or |
| 1256 |
NodeSet string as argument. Also, there is no strict definition of |
| 1257 |
one element, for example, it IS allowed to do: |
| 1258 |
|
| 1259 |
>>> nodeset = NodeSet("blue[1-50]") |
| 1260 |
>>> nodeset.remove("blue[36-40]") |
| 1261 |
>>> print(nodeset) |
| 1262 |
blue[1-35,41-50] |
| 1263 |
|
| 1264 |
Additionally, the NodeSet class recognizes the "extended string |
| 1265 |
pattern" which adds support for union (special character ","), |
| 1266 |
difference ("!"), intersection ("&") and symmetric difference ("^") |
| 1267 |
operations. String patterns are read from left to right, by |
| 1268 |
proceeding any character operators accordingly. |
| 1269 |
|
| 1270 |
Extended string pattern usage examples: |
| 1271 |
|
| 1272 |
>>> nodeset = NodeSet("node[0-10],node[14-16]") # union |
| 1273 |
>>> nodeset = NodeSet("node[0-10]!node[8-10]") # difference |
| 1274 |
>>> nodeset = NodeSet("node[0-10]&node[5-13]") # intersection |
| 1275 |
>>> nodeset = NodeSet("node[0-10]^node[5-13]") # xor |
| 1276 |
""" |
| 1277 |
|
| 1278 |
_VERSION = 2 |
| 1279 |
|
| 1280 |
def __init__(self, nodes=None, autostep=None, resolver=None, |
| 1281 |
fold_axis=None): |
| 1282 |
"""Initialize a NodeSet object. |
| 1283 |
|
| 1284 |
The `nodes` argument may be a valid nodeset string or a NodeSet |
| 1285 |
object. If no nodes are specified, an empty NodeSet is created. |
| 1286 |
|
| 1287 |
The optional `autostep` argument is passed to underlying |
| 1288 |
:class:`.RangeSet.RangeSet` objects and aims to enable and make use of |
| 1289 |
the range/step syntax (eg. ``node[1-9/2]``) when converting NodeSet to |
| 1290 |
string (using folding). To enable this feature, autostep must be set |
| 1291 |
there to the min number of indexes that are found at equal distance of |
| 1292 |
each other inside a range before NodeSet starts to use this syntax. For |
| 1293 |
example, `autostep=3` (or less) will pack ``n[2,4,6]`` into |
| 1294 |
``n[2-6/2]``. Default autostep value is None which means "inherit |
| 1295 |
whenever possible", ie. do not enable it unless set in NodeSet objects |
| 1296 |
passed as `nodes` here or during arithmetic operations. |
| 1297 |
You may however use the special ``AUTOSTEP_DISABLED`` constant to force |
| 1298 |
turning off autostep feature. |
| 1299 |
|
| 1300 |
The optional `resolver` argument may be used to override the group |
| 1301 |
resolving behavior for this NodeSet object. It can either be set to a |
| 1302 |
:class:`.NodeUtils.GroupResolver` object, to the ``RESOLVER_NOGROUP`` |
| 1303 |
constant to disable any group resolution, or to None (default) to use |
| 1304 |
standard NodeSet group resolver (see :func:`.set_std_group_resolver()` |
| 1305 |
at the module level to change it if needed). |
| 1306 |
|
| 1307 |
nD nodeset only: the optional `fold_axis` parameter, if specified, set |
| 1308 |
the public instance member `fold_axis` to an iterable over nD 0-indexed |
| 1309 |
axis integers. This parameter may be used to disengage some nD folding. |
| 1310 |
That may be useful as all cluster tools don't support folded-nD nodeset |
| 1311 |
syntax. Pass ``[0]``, for example, to only fold along first axis (that |
| 1312 |
is, to fold first dimension using ``[a-b]`` rangeset syntax whenever |
| 1313 |
possible). Using `fold_axis` ensures that rangeset won't be folded on |
| 1314 |
unspecified axis, but please note however, that using `fold_axis` may |
| 1315 |
lead to suboptimal folding, this is because NodeSet algorithms are |
| 1316 |
optimized for folding along all axis (default behavior). |
| 1317 |
""" |
| 1318 |
NodeSetBase.__init__(self, autostep=autostep, fold_axis=fold_axis) |
| 1319 |
|
| 1320 |
|
| 1321 |
if resolver in (RESOLVER_NOGROUP, RESOLVER_NOINIT): |
| 1322 |
self._resolver = None |
| 1323 |
else: |
| 1324 |
self._resolver = resolver or RESOLVER_STD_GROUP |
| 1325 |
|
| 1326 |
|
| 1327 |
if resolver == RESOLVER_NOINIT: |
| 1328 |
self._parser = None |
| 1329 |
else: |
| 1330 |
self._parser = ParsingEngine(self._resolver) |
| 1331 |
self.update(nodes) |
| 1332 |
|
| 1333 |
@classmethod |
| 1334 |
def _fromlist1(cls, nodelist, autostep=None, resolver=None): |
| 1335 |
"""Class method that returns a new NodeSet with single nodes from |
| 1336 |
provided list (optimized constructor).""" |
| 1337 |
inst = NodeSet(autostep=autostep, resolver=resolver) |
| 1338 |
for single in nodelist: |
| 1339 |
inst.update(inst._parser.parse_string_single(single, autostep)) |
| 1340 |
return inst |
| 1341 |
|
| 1342 |
@classmethod |
| 1343 |
def fromlist(cls, nodelist, autostep=None, resolver=None): |
| 1344 |
"""Class method that returns a new NodeSet with nodes from provided |
| 1345 |
list.""" |
| 1346 |
inst = NodeSet(autostep=autostep, resolver=resolver) |
| 1347 |
inst.updaten(nodelist) |
| 1348 |
return inst |
| 1349 |
|
| 1350 |
@classmethod |
| 1351 |
def fromall(cls, groupsource=None, autostep=None, resolver=None): |
| 1352 |
"""Class method that returns a new NodeSet with all nodes from optional |
| 1353 |
groupsource.""" |
| 1354 |
inst = NodeSet(autostep=autostep, resolver=resolver) |
| 1355 |
try: |
| 1356 |
if not inst._resolver: |
| 1357 |
raise NodeSetExternalError("Group resolver is not defined") |
| 1358 |
else: |
| 1359 |
|
| 1360 |
inst.updaten(inst._parser.all_nodes(groupsource)) |
| 1361 |
except NodeUtils.GroupResolverError as exc: |
| 1362 |
errmsg = "Group source error (%s: %s)" % (exc.__class__.__name__, |
| 1363 |
exc) |
| 1364 |
raise NodeSetExternalError(errmsg) |
| 1365 |
return inst |
| 1366 |
|
| 1367 |
def __getstate__(self): |
| 1368 |
"""Called when pickling: remove references to group resolver.""" |
| 1369 |
odict = self.__dict__.copy() |
| 1370 |
odict['_version'] = NodeSet._VERSION |
| 1371 |
del odict['_resolver'] |
| 1372 |
del odict['_parser'] |
| 1373 |
return odict |
| 1374 |
|
| 1375 |
def __setstate__(self, dic): |
| 1376 |
"""Called when unpickling: restore parser using non group |
| 1377 |
resolver.""" |
| 1378 |
self.__dict__.update(dic) |
| 1379 |
self._resolver = None |
| 1380 |
self._parser = ParsingEngine(None) |
| 1381 |
if getattr(self, '_version', 1) <= 1: |
| 1382 |
self.fold_axis = None |
| 1383 |
|
| 1384 |
|
| 1385 |
old_patterns = self._patterns |
| 1386 |
self._patterns = {} |
| 1387 |
for pat, rangeset in sorted(old_patterns.items()): |
| 1388 |
if rangeset: |
| 1389 |
assert isinstance(rangeset, RangeSet) |
| 1390 |
rgs = str(rangeset) |
| 1391 |
if len(rangeset) > 1: |
| 1392 |
rgs = "[%s]" % rgs |
| 1393 |
self.update(pat % rgs) |
| 1394 |
else: |
| 1395 |
self.update(pat) |
| 1396 |
|
| 1397 |
def copy(self): |
| 1398 |
"""Return a shallow copy of a NodeSet.""" |
| 1399 |
cpy = self.__class__(resolver=RESOLVER_NOINIT) |
| 1400 |
dic = {} |
| 1401 |
for pat, rangeset in self._patterns.items(): |
| 1402 |
if rangeset is None: |
| 1403 |
dic[pat] = None |
| 1404 |
else: |
| 1405 |
dic[pat] = rangeset.copy() |
| 1406 |
cpy._patterns = dic |
| 1407 |
cpy.fold_axis = self.fold_axis |
| 1408 |
cpy._autostep = self._autostep |
| 1409 |
cpy._resolver = self._resolver |
| 1410 |
cpy._parser = self._parser |
| 1411 |
return cpy |
| 1412 |
|
| 1413 |
__copy__ = copy |
| 1414 |
|
| 1415 |
def _find_groups(self, node, namespace, allgroups): |
| 1416 |
"""Find groups of node by namespace.""" |
| 1417 |
if allgroups: |
| 1418 |
|
| 1419 |
for grp, nodeset in allgroups.items(): |
| 1420 |
if node in nodeset: |
| 1421 |
yield grp |
| 1422 |
else: |
| 1423 |
|
| 1424 |
try: |
| 1425 |
for group in self._resolver.node_groups(node, namespace): |
| 1426 |
yield group |
| 1427 |
except NodeUtils.GroupSourceQueryFailed as exc: |
| 1428 |
msg = "Group source query failed: %s" % exc |
| 1429 |
raise NodeSetExternalError(msg) |
| 1430 |
|
| 1431 |
def _groups2(self, groupsource=None, autostep=None): |
| 1432 |
"""Find node groups this nodeset belongs to. [private]""" |
| 1433 |
if not self._resolver: |
| 1434 |
raise NodeSetExternalError("No node group resolver") |
| 1435 |
try: |
| 1436 |
|
| 1437 |
allgrplist = self._parser.grouplist(groupsource) |
| 1438 |
except NodeUtils.GroupSourceError: |
| 1439 |
|
| 1440 |
|
| 1441 |
allgrplist = None |
| 1442 |
groups_info = {} |
| 1443 |
allgroups = {} |
| 1444 |
|
| 1445 |
|
| 1446 |
|
| 1447 |
if self._resolver.has_node_groups(groupsource) and \ |
| 1448 |
(not allgrplist or len(allgrplist) >= len(self)): |
| 1449 |
|
| 1450 |
pass |
| 1451 |
else: |
| 1452 |
if not allgrplist: |
| 1453 |
return groups_info |
| 1454 |
try: |
| 1455 |
|
| 1456 |
for grp in allgrplist: |
| 1457 |
nodelist = self._resolver.group_nodes(grp, groupsource) |
| 1458 |
allgroups[grp] = NodeSet(",".join(nodelist), |
| 1459 |
resolver=self._resolver) |
| 1460 |
except NodeUtils.GroupSourceQueryFailed as exc: |
| 1461 |
|
| 1462 |
raise NodeSetExternalError("Unable to map a group " \ |
| 1463 |
"previously listed\n\tFailed command: %s" % exc) |
| 1464 |
|
| 1465 |
|
| 1466 |
for node in self._iterbase(): |
| 1467 |
for grp in self._find_groups(node, groupsource, allgroups): |
| 1468 |
if grp not in groups_info: |
| 1469 |
nodes = self._parser.parse_group(grp, groupsource, autostep) |
| 1470 |
groups_info[grp] = (1, nodes) |
| 1471 |
else: |
| 1472 |
i, nodes = groups_info[grp] |
| 1473 |
groups_info[grp] = (i + 1, nodes) |
| 1474 |
return groups_info |
| 1475 |
|
| 1476 |
def groups(self, groupsource=None, noprefix=False): |
| 1477 |
"""Find node groups this nodeset belongs to. |
| 1478 |
|
| 1479 |
Return a dictionary of the form: |
| 1480 |
group_name => (group_nodeset, contained_nodeset) |
| 1481 |
|
| 1482 |
Group names are always prefixed with "@". If groupsource is provided, |
| 1483 |
they are prefixed with "@groupsource:", unless noprefix is True. |
| 1484 |
""" |
| 1485 |
groups = self._groups2(groupsource, self._autostep) |
| 1486 |
result = {} |
| 1487 |
for grp, (_, nsb) in groups.items(): |
| 1488 |
if groupsource and not noprefix: |
| 1489 |
key = "@%s:%s" % (groupsource, grp) |
| 1490 |
else: |
| 1491 |
key = "@" + grp |
| 1492 |
result[key] = (NodeSet(nsb, resolver=self._resolver), |
| 1493 |
self.intersection(nsb)) |
| 1494 |
return result |
| 1495 |
|
| 1496 |
def regroup(self, groupsource=None, autostep=None, overlap=False, |
| 1497 |
noprefix=False): |
| 1498 |
"""Regroup nodeset using node groups. |
| 1499 |
|
| 1500 |
Try to find fully matching node groups (within specified groupsource) |
| 1501 |
and return a string that represents this node set (containing these |
| 1502 |
potential node groups). When no matching node groups are found, this |
| 1503 |
method returns the same result as str().""" |
| 1504 |
groups = self._groups2(groupsource, autostep) |
| 1505 |
if not groups: |
| 1506 |
return str(self) |
| 1507 |
|
| 1508 |
|
| 1509 |
fulls = [] |
| 1510 |
for k, (i, nodes) in groups.items(): |
| 1511 |
assert i <= len(nodes) |
| 1512 |
if i == len(nodes): |
| 1513 |
fulls.append((i, k)) |
| 1514 |
|
| 1515 |
rest = NodeSet(self, resolver=RESOLVER_NOGROUP) |
| 1516 |
regrouped = NodeSet(resolver=RESOLVER_NOGROUP) |
| 1517 |
|
| 1518 |
|
| 1519 |
for _, grp in sorted(fulls, key=lambda x: (-x[0], x[1])): |
| 1520 |
if not overlap and groups[grp][1] not in rest: |
| 1521 |
continue |
| 1522 |
if groupsource and not noprefix: |
| 1523 |
regrouped.update("@%s:%s" % (groupsource, grp)) |
| 1524 |
else: |
| 1525 |
regrouped.update("@" + grp) |
| 1526 |
rest.difference_update(groups[grp][1]) |
| 1527 |
if not rest: |
| 1528 |
return str(regrouped) |
| 1529 |
|
| 1530 |
if regrouped: |
| 1531 |
return "%s,%s" % (regrouped, rest) |
| 1532 |
|
| 1533 |
return str(rest) |
| 1534 |
|
| 1535 |
def issubset(self, other): |
| 1536 |
""" |
| 1537 |
Report whether another nodeset contains this nodeset. |
| 1538 |
""" |
| 1539 |
nodeset = self._parser.parse(other, self._autostep) |
| 1540 |
return NodeSetBase.issuperset(nodeset, self) |
| 1541 |
|
| 1542 |
def issuperset(self, other): |
| 1543 |
""" |
| 1544 |
Report whether this nodeset contains another nodeset. |
| 1545 |
""" |
| 1546 |
nodeset = self._parser.parse(other, self._autostep) |
| 1547 |
return NodeSetBase.issuperset(self, nodeset) |
| 1548 |
|
| 1549 |
def __getitem__(self, index): |
| 1550 |
""" |
| 1551 |
Return the node at specified index or a subnodeset when a slice |
| 1552 |
is specified. |
| 1553 |
""" |
| 1554 |
base = NodeSetBase.__getitem__(self, index) |
| 1555 |
if not isinstance(base, NodeSetBase): |
| 1556 |
return base |
| 1557 |
|
| 1558 |
inst = NodeSet(autostep=self._autostep, resolver=self._resolver) |
| 1559 |
inst._patterns = base._patterns |
| 1560 |
return inst |
| 1561 |
|
| 1562 |
def index(self, other, start=0, stop=None): |
| 1563 |
"""Return the zero-based index in the nodeset of the node `other`. |
| 1564 |
|
| 1565 |
Like the ``index()`` method of the ``list`` type, this returns the |
| 1566 |
position of `other` when iterating over the nodeset and raises a |
| 1567 |
:class:`ValueError` if the node is not present. The optional `start` |
| 1568 |
and `stop` arguments restrict the search and may be negative. |
| 1569 |
|
| 1570 |
The `other` argument is a single node and may be provided as a string |
| 1571 |
(it is parsed, so node groups are resolved if any). |
| 1572 |
|
| 1573 |
>>> NodeSet("node[0-9,20]").index("node20") |
| 1574 |
10 |
| 1575 |
""" |
| 1576 |
nodeset = self._parser.parse(other, self._autostep) |
| 1577 |
return NodeSetBase.index(self, nodeset, start, stop) |
| 1578 |
|
| 1579 |
def split(self, nbr): |
| 1580 |
""" |
| 1581 |
Split the nodeset into nbr sub-nodesets (at most). Each |
| 1582 |
sub-nodeset will have the same number of elements more or |
| 1583 |
less 1. Current nodeset remains unmodified. |
| 1584 |
|
| 1585 |
>>> for nodeset in NodeSet("foo[1-5]").split(3): |
| 1586 |
... print(nodeset) |
| 1587 |
foo[1-2] |
| 1588 |
foo[3-4] |
| 1589 |
foo5 |
| 1590 |
""" |
| 1591 |
assert(nbr > 0) |
| 1592 |
|
| 1593 |
|
| 1594 |
slice_size = len(self) // nbr |
| 1595 |
left = len(self) % nbr |
| 1596 |
|
| 1597 |
begin = 0 |
| 1598 |
for i in range(0, min(nbr, len(self))): |
| 1599 |
length = slice_size + int(i < left) |
| 1600 |
yield self[begin:begin + length] |
| 1601 |
begin += length |
| 1602 |
|
| 1603 |
def update(self, other): |
| 1604 |
""" |
| 1605 |
s.update(t) returns nodeset s with elements added from t. |
| 1606 |
""" |
| 1607 |
nodeset = self._parser.parse(other, self._autostep) |
| 1608 |
NodeSetBase.update(self, nodeset) |
| 1609 |
|
| 1610 |
def intersection_update(self, other): |
| 1611 |
""" |
| 1612 |
s.intersection_update(t) returns nodeset s keeping only |
| 1613 |
elements also found in t. |
| 1614 |
""" |
| 1615 |
nodeset = self._parser.parse(other, self._autostep) |
| 1616 |
NodeSetBase.intersection_update(self, nodeset) |
| 1617 |
|
| 1618 |
def difference_update(self, other, strict=False): |
| 1619 |
""" |
| 1620 |
s.difference_update(t) removes from s all the elements |
| 1621 |
found in t. If strict is True, raise KeyError if an |
| 1622 |
element in t cannot be removed from s. |
| 1623 |
""" |
| 1624 |
nodeset = self._parser.parse(other, self._autostep) |
| 1625 |
NodeSetBase.difference_update(self, nodeset, strict) |
| 1626 |
|
| 1627 |
def symmetric_difference_update(self, other): |
| 1628 |
""" |
| 1629 |
s.symmetric_difference_update(t) returns nodeset s keeping all |
| 1630 |
nodes that are in exactly one of the nodesets. |
| 1631 |
""" |
| 1632 |
nodeset = self._parser.parse(other, self._autostep) |
| 1633 |
NodeSetBase.symmetric_difference_update(self, nodeset) |
| 1634 |
|
| 1635 |
|
| 1636 |
def expand(pat): |
| 1637 |
""" |
| 1638 |
Commodity function that expands a nodeset pattern into a list of nodes. |
| 1639 |
""" |
| 1640 |
return list(NodeSet(pat)) |
| 1641 |
|
| 1642 |
def fold(pat): |
| 1643 |
""" |
| 1644 |
Commodity function that clean dups and fold provided pattern with ranges |
| 1645 |
and "/step" support. |
| 1646 |
""" |
| 1647 |
return str(NodeSet(pat)) |
| 1648 |
|
| 1649 |
def grouplist(namespace=None, resolver=None): |
| 1650 |
""" |
| 1651 |
Commodity function that retrieves the list of raw groups for a specified |
| 1652 |
group namespace (or use default namespace). |
| 1653 |
Group names are not prefixed with "@". |
| 1654 |
""" |
| 1655 |
return ParsingEngine(resolver or RESOLVER_STD_GROUP).grouplist(namespace) |
| 1656 |
|
| 1657 |
def std_group_resolver(): |
| 1658 |
""" |
| 1659 |
Get the current resolver used for standard "@" group resolution. |
| 1660 |
""" |
| 1661 |
return RESOLVER_STD_GROUP |
| 1662 |
|
| 1663 |
def set_std_group_resolver(new_resolver): |
| 1664 |
""" |
| 1665 |
Override the resolver used for standard "@" group resolution. The |
| 1666 |
new resolver should be either an instance of |
| 1667 |
NodeUtils.GroupResolver or None. In the latter case, the group |
| 1668 |
resolver is restored to the default one. |
| 1669 |
""" |
| 1670 |
global RESOLVER_STD_GROUP |
| 1671 |
RESOLVER_STD_GROUP = new_resolver or _DEF_RESOLVER_STD_GROUP |
| 1672 |
|
| 1673 |
def set_std_group_resolver_config(groupsconf, illegal_chars=None): |
| 1674 |
""" |
| 1675 |
Helper to create and set std group resolver from a config file path. |
| 1676 |
|
| 1677 |
By default, the GroupResolverConfig object is created using |
| 1678 |
illegal_chars=NodeSet.ILLEGAL_GROUP_CHARS. |
| 1679 |
|
| 1680 |
This method does nothing if groupsconf is not defined. |
| 1681 |
""" |
| 1682 |
if groupsconf: |
| 1683 |
if illegal_chars is None: |
| 1684 |
illegal_chars = ILLEGAL_GROUP_CHARS |
| 1685 |
group_resolver = NodeUtils.GroupResolverConfig(groupsconf, |
| 1686 |
illegal_chars) |
| 1687 |
set_std_group_resolver(group_resolver) |