Skip to content
Navigation Menu
{{ message }}
-
Notifications
You must be signed in to change notification settings - Fork 91
Expand file tree
/
Copy pathNodeSet.py
More file actions
1687 lines (1476 loc) · 64.2 KB
/
Copy pathNodeSet.py
File metadata and controls
1687 lines (1476 loc) · 64.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#
# Copyright (C) 2007-2016 CEA/DAM
# Copyright (C) 2007-2017 Aurelien Degremont <aurelien.degremont@cea.fr>
# Copyright (C) 2015-2017 Stephane Thiell <sthiell@stanford.edu>
#
# This file is part of ClusterShell.
#
# ClusterShell is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# ClusterShell is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with ClusterShell; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
"""
Cluster node set module.
A module to efficiently deal with node sets and node groups.
Instances of NodeSet provide similar operations than the builtin set() type,
see http://www.python.org/doc/lib/set-objects.html
Usage example
=============
>>> # Import NodeSet class
... from ClusterShell.NodeSet import NodeSet
>>>
>>> # Create a new nodeset from string
... nodeset = NodeSet("cluster[1-30]")
>>> # Add cluster32 to nodeset
... nodeset.update("cluster32")
>>> # Remove from nodeset
... nodeset.difference_update("cluster[2-5,8-31]")
>>> # Print nodeset as a pdsh-like pattern
... print nodeset
cluster[1,6-7,32]
>>> # Iterate over node names in nodeset
... for node in nodeset:
... print node
cluster1
cluster6
cluster7
cluster32
"""
import fnmatch
import re
import string
import sys
from ClusterShell.Defaults import config_paths, DEFAULTS
import ClusterShell.NodeUtils as NodeUtils
# Import all RangeSet module public objects
from ClusterShell.RangeSet import RangeSet, RangeSetND, AUTOSTEP_DISABLED
from ClusterShell.RangeSet import RangeSetParseError
# Python 3 compatibility
try:
basestring
except NameError:
basestring = str
# Define default GroupResolver object used by NodeSet
DEF_GROUPS_CONFIGS = config_paths('groups.conf')
ILLEGAL_GROUP_CHARS = set("@,!&^*")
_DEF_RESOLVER_STD_GROUP = NodeUtils.GroupResolverConfig(DEF_GROUPS_CONFIGS,
ILLEGAL_GROUP_CHARS)
# Standard group resolver
RESOLVER_STD_GROUP = _DEF_RESOLVER_STD_GROUP
# Special constants for NodeSet's resolver parameter
# RESOLVER_NOGROUP => avoid any group resolution at all
# RESOLVER_NOINIT => reserved use for optimized copy()
RESOLVER_NOGROUP = -1
RESOLVER_NOINIT = -2
# 1.5 compat (deprecated)
STD_GROUP_RESOLVER = RESOLVER_STD_GROUP
NOGROUP_RESOLVER = RESOLVER_NOGROUP
class NodeSetException(Exception):
"""Base NodeSet exception class."""
class NodeSetError(NodeSetException):
"""Raised when an error is encountered."""
class NodeSetParseError(NodeSetError):
"""Raised when NodeSet parsing cannot be done properly."""
def __init__(self, part, msg):
if part:
msg = "%s: \"%s\"" % (msg, part)
NodeSetError.__init__(self, msg)
# faulty part; this allows you to target the error
self.part = part
class NodeSetParseRangeError(NodeSetParseError):
"""Raised when bad range is encountered during NodeSet parsing."""
def __init__(self, rset_exc):
NodeSetParseError.__init__(self, str(rset_exc), "bad range")
class NodeSetExternalError(NodeSetError):
"""Raised when an external error is encountered."""
class NodeSetBase(object):
"""
Base class for NodeSet.
This class allows node set base object creation from specified string
pattern and rangeset object. If optional copy_rangeset boolean flag is
set to True (default), provided rangeset object is copied (if needed),
otherwise it may be referenced (should be seen as an ownership transfer
upon creation).
This class implements core node set arithmetic (no string parsing here).
Example:
>>> nsb = NodeSetBase('node%s-ipmi', RangeSet('1-5,7'), False)
>>> str(nsb)
'node[1-5,7]-ipmi'
>>> nsb = NodeSetBase('node%s-ib%s', RangeSetND([['1-5,7', '1-2']]), False)
>>> str(nsb)
'node[1-5,7]-ib[1-2]'
"""
def __init__(self, pattern=None, rangeset=None, copy_rangeset=True,
autostep=None, fold_axis=None):
"""New NodeSetBase object initializer"""
self._autostep = autostep
self._length = 0
self._patterns = {}
self.fold_axis = fold_axis #: iterable over nD 0-indexed axis
if self.fold_axis is None and DEFAULTS.fold_axis:
self.fold_axis = DEFAULTS.fold_axis # non-empty tuple
if pattern:
self._add(pattern, rangeset, copy_rangeset)
elif rangeset:
raise ValueError("missing pattern")
def get_autostep(self):
"""Get autostep value (property)"""
return self._autostep
def set_autostep(self, val):
"""Set autostep value (property)"""
if val is None:
self._autostep = None
else:
# Work around the pickling issue of sys.maxint (+inf) in py2.4
self._autostep = min(int(val), AUTOSTEP_DISABLED)
# Update our RangeSet/RangeSetND objects
for pat, rset in self._patterns.items():
if rset:
rset.autostep = self._autostep
autostep = property(get_autostep, set_autostep)
def _iter(self):
"""Iterator on internal item tuples
(pattern, indexes, autostep)."""
for pat, rset in sorted(self._patterns.items()):
if rset:
autostep = rset.autostep
if rset.dim() == 1:
assert isinstance(rset, RangeSet)
for idx in rset:
yield pat, (idx,), autostep
else:
for rvec in rset:
yield pat, rvec, autostep
else:
yield pat, None, None
def _iterbase(self):
"""Iterator on single, one-item NodeSetBase objects."""
for pat, ivec, autostep in self._iter():
rset = None # 'no node index' by default
if ivec is not None:
assert len(ivec) > 0
if len(ivec) == 1:
rset = RangeSet.fromone(ivec[0], autostep)
else:
rset = RangeSetND([ivec], autostep)
yield NodeSetBase(pat, rset)
def __iter__(self):
"""Iterator on single nodes as string."""
# Does not call self._iterbase() + str() for better performance.
for pat, ivec, _ in self._iter():
if ivec is not None:
yield pat % ivec
else:
yield pat % ()
# define striter() alias for convenience (to match RangeSet.striter())
striter = __iter__
# define nsiter() as an object-based iterator that could be used for
# __iter__() in the future...
def nsiter(self):
"""Object-based NodeSet iterator on single nodes."""
for pat, ivec, autostep in self._iter():
nodeset = self.__class__()
if ivec is not None:
if len(ivec) == 1:
nodeset._add_new(pat, RangeSet.fromone(ivec[0]))
else:
nodeset._add_new(pat, RangeSetND([ivec], autostep))
else:
nodeset._add_new(pat, None)
yield nodeset
def contiguous(self):
"""Object-based NodeSet iterator on contiguous node sets.
Contiguous node set contains nodes with same pattern name and a
contiguous range of indexes, like foobar[1-100]."""
for pat, rangeset in sorted(self._patterns.items()):
if rangeset:
for cont_rset in rangeset.contiguous():
nodeset = self.__class__()
nodeset._add_new(pat, cont_rset)
yield nodeset
else:
nodeset = self.__class__()
nodeset._add_new(pat, None)
yield nodeset
def __len__(self):
"""Get the number of nodes in NodeSet."""
cnt = 0
for rangeset in self._patterns.values():
if rangeset:
cnt += len(rangeset)
else:
cnt += 1
return cnt
def _iter_nd_pat(self, pat, rset):
"""
Take a pattern and a RangeSetND object and iterate over nD computed
nodeset strings while following fold_axis constraints.
"""
try:
dimcnt = rset.dim()
if self.fold_axis is None:
# fold along all axis (default)
fold_axis = range(dimcnt)
else:
# set of user-provided fold axis (support negative numbers)
fold_axis = [int(x) % dimcnt for x in self.fold_axis
if -dimcnt <= int(x) < dimcnt]
except (TypeError, ValueError) as exc:
raise NodeSetParseError("fold_axis=%s" % self.fold_axis, exc)
for rgvec in rset.vectors():
rgnargs = [] # list of str rangeset args
for axis, rangeset in enumerate(rgvec):
# build an iterator over rangeset strings to add
if len(rangeset) > 1:
if axis not in fold_axis: # expand
rgstrit = rangeset.striter()
else:
rgstrit = ["[%s]" % rangeset]
else:
rgstrit = [str(rangeset)]
# aggregate/expand along previous computed axis...
t_rgnargs = []
for rgstr in rgstrit: # 1-time when not expanding
if not rgnargs:
t_rgnargs.append([rgstr])
else:
for rga in rgnargs:
t_rgnargs.append(rga + [rgstr])
rgnargs = t_rgnargs
# get nodeset patterns formatted with range strings
for rgargs in rgnargs:
yield pat % tuple(rgargs)
def __str__(self):
"""Get ranges-based pattern of node list."""
results = []
try:
for pat, rset in sorted(self._patterns.items()):
if not rset:
results.append(pat % ())
elif rset.dim() == 1:
# check if allowed to fold even for 1D pattern
if self.fold_axis is None or \
list(x for x in self.fold_axis if -1 <= int(x) < 1):
rgs = str(rset)
cnt = len(rset)
if cnt > 1:
rgs = "[%s]" % rgs
results.append(pat % rgs)
else:
results.extend((pat % rgs for rgs in rset.striter()))
elif rset.dim() > 1:
results.extend(self._iter_nd_pat(pat, rset))
except TypeError:
raise NodeSetParseError(pat, "Internal error: node pattern and "
"ranges mismatch")
return ",".join(results)
def copy(self):
"""Return a shallow copy."""
cpy = self.__class__()
cpy.fold_axis = self.fold_axis
cpy._autostep = self._autostep
cpy._length = self._length
dic = {}
for pat, rangeset in self._patterns.items():
if rangeset is None:
dic[pat] = None
else:
dic[pat] = rangeset.copy()
cpy._patterns = dic
return cpy
def __contains__(self, other):
"""Is node contained in NodeSet ?"""
return self.issuperset(other)
def _binary_sanity_check(self, other):
# check that the other argument to a binary operation is also
# a NodeSet, raising a TypeError otherwise.
if not isinstance(other, NodeSetBase):
raise TypeError("Binary operation only permitted between "
"NodeSetBase")
def issubset(self, other):
"""Report whether another nodeset contains this nodeset."""
self._binary_sanity_check(other)
return other.issuperset(self)
def issuperset(self, other):
"""Report whether this nodeset contains another nodeset."""
self._binary_sanity_check(other)
status = True
for pat, erangeset in other._patterns.items():
rangeset = self._patterns.get(pat)
if rangeset:
status = rangeset.issuperset(erangeset)
else:
# might be an unnumbered node (key in dict but no value)
status = pat in self._patterns
if not status:
break
return status
def __eq__(self, other):
"""NodeSet equality comparison."""
# See comment for for RangeSet.__eq__()
if not isinstance(other, NodeSetBase):
return NotImplemented
return len(self) == len(other) and self.issuperset(other)
# inequality comparisons using the is-subset relation
__le__ = issubset
__ge__ = issuperset
def __lt__(self, other):
"""x.__lt__(y) <==> x<y"""
self._binary_sanity_check(other)
return len(self) < len(other) and self.issubset(other)
def __gt__(self, other):
"""x.__gt__(y) <==> x>y"""
self._binary_sanity_check(other)
return len(self) > len(other) and self.issuperset(other)
def _extractslice(self, index):
"""Private utility function: extract slice parameters from slice object
`index` for an list-like object of size `length`."""
length = len(self)
if index.start is None:
sl_start = 0
elif index.start < 0:
sl_start = max(0, length + index.start)
else:
sl_start = index.start
if index.stop is None:
sl_stop = sys.maxsize
elif index.stop < 0:
sl_stop = max(0, length + index.stop)
else:
sl_stop = index.stop
if index.step is None:
sl_step = 1
elif index.step < 0:
# We support negative step slicing with no start/stop, ie. r[::-n].
if index.start is not None or index.stop is not None:
raise IndexError("illegal start and stop when negative step "
"is used")
# As RangeSet elements are ordered internally, adjust sl_start
# to fake backward stepping in case of negative slice step.
stepmod = (length + -index.step - 1) % -index.step
if stepmod > 0:
sl_start += stepmod
sl_step = -index.step
else:
sl_step = index.step
if not isinstance(sl_start, int) or not isinstance(sl_stop, int) \
or not isinstance(sl_step, int):
raise TypeError("slice indices must be integers")
return sl_start, sl_stop, sl_step
def __getitem__(self, index):
"""Return the node at specified index or a subnodeset when a slice is
specified."""
if isinstance(index, slice):
inst = NodeSetBase()
sl_start, sl_stop, sl_step = self._extractslice(index)
sl_next = sl_start
if sl_stop <= sl_next:
return inst
length = 0
for pat, rangeset in sorted(self._patterns.items()):
if rangeset:
cnt = len(rangeset)
offset = sl_next - length
if offset < cnt:
num = min(sl_stop - sl_next, cnt - offset)
inst._add(pat, rangeset[offset:offset + num:sl_step])
else:
#skip until sl_next is reached
length += cnt
continue
else:
cnt = num = 1
if sl_next > length:
length += cnt
continue
inst._add(pat, None)
# adjust sl_next...
sl_next += num
if (sl_next - sl_start) % sl_step:
sl_next = sl_start + \
((sl_next - sl_start)/sl_step + 1) * sl_step
if sl_next >= sl_stop:
break
length += cnt
return inst
elif isinstance(index, int):
if index < 0:
length = len(self)
if index >= -length:
index = length + index # - -index
else:
raise IndexError("%d out of range" % index)
length = 0
for pat, rangeset in sorted(self._patterns.items()):
if rangeset:
cnt = len(rangeset)
if index < length + cnt:
# return a subrangeset of size 1 to manage padding
if rangeset.dim() == 1:
return pat % rangeset[index-length:index-length+1]
else:
sub = rangeset[index-length:index-length+1]
for rgvec in sub.vectors():
return pat % (tuple(rgvec))
else:
cnt = 1
if index == length:
return pat
length += cnt
raise IndexError("%d out of range" % index)
else:
raise TypeError("NodeSet indices must be integers")
def _rangeset_index(self, rangeset, orangeset):
"""Return the position of the single index held by `orangeset`
within `rangeset`, following the same order as iteration, or None
if the index is not contained in `rangeset`.
Both arguments are the RangeSet/RangeSetND/None objects respectively
associated to the same pattern in this nodeset and in the searched
single node.
"""
# unnumbered node (eg. 'server'): both must have no index
if rangeset is None or orangeset is None:
return 0 if rangeset is None and orangeset is None else None
try:
if isinstance(orangeset, RangeSetND):
# nD: orangeset holds a single index vector
return rangeset.index(next(iter(orangeset)))
# 1D: orangeset holds a single (possibly zero-padded) index
return rangeset.index(next(orangeset.striter()))
except ValueError:
return None
def index(self, other, start=0, stop=None):
"""Return the zero-based index in the nodeset of the node `other`.
This behaves like the ``index()`` method of the ``list`` type: it
returns the position of the node when iterating over the nodeset and
raises a :class:`ValueError` if the node is not present. The optional
`start` and `stop` arguments restrict the search to the matching
subsequence, and may be negative (counted from the end).
Unlike a naive linear search, this implementation does not expand the
whole nodeset: it only sums the size of the patterns that precede the
searched node and locates it within its own pattern.
Example:
>>> NodeSetBase('node%s', RangeSet('0-9,20')).index(
... NodeSetBase('node%s', RangeSet('20')))
10
"""
self._binary_sanity_check(other)
if len(other) != 1:
raise ValueError("index() argument must be a single node")
# extract the single (pattern, rangeset) of the searched node
opat, orangeset = list(other._patterns.items())[0]
# walk patterns in iteration order, summing sizes until we reach the
# pattern of the searched node
found = None
base = 0
for pat, rangeset in sorted(self._patterns.items()):
if pat == opat:
offset = self._rangeset_index(rangeset, orangeset)
if offset is not None:
found = base + offset
break
if rangeset:
base += len(rangeset)
else:
base += 1
if found is None:
raise ValueError("'%s' is not in nodeset" % other)
# honor optional start/stop search window (list.index() semantics)
if start != 0 or stop is not None:
length = len(self)
if start < 0:
start = max(0, length + start)
if stop is None:
stop = length
elif stop < 0:
stop = max(0, length + stop)
if not start <= found < stop:
raise ValueError("'%s' is not in nodeset" % other)
return found
def _add_new(self, pat, rangeset):
"""Add nodes from a (pat, rangeset) tuple.
Predicate: pattern does not exist in current set. RangeSet object is
referenced (not copied)."""
assert pat not in self._patterns
self._patterns[pat] = rangeset
def _add(self, pat, rangeset, copy_rangeset=True):
"""Add nodes from a (pat, rangeset) tuple.
`pat' may be an existing pattern and `rangeset' may be None.
RangeSet or RangeSetND objects are copied if re-used internally
when provided and if copy_rangeset flag is set.
"""
if pat in self._patterns:
# existing pattern: get RangeSet or RangeSetND entry...
pat_e = self._patterns[pat]
# sanity checks
if (pat_e is None) is not (rangeset is None):
raise NodeSetError("Invalid operation")
# entry may exist but set to None (single node)
if pat_e:
pat_e.update(rangeset)
else:
# new pattern...
if rangeset and copy_rangeset:
# default is to inherit rangeset autostep value
rangeset = rangeset.copy()
# but if set, self._autostep does override it
if self._autostep is not None:
# works with rangeset 1D or nD
rangeset.autostep = self._autostep
self._add_new(pat, rangeset)
def union(self, other):
"""
s.union(t) returns a new set with elements from both s and t.
"""
self_copy = self.copy()
self_copy.update(other)
return self_copy
def __or__(self, other):
"""
Implements the | operator. So s | t returns a new nodeset with
elements from both s and t.
"""
if not isinstance(other, NodeSetBase):
return NotImplemented
return self.union(other)
def add(self, other):
"""
Add node to NodeSet.
"""
self.update(other)
def update(self, other):
"""
s.update(t) updates nodeset s with elements added from t.
"""
for pat, rangeset in other._patterns.items():
self._add(pat, rangeset)
def updaten(self, others):
"""
s.updaten(list) updates nodeset s with elements added from given list.
"""
for other in others:
self.update(other)
def clear(self):
"""
Remove all nodes from this nodeset.
"""
self._patterns.clear()
def __ior__(self, other):
"""
Implements the ``|=`` operator. So ``s |= t`` returns nodeset s
with elements added from t. (Python version 2.5+ required)
"""
self._binary_sanity_check(other)
self.update(other)
return self
def intersection(self, other):
"""
s.intersection(t) returns a new set with elements common to s
and t.
"""
self_copy = self.copy()
self_copy.intersection_update(other)
return self_copy
def __and__(self, other):
"""
Implements the & operator. So ``s & t`` returns a new nodeset with
elements common to s and t.
"""
if not isinstance(other, NodeSet):
return NotImplemented
return self.intersection(other)
def intersection_update(self, other):
"""
``s.intersection_update(t)`` updates nodeset s keeping only
elements also found in t.
"""
if other is self:
return
tmp_ns = NodeSetBase()
for pat, irangeset in other._patterns.items():
rangeset = self._patterns.get(pat)
if rangeset:
irset = rangeset.intersection(irangeset)
# ignore pattern if empty rangeset
if len(irset) > 0:
tmp_ns._add(pat, irset, copy_rangeset=False)
elif not irangeset and pat in self._patterns:
# intersect two nodes with no rangeset
tmp_ns._add(pat, None)
# Substitute
self._patterns = tmp_ns._patterns
def __iand__(self, other):
"""
Implements the &= operator. So ``s &= t`` returns nodeset s keeping
only elements also found in t. (Python version 2.5+ required)
"""
self._binary_sanity_check(other)
self.intersection_update(other)
return self
def difference(self, other):
"""
``s.difference(t)`` returns a new NodeSet with elements in s but not
in t.
"""
self_copy = self.copy()
self_copy.difference_update(other)
return self_copy
def __sub__(self, other):
"""
Implement the - operator. So ``s - t`` returns a new nodeset with
elements in s but not in t.
"""
if not isinstance(other, NodeSetBase):
return NotImplemented
return self.difference(other)
def difference_update(self, other, strict=False):
"""
``s.difference_update(t)`` removes from s all the elements found in t.
:raises KeyError: an element cannot be removed (only if strict is
True)
"""
# the purge of each empty pattern is done afterward to allow self = ns
purge_patterns = []
# iterate first over exclude nodeset rangesets which is usually smaller
for pat, erangeset in other._patterns.items():
# if pattern is found, deal with it
rangeset = self._patterns.get(pat)
if rangeset:
# sub rangeset, raise KeyError if not found
rangeset.difference_update(erangeset, strict)
# check if no range left and add pattern to purge list
if len(rangeset) == 0:
purge_patterns.append(pat)
else:
# unnumbered node exclusion
if pat in self._patterns:
purge_patterns.append(pat)
elif strict:
raise KeyError(pat)
for pat in purge_patterns:
del self._patterns[pat]
def __isub__(self, other):
"""
Implement the -= operator. So ``s -= t`` returns nodeset s after
removing elements found in t. (Python version 2.5+ required)
"""
self._binary_sanity_check(other)
self.difference_update(other)
return self
def remove(self, elem):
"""
Remove element elem from the nodeset. Raise KeyError if elem
is not contained in the nodeset.
:raises KeyError: elem is not contained in the nodeset
"""
self.difference_update(elem, True)
def symmetric_difference(self, other):
"""
``s.symmetric_difference(t)`` returns the symmetric difference of
two nodesets as a new NodeSet.
(ie. all nodes that are in exactly one of the nodesets.)
"""
self_copy = self.copy()
self_copy.symmetric_difference_update(other)
return self_copy
def __xor__(self, other):
"""
Implement the ^ operator. So ``s ^ t`` returns a new NodeSet with
nodes that are in exactly one of the nodesets.
"""
if not isinstance(other, NodeSet):
return NotImplemented
return self.symmetric_difference(other)
def symmetric_difference_update(self, other):
"""
``s.symmetric_difference_update(t)`` updates nodeset s keeping all
nodes that are in exactly one of the nodesets.
"""
purge_patterns = []
# iterate over our rangesets
for pat, rangeset in self._patterns.items():
brangeset = other._patterns.get(pat)
if brangeset:
rangeset.symmetric_difference_update(brangeset)
else:
if pat in other._patterns:
purge_patterns.append(pat)
# iterate over other's rangesets
for pat, brangeset in other._patterns.items():
rangeset = self._patterns.get(pat)
if not rangeset and not pat in self._patterns:
self._add(pat, brangeset)
# check for patterns cleanup
for pat, rangeset in self._patterns.items():
if rangeset is not None and len(rangeset) == 0:
purge_patterns.append(pat)
# cleanup
for pat in purge_patterns:
del self._patterns[pat]
def __ixor__(self, other):
"""
Implement the ^= operator. So ``s ^= t`` returns nodeset s after
keeping all nodes that are in exactly one of the nodesets.
(Python version 2.5+ required)
"""
self._binary_sanity_check(other)
self.symmetric_difference_update(other)
return self
def _strip_escape(nsstr):
"""
Helper to prepare a nodeset string for parsing: trim boundary
whitespaces and escape special characters.
"""
return nsstr.strip().replace('%', '%%')
def _rsets4nsb(rsets, autostep):
"""
Helper to convert a list of RangeSet objects into the proper object
for NodeSetBase: RangeSet, RangeSetND or None (no node index).
"""
if len(rsets) > 1:
return RangeSetND([rsets], None, autostep, copy_rangeset=False)
elif len(rsets) == 1:
return rsets[0]
class ParsingEngine(object):
"""
Class that is able to transform a source into a NodeSetBase.
"""
OP_CODES = {',': 'update',
'!': 'difference_update',
'&': 'intersection_update',
'^': 'symmetric_difference_update'}
OP_CODES_PAT = '[%s]' % re.escape(''.join(OP_CODES.keys()))
BRACKET_OPEN = '['
BRACKET_CLOSE = ']'
def __init__(self, group_resolver, node_wildcard_enable=True):
"""
Initialize Parsing Engine.
"""
self.group_resolver = group_resolver
self.base_node_re = re.compile(r"(\D*)(\d*)")
self.node_wc = node_wildcard_enable # node wildcard support
def parse(self, nsobj, autostep):
"""
Parse provided object if possible and return a NodeSetBase object.
"""
# passing None is supported
if nsobj is None:
return NodeSetBase()
# is nsobj a NodeSetBase instance?
if isinstance(nsobj, NodeSetBase):
return nsobj
# or is nsobj a string?
if isinstance(nsobj, basestring):
try:
return self.parse_string(str(nsobj), autostep)
except (NodeUtils.GroupSourceQueryFailed, RuntimeError) as exc:
raise NodeSetParseError(nsobj, str(exc))
raise TypeError("Unsupported NodeSet input %s" % type(nsobj))
def parse_string(self, nsstr, autostep, namespace=None):
"""Parse provided string in optional namespace.
This method parses string, resolves all node groups, and
computes set operations.
Return a NodeSetBase object.
"""
alln_cache = None # used to compute 'all nodes' only once
nodeset = NodeSetBase()
nsstr = _strip_escape(nsstr)
for opc, pat, rgnd in self._scan_string(nsstr, autostep):
# Parser main debugging:
#print "OPC %s PAT %s RANGESETS %s" % (opc, pat, rgnd)
if self.group_resolver and pat[0] == '@':
ns_group = NodeSetBase()
for nodegroup in NodeSetBase(pat, rgnd):
# parse/expand nodes group: get group string and namespace
ns_str_ext, ns_nsp_ext = self.parse_group_string(nodegroup,
namespace)
if ns_str_ext: # may still contain groups
# recursively parse and aggregate result
ns_group.update(self.parse_string(ns_str_ext,
autostep,
ns_nsp_ext))
# perform operation
getattr(nodeset, opc)(ns_group)
elif self.group_resolver and self.node_wc and ('*' in pat or
'?' in pat):
# We support ranges with wildcard mask by testing all nodes
# against each expanded mask (wcmasks).
wcmasks = (str(wcn) for wcn in NodeSetBase(pat, rgnd, False))
# Our reference set is 'all nodes', we need to build it from
# NodeSetBase to iterate over each individual node.
if alln_cache is None:
self.node_wc = False # avoid infinite recursion
try:
nsb = NodeSetBase()
for res in self.all_nodes(namespace):
nsb.update(self.parse_string(res, autostep,
namespace))
alln_cache = set(str(node) for node in nsb)
finally:
self.node_wc = True
alln = alln_cache.copy()
# A wildcarded nodeset can be seen as a single nodeset, so we
# compute the union of nodes matching the wildcard mask(s) and
# use the resulting NodeSetBase object as argument of the next
# operation (opc).
wcns = NodeSetBase()
for wcmask in wcmasks:
# Expand nodes matching any of the wildcard mask
for node in fnmatch.filter(alln, wcmask):
alln.remove(node) # remove matching node for next iter
wcp, wcr = self._scan_string_single(node, autostep)
wcrgnd = _rsets4nsb(wcr, autostep)
wcns.update(NodeSetBase(wcp, wcrgnd, False))
getattr(nodeset, opc)(wcns)
else:
getattr(nodeset, opc)(NodeSetBase(pat, rgnd, False))
return nodeset
def parse_string_single(self, nsstr, autostep):
"""Parse provided string and return a NodeSetBase object."""
pat, rangesets = self._scan_string_single(_strip_escape(nsstr),
autostep)
if len(rangesets) > 1:
rgobj = RangeSetND([rangesets], None, autostep, copy_rangeset=False)
elif len(rangesets) == 1:
rgobj = rangesets[0]
else: # non-indexed nodename
rgobj = None
return NodeSetBase(pat, rgobj, False)
def parse_group(self, group, namespace=None, autostep=None):
"""Parse provided single group name (without @ prefix)."""
assert self.group_resolver is not None
nodestr = self.group_resolver.group_nodes(group, namespace)
return self.parse(",".join(nodestr), autostep)
def parse_group_string(self, nodegroup, namespace=None):
"""Parse provided raw nodegroup string in optional namespace.
Warning: 1 pass only, may still return groups.
Return a tuple (grp_resolved_string, namespace).
"""
assert nodegroup[0] == '@'
assert self.group_resolver is not None
grpstr = group = nodegroup[1:]
if grpstr.find(':') >= 0:
# specified namespace does always override
namespace, group = grpstr.split(':', 1)
if group == '*': # @* or @source:* magic
reslist = self.all_nodes(namespace)
elif group.startswith('@'): # @@source group name list
reslist = self.grouplist(grpstr[1:])
else:
reslist = self.group_resolver.group_nodes(group, namespace)
return ','.join(reslist), namespace
def grouplist(self, namespace=None):
"""
Return a sorted list of groups from current resolver (in optional
group source / namespace).
"""
You can’t perform that action at this time.
