/
cim_obj.py
1521 lines (1134 loc) · 47.3 KB
/
cim_obj.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-2007 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: Tim Potter <tpot@hp.com>
# Martin Pool <mbp@hp.com>
# Bart Whiteley <bwhiteley@suse.de>
import string, re
import cim_xml, cim_types
from types import StringTypes
from cim_types import atomic_to_cim_xml, CIMDateTime
from cim_xml import *
from datetime import datetime, timedelta
"""
Representations of CIM Objects.
In general we try to map CIM objects directly into Python primitives,
except when that is not possible or would be ambiguous. For example,
CIM Class names are simply Python strings, but a ClassPath is
represented as a special Python object.
These objects can also be mapped back into XML, by the toxml() method
which returns a string.
"""
class NocaseDict(object):
"""Yet another implementation of a case-insensitive dictionary."""
def __init__(self, *args, **kwargs):
self.data = {}
# Initialise from sequence object
if len(args) == 1 and type(args[0]) == list:
for item in args[0]:
self[item[0]] = item[1]
# Initialise from mapping object
if len(args) == 1 and type(args[0]) == dict:
self.update(args[0])
# Initialise from NocaseDict
if len(args) == 1 and isinstance(args[0], NocaseDict):
self.data = args[0].data.copy()
# Initialise from keyword args
self.update(kwargs)
# Basic accessor and settor methods
def __getitem__(self, key):
k = key
if isinstance(key, (str, unicode)):
k = key.lower()
try:
return self.data[k][1]
except KeyError, arg:
raise KeyError, key
def __setitem__(self, key, value):
if not isinstance(key, (str, unicode)):
raise KeyError, 'Key must be string type'
k = key.lower()
self.data[k] = (key, value)
def __delitem__(self, key):
k = key
if isinstance(key, (str, unicode)):
k = key.lower()
del self.data[k]
def __len__(self):
return len(self.data)
def has_key(self, key):
k = key
if isinstance(key, (str, unicode)):
k = key.lower()
return self.data.has_key(k)
def __contains__(self, key):
k = key
if isinstance(key, (str, unicode)):
k = key.lower()
return k in self.data
def get(self, key, default = None):
try:
return self[key]
except KeyError:
return default
def setdefault(self, key, default):
if not self.has_key(key):
self[key] = default
return self[key]
# Other accessor expressed in terms of iterators
def keys(self):
return list(self.iterkeys())
def values(self):
return list(self.itervalues())
def items(self):
return list(self.iteritems())
# Iterators
def iterkeys(self):
for item in self.data.iteritems():
yield item[1][0]
def itervalues(self):
for item in self.data.iteritems():
yield item[1][1]
def iteritems(self):
for item in self.data.iteritems():
yield item[1]
# Other stuff
def __repr__(self):
items = ', '.join([('%r: %r' % (key, value))
for key, value in self.items()])
return 'NocaseDict({%s})' % items
def update(self, *args, **kwargs):
for mapping in args:
if hasattr(mapping, 'items'):
for k, v in mapping.items():
self[k] = v
else:
for (k, v) in mapping:
self[k] = v
for k, v in kwargs.items():
self[k] = v
def clear(self):
self.data.clear()
def popitem(self):
pass
def copy(self):
result = NocaseDict()
result.data = self.data.copy()
return result
def __eq__(self, other):
for key, value in self.iteritems():
if not (key in other) or not (other[key] == value):
return 0
return len(self) == len(other)
def __cmp__(self, other):
for key, value in self.iteritems():
if not (key in other):
return -1
rv = cmp(value, other[key])
if rv != 0:
return rv
return len(self) - len(other)
def cmpname(name1, name2):
"""Compare to CIM names. The comparison is done
case-insensitvely, and one or both of the names may be None."""
if name1 is None and name2 is None:
return 0
if name1 is None:
return -1
if name2 is None:
return 1
lower_name1 = name1.lower()
lower_name2 = name2.lower()
return cmp(lower_name1, lower_name2)
class CIMClassName(object):
def __init__(self, classname, host = None, namespace = None):
if not isinstance(classname, StringTypes):
raise TypeError('classname argument must be a string')
# TODO: There are some odd restrictions on what a CIM
# classname can look like (i.e must start with a
# non-underscore and only one underscore per classname).
self.classname = classname
self.host = host
self.namespace = namespace
def copy(self):
return CIMClassName(self.classname, host = self.host,
namespace = self.namespace)
def __cmp__(self, other):
if self is other:
return 0
elif not isinstance(other, CIMClassName):
return 1
return (cmpname(self.classname, other.classname) or
cmpname(self.host, other.host) or
cmpname(self.namespace, other.namespace))
def __str__(self):
s = ''
if self.host is not None:
s += '//%s/' % self.host
if self.namespace is not None:
s += '%s:' % self.namespace
s += self.classname
return s
def __repr__(self):
r = '%s(classname=%s' % (self.__class__.__name__, `self.classname`)
if self.host is not None:
r += ', host=%s' % `self.host`
if self.namespace is not None:
r += ', namespace=%s' % `self.namespace`
r += ')'
return r
def tocimxml(self):
classname = cim_xml.CLASSNAME(self.classname)
if self.namespace is not None:
localnsp = cim_xml.LOCALNAMESPACEPATH(
[cim_xml.NAMESPACE(ns)
for ns in string.split(self.namespace, '/')])
if self.host is not None:
# Classname + namespace + host = CLASSPATH
return cim_xml.CLASSPATH(
cim_xml.NAMESPACEPATH(cim_xml.HOST(self.host), localnsp),
classname)
# Classname + namespace = LOCALCLASSPATH
return cim_xml.LOCALCLASSPATH(localnsp, classname)
# Just classname = CLASSNAME
return cim_xml.CLASSNAME(self.classname)
class CIMProperty(object):
"""A property of a CIMInstance.
Property objects represent both properties on particular instances,
and the property defined in a class. In the first case, the property
will have a Value and in the second it will not.
The property may hold an array value, in which case it is encoded
in XML to PROPERTY.ARRAY containing VALUE.ARRAY."""
def __init__(self, name, value, type = None,
class_origin = None, array_size = None, propagated = None,
is_array = False, reference_class = None, qualifiers = {},
embedded_object = None):
# Initialise members
self.name = name
self.value = value
self.type = type
self.class_origin = class_origin
self.array_size = array_size
self.propagated = propagated
self.qualifiers = NocaseDict(qualifiers)
self.is_array = is_array
self.reference_class = reference_class
self.embedded_object = embedded_object
if isinstance(value, (datetime, timedelta)):
value = CIMDateTime(value)
import __builtin__
if __builtin__.type(value) == list:
self.is_array = True
# Determine type of value if not specified
if type is None:
# Can't work out what is going on if type and value are
# both not set.
if value is None:
raise TypeError('Null property "%s" must have a type' % name)
if self.is_array:
# Determine type for list value
if len(value) == 0:
raise TypeError(
'Empty property array "%s" must have a type' % name)
elif isinstance(value[0], CIMInstance):
self.type = 'string'
self.embedded_object = 'instance'
elif isinstance(value[0], CIMClass):
self.type = 'string'
self.embedded_object = 'object'
else:
self.type = cim_types.cimtype(value[0])
elif isinstance(value, CIMInstanceName):
self.type = 'reference'
elif isinstance(value, CIMInstance):
self.type = 'string'
self.embedded_object = 'instance'
elif isinstance(value, CIMClass):
self.type = 'string'
self.embedded_object = 'object'
else:
# Determine type for regular value
self.type = cim_types.cimtype(value)
def copy(self):
return CIMProperty(self.name,
self.value,
type = self.type,
class_origin = self.class_origin,
array_size = self.array_size,
propagated = self.propagated,
is_array = self.is_array,
reference_class = self.reference_class,
qualifiers = self.qualifiers.copy())
def __repr__(self):
return '%s(name=%s, type=%s, value=%s, is_array=%s)' % \
(self.__class__.__name__, `self.name`, `self.type`,
`self.value`, `self.is_array`)
def tocimxml(self):
if self.is_array:
value = self.value
if value is not None:
if value:
if self.embedded_object is not None:
value = [v.tocimxml().toxml() for v in value]
value = VALUE_ARRAY([VALUE(atomic_to_cim_xml(v)) for v in value])
return PROPERTY_ARRAY(
self.name,
self.type,
value,
self.array_size,
self.class_origin,
self.propagated,
qualifiers = [q.tocimxml() for q in self.qualifiers.values()],
embedded_object = self.embedded_object)
elif self.type == 'reference':
value_reference = None
if self.value is not None:
value_reference = VALUE_REFERENCE(self.value.tocimxml())
return PROPERTY_REFERENCE(
self.name,
value_reference,
reference_class = self.reference_class,
class_origin = self.class_origin,
propagated = self.propagated,
qualifiers = [q.tocimxml() for q in self.qualifiers.values()])
else:
value = self.value
if value is not None:
if self.embedded_object is not None:
value = value.tocimxml().toxml()
else:
value = atomic_to_cim_xml(value)
value = VALUE(value)
return PROPERTY(
self.name,
self.type,
value,
class_origin = self.class_origin,
propagated = self.propagated,
qualifiers = [q.tocimxml() for q in self.qualifiers.values()],
embedded_object = self.embedded_object)
def __cmp__(self, other):
if self is other:
return 0
elif not isinstance(other, self.__class__):
return 1
return (cmpname(self.name, other.name)
or cmp(self.value, other.value)
or cmp(self.type, other.type)
or cmp(self.class_origin, other.class_origin)
or cmp(self.array_size, other.array_size)
or cmp(self.propagated, other.propagated)
or cmp(self.qualifiers, other.qualifiers)
or cmp(self.is_array, other.is_array)
or cmpname(self.reference_class, other.reference_class))
class CIMInstanceName(object):
"""Name (keys) identifying an instance.
This may be treated as a dictionary to retrieve the keys."""
def __init__(self, classname, keybindings = {}, host = None,
namespace = None):
self.classname = classname
self.keybindings = NocaseDict(keybindings)
self.host = host
self.namespace = namespace
def copy(self):
result = CIMInstanceName(self.classname)
result.keybindings = self.keybindings.copy()
result.host = self.host
result.namespace = self.namespace
return result
def __cmp__(self, other):
if self is other:
return 0
elif not isinstance(other, CIMInstanceName):
return 1
return (cmpname(self.classname, other.classname) or
cmp(self.keybindings, other.keybindings) or
cmpname(self.host, other.host) or
cmpname(self.namespace, other.namespace))
def __str__(self):
s = ''
if self.host is not None:
s += '//%s/' % self.host
if self.namespace is not None:
s += '%s:' % self.namespace
s += '%s.' % self.classname
for key, value in self.keybindings.items():
s +='%s=' % key
if type(value) == int or type(value) == long:
s += str(value)
else:
s += '"%s"' % value
s += ','
return s[:-1]
def __repr__(self):
r = '%s(classname=%s, keybindings=%s' % \
(self.__class__.__name__,
`self.classname`,
`self.keybindings`)
if self.host is not None:
r += ', host=%s' % `self.host`
if self.namespace is not None:
r += ', namespace=%s' % `self.namespace`
r += ')'
return r
# A whole bunch of dictionary methods that map to the equivalent
# operation on self.keybindings.
def __getitem__(self, key): return self.keybindings[key]
def __contains__(self, key): return key in self.keybindings
def __delitem__(self, key): del self.keybindings[key]
def __setitem__(self, key, value): self.keybindings[key] = value
def __len__(self): return len(self.keybindings)
def has_key(self, key): return self.keybindings.has_key(key)
def keys(self): return self.keybindings.keys()
def values(self): return self.keybindings.values()
def items(self): return self.keybindings.items()
def iterkeys(self): return self.keybindings.iterkeys()
def itervalues(self): return self.keybindings.itervalues()
def iteritems(self): return self.keybindings.iteritems()
def update(self, *args, **kwargs): self.keybindings.update(*args, **kwargs)
def tocimxml(self):
# Generate an XML representation of the instance classname and
# keybindings.
if type(self.keybindings) == str:
# Class with single key string property
instancename_xml = cim_xml.INSTANCENAME(
self.classname,
cim_xml.KEYVALUE(self.keybindings, 'string'))
elif isinstance(self.keybindings, (long, float, int)):
# Class with single key numeric property
instancename_xml = cim_xml.INSTANCENAME(
self.classname,
cim_xml.KEYVALUE(str(self.keybindings), 'numeric'))
elif isinstance(self.keybindings, (dict, NocaseDict)):
# Dictionary of keybindings
# NOCASE_TODO should remove dict below.
kbs = []
for kb in self.keybindings.items():
# Keybindings can be integers, booleans, strings or
# value references.
if hasattr(kb[1], 'tocimxml'):
kbs.append(cim_xml.KEYBINDING(
kb[0],
cim_xml.VALUE_REFERENCE(kb[1].tocimxml())))
continue
if type(kb[1]) == bool:
_type = 'boolean'
if kb[1]:
value = 'TRUE'
else:
value = 'FALSE'
elif isinstance(kb[1], (long, float, int)):
# pywbem.cim_type.{Sint32, Real64, ... } derive from
# long or float
_type = 'numeric'
value = str(kb[1])
elif type(kb[1]) == str or type(kb[1]) == unicode:
_type = 'string'
value = kb[1]
else:
raise TypeError(
'Invalid keybinding type for keybinding ' '%s: %s' % (kb[0],`type(kb[1])`))
kbs.append(cim_xml.KEYBINDING(
kb[0],
cim_xml.KEYVALUE(value, _type)))
instancename_xml = cim_xml.INSTANCENAME(self.classname, kbs)
else:
# Value reference
instancename_xml = cim_xml.INSTANCENAME(
self.classname,
cim_xml.VALUE_REFERENCE(self.keybindings.tocimxml()))
# Instance name plus namespace = LOCALINSTANCEPATH
if self.host is None and self.namespace is not None:
return cim_xml.LOCALINSTANCEPATH(
cim_xml.LOCALNAMESPACEPATH(
[cim_xml.NAMESPACE(ns)
for ns in string.split(self.namespace, '/')]),
instancename_xml)
# Instance name plus host and namespace = INSTANCEPATH
if self.host is not None and self.namespace is not None:
return cim_xml.INSTANCEPATH(
cim_xml.NAMESPACEPATH(
cim_xml.HOST(self.host),
cim_xml.LOCALNAMESPACEPATH([
cim_xml.NAMESPACE(ns)
for ns in string.split(self.namespace, '/')])),
instancename_xml)
# Just a regular INSTANCENAME
return instancename_xml
class CIMInstance(object):
"""Instance of a CIM Object.
Has a classname (string), and named arrays of properties and qualifiers.
The properties is indexed by name and points to CIMProperty
instances."""
def __init__(self, classname, properties = {}, qualifiers = {},
path = None, property_list = None):
"""Create CIMInstance.
bindings is a concise way to initialize property values;
it is a dictionary from property name to value. This is
merely a convenience and gets the same result as the
properties parameter.
properties is a list of full CIMProperty objects. """
self.classname = classname
self.qualifiers = NocaseDict(qualifiers)
self.path = path
if property_list is not None:
self.property_list = [x.lower() for x in property_list]
else:
self.property_list = None
# Assign initialised property values and run through
# __setitem__ to enforce CIM types for each property.
self.properties = NocaseDict()
[self.__setitem__(k, v) for k, v in properties.items()]
def update(self, *args, **kwargs):
"""D.update(E, **F) -> None.
Update D from E and F: for k in E: D[k] = E[k]
(if E has keys else: for (k, v) in E: D[k] = v)
then: for k in F: D[k] = F[k] """
for mapping in args:
if hasattr(mapping, 'items'):
for k, v in mapping.items():
self[k] = v
else:
for (k, v) in mapping:
self[k] = v
for k, v in kwargs.items():
self[k] = v
def update_existing(self, *args, **kwargs):
"""Update property values iff the property previously exists.
Update D from E and F: for k in E: D[k] = E[k]
(if E has keys else: for (k, v) in E: D[k] = v)
then: for k in F: D[k] = F[k]
Like update, but properties that are not already present in the
instance are skipped. """
for mapping in args:
if hasattr(mapping, 'items'):
for k, v in mapping.items():
try:
prop = self.properties[k]
except KeyError:
continue
prop.value = tocimobj(prop.type, v)
else:
for (k, v) in mapping:
try:
prop = self.properties[k]
except KeyError:
continue
prop.value = tocimobj(prop.type, v)
for k, v in kwargs.items():
try:
prop = self.properties[k]
except KeyError:
continue
prop.value = tocimobj(prop.type, v)
def copy(self):
result = CIMInstance(self.classname)
result.properties = self.properties.copy()
result.qualifiers = self.qualifiers.copy()
result.path = (self.path is not None and [self.path.copy()] or [None])[0]
return result
def __cmp__(self, other):
if self is other:
return 0
elif not isinstance(other, CIMInstance):
return 1
return (cmpname(self.classname, other.classname) or
cmp(self.path, other.path) or
cmp(self.properties, other.properties) or
cmp(self.qualifiers, other.qualifiers))
def __repr__(self):
# Don't show all the properties and qualifiers because they're
# just too big
return '%s(classname=%s, ...)' % (self.__class__.__name__,
`self.classname`)
# A whole bunch of dictionary methods that map to the equivalent
# operation on self.properties.
def __contains__(self, key):
return key in self.properties
def __getitem__(self, key):
return self.properties[key].value
def __delitem__(self, key):
del self.properties[key]
def __len__(self):
return len(self.properties)
def has_key(self, key):
return self.properties.has_key(key)
def keys(self):
return self.properties.keys()
def values(self):
return [v.value for v in self.properties.values()]
def items(self):
return [(k, v.value) for k, v in self.properties.items()]
def iterkeys(self):
return self.properties.iterkeys()
def itervalues(self):
for k, v in self.properties.iteritems():
yield v.value
def iteritems(self):
for k, v in self.properties.iteritems():
yield (k, v.value)
def __setitem__(self, key, value):
# Don't let anyone set integer or float values. You must use
# a subclass from the cim_type module.
if type(value) == int or type(value) == float or type(value) == long:
raise TypeError('Must use a CIM type assigning numeric values.')
if self.property_list is not None and key.lower() not in \
self.property_list:
if self.path is not None and key not in self.path.keybindings:
return
# Convert value to appropriate PyWBEM type
if isinstance(value, CIMProperty):
v = value
else:
v = CIMProperty(key, value)
self.properties[key] = v
if self.path is not None and key in self.path.keybindings:
self.path[key] = v.value
def tocimxml(self):
props = []
for key, value in self.properties.items():
# Value has already been converted into a CIM object
# property type (e.g for creating null property values).
if isinstance(value, CIMProperty):
props.append(value)
continue
props.append(CIMProperty(key, value))
instance_xml = cim_xml.INSTANCE(
self.classname,
properties = [p.tocimxml() for p in props],
qualifiers = [q.tocimxml() for q in self.qualifiers.values()])
if self.path is None:
return instance_xml
return cim_xml.VALUE_NAMEDINSTANCE(self.path.tocimxml(),
instance_xml)
def tomof(self):
def _prop2mof(_type, value):
if value is None:
val = 'NULL'
elif isinstance(value, list):
val = '{'
for i,x in enumerate(value):
if i > 0:
val += ', '
val += _prop2mof(_type, x)
val += '}'
elif _type == 'string':
val = '"' + value + '"'
else:
val = str(value)
return val
s = 'instance of %s {\n' % self.classname
for p in self.properties.values():
s+= '\t%s = %s;\n' % (p.name, _prop2mof(p.type, p.value))
s+= '};\n'
return s
class CIMClass(object):
def __init__(self, classname, properties = {}, methods = {},
superclass = None, qualifiers = {}):
self.classname = classname
self.properties = NocaseDict(properties)
self.qualifiers = NocaseDict(qualifiers)
self.methods = NocaseDict(methods)
self.superclass = superclass
def copy(self):
result = CIMClass(self.classname)
result.properties = self.properties.copy()
result.methods = self.methods.copy()
result.superclass = self.superclass
result.qualifiers = self.qualifiers.copy()
return result
def __repr__(self):
return "%s(%s, ...)" % (self.__class__.__name__, `self.classname`)
def __cmp__(self, other):
if self is other:
return 0
elif not isinstance(other, CIMClass):
return 1
return (cmpname(self.classname, other.classname)
or cmpname(self.superclass, other.superclass)
or cmp(self.properties, other.properties)
or cmp(self.qualifiers, other.qualifiers)
or cmp(self.methods, other.methods))
def tocimxml(self):
return cim_xml.CLASS(
self.classname,
properties = [p.tocimxml() for p in self.properties.values()],
methods = [m.tocimxml() for m in self.methods.values()],
qualifiers = [q.tocimxml() for q in self.qualifiers.values()],
superclass = self.superclass)
def tomof(self):
def _makequalifiers(qualifiers, indent):
"""Return a mof fragment for a NocaseDict of qualifiers."""
if len(qualifiers) == 0:
return ''
return '[%s]' % ',\n '.ljust(indent+2).join([q.tomof() for q in qualifiers.values()])
# Class definition
s = ' %s\n' % _makequalifiers(self.qualifiers, 4)
s += 'class %s ' % self.classname
# Superclass
if self.superclass is not None:
s += ': %s ' % self.superclass
s += '{\n'
# Properties
for p in self.properties.values():
s += ' %s\n' % (_makequalifiers(p.qualifiers, 7))
s += ' %s %s;\n' % (p.type, p.name)
# Methods
for m in self.methods.values():
s += ' %s\n' % (_makequalifiers(m.qualifiers, 7))
s += ' %s\n' % m.tomof()
s += '};\n'
return s
class CIMMethod(object):
def __init__(self, methodname, return_type = None, parameters = {},
class_origin = None, propagated = False, qualifiers = {}):
self.name = methodname
self.return_type = return_type
self.parameters = NocaseDict(parameters)
self.class_origin = class_origin
self.propagated = propagated
self.qualifiers = NocaseDict(qualifiers)
def copy(self):
result = CIMMethod(self.name,
return_type = self.return_type,
class_origin = self.class_origin,
propagated = self.propagated)
result.parameters = self.parameters.copy()
result.qualifiers = self.qualifiers.copy()
return result
def tocimxml(self):
return cim_xml.METHOD(
self.name,
parameters = [p.tocimxml() for p in self.parameters.values()],
return_type = self.return_type,
class_origin = self.class_origin,
propagated = self.propagated,
qualifiers = [q.tocimxml() for q in self.qualifiers.values()])
def __repr__(self):
return '%s(name=%s, return_type=%s...)' % \
(self.__class__.__name__, `self.name`, `self.return_type`)
def __cmp__(self, other):
if self is other:
return 0
elif not isinstance(other, CIMMethod):
return 1
return (cmpname(self.name, other.name) or
cmp(self.parameters, other.parameters) or
cmp(self.qualifiers, other.qualifiers) or
cmp(self.class_origin, other.class_origin) or
cmp(self.propagated, other.propagated) or
cmp(self.return_type, other.return_type))