-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcim_obj.py
2259 lines (1764 loc) · 76.9 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 <[email protected]>
# Martin Pool <[email protected]>
# Bart Whiteley <[email protected]>
# Ross Peoples <[email protected]>
"""
Representations of CIM objects, and a case-insensitive dictionary.
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 class path is
represented as a special Python object.
These objects can also be mapped back into CIM-XML, by their `tocimxml()`
method which returns a CIM-XML string.
"""
# This module is meant to be safe for 'import *'.
from datetime import datetime, timedelta
from . import cim_xml, cim_types
import six
if six.PY3:
def cmp(a, b):
"""
Backwards-compatible compare method for PY3
"""
return (a > b) - (a < b)
else:
cmp = cmp
class NocaseDict(object):
"""
Yet another implementation of a case-insensitive dictionary.
Whenever keys are looked up, that is done case-insensitively. Whenever
keys are returned, they are returned with the lexical case that was
originally specified.
In addition to the methods listed, the dictionary supports:
* Retrieval of values based on key: `val = d[key]`
* Assigning values for a key: `d[key] = val`
* Deleting a key/value pair: `del d[key]`
* Equality comparison (`==`, `!=`)
* Ordering comparison (`<`, `<=`, `>=`, `>`)
* Containment test: `key in d`
* For loops: `for key in d`
* Determining length: `len(d)`
"""
def __init__(self, *args, **kwargs):
"""
Initialize the new dictionary from at most one positional argument and
optionally from additional keyword arguments.
Initialization happens in two steps, first from the positional
argument:
* If no positional argument is provided, or if one argument with the
value None is provided, the new dictionary will be left empty in
this step.
* If one positional argument of sequence type is provided, the items
in that sequence must be tuples of key and value, respectively.
The key/value pairs will be put into the new dictionary (without
copying them).
* If one positional argument of dictionary (mapping) or `NocaseDict`
type is provided, its key/value pairs are put into the new
dictionary (without copying them).
* Otherwise, `TypeError` is raised.
After that, any provided keyword arguments are put into the so
initialized dictionary as key/value pairs (without copying them).
"""
self._data = {}
# Step 1: Initialize from at most one positional argument
if len(args) == 1:
if isinstance(args[0], list):
# Initialize from sequence object
for item in args[0]:
self[item[0]] = item[1]
elif isinstance(args[0], dict):
# Initialize from mapping object
self.update(args[0])
elif isinstance(args[0], NocaseDict):
# Initialize from another NocaseDict object
self._data = args[0]._data.copy() # pylint: disable=protected-access
elif args[0] is None:
# Leave empty
pass
else:
raise TypeError("Invalid type for NocaseDict " \
"initialization: %s" % repr(args[0]))
elif len(args) > 1:
raise TypeError("Too many positional arguments for NocaseDict " \
"initialization: %s" % repr(args))
# Step 2: Add any keyword arguments
self.update(kwargs)
# Basic accessor and settor methods
def __getitem__(self, key):
"""
Invoked when retrieving the value for a key, using `val = d[key]`.
The key is looked up case-insensitively. Raises `KeyError` if the
specified key does not exist. Note that __setitem__() ensures that
only string typed keys will exist, so the key type is not tested here
and specifying non-string typed keys will simply lead to a KeyError.
"""
k = key
if isinstance(key, (str, six.string_types)):
k = k.lower()
try:
return self._data[k][1]
except KeyError:
raise KeyError('Key %s not found in %r' % (key, self))
def __setitem__(self, key, value):
"""
Invoked when assigning a value for a key using `d[key] = val`.
The key is looked up case-insensitively. If the key does not exist,
it is added with the new value. Otherwise, its value is overwritten
with the new value.
Raises `TypeError` if the specified key does not have string type.
"""
if not isinstance(key, (str, six.string_types)):
raise TypeError('NocaseDict key %s must be string type, ' \
'but is %s' % (key, type(key)))
k = key.lower()
self._data[k] = (key, value)
def __delitem__(self, key):
"""
Invoked when deleting a key/value pair using `del d[key]`.
The key is looked up case-insensitively. Raises `KeyError` if the
specified key does not exist. Note that __setitem__() ensures that
only string typed keys will exist, so the key type is not tested here
and specifying non-string typed keys will simply lead to a KeyError.
"""
k = key
if isinstance(key, (str, six.string_types)):
k = k.lower()
try:
del self._data[k]
except KeyError:
raise KeyError('Key %s not found in %r' % (key, self))
def __len__(self):
"""
Invoked when determining the number of key/value pairs in the
dictionary using `len(d)`.
"""
return len(self._data)
def has_key(self, key):
"""
Return a boolean indicating whether a specific key is in the
dictionary.
The key is looked up case-insensitively.
This method is deprecated in favor of using `key in d`.
"""
return self.__contains__(key)
def __contains__(self, key):
"""
Invoked when determining whether a specific key is in the dictionary
using `key in d`.
The key is looked up case-insensitively.
"""
k = key
if isinstance(key, (str, six.string_types)):
k = k.lower()
return k in self._data
def get(self, key, default=None):
"""
Get the value for a specific key, or the specified default value if
the key does not exist.
The key is looked up case-insensitively.
"""
try:
return self[key]
except KeyError:
return default
def setdefault(self, key, default):
"""
Assign the specified default value for a specific key if the key did
not exist and return the value for the key.
The key is looked up case-insensitively.
"""
if not key in self:
self[key] = default
return self[key]
# Other accessor expressed in terms of iterators
def keys(self):
"""
Return a copied list of the dictionary keys, in their original case.
"""
return [v[0] for v in sorted(self._data.values())]
def values(self):
"""
Return a copied list of the dictionary values.
"""
return [v[0] for v in sorted(self._data.values())]
def items(self):
"""
Return a copied list of the dictionary items, where each item is a
tuple of its original key and its value.
"""
return list(self._data.values())
# Iterators
def iterkeys(self):
"""
Return an iterator through the dictionary keys in their original
case.
"""
for item in self._data.items():
yield item[1][0]
def itervalues(self):
"""
Return an iterator through the dictionary values.
"""
for item in self._data.items():
yield item[1][1]
def iteritems(self):
"""
Return an iterator through the dictionary items, where each item is a
tuple of its original key and its value.
"""
for item in self._data.items():
yield item[1]
def __iter__(self):
"""
Invoked when iterating through the dictionary using `for key in d`.
The returned keys have their original case.
"""
return self._data.keys()
# Other stuff
def __repr__(self):
"""
Invoked when using `repr(d)`.
The representation hides the implementation data structures and shows
a dictionary that can be used for the constructor.
"""
items = ', '.join([('%r: %r' % (key, value))
for key, value in self.items()])
return 'NocaseDict({%s})' % items
def update(self, *args, **kwargs):
"""
Update the dictionary from sequences of key/value pairs provided in any
positional arguments, and from key/value pairs provided in any keyword
arguments. The key/value pairs are not copied.
Each positional argument can be:
* an object with a method `items()` that returns an iterable of
tuples containing key and value.
* an object without such a method, that is an iterable of tuples
containing key and value.
Each keyword argument is a key/value pair.
"""
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):
"""
Remove all items from the dictionary.
"""
self._data.clear()
def popitem(self):
"""
This function does nothing.
In a standard mapping implementation, it would remove and return an
arbitrary item from the dictionary.
TODO: Why does popitem() do nothing; was it simply not implemented?
"""
pass
def copy(self):
"""
Return a shallow copy of the dictionary (i.e. the keys and values are
not copied).
"""
result = NocaseDict()
result._data = self._data.copy() # pylint: disable=protected-access
return result
def __eq__(self, other):
"""
Invoked when two dictionaries are compared for equality or inequality.
The keys are looked up case-insensitively.
The comparison is delegated to equality comparison of matching
key/value pairs.
"""
for key, value in self.items():
if not key in other or not other[key] == value:
return 0
return len(self) == len(other)
def __cmp__(self, other):
"""
Invoked when two dictionaries are compared for equality, inequality,
and greater-than/less-than comparisons.
The keys are looked up case-insensitively.
`Self` is less than `other`, if:
* a key in `self` is not in `other`, or
* the value for a key in `self` is less than the value for that key
in `other`, or
* `self` has less key/value pairs than `other`.
"""
for key, value in self.items():
if not key in other:
return -1
rv = value == other[key]
if rv != 0:
return rv
return len(self) - len(other)
def _intended_value(intended, unspecified, actual, name, msg):
"""
Return the intended value if the actual value is unspecified or has
the intended value already, and otherwise raise a ValueError with the
specified error message.
Arguments:
* `intended`: The intended value, or sequence of values. The first
item in the sequence will act as the intended value, the others
are also valid values.
* `unspecified`: A value indicating 'unspecified' (usually `None`).
* `actual`: The actual value.
* `name`: The name of the attribute that this is about, for use in the
exception message.
* `msg`: A context setting message, for use in the exception message.
"""
if isinstance(intended, (tuple, list)):
if actual == unspecified:
return intended[0] # the default
elif actual in intended:
return actual
else:
raise ValueError(msg + ", but specifies %s=%r (must be one of %r)"\
% (name, actual, intended))
else:
if actual == unspecified:
return intended
elif actual == intended:
return actual
else:
raise ValueError(msg + ", but specifies %s=%r (must be %r)"\
% (name, actual, intended))
def cmpname(name1, name2):
"""
Compare two CIM names. The comparison is done
case-insensitively, 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 lower_name1 == lower_name2
class CIMClassName(object):
"""
A CIM class path.
A CIM class path references a CIM class in a namespace in a WBEM server.
Namespace and WBEM server may be unknown.
:Ivariables:
...
All parameters of `__init__` are set as instance variables.
"""
def __init__(self, classname, host=None, namespace=None):
"""
Initialize the `CIMClassName` object.
:Parameters:
classname : `unicode` or UTF-8 encoded `str`
Name of the referenced class.
host : `unicode` or UTF-8 encoded `str`
Optional: URL of the WBEM server that contains the CIM namespace
of this class path.
If `None`, the class path will not specify a WBEM server.
Default: `None`.
namespace : `unicode` or UTF-8 encoded `str`
Optional: Name of the CIM namespace that contains the referenced
class.
If `None`, the class path will not specify a CIM namespace.
Default: `None`.
:Raises:
:raise TypeError:
:raise ValueError:
"""
if not isinstance(classname, six.string_types):
raise TypeError('classname argument has an invalid type: %s '\
'(expected string)' % type(classname))
# 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=%r' % (self.__class__.__name__, self.classname)
if self.host is not None:
r += ', host=%r' % self.host
if self.namespace is not None:
r += ', namespace=%r' % 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 self.namespacec.split('/')])
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 CIM property.
The property can be used in a CIM instance (as part of a `CIMInstance`
object) or in a CIM class (as part of a `CIMClass` object).
For properties in CIM instances:
* The `value` instance variable is the actual value of the property.
* Qualifiers are not allowed.
For properties in CIM classes:
* The `value` instance variable is the default value for the property.
* Qualifiers are allowed.
Scalar (=non-array) properties may have a value of NULL (= `None`), any
primitive CIM type, reference type, and string type with embedded instance
or embedded object.
Array properties may be Null or may have elements with a value of NULL, any
primitive CIM type, and string type with embedded instance or embedded
object. Reference types are not allowed in property arrays in CIM, as per
DMTF DSP0004.
:Ivariables:
...
All parameters of `__init__` are set as instance variables.
"""
def __init__(self, name, value, _type=None,
class_origin=None, array_size=None, propagated=None,
is_array=None, reference_class=None, qualifiers=None,
embedded_object=None):
"""
Initialize the `CIMProperty` object.
This function infers optional arguments that are not specified (for
example, it infers `type` from the Python type of `value` and other
information). If the specified arguments are inconsistent, an
exception is raised. If an optional argument is needed for some reason,
an exception is raised.
:Parameters:
name : `unicode` or UTF-8 encoded `str`
Name of the property. Must not be `None`.
value
Value of the property (interpreted as actual value when the
property object is used in an instance, and as default value when
it is used in a class).
For valid types for CIM values, see `cim_types`.
type : string
Name of the CIM type of the property (e.g. `'uint8'`).
`None` means that the argument is unspecified, causing the
corresponding instance variable to be inferred. An exception is
raised if it cannot be inferred.
class_origin : `unicode` or UTF-8 encoded `str`
The CIM class origin of the property (the name
of the most derived class that defines or overrides the property in
the class hierarchy of the class owning the property).
`None` means that class origin information is not available.
array_size : `int`
The size of the array property, for fixed-size arrays.
`None` means that the array property has variable size.
propagated : `unicode` or UTF-8 encoded `str`
The CIM *propagated* attribute of the property (the effective value
of the `Propagated` qualifier of the property, which is a string
that specifies the name of the source property from which the
property value should be propagated).
`None` means that propagation information is not available.
is_array : `bool`
A boolean indicating whether the property is an array (`True`) or a
scalar (`False`).
`None` means that the argument is unspecified, causing the
corresponding instance variable to be inferred from the `value`
parameter, and if that is `None` it defaults to `False` (scalar).
reference_class : `unicode` or UTF-8 encoded `str`
The name of the referenced class, for reference properties.
`None` means that the argument is unspecified, causing the
corresponding instance variable to be inferred. An exception is
raised if it cannot be inferred.
qualifiers : `dict` or `NocaseDict`
A dictionary specifying CIM qualifier values.
The dictionary keys must be the qualifier names. The dictionary
values must be `CIMQualifier` objects specifying the qualifier
values.
`None` means that there are no qualifier values. In all cases,
the `qualifiers` instance variable will be a `NocaseDict` object.
embedded_object : string
A string value indicating the kind of
embedded object represented by the property value. The following
values are defined for this argument:
`'instance'`: The property is declared with the
`EmbeddedInstance` qualifier, indicating that the property
value is an embedded instance of a known class name.
`'object'`: The property is declared with the
`EmbeddedObject` qualifier, indicating that the property
value is an embedded object (instance or class) of which the
class name is not known.
`None` means that the argument is unspecified, causing the
corresponding instance variable to be inferred. An exception is
raised if it cannot be inferred.
Examples:
* `CIMProperty("MyString", "abc")`
-> a string property
* `CIMProperty("MyNum", 42, "uint8")`
-> a uint8 property
* `CIMProperty("MyNum", Uint8(42))`
-> a uint8 property
* `CIMProperty("MyNumArray", [1,2,3], "uint8")`
-> a uint8 array property
* `CIMProperty("MyRef", CIMInstanceName(...))`
-> a reference property
* `CIMProperty("MyEmbObj", CIMClass(...))`
-> an embedded object property containing a class
* `CIMProperty("MyEmbObj", CIMInstance(...),
embedded_object='object')`
-> an embedded object property containing an instance
* `CIMProperty("MyEmbInst", CIMInstance(...))`
-> an embedded instance property
* `CIMProperty("MyString", None, "string")`
-> a string property that is Null
* `CIMProperty("MyNum", None, "uint8")`
-> a uint8 property that is Null
* `CIMProperty("MyRef", None, reference_class="MyClass")`
-> a reference property that is Null
* `CIMProperty("MyEmbObj", None, embedded_object='object')`
-> an embedded object property that is Null
* `CIMProperty("MyEmbInst", None, embedded_object='instance')`
-> an embedded instance property that is Null
:Raises:
:raise TypeError:
:raise ValueError:
"""
# Check `name`
if name is None:
raise ValueError('Property must have a name')
# General checks:
if embedded_object not in (None, 'instance', 'object'):
raise ValueError('Property %r specifies an invalid ' \
'embedded_object=%r' % (name, embedded_object))
if is_array not in (None, True, False):
raise ValueError('Property %r specifies an invalid ' \
'is_array=%r' % (name, is_array))
# Set up is_array
if isinstance(value, (list, tuple)):
is_array = _intended_value(True,
None, is_array, 'is_array',
'Property %r has a value that is an array (%s)' % \
(name, type(value)))
elif value is not None: # Scalar value
is_array = _intended_value(False,
None, is_array, 'is_array',
'Property %r has a value that is a scalar (%s)' % \
(name, type(value)))
else: # Null value
if is_array is None:
is_array = False # For compatibility with old default
if not is_array and array_size is not None:
raise ValueError('Scalar property %r specifies array_size=%r ' \
'(must be None)' % (name, array_size))
# Determine type, embedded_object, and reference_class attributes.
# Make sure value is CIM-typed.
if is_array: # Array property
if reference_class is not None:
raise ValueError(
'Array property %r cannot specify reference_class' % name)
elif value is None or len(value) == 0 or value[0] is None:
# Cannot infer from value, look at embedded_object and type
if embedded_object == 'instance':
raise ValueError(
'Limitation: Array property %r that is Null, ' \
'empty, or has Null as its first element cannot ' \
'have embedded instances (class cannot be ' \
'specified)' % name)
elif embedded_object == 'object':
_type = _intended_value('string',
None, _type, 'type',
'Array property %r contains embedded objects' % \
name)
elif _type is not None:
# Leave type as specified, but check it for validity
dummy_type_obj = cim_types.type_from_name(_type)
else:
raise ValueError(
'Cannot infer type of array property %r that is ' \
'Null, empty, or has Null as its first element' % \
name)
elif isinstance(value[0], CIMInstance):
msg = 'Array property %r contains CIMInstance values' % name
_type = _intended_value('string',
None, _type, 'type', msg)
embedded_object = _intended_value(('instance', 'object'),
None, embedded_object, 'embedded_object', msg)
elif isinstance(value[0], CIMClass):
msg = 'Array property %r contains CIMClass values' % name
_type = _intended_value('string',
None, _type, 'type', msg)
embedded_object = _intended_value('object',
None, embedded_object, 'embedded_object', msg)
elif isinstance(value[0], (datetime, timedelta)):
value = [cim_types.CIMDateTime(val) if val is not None
else val for val in value]
msg = 'Array property %r contains datetime or timedelta ' \
'values' % name
_type = _intended_value('datetime',
None, _type, 'type', msg)
embedded_object = _intended_value(None,
None, embedded_object, 'embedded_object', msg)
elif _type == 'datetime':
value = [cim_types.CIMDateTime(val) if val is not None
and not isinstance(val, cim_types.CIMDateTime)
else val for val in value]
msg = 'Array property %r specifies CIM type %r' % (name, _type)
embedded_object = _intended_value(None,
None, embedded_object, 'embedded_object', msg)
elif _type is None:
# Determine simple type from (non-Null) value
_type = cim_types.cimtype(value[0])
msg = 'Array property %r contains simple typed values ' \
'with no CIM type specified' % name
embedded_object = _intended_value(None,
None, embedded_object, 'embedded_object', msg)
else: # type is specified and value (= entire array) is not Null
# Make sure the array elements are of the corresponding Python
# type.
value = [cim_types.type_from_name(_type)(val) if val is not None
else val for val in value]
msg = 'Array property %r contains simple typed values ' \
'and specifies CIM type %r' % (name, _type)
embedded_object = _intended_value(None,
None, embedded_object, 'embedded_object', msg)
else: # Scalar property
if value is None:
# Try to infer from embedded_object, reference_class, and type
if embedded_object == 'instance':
raise ValueError('Limitation: Simple property %r that ' \
'is Null cannot have embedded instances '\
'(class cannot be specified)' % name)
elif embedded_object == 'object':
msg = 'Property %r contains embedded object' % name
_type = _intended_value('string',
None, _type, 'type', msg)
reference_class = _intended_value(None,
None, reference_class, 'reference_class', msg)
elif reference_class is not None:
msg = 'Property %r is a reference' % name
embedded_object = _intended_value(None,
None, embedded_object, 'embedded_object', msg)
_type = _intended_value('reference',
None, _type, 'type', msg)
elif _type is not None:
# Leave type as specified, but check it for validity
dummy_type_obj = cim_types.type_from_name(_type)
else:
raise ValueError('Cannot infer type of simple ' \
'property %r that is Null' % name)
elif isinstance(value, CIMInstanceName):
msg = 'Property %r has a CIMInstanceName value with ' \
'classname=%r' % (name, value.classname)
reference_class = _intended_value(value.classname,
None, reference_class, 'reference_class', msg)
_type = _intended_value('reference',
None, _type, 'type', msg)
embedded_object = _intended_value(None,
None, embedded_object, 'embedded_object', msg)
elif isinstance(value, CIMInstance):
msg = 'Property %r has a CIMInstance value' % name
_type = _intended_value('string',
None, _type, 'type', msg)
embedded_object = _intended_value(('instance', 'object'),
None, embedded_object, 'embedded_object', msg)
reference_class = _intended_value(None,
None, reference_class, 'reference_class', msg)
elif isinstance(value, CIMClass):
msg = 'Property %r has a CIMClass value' % name
_type = _intended_value('string',
None, _type, 'type', msg)
embedded_object = _intended_value('object',
None, embedded_object, 'embedded_object', msg)
reference_class = _intended_value(None,
None, reference_class, 'reference_class', msg)
elif isinstance(value, (datetime, timedelta)):
value = cim_types.CIMDateTime(value)
msg = 'Property %r has a datetime or timedelta value' % name
_type = _intended_value('datetime',
None, _type, 'type', msg)
embedded_object = _intended_value(None,
None, embedded_object, 'embedded_object', msg)
reference_class = _intended_value(None,
None, reference_class, 'reference_class', msg)
elif _type == 'datetime':
if not isinstance(value, cim_types.CIMDateTime):
value = cim_types.CIMDateTime(value)
msg = 'Property %r specifies CIM type %r' % (name, _type)
embedded_object = _intended_value(None,
None, embedded_object, 'embedded_object', msg)
reference_class = _intended_value(None,
None, reference_class, 'reference_class', msg)
elif _type is None:
# Determine simple type from (non-Null) value
_type = cim_types.cimtype(value)
msg = 'Property %r has a simple typed value ' \
'with no CIM type specified' % name
embedded_object = _intended_value(None,
None, embedded_object, 'embedded_object', msg)
reference_class = _intended_value(None,
None, reference_class, 'reference_class', msg)
else: # type is specified and value is not Null
# Make sure the value is of the corresponding Python type.
_type_obj = cim_types.type_from_name(_type)
value = _type_obj(value)
msg = 'Property %r has a simple typed value ' \
'and specifies CIM type %r' % (name, _type)
embedded_object = _intended_value(None,
None, embedded_object, 'embedded_object', msg)
reference_class = _intended_value(None,
None, reference_class, 'reference_class', msg)
# Initialize members
self.name = name
self.value = value
self.type = _type
self.class_origin = class_origin
self.array_size = array_size
self.propagated = propagated
self.is_array = is_array
self.reference_class = reference_class
self.qualifiers = NocaseDict(qualifiers)
self.embedded_object = embedded_object
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=%r, value=%r, type=%r, class_origin=%r, ' \
'array_size=%r, propagated=%r, is_array=%r, ' \
'reference_class=%r, qualifiers=%r, embedded_object=%r)' % \
(self.__class__.__name__, self.name, self.value, self.type,
self.class_origin, self.array_size, self.propagated,
self.is_array, self.reference_class, self.qualifiers,
self.embedded_object)
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 = cim_xml.VALUE_ARRAY(
[cim_xml.VALUE(
cim_types.atomic_to_cim_xml(v)) for v in value])
return cim_xml.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 = cim_xml.VALUE_REFERENCE(self.value.tocimxml())
return cim_xml.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 = cim_types.atomic_to_cim_xml(value)
value = cim_xml.VALUE(value)
return cim_xml.PROPERTY(