forked from rosspeoples/python3-pywbem
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcim_operations.py
2027 lines (1477 loc) · 67.5 KB
/
cim_operations.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]>
"""CIM operations over HTTP.
The `WBEMConnection` class in this module opens a connection to a remote
WBEM server. Across this connection you can run various CIM operations.
Each method of this class corresponds fairly directly to a single CIM
operation.
"""
# This module is meant to be safe for 'import *'.
import six
from xml.dom import minidom
from datetime import datetime, timedelta
from . import cim_obj, cim_xml, cim_http, cim_types, tupletree, tupleparse
from .cim_obj import CIMInstance, CIMInstanceName, CIMClass, \
CIMClassName, NocaseDict
DEFAULT_NAMESPACE = 'root/cimv2'
def _check_classname(val):
"""
Validate a classname.
At this point, only the type is validated to be a string.
"""
if not isinstance(val, six.string_types):
raise ValueError("string expected for classname, not %s" % repr(val))
class CIMError(Exception):
"""
Exception indicating that a CIM error has happened.
The exception value is a tuple of ``(error_code, description)``, where:
* ``error_code``: a numeric error code.
A value of 0 indicates an error detected by the PyWBEM client, or a
connection error, or an HTTP error reported by the WBEM server.
Values other than 0 indicate that the WBEM server has returned an error
response, and the value is the CIM status code of the error response.
See `cim_constants` for constants defining CIM status code values.
* ``description``: a string (`unicode` or UTF-8 encoded `str`)
representing a human readable message describing the error. If
`error_code` is not 0, this string is the CIM status description of the
error response returned by the WBEM server. Otherwise, this is a
message issued by the PyWBEM client.
"""
class WBEMConnection(object):
"""
A client's connection to a WBEM server. This is the main class of the
PyWBEM client.
The connection object knows a default CIM namespace, which is used when no
namespace is specified on subsequent CIM operations (that support
specifying namespaces). Thus, the connection object can be used as a
connection to multiple CIM namespaces on a WBEM server (when the namespace
is specified on subsequent operations), or as a connection to only the
default namespace (this allows omitting the namespace on subsequent
operations).
As usual in HTTP, there is no persistent TCP connection; the connectedness
provided by this class is only conceptual. That is, the creation of the
connection object does not cause any interaction with the WBEM server, and
each subsequent CIM operation performs an independent, state-less
HTTP/HTTPS request.
After creating a `WBEMConnection` object, various methods may be called on
the object, which cause CIM operations to be invoked on the WBEM server.
All these methods take regular Python objects or objects defined in
`cim_types` as arguments, and return the same.
The caller does not need to know about the CIM-XML encoding that is used
underneath (It should be possible to use a different transport below this
layer without disturbing any callers).
The connection remembers the XML of the last request and last reply if
debugging is turned on via the `debug` instance variable of the connection
object.
This may be useful in debugging: If a problem occurs, you can examine the
`last_request` and `last_reply` instance variables of the connection
object. These are the prettified XML of request and response, respectively.
The real request and response that are sent and received are available in
the `last_raw_request` and `last_raw_reply` instance variables of the
connection object.
The methods of this class may raise the following exceptions:
* Exceptions indicating processing errors:
- `pywbem.Error` - HTTP transport error.
- `pywbem.AuthError` - Authentication failed with the WBEM server.
- `pywbem.CIMError` - CIM error.
With an ``error_code`` value of 0, the reason is one of:
* Error in the arguments of a method.
* Connection problem with the WBEM server.
* HTTP-level errors reported by the WBEM server (except for HTTP
transport errors and authentication failures).
With other ``error_code`` values, the reason is always that the
operation invoked on the WBEM server failed and returned a CIM error.
For the possible CIM errors that can be returned by each operation, see
DMTF DSP0200.
- `pywbem.ParseError` - CIM-XML validation problem in the response from
the WBEM server.
- `xml.parsers.expat.ExpatError` - XML error in the response from the
WBEM server, such as ill-formed XML or illegal XML characters.
* Exceptions indicating programming errors in PyWBEM or layers below:
- `TypeError`
- `KeyError`
- `ValueError`
- ... possibly others ...
Exceptions indicating programming errors should not happen and should be
reported as bugs.
:Ivariables:
...
All parameters of `__init__` are set as instance variables.
debug : `bool`
A boolean indicating whether logging of the last request and last reply
is enabled.
The initial value of this instance variable is `False`.
Debug logging can be enabled for future operations by setting this
instance variable to `True`.
last_request : `unicode`
CIM-XML data of the last request sent to the WBEM server
on this connection, formatted as prettified XML.
last_raw_request : `unicode`
CIM-XML data of the last request sent to the WBEM server
on this connection, formatted as it was sent.
last_reply : `unicode`
CIM-XML data of the last response received from the WBEM server
on this connection, formatted as prettified XML.
last_raw_reply : `unicode`
CIM-XML data of the last response received from the WBEM server
on this connection, formatted as it was received.
"""
def __init__(self, url, creds=None, default_namespace=DEFAULT_NAMESPACE,
x509=None, verify_callback=None, ca_certs=None,
no_verification=False):
"""
Initialize the `WBEMConnection` object.
:Parameters:
url : string
URL of the WBEM server (e.g. ``"https://10.11.12.13:6988"``).
TODO: Describe supported formats.
creds
Credentials for authenticating with the WBEM server. Currently,
that is always a tuple of ``(userid, password)``, where:
* ``userid`` is a string that is the userid to be used for
authenticating with the WBEM server.
* ``password`` is a string that is the password for that userid.
default_namespace : string
Optional: Name of the CIM namespace to be used by default (if no
namespace is specified for an operation).
Default: See method definition.
x509 : dictionary
Optional: X.509 certificates for HTTPS to be used instead of the
credentials provided in the `creds` parameter. This parameter is
used only when the `url` parameter specifies a scheme of ``https``.
If `None`, certificates are not used (and credentials are used
instead).
Otherwise, certificates are used instead of the credentials, and
this parameter must be a dictionary containing the following
key/value pairs:
* ``'cert_file'`` : The file path of a file containing an X.509
certificate.
* ``'key_file'`` : The file path of a file containing the private
key belonging to the public key that is part of the X.509
certificate file.
Default: `None`.
verify_callback : function
Optional: Registers a callback function that will be called to
verify the certificate returned by the WBEM server during the SSL
handshake, in addition to the verification alreay performed by
`M2Crypto`.
If `None`, no such callback function will be registered.
The specified function will be called for the returned certificate,
and for each of the certificates in its chain of trust.
See `M2Crypto.SSL.Context.set_verify` for details, as well as
http://blog.san-ss.com.ar/2012/05/validating-ssl-certificate-in-python.html):
The callback function must take five parameters:
* the `M2Crypto.SSL.Connection` object that triggered the
verification.
* an `OpenSSL.crypto.X509` object representing the certificate
to be validated (the returned certificate or one of the
certificates in its chain of trust).
* an integer containing the error number (0 in case no error) of
any validation error detected by `M2Crypto`.
You can find their meaning in the OpenSSL documentation.
* an integer indicating the depth (=position) of the certificate to
be validated (the one in the second parameter) in the chain of
trust of the returned certificate. A value of 0 indicates
that the returned is currently validated; any other value
indicates the distance of the currently validated certificate to
the returned certificate in its chain of trust.
* an integer that indicates whether the validation of the
certificate specified in the second argument passed or did not
pass the validation by `M2Crypto`. A value of 1 indicates a
successful validation and 0 an unsuccessful one.
The callback function must return `True` if the verification
passes and `False` otherwise.
Default: `None`.
ca_certs : string
Optional: Location of CA certificates (trusted certificates) for
verification purposes.
The parameter value is either the directory path of a directory
prepared using the ``c_rehash`` tool included with OpenSSL, or the
file path of a file in PEM format.
If `None`, the default system path will be used.
Default: `None`.
no_verification : `bool`
Optional: Indicates that verification of the certificate returned
by the WBEM server is disabled (both by `M2Crypto` and by the
callback function specified in `verify_callback`).
Disabling the verification is insecure and should be avoided.
If `True`, verification is disabled; otherwise, it is enabled.
Default: `False`.
:Exceptions:
See the list of exceptions described in `WBEMConnection`.
"""
self.url = url
self.creds = creds
self.x509 = x509
self.verify_callback = verify_callback
self.ca_certs = ca_certs
self.no_verification = no_verification
self.last_request = self.last_reply = ''
self.default_namespace = default_namespace
self.debug = False
def __repr__(self):
"""
Return a representation of the connection object with the major
instance variables, except for the password in the credentials.
TODO: Change to show all instance variables.
"""
if self.creds is None:
user = 'anonymous'
else:
user = 'user=%s' % repr(self.creds[0])
return "%s(%s, %s, namespace=%s)" % \
(self.__class__.__name__, repr(self.url), user,
repr(self.default_namespace))
def imethodcall(self, methodname, namespace, **params):
"""
Perform an intrinsic method call (= CIM operation).
This is a low-level function that is used by the operation-specific
methods of this class (e.g. `EnumerateInstanceNames`). In general,
clients should call these operation-specific methods instead of this
function.
The parameters are automatically converted to the right CIM-XML
elements.
:Returns:
A tupletree (see `tupletree` module) with an ``IRETURNVALUE``
element at the root.
:Exceptions:
See the list of exceptions described in `WBEMConnection`.
"""
# Create HTTP headers
headers = ['CIMOperation: MethodCall',
'CIMMethod: %s' % methodname,
cim_http.get_object_header(namespace)]
# Create parameter list
plist = [cim_xml.IPARAMVALUE(x[0], cim_obj.tocimxml(x[1])) for x in list(params.items())]
# Build XML request
req_xml = cim_xml.CIM(
cim_xml.MESSAGE(
cim_xml.SIMPLEREQ(
cim_xml.IMETHODCALL(
methodname,
cim_xml.LOCALNAMESPACEPATH(
[cim_xml.NAMESPACE(ns)
for ns in namespace.split('/')]),
plist)),
'1001', '1.0'),
'2.0', '2.0')
if self.debug:
self.last_raw_request = req_xml.toxml()
self.last_request = req_xml.toprettyxml(indent=' ')
# Reset replies in case we fail before they are set
self.last_reply = None
self.last_raw_reply = None
# Get XML response
try:
resp_xml = cim_http.wbem_request(
self.url, req_xml.toxml(), self.creds, headers,
x509=self.x509,
verify_callback=self.verify_callback,
ca_certs=self.ca_certs,
no_verification=self.no_verification)
except cim_http.AuthError:
raise
except cim_http.Error as arg:
# Convert cim_http exceptions to CIMError exceptions
raise CIMError(0, str(arg))
## TODO: Perhaps only compute this if it's required? Should not be
## all that expensive.
reply_dom = minidom.parseString(resp_xml)
if self.debug:
self.last_reply = reply_dom.toprettyxml(indent=' ')
self.last_raw_reply = resp_xml
# Parse response
tt = tupleparse.parse_cim(tupletree.dom_to_tupletree(reply_dom))
if tt[0] != 'CIM':
raise CIMError(0, 'Expecting CIM element, got %s' % tt[0])
tt = tt[2]
if tt[0] != 'MESSAGE':
raise CIMError(0, 'Expecting MESSAGE element, got %s' % tt[0])
tt = tt[2]
if len(tt) != 1 or tt[0][0] != 'SIMPLERSP':
raise CIMError(0, 'Expecting one SIMPLERSP element')
tt = tt[0][2]
if tt[0] != 'IMETHODRESPONSE':
raise CIMError(
0, 'Expecting IMETHODRESPONSE element, got %s' % tt[0])
if tt[1]['NAME'] != methodname:
raise CIMError(0, 'Expecting attribute NAME=%s, got %s' %
(methodname, tt[1]['NAME']))
tt = tt[2]
# At this point we either have a IRETURNVALUE, ERROR element
# or None if there was no child nodes of the IMETHODRESPONSE
# element.
if tt is None:
return None
if tt[0] == 'ERROR':
code = int(tt[1]['CODE'])
if 'DESCRIPTION' in tt[1]:
raise CIMError(code, tt[1]['DESCRIPTION'])
raise CIMError(code, 'Error code %s' % tt[1]['CODE'])
if tt[0] != 'IRETURNVALUE':
raise CIMError(0, 'Expecting IRETURNVALUE element, got %s' % tt[0])
return tt
def methodcall(self, methodname, localobject, **params):
"""
Perform an extrinsic method call (= CIM method invocation).
This is a low-level function that is used by the 'InvokeMethod'
method of this class. In general, clients should use 'InvokeMethod'
instead of this function.
The parameters are automatically converted to the right CIM-XML
elements.
:Returns:
A tupletree (see `tupletree` module) with a ``RETURNVALUE``
element at the root.
:Exceptions:
See the list of exceptions described in `WBEMConnection`.
"""
# METHODCALL only takes a LOCALCLASSPATH or LOCALINSTANCEPATH
if hasattr(localobject, 'host') and localobject.host is not None:
localobject = localobject.copy()
localobject.host = None
# Create HTTP headers
headers = ['CIMOperation: MethodCall',
'CIMMethod: %s' % methodname,
cim_http.get_object_header(localobject)]
# Create parameter list
def paramtype(obj):
"""Return a string to be used as the CIMTYPE for a parameter."""
if isinstance(obj, cim_types.CIMType):
return obj.cimtype
elif type(obj) == bool:
return 'boolean'
elif isinstance(obj, six.string_types):
return 'string'
elif isinstance(obj, (datetime, timedelta)):
return 'datetime'
elif isinstance(obj, (CIMClassName, CIMInstanceName)):
return 'reference'
elif isinstance(obj, (CIMClass, CIMInstance)):
return 'string'
elif isinstance(obj, list):
if obj:
return paramtype(obj[0])
else:
return None
raise TypeError('Unsupported parameter type "%s"' % type(obj))
def paramvalue(obj):
"""Return a cim_xml node to be used as the value for a
parameter."""
if isinstance(obj, (datetime, timedelta)):
obj = cim_types.CIMDateTime(obj)
if isinstance(obj, (cim_types.CIMType, bool) + six.string_types):
return cim_xml.VALUE(cim_types.atomic_to_cim_xml(obj))
if isinstance(obj, (CIMClassName, CIMInstanceName)):
return cim_xml.VALUE_REFERENCE(obj.tocimxml())
if isinstance(obj, (CIMClass, CIMInstance)):
return cim_xml.VALUE(obj.tocimxml().toxml())
if isinstance(obj, list):
if obj and isinstance(obj[0], (CIMClassName, CIMInstanceName)):
return cim_xml.VALUE_REFARRAY([paramvalue(x) for x in obj])
return cim_xml.VALUE_ARRAY([paramvalue(x) for x in obj])
raise TypeError('Unsupported parameter type "%s"' % type(obj))
def is_embedded(obj):
"""Determine if an object requires an EmbeddedObject attribute"""
if isinstance(obj, list) and obj:
return is_embedded(obj[0])
elif isinstance(obj, CIMClass):
return 'object'
elif isinstance(obj, CIMInstance):
return 'instance'
return None
plist = [cim_xml.PARAMVALUE(x[0],
paramvalue(x[1]),
paramtype(x[1]),
embedded_object=is_embedded(x[1]))
for x in params.items()]
# Build XML request
req_xml = cim_xml.CIM(
cim_xml.MESSAGE(
cim_xml.SIMPLEREQ(
cim_xml.METHODCALL(
methodname,
localobject.tocimxml(),
plist)),
'1001', '1.0'),
'2.0', '2.0')
if self.debug:
self.last_request = req_xml.toprettyxml(indent=' ')
self.last_raw_request = req_xml.toxml()
# Reset replies in case we fail before they are set
self.last_reply = None
self.last_raw_reply = None
# Get XML response
try:
resp_xml = cim_http.wbem_request(
self.url, req_xml.toxml(), self.creds, headers,
x509=self.x509,
verify_callback=self.verify_callback,
ca_certs=self.ca_certs,
no_verification=self.no_verification)
except cim_http.Error as arg:
# Convert cim_http exceptions to CIMError exceptions
raise CIMError(0, str(arg))
if self.debug:
self.last_raw_reply = resp_xml
resp_dom = minidom.parseString(resp_xml)
self.last_reply = resp_dom.toprettyxml(indent=' ')
tt = tupleparse.parse_cim(tupletree.xml_to_tupletree(resp_xml))
if tt[0] != 'CIM':
raise CIMError(0, 'Expecting CIM element, got %s' % tt[0])
tt = tt[2]
if tt[0] != 'MESSAGE':
raise CIMError(0, 'Expecting MESSAGE element, got %s' % tt[0])
tt = tt[2]
if len(tt) != 1 or tt[0][0] != 'SIMPLERSP':
raise CIMError(0, 'Expecting one SIMPLERSP element')
tt = tt[0][2]
if tt[0] != 'METHODRESPONSE':
raise CIMError(
0, 'Expecting METHODRESPONSE element, got %s' % tt[0])
if tt[1]['NAME'] != methodname:
raise CIMError(0, 'Expecting attribute NAME=%s, got %s' %
(methodname, tt[1]['NAME']))
tt = tt[2]
# At this point we have an optional RETURNVALUE and zero or
# more PARAMVALUE elements representing output parameters.
if len(tt) > 0 and tt[0][0] == 'ERROR':
code = int(tt[0][1]['CODE'])
if 'DESCRIPTION' in tt[0][1]:
raise CIMError(code, tt[0][1]['DESCRIPTION'])
raise CIMError(code, 'Error code %s' % tt[0][1]['CODE'])
return tt
#
# Instance provider API
#
def EnumerateInstanceNames(self, ClassName, namespace=None, **params):
# pylint: disable=invalid-name
"""
Enumerate the instance paths of instances of a class (including
instances of its subclasses).
This method performs the EnumerateInstanceNames CIM-XML operation.
If the operation succeeds, this method returns.
Otherwise, this method raises an exception.
:Parameters:
ClassName : string
Name of the class to be enumerated.
namespace : string
Optional: Name of the CIM namespace to be used. The value `None`
causes the default namespace of the connection object to be used.
Default: `None`.
:Returns:
A list of `CIMInstanceName` objects that are the enumerated
instance paths.
:Exceptions:
See the list of exceptions described in `WBEMConnection`.
"""
if namespace is None:
namespace = self.default_namespace
result = self.imethodcall(
'EnumerateInstanceNames',
namespace,
ClassName=CIMClassName(ClassName),
**params)
names = []
if result is not None:
names = result[2]
[setattr(n, 'namespace', namespace) for n in names]
return names
def EnumerateInstances(self, ClassName, namespace=None, **params):
# pylint: disable=invalid-name
"""
Enumerate the instances of a class (including instances of its
subclasses).
This method performs the EnumerateInstances CIM-XML operation.
If the operation succeeds, this method returns.
Otherwise, this method raises an exception.
:Parameters:
ClassName : string
Name of the class to be enumerated.
namespace : string
Optional: Name of the CIM namespace to be used. The value `None`
causes the default namespace of the connection object to be used.
Default: `None`.
LocalOnly : `bool`
Optional: Controls the exclusion of inherited properties from the
returned instances, as follows:
* If `False`, inherited properties are not excluded.
* If `True`, the behavior is WBEM server specific.
Default: `True`.
This parameter has been deprecated in CIM-XML and should be set to
`False` by the caller.
DeepInheritance : `bool`
Optional: Indicates that properties added by subclasses of the
specified class are to be included in the returned instances.
Note, the semantics of this parameter differs between instance and
class level operations.
Default: `True`.
IncludeQualifiers : `bool`
Optional: Indicates that qualifiers are to be included in the
returned instance.
Default: `False`.
This parameter has been deprecated in CIM-XML. Clients cannot rely
on it being implemented by WBEM servers.
IncludeClassOrigin : `bool`
Optional: Indicates that class origin information is to be included
on each property in the returned instances.
Default: `False`.
PropertyList : iterable of string
Optional: An iterable specifying the names of the properties to be
included in the returned instances. An empty iterable indicates to
include no properties. A value of `None` for this parameter
indicates to include all properties.
Default: `None`.
:Returns:
A list of `CIMInstance` objects that are representations of
the enumerated instances.
:Exceptions:
See the list of exceptions described in `WBEMConnection`.
"""
if namespace is None:
namespace = self.default_namespace
result = self.imethodcall(
'EnumerateInstances',
namespace,
ClassName=CIMClassName(ClassName),
**params)
instances = []
if result is not None:
instances = result[2]
[setattr(i.path, 'namespace', namespace) for i in instances]
return instances
def GetInstance(self, InstanceName, **params):
# pylint: disable=invalid-name
"""
Retrieve an instance.
This method performs the GetInstance CIM-XML operation.
If the operation succeeds, this method returns.
Otherwise, this method raises an exception.
:Parameters:
InstanceName : `CIMInstanceName`
Instance path of the instance to be retrieved.
LocalOnly : `bool`
Optional: Controls the exclusion of inherited properties from the
returned instance, as follows:
* If `False`, inherited properties are not excluded.
* If `True`, the behavior is WBEM server specific.
Default: `True`.
This parameter has been deprecated in CIM-XML and should be set to
`False` by the caller.
IncludeQualifiers : `bool`
Optional: Indicates that qualifiers are to be included in the
returned instance.
Default: `False`.
This parameter has been deprecated in CIM-XML. Clients cannot rely
on it being implemented by WBEM servers.
IncludeClassOrigin : `bool`
Optional: Indicates that class origin information is to be included
on each property in the returned instance.
Default: `False`.
PropertyList : iterable of string
Optional: An iterable specifying the names of the properties to be
included in the returned instances. An empty iterable indicates to
include no properties. A value of `None` for this parameter
indicates to include all properties.
Default: `None`.
:Returns:
A `CIMInstance` object that is a representation of the
retrieved instance.
:Exceptions:
See the list of exceptions described in `WBEMConnection`.
"""
# Strip off host and namespace to make this a "local" object
iname = InstanceName.copy()
iname.host = None
iname.namespace = None
if InstanceName.namespace is None:
namespace = self.default_namespace
else:
namespace = InstanceName.namespace
result = self.imethodcall(
'GetInstance',
namespace,
InstanceName=iname,
**params)
instance = result[2][0]
instance.path = InstanceName
instance.path.namespace = namespace
return instance
def DeleteInstance(self, InstanceName, **params):
# pylint: disable=invalid-name
"""
Delete an instance.
This method performs the DeleteInstance CIM-XML operation.
If the operation succeeds, this method returns.
Otherwise, this method raises an exception.
:Parameters:
InstanceName : `CIMInstanceName`
Instance path of the instance to be deleted.
:Exceptions:
See the list of exceptions described in `WBEMConnection`.
"""
# Strip off host and namespace to make this a "local" object
iname = InstanceName.copy()
iname.host = None
iname.namespace = None
if InstanceName.namespace is None:
namespace = self.default_namespace
else:
namespace = InstanceName.namespace
self.imethodcall(
'DeleteInstance',
namespace,
InstanceName=iname,
**params)
def CreateInstance(self, NewInstance, **params):
# pylint: disable=invalid-name
"""
Create an instance.
This method performs the CreateInstance CIM-XML operation.
If the operation succeeds, this method returns.
Otherwise, this method raises an exception.
:Parameters:
NewInstance : `CIMInstance`
A representation of the instance to be created.
The `namespace` and `classname` instance variables of this object
specify CIM namespace and creation class for the new instance,
respectively.
An instance path specified using the `path` instance variable of
this object will be ignored.
The `properties` instance variable of this object specifies initial
property values for the new instance.
Instance-level qualifiers have been deprecated in CIM, so any
qualifier values specified using the `qualifiers` instance variable
of this object will be ignored.
:Returns:
`CIMInstanceName` object that is the instance path of the new
instance.
:Exceptions:
See the list of exceptions described in `WBEMConnection`.
"""
# Take namespace path from object parameter
if NewInstance.path is not None and \
NewInstance.path.namespace is not None:
namespace = NewInstance.path.namespace
else:
namespace = self.default_namespace
# Strip off path to avoid producing a VALUE.NAMEDINSTANCE
# element instead of an INSTANCE element.
instance = NewInstance.copy()
instance.path = None
result = self.imethodcall(
'CreateInstance',
namespace,
NewInstance=instance,
**params)
name = result[2][0]
name.namespace = namespace
return name
def ModifyInstance(self, ModifiedInstance, **params):
# pylint: disable=invalid-name
"""
Modify the property values of an instance.
This method performs the ModifyInstance CIM-XML operation.
If the operation succeeds, this method returns.
Otherwise, this method raises an exception.
:Parameters:
ModifiedInstance : `CIMInstance`
A representation of the modified instance. This object needs to
contain any new property values and the instance path of the
instance to be modified. Missing properties (relative to the class
declaration) and properties provided with a value of `None` will be
set to NULL. Typically, this object has been retrieved by other
operations, such as GetInstance.
IncludeQualifiers : `bool`
Optional: Indicates that qualifiers are to be modified as specified
in the `ModifiedInstance` parameter.
Default: `True`.
This parameter has been deprecated in CIM-XML. Clients cannot rely
on it being implemented by WBEM servers.
PropertyList : iterable of string
Optional: An iterable specifying the names of the properties to be
modified. An empty iterable indicates to modify no properties. A
value of `None` for this parameter indicates to modify all
properties.
Default: `None`.
:Exceptions:
See the list of exceptions described in `WBEMConnection`.
"""
# Must pass a named CIMInstance here (i.e path attribute set)
if ModifiedInstance.path is None:
raise ValueError(
'ModifiedInstance parameter must have path attribute set')
# Take namespace path from object parameter
if ModifiedInstance.path.namespace is None:
namespace = self.default_namespace
else:
namespace = ModifiedInstance.path.namespace
instance = ModifiedInstance.copy()
instance.path.namespace = None
self.imethodcall(
'ModifyInstance',
namespace,
ModifiedInstance=instance,
**params)
def ExecQuery(self, QueryLanguage, Query, namespace=None):
# pylint: disable=invalid-name
"""
Execute a query in a namespace.