forked from rosspeoples/python3-pywbem
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtupleparse.py
1463 lines (1054 loc) · 41.3 KB
/
tupleparse.py
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
#
# (C) Copyright 2003, 2004 Hewlett-Packard Development Company, L.P.
# (C) Copyright 2006-2007 Novell, Inc.
#
# This program 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; version 2 of the License.
#
# This program 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 this program; if not, write to the Free Software
# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
#
# Author: Martin Pool <[email protected]>
# Tim Potter <[email protected]>
# Bart Whiteley <[email protected]>
# Ross Peoples <[email protected]>
'''Tuple parser for the XML schema representing CIM messages.
This framework is meant to add some value to the tuple-tree
representation of CIM in XML by having the following properties:
- Silently ignoring whitespace text elements
- Conversion from tuple-tree representation into a python dictionary
which can then be accessed in a readable fashion.
- Validation of the XML elements and attributes without having to
use the DTD file or any external tools.
'''
# Implementation: this works by a recursive descent down the CIM XML
# tupletree. As we walk down, we produce cim_obj and cim_type
# objects representing the CIM message in digested form.
# For each XML node type FOO there is one function parse_foo, which
# returns the digested form by examining a tuple tree rooted at FOO.
# The resulting objects are constrained to the shape of the CIM XML
# tree: if one node in XML contains another, then the corresponding
# CIM object will contain the second. However, there can be local
# transformations at each node: some levels are ommitted, some are
# transformed into lists or hashes.
# We try to validate that the tree is well-formed too. The validation
# is more strict than the DTD, but it is forgiving of implementation
# quirks and bugs in Pegasus.
# Bear in mind in the parse functions that each tupletree tuple is
# structured as
# tt[0]: name string == name(tt)
# tt[1]: hash of attributes == attrs(tt)
# tt[2]: sequence of children == kids(tt)
# At the moment this layer is a little inconsistent: in some places it
# returns tupletrees, and in others Python objects. It may be better
# to hide the tupletree/XML representation from higher level code.
# TODO: Maybe take a DTD fragment like "(DECLGROUP |
# DECLGROUP.WITHNAME | DECLGROUP.WITHPATH)*", parse that and check it
# directly.
# TODO: Syntax-check some attributes with defined formats, such as NAME
# TODO: Implement qualifiers by making subclasses of CIM types with a
# .qualifiers property.
# This module is meant to be safe for 'import *'.
import six
from . import cim_obj, tupletree
from .cim_obj import CIMInstance, CIMInstanceName, CIMClass, \
CIMClassName, CIMProperty, CIMMethod, \
CIMParameter, CIMQualifier, CIMQualifierDeclaration
class ParseError(Exception):
"""This exception is raised when there is a validation error detected
by the parser."""
pass
def filter_tuples(l):
"""Return only the tuples in a list.
In a tupletree, tuples correspond to XML elements. Useful for
stripping out whitespace data in a child list."""
if l is None:
return []
else:
return [x for x in l if type(x) == tuple]
def pcdata(tt):
"""Return the concatenated character data within a tt.
The tt must not have non-character children."""
for x in tt[2]:
if not isinstance(x, six.string_types):
raise ParseError('unexpected node %s under %s' % (repr(x), repr(tt)))
return ''.join(tt[2])
def name(tt):
return tt[0]
def attrs(tt):
return tt[1]
def kids(tt):
return filter_tuples(tt[2])
def check_node(tt, nodename, required_attrs=[], optional_attrs=[],
allowed_children=None,
allow_pcdata=False):
"""Check static local constraints on a single node.
The node must have the given name. The required attrs must be
present, and the optional attrs may be.
If allowed_children is not None, the node may have children of the
given types. It can be [] for nodes that may not have any
children. If it's None, it is assumed the children are validated
in some other way.
If allow_pcdata is true, then non-whitespace text children are allowed.
(Whitespace text nodes are always allowed.)
"""
if name(tt) != nodename:
raise ParseError('expected node type %s, not %s' %
(nodename, name(tt)))
# Check we have all the required attributes, and no unexpected ones
tt_attrs = {}
if attrs(tt) is not None:
tt_attrs = attrs(tt).copy()
for attr in required_attrs:
if not attr in tt_attrs:
raise ParseError('expected %s attribute on %s node, but only '
'have %s' % (attr, name(tt), attrs(tt).keys()))
del tt_attrs[attr]
for attr in optional_attrs:
if attr in tt_attrs:
del tt_attrs[attr]
if len(tt_attrs.keys()) > 0:
raise ParseError('invalid extra attributes %s' % tt_attrs.keys())
if allowed_children is not None:
for c in kids(tt):
if name(c) not in allowed_children:
raise ParseError('unexpected node %s under %s; wanted %s'
% (name(c), name(tt), allowed_children))
if not allow_pcdata:
for c in tt[2]:
if isinstance(c, six.string_types):
if c.lstrip(' \t\n') != '':
raise ParseError('unexpected non-blank pcdata node %s '
'under %s' % (repr(c), name(tt)))
def one_child(tt, acceptable):
"""Parse children of a node with exactly one child node.
PCData is ignored.
"""
k = kids(tt)
if len(k) != 1:
raise ParseError('In element %s with attributes %s, expected just '\
'one child element %s, but got child elements %s' %\
(name(tt), attrs(tt), acceptable, [t[0] for t in k]))
child = k[0]
if name(child) not in acceptable:
raise ParseError('In element %s with attributes %s, expected one '\
'child element %s, but got child element %s' %\
(name(tt), attrs(tt), acceptable, name(child)))
return parse_any(child)
def optional_child(tt, allowed):
"""Parse exactly zero or one of a list of elements from the
child nodes."""
k = kids(tt)
if len(k) > 1:
raise ParseError('In element %s with attributes %s, expected zero or '\
'one child element %s, but got child elements %s' %\
(name(tt), attrs(tt), allowed, [t[0] for t in k]))
elif len(k) == 1:
return one_child(tt, allowed)
else:
return None
def list_of_various(tt, acceptable):
"""Parse zero or more of a list of elements from the child nodes.
Each element of the list can be any type from the list of acceptable
nodes."""
r = []
for child in kids(tt):
if name(child) not in acceptable:
raise ParseError('In element %s with attributes %s, expected zero '\
'or more child elements %s, but got child element %s' %\
(name(tt), attrs(tt), acceptable, name(child)))
r.append(parse_any(child))
return r
def list_of_matching(tt, matched):
"""Parse only the children of particular types under tt.
Other children are ignored rather than giving an error."""
r = []
for child in kids(tt):
if name(child) not in matched:
continue
r.append(parse_any(child))
return r
def list_of_same(tt, acceptable):
"""Parse a list of elements from child nodes.
The children can be any of the listed acceptable types, but they
must all be the same.
"""
k = kids(tt)
if not k: # empty list, consistent with list_of_various
return []
w = name(k[0])
if w not in acceptable:
raise ParseError('In element %s with attributes %s, expected child '\
'elements %s, but got child element %s' %\
(name(tt), attrs(tt), acceptable, w))
r = []
for child in k:
if name(child) != w:
raise ParseError('In element %s with attributes %s, expected '\
'sequence of only child elements %s, but got child '\
'element %s' % (name(tt), attrs(tt), w, name(child)))
r.append(parse_any(child))
return r
def notimplemented(tt):
raise ParseError('parser for %s not implemented' % name(tt))
#
# Root element
#
def parse_cim(tt):
"""
<!ELEMENT CIM (MESSAGE | DECLARATION)>
<!ATTLIST CIM
CIMVERSION CDATA #REQUIRED
DTDVERSION CDATA #REQUIRED>
"""
check_node(tt, 'CIM', ['CIMVERSION', 'DTDVERSION'])
if not attrs(tt)['CIMVERSION'].startswith('2.'):
raise ParseError('CIMVERSION is %s, expected 2.x.y' %
attrs(tt)['CIMVERSION'])
child = one_child(tt, ['MESSAGE', 'DECLARATION'])
return name(tt), attrs(tt), child
#
# Object value elements
#
def parse_value(tt):
'''Return VALUE contents as a string'''
## <!ELEMENT VALUE (#PCDATA)>
check_node(tt, 'VALUE', [], [], [], True)
return pcdata(tt)
def parse_value_array(tt):
"""Return list of strings."""
## <!ELEMENT VALUE.ARRAY (VALUE*)>
check_node(tt, 'VALUE.ARRAY', [], [], ['VALUE'])
return list_of_same(tt, ['VALUE'])
def parse_value_reference(tt):
"""
<!ELEMENT VALUE.REFERENCE (CLASSPATH | LOCALCLASSPATH | CLASSNAME |
INSTANCEPATH | LOCALINSTANCEPATH |
INSTANCENAME)>
"""
check_node(tt, 'VALUE.REFERENCE', [])
child = one_child(tt,
['CLASSPATH', 'LOCALCLASSPATH', 'CLASSNAME',
'INSTANCEPATH', 'LOCALINSTANCEPATH',
'INSTANCENAME'])
# The VALUE.REFERENCE wrapper element is discarded
return child
def parse_value_refarray(tt):
"""
<!ELEMENT VALUE.REFARRAY (VALUE.REFERENCE*)>
"""
check_node(tt, 'VALUE.REFARRAY')
children = list_of_various(tt, ['VALUE.REFERENCE'])
# The VALUE.REFARRAY wrapper element is discarded
return children
def parse_value_object(tt):
"""
<!ELEMENT VALUE.OBJECT (CLASS | INSTANCE)>
"""
check_node(tt, 'VALUE.OBJECT')
child = one_child(tt, ['CLASS', 'INSTANCE', 'QUALIFIER.DECLARATION'])
return (name(tt), attrs(tt), child)
def parse_value_namedinstance(tt):
"""
<!ELEMENT VALUE.NAMEDINSTANCE (INSTANCENAME, INSTANCE)>
"""
check_node(tt, 'VALUE.NAMEDINSTANCE')
k = kids(tt)
if len(k) != 2:
raise ParseError('expecting (INSTANCENAME, INSTANCE), got %s' % repr(k))
instancename = parse_instancename(k[0])
instance = parse_instance(k[1])
instance.path = instancename
return instance
def parse_value_namedobject(tt):
"""
<!ELEMENT VALUE.NAMEDOBJECT (CLASS | (INSTANCENAME, INSTANCE))>
"""
check_node(tt, 'VALUE.NAMEDOBJECT')
k = kids(tt)
if len(k) == 1:
object = parse_class(k[0])
elif len(k) == 2:
path = parse_instancename(kids(tt)[0])
object = parse_instance(kids(tt)[1])
object.path = path
else:
raise ParseError('Expecting one or two elements, got %s' %
repr(kids(tt)))
return (name(tt), attrs(tt), object)
def parse_value_objectwithlocalpath(tt):
"""
<!ELEMENT VALUE.OBJECTWITHLOCALPATH ((LOCALCLASSPATH, CLASS) |
(LOCALINSTANCEPATH, INSTANCE))>
"""
check_node(tt, 'VALUE.OBJECTWITHLOCALPATH')
if len(kids(tt)) != 2:
raise ParseError('Expecting two elements, got %s' %
len(kids(tt)));
if kids(tt)[0][0] == 'LOCALCLASSPATH':
object = (parse_localclasspath(kids(tt)[0]),
parse_class(kids(tt)[1]))
else:
path = parse_localinstancepath(kids(tt)[0])
object = parse_instance(kids(tt)[1])
object.path = path
return (name(tt), attrs(tt), object)
def parse_value_objectwithpath(tt):
"""
<!ELEMENT VALUE.OBJECTWITHPATH ((CLASSPATH, CLASS) |
(INSTANCEPATH, INSTANCE))>
"""
check_node(tt, 'VALUE.OBJECTWITHPATH')
k = kids(tt)
if len(k) != 2:
raise ParseError('Expecting two elements, got %s' % k)
if name(k[0]) == 'CLASSPATH':
object = (parse_classpath(k[0]),
parse_class(k[1]))
else:
path = parse_instancepath(k[0])
object = parse_instance(k[1])
object.path = path
return (name(tt), attrs(tt), object)
#
# Object naming and locating elements
#
def parse_namespacepath(tt):
"""
<!ELEMENT NAMESPACEPATH (HOST, LOCALNAMESPACEPATH)>
"""
check_node(tt, 'NAMESPACEPATH')
if len(kids(tt)) != 2:
raise ParseError('Expecting (HOST, LOCALNAMESPACEPATH) '
'got %s' % kids(tt).keys())
host = parse_host(kids(tt)[0])
localnspath = parse_localnamespacepath(kids(tt)[1])
return (host, localnspath)
def parse_localnamespacepath(tt):
"""
<!ELEMENT LOCALNAMESPACEPATH (NAMESPACE+)>
"""
check_node(tt, 'LOCALNAMESPACEPATH', [], [], ['NAMESPACE'])
if len(kids(tt)) == 0:
raise ParseError('Expecting one or more of NAMESPACE, got nothing')
ns_list = list_of_various(tt, ['NAMESPACE'])
return '/'.join(ns_list)
def parse_host(tt):
"""
<!ELEMENT HOST (#PCDATA)>
"""
check_node(tt, 'HOST', allow_pcdata=True)
return pcdata(tt)
def parse_namespace(tt):
"""
<!ELEMENT NAMESPACE EMPTY>
<!ATTLIST NAMESPACE
%CIMName;>
"""
check_node(tt, 'NAMESPACE', ['NAME'], [], [])
return attrs(tt)['NAME']
def parse_classpath(tt):
"""
<!ELEMENT CLASSPATH (NAMESPACEPATH, CLASSNAME)>
"""
check_node(tt, 'CLASSPATH')
if len(kids(tt)) != 2:
raise ParseError('Expecting (NAMESPACEPATH, CLASSNAME) '
'got %s' % kids(tt).keys())
nspath = parse_namespacepath(kids(tt)[0])
classname = parse_classname(kids(tt)[1])
return CIMClassName(classname.classname,
host=nspath[0], namespace=nspath[1])
def parse_localclasspath(tt):
"""
<!ELEMENT LOCALCLASSPATH (LOCALNAMESPACEPATH, CLASSNAME)>
"""
check_node(tt, 'LOCALCLASSPATH')
if len(kids(tt)) != 2:
raise ParseError('Expecting (LOCALNAMESPACEPATH, CLASSNAME) '
'got %s' % kids(tt).keys())
localnspath = parse_localnamespacepath(kids(tt)[0])
classname = parse_classname(kids(tt)[1])
return CIMClassName(classname.classname, namespace=localnspath)
def parse_classname(tt):
"""
<!ELEMENT CLASSNAME EMPTY>
<!ATTLIST CLASSNAME
%CIMName;>
"""
check_node(tt, 'CLASSNAME', ['NAME'], [], [])
return CIMClassName(attrs(tt)['NAME'])
def parse_instancepath(tt):
"""
<!ELEMENT INSTANCEPATH (NAMESPACEPATH, INSTANCENAME)>
"""
check_node(tt, 'INSTANCEPATH')
if len(kids(tt)) != 2:
raise ParseError('Expecting (NAMESPACEPATH, INSTANCENAME), got %s'
% repr(kids(tt)))
nspath = parse_namespacepath(kids(tt)[0])
instancename = parse_instancename(kids(tt)[1])
instancename.host = nspath[0]
instancename.namespace = nspath[1]
return instancename
def parse_localinstancepath(tt):
"""
<!ELEMENT LOCALINSTANCEPATH (LOCALNAMESPACEPATH, INSTANCENAME)>
"""
check_node(tt, 'LOCALINSTANCEPATH')
if len(kids(tt)) != 2:
raise ParseError('Expecting (LOCALNAMESPACEPATH, INSTANCENAME), '
'got %s' % kids(tt).keys())
localnspath = parse_localnamespacepath(kids(tt)[0])
instancename = parse_instancename(kids(tt)[1])
instancename.namespace = localnspath
return instancename
def parse_instancename(tt):
"""Parse XML INSTANCENAME into CIMInstanceName object."""
## <!ELEMENT INSTANCENAME (KEYBINDING* | KEYVALUE? | VALUE.REFERENCE?)>
## <!ATTLIST INSTANCENAME %ClassName;>
check_node(tt, 'INSTANCENAME', ['CLASSNAME'])
if len(kids(tt)) == 0:
# probably not ever going to see this, but it's valid
# according to the grammar
return CIMInstanceName(attrs(tt)['CLASSNAME'], {})
k0 = kids(tt)[0]
w = name(k0)
classname = attrs(tt)['CLASSNAME']
if w == 'KEYVALUE' or w == 'VALUE.REFERENCE':
if len(kids(tt)) != 1:
raise ParseError('expected only one %s under %s' %
w, name(tt))
# FIXME: This is probably not the best representation of these forms...
val = parse_any(k0)
return CIMInstanceName(classname, {None: val})
elif w == 'KEYBINDING':
kbs = {}
for kb in list_of_various(tt, ['KEYBINDING']):
kbs.update(kb)
return CIMInstanceName(classname, kbs)
else:
raise ParseError('unexpected node %s under %s' %
(name(kids(tt)[0]), name(tt)))
def parse_objectpath(tt):
"""
<!ELEMENT OBJECTPATH (INSTANCEPATH | CLASSPATH)>
"""
check_node(tt, 'OBJECTPATH')
child = one_child(tt, ['INSTANCEPATH', 'CLASSPATH'])
return (name(tt), attrs(tt), child)
def parse_keybinding(tt):
##<!ELEMENT KEYBINDING (KEYVALUE | VALUE.REFERENCE)>
##<!ATTLIST KEYBINDING
## %CIMName;>
"""Returns one-item dictionary from name to Python value."""
check_node(tt, 'KEYBINDING', ['NAME'])
child = one_child(tt, ['KEYVALUE', 'VALUE.REFERENCE'])
return {attrs(tt)['NAME']: child}
def parse_keyvalue(tt):
##<!ELEMENT KEYVALUE (#PCDATA)>
##<!ATTLIST KEYVALUE
## VALUETYPE (string | boolean | numeric) "string"
## %CIMType; #IMPLIED>
"""Parse VALUETYPE into Python primitive value"""
check_node(tt, 'KEYVALUE', ['VALUETYPE'], ['TYPE'], [], True)
p = pcdata(tt)
if not 'VALUETYPE' in attrs(tt):
return p;
vt = attrs(tt).get('VALUETYPE')
if vt == 'string':
return p
elif vt == 'boolean':
return unpack_boolean(p)
elif vt == 'numeric':
try:
# XXX: Use TYPE attribute to create named CIM type.
# if attrs(tt).has_key('TYPE'):
# return cim_obj.tocimobj(attrs(tt)['TYPE'], p.strip())
# XXX: Would like to use long() here, but that tends to cause
# trouble when it's written back out as '2L'
return int(p.strip())
except ValueError as e:
raise ParseError('invalid numeric %s under %s' %
(repr(p), name(tt)))
else:
raise ParseError('invalid VALUETYPE %s in %s',
vt, name(tt))
#
# Object definition elements
#
def parse_class(tt):
## <!ELEMENT CLASS (QUALIFIER*, (PROPERTY | PROPERTY.ARRAY |
## PROPERTY.REFERENCE)*, METHOD*)>
## <!ATTLIST CLASS
## %CIMName;
## %SuperClass;>
# This doesn't check the ordering of elements, but it's not very important
check_node(tt, 'CLASS', ['NAME'], ['SUPERCLASS'],
['QUALIFIER', 'PROPERTY', 'PROPERTY.REFERENCE',
'PROPERTY.ARRAY', 'METHOD'])
superclass = attrs(tt).get('SUPERCLASS')
# TODO: Return these as maps, not lists
properties = cim_obj.byname(list_of_matching(tt, ['PROPERTY',
'PROPERTY.REFERENCE',
'PROPERTY.ARRAY']))
qualifiers = cim_obj.byname(list_of_matching(tt, ['QUALIFIER']))
methods = cim_obj.byname(list_of_matching(tt, ['METHOD']))
return CIMClass(attrs(tt)['NAME'],
superclass=superclass,
properties=properties,
qualifiers=qualifiers,
methods=methods)
def parse_instance(tt):
"""Return a CIMInstance.
The instance contains the properties, qualifiers and classname for
the instance"""
##<!ELEMENT INSTANCE (QUALIFIER*, (PROPERTY | PROPERTY.ARRAY |
## PROPERTY.REFERENCE)*)>
##<!ATTLIST INSTANCE
## %ClassName;>
check_node(tt, 'INSTANCE', ['CLASSNAME'],
['QUALIFIER', 'PROPERTY', 'PROPERTY.ARRAY',
'PROPERTY.REFERENCE'])
## XXX: This does not enforce ordering constraint
## XXX: This does not enforce the constraint that there be only
## one PROPERTY or PROPERTY.ARRAY.
## TODO: Parse instance qualifiers
qualifiers = {}
props = list_of_matching(tt, ['PROPERTY.REFERENCE', 'PROPERTY',
'PROPERTY.ARRAY'])
obj = CIMInstance(attrs(tt)['CLASSNAME'],
qualifiers=qualifiers)
[obj.__setitem__(p.name, p) for p in props]
return obj
def parse_scope(tt):
# <!ELEMENT SCOPE EMPTY>
# <!ATTLIST SCOPE
# CLASS (true | false) "false"
# ASSOCIATION (true | false) "false"
# REFERENCE (true | false) "false"
# PROPERTY (true | false) "false"
# METHOD (true | false) "false"
# PARAMETER (true | false) "false"
# INDICATION (true | false) "false"
check_node(tt, 'SCOPE', [],
['CLASS', 'ASSOCIATION', 'REFERENCE', 'PROPERTY', 'METHOD',
'PARAMETER', 'INDICATION'], [])
return dict([(k, v.lower() == 'true') for k, v in attrs(tt).items()])
def parse_qualifier_declaration(tt):
## <!ELEMENT QUALIFIER.DECLARATION (SCOPE?, (VALUE | VALUE.ARRAY)?)>
## <!ATTLIST QUALIFIER.DECLARATION
## %CIMName;
## %CIMType; #REQUIRED
## ISARRAY (true|false) #IMPLIED
## %ArraySize;
## %QualifierFlavor;>
check_node(tt, 'QUALIFIER.DECLARATION',
['NAME', 'TYPE'],
['ISARRAY', 'ARRAYSIZE', 'OVERRIDABLE', 'TOSUBCLASS',
'TOINSTANCE', 'TRANSLATABLE'],
['SCOPE', 'VALUE', 'VALUE.ARRAY'])
a = attrs(tt)
qname = a['NAME']
type = a['TYPE']
try:
is_array = a['ISARRAY'].lower() == 'true'
except KeyError:
is_array = False
try:
array_size = int(a['ARRAYSIZE'])
except KeyError:
array_size = None
flavors = {}
for f in ['OVERRIDABLE', 'TOSUBCLASS', 'TOINSTANCE', 'TRANSLATABLE']:
try:
flavors[f.lower()] = a[f].lower() == 'true'
except KeyError:
pass
scopes = None
value = None
for child in kids(tt):
if name(child) == 'SCOPE':
if scopes is not None:
raise ParseError("Multiple SCOPE tags encountered")
scopes = parse_any(child)
else:
if value is not None:
raise ParseError("Multiple VALUE/VALUE.ARRAY tags encountered")
value = cim_obj.tocimobj(type, parse_any(child))
return CIMQualifierDeclaration(qname, type, value, is_array,
array_size, scopes, **flavors)
def parse_qualifier(tt):
## <!ELEMENT QUALIFIER (VALUE | VALUE.ARRAY)>
## <!ATTLIST QUALIFIER %CIMName;
## %CIMType; #REQUIRED
## %Propagated;
## %QualifierFlavor;>
check_node(tt, 'QUALIFIER', ['NAME', 'TYPE'],
['OVERRIDABLE', 'TOSUBCLASS', 'TOINSTANCE',
'TRANSLATABLE', 'PROPAGATED'],
['VALUE', 'VALUE.ARRAY'])
a = attrs(tt)
q = CIMQualifier(a['NAME'], unpack_value(tt), type=a['TYPE'])
## TODO: Lift this out?
for i in ['OVERRIDABLE', 'TOSUBCLASS', 'TOINSTANCE',
'TRANSLATABLE', 'PROPAGATED']:
rv = a.get(i)
if rv not in ['true', 'false', None]:
raise ParseError("invalid value %s for %s on %s" %
(repr(rv), i, name(tt)))
if rv == 'true':
rv = True
elif rv == 'false':
rv = False
setattr(q, i.lower(), rv)
return q
def parse_property(tt):
"""Parse PROPERTY into a CIMProperty object.
VAL is just the pcdata of the enclosed VALUE node."""
## <!ELEMENT PROPERTY (QUALIFIER*, VALUE?)>
## <!ATTLIST PROPERTY %CIMName;
## %ClassOrigin;
## %Propagated;
## %CIMType; #REQUIRED>
## TODO: Parse this into NAME, VALUE, where the value contains
## magic fields for the qualifiers and the propagated flag.
check_node(tt, 'PROPERTY', ['TYPE', 'NAME'],
['NAME', 'CLASSORIGIN', 'PROPAGATED', 'EmbeddedObject',
'EMBEDDEDOBJECT'],
['QUALIFIER', 'VALUE'])
quals = {}
for q in list_of_matching(tt, ['QUALIFIER']):
quals[q.name] = q
val = unpack_value(tt)
a = attrs(tt)
embedded_object = None
if 'EmbeddedObject' in a or 'EMBEDDEDOBJECT' in a:
try:
embedded_object = a['EmbeddedObject']
except KeyError:
embedded_object = a['EMBEDDEDOBJECT']
if embedded_object is not None:
val = parse_embeddedObject(val)
return CIMProperty(a['NAME'],
val,
a['TYPE'],
class_origin=a.get('CLASSORIGIN'),
propagated=unpack_boolean(a.get('PROPAGATED')),
qualifiers=quals,
embedded_object=embedded_object)
def parse_property_array(tt):
"""
<!ELEMENT PROPERTY.ARRAY (QUALIFIER*, VALUE.ARRAY?)>
<!ATTLIST PROPERTY.ARRAY %CIMName;
%CIMType; #REQUIRED
%ArraySize;
%ClassOrigin;
%Propagated;>
"""
check_node(tt, 'PROPERTY.ARRAY', ['NAME', 'TYPE'],
['REFERENCECLASS', 'CLASSORIGIN', 'PROPAGATED',
'ARRAYSIZE', 'EmbeddedObject', 'EMBEDDEDOBJECT'],
['QUALIFIER', 'VALUE.ARRAY'])
quals = {}
for q in list_of_matching(tt, ['QUALIFIER']):
quals[q.name] = q
values = unpack_value(tt)
a = attrs(tt)
embedded_object = None
if 'EmbeddedObject' in a or 'EMBEDDEDOBJECT' in a:
try:
embedded_object = a['EmbeddedObject']
except KeyError:
embedded_object = a['EMBEDDEDOBJECT']
if embedded_object is not None:
values = parse_embeddedObject(values)
obj = CIMProperty(a['NAME'],
values,
a['TYPE'],
class_origin=a.get('CLASSORIGIN'),
qualifiers=quals,
is_array=True,
embedded_object=embedded_object)
## TODO: qualifiers, other attributes
return obj
def parse_property_reference(tt):
"""
<!ELEMENT PROPERTY.REFERENCE (QUALIFIER*, (VALUE.REFERENCE)?)>
<!ATTLIST PROPERTY.REFERENCE
%CIMName;
%ReferenceClass;
%ClassOrigin;
%Propagated;>
"""
check_node(tt, 'PROPERTY.REFERENCE', ['NAME'],
['REFERENCECLASS', 'CLASSORIGIN', 'PROPAGATED'])
value = list_of_matching(tt, ['VALUE.REFERENCE'])
if value is None or len(value) == 0:
value = None
elif len(value) == 1:
value = value[0]
else:
raise ParseError('Too many VALUE.REFERENCE elements.')
attributes = attrs(tt)
pref = CIMProperty(attributes['NAME'], value, _type='reference')
for q in list_of_matching(tt, ['QUALIFIER']):
pref.qualifiers[q.name] = q
if 'REFERENCECLASS' in attributes:
pref.reference_class = attributes['REFERENCECLASS']
if 'CLASSORIGIN' in attributes:
pref.class_origin = attributes['CLASSORIGIN']
if 'PROPAGATED' in attributes:
pref.propagated = attributes['PROPAGATED']
return pref
def parse_method(tt):
"""
<!ELEMENT METHOD (QUALIFIER*, (PARAMETER | PARAMETER.REFERENCE |
PARAMETER.ARRAY | PARAMETER.REFARRAY)*)>
<!ATTLIST METHOD %CIMName;
%CIMType; #IMPLIED
%ClassOrigin;
%Propagated;>
"""
check_node(tt, 'METHOD', ['NAME'],
['TYPE', 'CLASSORIGIN', 'PROPAGATED'],
['QUALIFIER', 'PARAMETER', 'PARAMETER.REFERENCE',
'PARAMETER.ARRAY', 'PARAMETER.REFARRAY'])
qualifiers = cim_obj.byname(list_of_matching(tt, ['QUALIFIER']))