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 """CIM operations over HTTP.
26
27 The `WBEMConnection` class in this module opens a connection to a remote
28 WBEM server. Across this connection you can run various CIM operations.
29 Each method of this class corresponds fairly directly to a single CIM
30 operation.
31 """
32
33
34
35 import re
36 from datetime import datetime, timedelta
37 from xml.dom import minidom
38 from xml.parsers.expat import ExpatError
39 import six
40
41 from . import cim_xml
42 from .cim_constants import DEFAULT_NAMESPACE
43 from .cim_types import CIMType, CIMDateTime, atomic_to_cim_xml
44 from .cim_obj import CIMInstance, CIMInstanceName, CIMClass, \
45 CIMClassName, NocaseDict, _ensure_unicode, tocimxml, \
46 tocimobj
47 from .cim_http import get_object_header, wbem_request, Error, AuthError, \
48 ConnectionError, TimeoutError
49 from .tupleparse import ParseError, parse_cim
50 from .tupletree import dom_to_tupletree
51
52 __all__ = ['CIMError', 'WBEMConnection',
53 'PegasusUDSConnection', 'SFCBUDSConnection',
54 'OpenWBEMUDSConnection']
55
56 if len(u'\U00010122') == 2:
57
58 _ILLEGAL_XML_CHARS_RE = re.compile(
59 u'([\u0000-\u0008\u000B-\u000C\u000E-\u001F\uFFFE\uFFFF])')
60 else:
61
62 _ILLEGAL_XML_CHARS_RE = re.compile(
63 u'([\u0000-\u0008\u000B-\u000C\u000E-\u001F\uD800-\uDFFF\uFFFE\uFFFF])')
64
65 _ILL_FORMED_UTF8_RE = re.compile(
66 b'(\xED[\xA0-\xBF][\x80-\xBF])')
67
68
70 """
71 Validate a classname.
72
73 At this point, only the type is validated to be a string.
74 """
75 if not isinstance(val, six.string_types):
76 raise ValueError("string expected for classname, not %r" % val)
77
79 """
80 Examine a UTF-8 encoded XML string and raise a `pywbem.ParseError`
81 exception if the response contains Bytes that are invalid UTF-8
82 sequences (incorrectly encoded or ill-formed) or that are invalid XML
83 characters.
84
85 This function works in both "wide" and "narrow" Unicode builds of Python
86 and supports the full range of Unicode characters from U+0000 to U+10FFFF.
87
88 This function is just a workaround for the bad error handling of Python's
89 `xml.dom.minidom` package. It replaces the not very informative
90 `ExpatError` "not well-formed (invalid token): line: x, column: y" with a
91 `pywbem.ParseError` providing more useful information.
92
93 :Parameters:
94
95 utf8_xml : UTF-8 encoded byte string
96 The XML string to be examined.
97
98 meaning : string
99 Short text with meaning of the XML string, for messages in exceptions.
100
101 :Exceptions:
102
103 `TypeError`, if invoked with incorrect Python object type for `utf8_xml`.
104
105 `pywbem.ParseError`, if `utf8_xml` contains Bytes that are invalid UTF-8
106 sequences (incorrectly encoded or ill-formed) or invalid XML characters.
107
108 Notes on Unicode support in Python:
109
110 (1) For internally representing Unicode characters in the unicode type, a
111 "wide" Unicode build of Python uses UTF-32, while a "narrow" Unicode
112 build uses UTF-16. The difference is visible to Python programs for
113 Unicode characters assigned to code points above U+FFFF: The "narrow"
114 build uses 2 characters (a surrogate pair) for them, while the "wide"
115 build uses just 1 character. This affects all position- and
116 length-oriented functions, such as `len()` or string slicing.
117
118 (2) In a "wide" Unicode build of Python, the Unicode characters assigned to
119 code points U+10000 to U+10FFFF are represented directly (using code
120 points U+10000 to U+10FFFF) and the surrogate code points
121 U+D800...U+DFFF are never used; in a "narrow" Unicode build of Python,
122 the Unicode characters assigned to code points U+10000 to U+10FFFF are
123 represented using pairs of the surrogate code points U+D800...U+DFFF.
124
125 Notes on the Unicode code points U+D800...U+DFFF ("surrogate code points"):
126
127 (1) These code points have no corresponding Unicode characters assigned,
128 because they are reserved for surrogates in the UTF-16 encoding.
129
130 (2) The UTF-8 encoding can technically represent the surrogate code points.
131 ISO/IEC 10646 defines that a UTF-8 sequence containing the surrogate
132 code points is ill-formed, but it is technically possible that such a
133 sequence is in a UTF-8 encoded XML string.
134
135 (3) The Python escapes ``\\u`` and ``\\U`` used in literal strings can
136 represent the surrogate code points (as well as all other code points,
137 regardless of whether they are assigned to Unicode characters).
138
139 (4) The Python `encode()` and `decode()` functions successfully
140 translate the surrogate code points back and forth for encoding UTF-8.
141
142 For example, ``b'\\xed\\xb0\\x80'.decode("utf-8") = u'\\udc00'``.
143
144 (5) Because Python supports the encoding and decoding of UTF-8 sequences
145 also for the surrogate code points, the "narrow" Unicode build of
146 Python can be (mis-)used to transport each surrogate unit separately
147 encoded in (ill-formed) UTF-8.
148
149 For example, code point U+10122 can be (illegally) created from a
150 sequence of code points U+D800,U+DD22 represented in UTF-8:
151
152 ``b'\\xED\\xA0\\x80\\xED\\xB4\\xA2'.decode("utf-8") = u'\\U00010122'``
153
154 while the correct UTF-8 sequence for this code point is:
155
156 ``u'\\U00010122'.encode("utf-8") = b'\\xf0\\x90\\x84\\xa2'``
157
158 Notes on XML characters:
159
160 (1) The legal XML characters are defined in W3C XML 1.0 (Fith Edition):
161
162 ::
163
164 Char ::= #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] |
165 [#x10000-#x10FFFF]
166
167 These are the code points of Unicode characters using a non-surrogate
168 representation.
169 """
170
171 context_before = 16
172 context_after = 16
173
174 if not isinstance(utf8_xml, six.binary_type):
175 raise TypeError("utf8_xml argument is not a byte string, "\
176 "but has type %s" % type(utf8_xml))
177
178
179
180
181
182 ifs_list = list()
183 for m in _ILL_FORMED_UTF8_RE.finditer(utf8_xml):
184 ifs_pos = m.start(1)
185 ifs_seq = m.group(1)
186 ifs_list.append((ifs_pos, ifs_seq))
187 if len(ifs_list) > 0:
188 exc_txt = "Ill-formed (surrogate) UTF-8 Byte sequences found in %s:" %\
189 meaning
190 for (ifs_pos, ifs_seq) in ifs_list:
191 exc_txt += "\n At offset %d:" % ifs_pos
192 for ifs_ord in six.iterbytes(ifs_seq):
193 exc_txt += " 0x%02X" % ifs_ord
194 cpos1 = max(ifs_pos-context_before, 0)
195 cpos2 = min(ifs_pos+context_after, len(utf8_xml))
196 exc_txt += ", CIM-XML snippet: %r" % utf8_xml[cpos1:cpos2]
197 raise ParseError(exc_txt)
198
199
200
201 try:
202 utf8_xml_u = utf8_xml.decode("utf-8")
203 except UnicodeDecodeError as exc:
204
205
206
207
208
209
210 unused_codec, unused_str, _p1, _p2, unused_msg = exc.args
211 exc_txt = "Incorrectly encoded UTF-8 Byte sequences found in %s" %\
212 meaning
213 exc_txt += "\n At offset %d:" % _p1
214 ies_seq = utf8_xml[_p1:_p2+1]
215 for ies_ord in six.iterbytes(ies_seq):
216 exc_txt += " 0x%02X" % ies_ord
217 cpos1 = max(_p1-context_before, 0)
218 cpos2 = min(_p2+context_after, len(utf8_xml))
219 exc_txt += ", CIM-XML snippet: %r" % utf8_xml[cpos1:cpos2]
220 raise ParseError(exc_txt)
221
222
223
224
225 ixc_list = list()
226 last_ixc_pos = -2
227 for m in _ILLEGAL_XML_CHARS_RE.finditer(utf8_xml_u):
228 ixc_pos = m.start(1)
229 ixc_char_u = m.group(1)
230 if ixc_pos > last_ixc_pos + 1:
231 ixc_list.append((ixc_pos, ixc_char_u))
232 last_ixc_pos = ixc_pos
233 if len(ixc_list) > 0:
234 exc_txt = "Invalid XML characters found in %s:" % meaning
235 for (ixc_pos, ixc_char_u) in ixc_list:
236 cpos1 = max(ixc_pos-context_before, 0)
237 cpos2 = min(ixc_pos+context_after, len(utf8_xml_u))
238 exc_txt += "\n At offset %d: U+%04X, CIM-XML snippet: %r" % \
239 (ixc_pos, ord(ixc_char_u), utf8_xml_u[cpos1:cpos2])
240 raise ParseError(exc_txt)
241
242 return utf8_xml
243
244
246 """
247 Exception indicating that the WBEM server has returned an error response
248 with a CIM status code.
249
250 The exception value is a tuple of
251 ``(error_code, description, exception_obj)``, where:
252
253 * ``error_code``: the numeric CIM status code. See `cim_constants` for
254 constants defining CIM status code values.
255
256 * ``description``: a string (`unicode` or UTF-8 encoded `str`)
257 that is the CIM status description text returned by the server,
258 representing a human readable message describing the error.
259
260 * ``exception_obj``: the underlying exception object that caused this
261 exception to be raised, or ``None``. Will always be ``None``.
262 """
263 pass
264
266 """
267 A client's connection to a WBEM server. This is the main class of the
268 PyWBEM client.
269
270 The connection object knows a default CIM namespace, which is used when no
271 namespace is specified on subsequent CIM operations (that support
272 specifying namespaces). Thus, the connection object can be used as a
273 connection to multiple CIM namespaces on a WBEM server (when the namespace
274 is specified on subsequent operations), or as a connection to only the
275 default namespace (this allows omitting the namespace on subsequent
276 operations).
277
278 As usual in HTTP, there is no persistent TCP connection; the connectedness
279 provided by this class is only conceptual. That is, the creation of the
280 connection object does not cause any interaction with the WBEM server, and
281 each subsequent CIM operation performs an independent, state-less
282 HTTP/HTTPS request.
283
284 After creating a `WBEMConnection` object, various methods may be called on
285 the object, which cause CIM operations to be invoked on the WBEM server.
286 All these methods take regular Python objects or objects defined in
287 `cim_types` as arguments, and return the same.
288 The caller does not need to know about the CIM-XML encoding that is used
289 underneath (It should be possible to use a different transport below this
290 layer without disturbing any callers).
291
292 The connection remembers the XML of the last request and last reply if
293 debugging is turned on via the `debug` instance variable of the connection
294 object.
295 This may be useful in debugging: If a problem occurs, you can examine the
296 `last_request` and `last_reply` instance variables of the connection
297 object. These are the prettified XML of request and response, respectively.
298 The real request and response that are sent and received are available in
299 the `last_raw_request` and `last_raw_reply` instance variables of the
300 connection object.
301
302 The methods of this class may raise the following exceptions:
303
304 * Exceptions indicating processing errors:
305
306 - `pywbem.ConnectionError` - A connection with the WBEM server could not
307 be established or broke down.
308
309 - `pywbem.AuthError` - Authentication failed with the WBEM server.
310
311 - `pywbem.ParseError` - The response from the WBEM server cannot be
312 parsed (for example, invalid characters or UTF-8 sequences, ill-formed
313 XML, or invalid CIM-XML).
314
315 - `pywbem.CIMError` - The WBEM server returned an error response with a
316 CIM status code.
317
318 - `pywbem.TimeoutError` - The WBEM server did not respond in time and the
319 client timed out.
320
321 * Exceptions indicating programming errors:
322
323 - `TypeError`
324 - `KeyError`
325 - `ValueError`
326 - `AttributeError`
327 - ... possibly others ...
328
329 Exceptions indicating programming errors should not happen and should be
330 reported as bugs, unless caused by the code using this class.
331
332 :Ivariables:
333
334 ...
335 All parameters of `__init__` are set as instance variables.
336
337 debug : `bool`
338 A boolean indicating whether logging of the last request and last reply
339 is enabled.
340
341 The initial value of this instance variable is `False`.
342 Debug logging can be enabled for future operations by setting this
343 instance variable to `True`.
344
345 last_request : `unicode`
346 CIM-XML data of the last request sent to the WBEM server
347 on this connection, formatted as prettified XML. Prior to sending the
348 very first request on this connection object, it is `None`.
349
350 last_raw_request : `unicode`
351 CIM-XML data of the last request sent to the WBEM server
352 on this connection, formatted as it was sent. Prior to sending the
353 very first request on this connection object, it is `None`.
354
355 last_reply : `unicode`
356 CIM-XML data of the last response received from the WBEM server
357 on this connection, formatted as prettified XML. Prior to sending the
358 very first request on this connection object, while waiting for any
359 response, it is `None`.
360
361 last_raw_reply : `unicode`
362 CIM-XML data of the last response received from the WBEM server
363 on this connection, formatted as it was received. Prior to sending the
364 very first request on this connection object, while waiting for any
365 response, it is `None`.
366 """
367
368 - def __init__(self, url, creds=None, default_namespace=DEFAULT_NAMESPACE,
369 x509=None, verify_callback=None, ca_certs=None,
370 no_verification=False, timeout=None):
371 """
372 Initialize the `WBEMConnection` object.
373
374 :Parameters:
375
376 url : string
377 URL of the WBEM server (e.g. ``"https://10.11.12.13:6988"``).
378
379 TODO: Describe supported formats.
380
381 creds
382 Credentials for authenticating with the WBEM server. Currently,
383 that is always a tuple of ``(userid, password)``, where:
384
385 * ``userid`` is a string that is the userid to be used for
386 authenticating with the WBEM server.
387
388 * ``password`` is a string that is the password for that userid.
389
390 default_namespace : string
391 Optional: Name of the CIM namespace to be used by default (if no
392 namespace is specified for an operation).
393
394 Default: See method definition.
395
396 x509 : dictionary
397 Optional: X.509 certificates for HTTPS to be used instead of the
398 credentials provided in the `creds` parameter. This parameter is
399 used only when the `url` parameter specifies a scheme of ``https``.
400
401 If `None`, certificates are not used (and credentials are used
402 instead).
403
404 Otherwise, certificates are used instead of the credentials, and
405 this parameter must be a dictionary containing the following
406 key/value pairs:
407
408 * ``'cert_file'`` : The file path of a file containing an X.509
409 certificate.
410
411 * ``'key_file'`` : The file path of a file containing the private
412 key belonging to the public key that is part of the X.509
413 certificate file.
414
415 Default: `None`.
416
417 verify_callback : function
418 Optional: Registers a callback function that will be called to
419 verify the certificate returned by the WBEM server during the SSL
420 handshake, in addition to the verification alreay performed by
421 `M2Crypto`.
422
423 If `None`, no such callback function will be registered.
424
425 The specified function will be called for the returned certificate,
426 and for each of the certificates in its chain of trust.
427
428 See `M2Crypto.SSL.Context.set_verify` for details, as well as
429 http://blog.san-ss.com.ar/2012/05/validating-ssl-certificate-in-python.html):
430
431 The callback function must take five parameters:
432
433 * the `M2Crypto.SSL.Connection` object that triggered the
434 verification.
435
436 * an `OpenSSL.crypto.X509` object representing the certificate
437 to be validated (the returned certificate or one of the
438 certificates in its chain of trust).
439
440 * an integer containing the error number (0 in case no error) of
441 any validation error detected by `M2Crypto`.
442 You can find their meaning in the OpenSSL documentation.
443
444 * an integer indicating the depth (=position) of the certificate to
445 be validated (the one in the second parameter) in the chain of
446 trust of the returned certificate. A value of 0 indicates
447 that the returned is currently validated; any other value
448 indicates the distance of the currently validated certificate to
449 the returned certificate in its chain of trust.
450
451 * an integer that indicates whether the validation of the
452 certificate specified in the second argument passed or did not
453 pass the validation by `M2Crypto`. A value of 1 indicates a
454 successful validation and 0 an unsuccessful one.
455
456 The callback function must return `True` if the verification
457 passes and `False` otherwise.
458
459 Default: `None`.
460
461 ca_certs : string
462 Optional: Location of CA certificates (trusted certificates) for
463 verification purposes.
464
465 The parameter value is either the directory path of a directory
466 prepared using the ``c_rehash`` tool included with OpenSSL, or the
467 file path of a file in PEM format.
468
469 If `None`, the default system path will be used.
470
471 Default: `None`.
472
473 no_verification : `bool`
474 Optional: Indicates that verification of the certificate returned
475 by the WBEM server is disabled (both by `M2Crypto` and by the
476 callback function specified in `verify_callback`).
477
478 Disabling the verification is insecure and should be avoided.
479
480 If `True`, verification is disabled; otherwise, it is enabled.
481
482 Default: `False`.
483
484 timeout : number
485 Timeout in seconds, for requests sent to the server. If the server
486 did not respond within the timeout duration, the socket for the
487 connection will be closed, causing a `TimeoutError` to be raised.
488
489 A value of ``None`` means there is no timeout.
490
491 A value of ``0`` means the timeout is very short, and does not
492 really make any sense.
493
494 Note that not all situations can be handled within this timeout, so
495 for some issues, operations may take longer before raising an
496 exception.
497
498 :Exceptions:
499
500 See the list of exceptions described in `WBEMConnection`.
501 """
502
503 self.url = url
504 self.creds = creds
505 self.x509 = x509
506 self.verify_callback = verify_callback
507 self.ca_certs = ca_certs
508 self.no_verification = no_verification
509 self.default_namespace = default_namespace
510 self.timeout = timeout
511
512 self.debug = False
513 self.last_raw_request = None
514 self.last_raw_reply = None
515 self.last_request = None
516 self.last_reply = None
517
519 """
520 Return a representation of the connection object with the major
521 instance variables, except for the password in the credentials.
522
523 TODO: Change to show all instance variables.
524 """
525 if self.creds is None:
526 user = 'anonymous'
527 else:
528 user = 'user=%s' % self.creds[0]
529 return "%s(%s, %s, namespace=%s)" % \
530 (self.__class__.__name__, self.url, user,
531 self.default_namespace)
532
533 - def imethodcall(self, methodname, namespace, **params):
534 """
535 Perform an intrinsic method call (= CIM operation).
536
537 This is a low-level function that is used by the operation-specific
538 methods of this class (e.g. `EnumerateInstanceNames`). In general,
539 clients should call these operation-specific methods instead of this
540 function.
541
542 The parameters are automatically converted to the right CIM-XML
543 elements.
544
545 :Returns:
546
547 A tupletree (see `tupletree` module) with an ``IRETURNVALUE``
548 element at the root.
549
550 :Exceptions:
551
552 See the list of exceptions described in `WBEMConnection`.
553 """
554
555
556
557 headers = ['CIMOperation: MethodCall',
558 'CIMMethod: %s' % methodname,
559 get_object_header(namespace)]
560
561
562
563 plist = [cim_xml.IPARAMVALUE(x[0], tocimxml(x[1])) \
564 for x in params.items()]
565
566
567
568 req_xml = cim_xml.CIM(
569 cim_xml.MESSAGE(
570 cim_xml.SIMPLEREQ(
571 cim_xml.IMETHODCALL(
572 methodname,
573 cim_xml.LOCALNAMESPACEPATH(
574 [cim_xml.NAMESPACE(ns)
575 for ns in namespace.split('/')]),
576 plist)),
577 '1001', '1.0'),
578 '2.0', '2.0')
579
580 if self.debug:
581 self.last_raw_request = req_xml.toxml()
582 self.last_request = req_xml.toprettyxml(indent=' ')
583
584 self.last_raw_reply = None
585 self.last_reply = None
586
587
588
589 try:
590 reply_xml = wbem_request(
591 self.url, req_xml.toxml(), self.creds, headers,
592 x509=self.x509,
593 verify_callback=self.verify_callback,
594 ca_certs=self.ca_certs,
595 no_verification=self.no_verification,
596 timeout=self.timeout)
597 except (AuthError, ConnectionError, TimeoutError, Error):
598 raise
599
600
601
602 except Exception:
603 raise
604
605
606 if self.debug:
607 self.last_raw_reply = reply_xml
608
609 try:
610 reply_dom = minidom.parseString(reply_xml)
611 except ParseError as exc:
612 msg = str(exc)
613 parsing_error = True
614 except ExpatError as exc:
615
616
617
618 xml_lines = _ensure_unicode(reply_xml).splitlines()
619 if len(xml_lines) >= exc.lineno:
620 parsed_line = xml_lines[exc.lineno - 1]
621 else:
622 parsed_line = "<error: Line number indicated in ExpatError "\
623 "out of range: %s (only %s lines in XML)>" %\
624 (exc.lineno, len(xml_lines))
625 msg = "ExpatError %s: %s: %r" % (str(exc.code), str(exc),
626 parsed_line)
627 parsing_error = True
628 else:
629 parsing_error = False
630
631 if parsing_error or self.debug:
632
633
634
635
636 try:
637 check_utf8_xml_chars(reply_xml, "CIM-XML response")
638 except ParseError:
639 raise
640 else:
641 if parsing_error:
642
643
644 raise ParseError(msg)
645
646 if self.debug:
647 pretty_reply = reply_dom.toprettyxml(indent=' ')
648 self.last_reply = re.sub(r'>( *[\r\n]+)+( *)<', r'>\n\2<',
649 pretty_reply)
650
651
652
653 tup_tree = parse_cim(dom_to_tupletree(reply_dom))
654
655 if tup_tree[0] != 'CIM':
656 raise ParseError('Expecting CIM element, got %s' % tup_tree[0])
657 tup_tree = tup_tree[2]
658
659 if tup_tree[0] != 'MESSAGE':
660 raise ParseError('Expecting MESSAGE element, got %s' % tup_tree[0])
661 tup_tree = tup_tree[2]
662
663 if len(tup_tree) != 1 or tup_tree[0][0] != 'SIMPLERSP':
664 raise ParseError('Expecting one SIMPLERSP element')
665 tup_tree = tup_tree[0][2]
666
667 if tup_tree[0] != 'IMETHODRESPONSE':
668 raise ParseError('Expecting IMETHODRESPONSE element, got %s' %\
669 tup_tree[0])
670
671 if tup_tree[1]['NAME'] != methodname:
672 raise ParseError('Expecting attribute NAME=%s, got %s' %\
673 (methodname, tup_tree[1]['NAME']))
674 tup_tree = tup_tree[2]
675
676
677
678
679
680 if tup_tree is None:
681 return None
682
683 if tup_tree[0] == 'ERROR':
684 code = int(tup_tree[1]['CODE'])
685 if 'DESCRIPTION' in tup_tree[1]:
686 raise CIMError(code, tup_tree[1]['DESCRIPTION'])
687 raise CIMError(code, 'Error code %s' % tup_tree[1]['CODE'])
688
689 if tup_tree[0] != 'IRETURNVALUE':
690 raise ParseError('Expecting IRETURNVALUE element, got %s' \
691 % tup_tree[0])
692
693 return tup_tree
694
695
696 - def methodcall(self, methodname, localobject, Params=None, **params):
697 """
698 Perform an extrinsic method call (= CIM method invocation).
699
700 This is a low-level function that is used by the 'InvokeMethod'
701 method of this class. In general, clients should use 'InvokeMethod'
702 instead of this function.
703
704 The Python method parameters are automatically converted to the right
705 CIM-XML elements. See `InvokeMethod` for details.
706
707 :Returns:
708
709 A tupletree (see `tupletree` module) with a ``RETURNVALUE``
710 element at the root.
711
712 :Exceptions:
713
714 See the list of exceptions described in `WBEMConnection`.
715 """
716
717
718 if hasattr(localobject, 'host') and localobject.host is not None:
719 localobject = localobject.copy()
720 localobject.host = None
721
722
723
724 headers = ['CIMOperation: MethodCall',
725 'CIMMethod: %s' % methodname,
726 get_object_header(localobject)]
727
728
729
730 def paramtype(obj):
731 """Return a string to be used as the CIMTYPE for a parameter."""
732 if isinstance(obj, CIMType):
733 return obj.cimtype
734 elif isinstance(obj, bool):
735 return 'boolean'
736 elif isinstance(obj, six.string_types):
737 return 'string'
738 elif isinstance(obj, (datetime, timedelta)):
739 return 'datetime'
740 elif isinstance(obj, (CIMClassName, CIMInstanceName)):
741 return 'reference'
742 elif isinstance(obj, (CIMClass, CIMInstance)):
743 return 'string'
744 elif isinstance(obj, list):
745 if obj:
746 return paramtype(obj[0])
747 else:
748 return None
749 raise TypeError('Unsupported parameter type "%s"' % type(obj))
750
751 def paramvalue(obj):
752 """Return a cim_xml node to be used as the value for a
753 parameter."""
754 if isinstance(obj, (datetime, timedelta)):
755 obj = CIMDateTime(obj)
756 if isinstance(obj, (CIMType, bool, six.string_types)):
757 return cim_xml.VALUE(atomic_to_cim_xml(obj))
758 if isinstance(obj, (CIMClassName, CIMInstanceName)):
759
760
761 return cim_xml.VALUE_REFERENCE(obj.tocimxml())
762 if isinstance(obj, (CIMClass, CIMInstance)):
763
764
765 return cim_xml.VALUE(obj.tocimxml().toxml())
766 if isinstance(obj, list):
767 if obj and isinstance(obj[0], (CIMClassName, CIMInstanceName)):
768 return cim_xml.VALUE_REFARRAY([paramvalue(x) for x in obj])
769 return cim_xml.VALUE_ARRAY([paramvalue(x) for x in obj])
770 raise TypeError('Unsupported parameter type "%s"' % type(obj))
771
772 def is_embedded(obj):
773 """Determine if an object requires an EmbeddedObject attribute"""
774 if isinstance(obj, list) and obj:
775 return is_embedded(obj[0])
776 elif isinstance(obj, CIMClass):
777 return 'object'
778 elif isinstance(obj, CIMInstance):
779 return 'instance'
780 return None
781
782 if Params is None:
783 Params = []
784 plist = [cim_xml.PARAMVALUE(x[0],
785 paramvalue(x[1]),
786 paramtype(x[1]),
787 embedded_object=is_embedded(x[1]))
788 for x in Params]
789 plist += [cim_xml.PARAMVALUE(x[0],
790 paramvalue(x[1]),
791 paramtype(x[1]),
792 embedded_object=is_embedded(x[1]))
793 for x in params.items()]
794
795
796
797 req_xml = cim_xml.CIM(
798 cim_xml.MESSAGE(
799 cim_xml.SIMPLEREQ(
800 cim_xml.METHODCALL(
801 methodname,
802 localobject.tocimxml(),
803 plist)),
804 '1001', '1.0'),
805 '2.0', '2.0')
806
807 if self.debug:
808 self.last_raw_request = req_xml.toxml()
809 self.last_request = req_xml.toprettyxml(indent=' ')
810
811 self.last_raw_reply = None
812 self.last_reply = None
813
814
815
816 try:
817 reply_xml = wbem_request(
818 self.url, req_xml.toxml(), self.creds, headers,
819 x509=self.x509,
820 verify_callback=self.verify_callback,
821 ca_certs=self.ca_certs,
822 no_verification=self.no_verification,
823 timeout=self.timeout)
824 except (AuthError, ConnectionError, TimeoutError, Error):
825 raise
826
827
828
829 except Exception:
830 raise
831
832
833 if self.debug:
834 self.last_raw_reply = reply_xml
835
836 try:
837 reply_dom = minidom.parseString(reply_xml)
838 except ParseError as exc:
839 msg = str(exc)
840 parsing_error = True
841 except ExpatError as exc:
842
843
844
845 xml_lines = _ensure_unicode(reply_xml).splitlines()
846 if len(xml_lines) >= exc.lineno:
847 parsed_line = xml_lines[exc.lineno - 1]
848 else:
849 parsed_line = "<error: Line number indicated in ExpatError "\
850 "out of range: %s (only %s lines in XML)>" %\
851 (exc.lineno, len(xml_lines))
852 msg = "ExpatError %s: %s: %r" % (str(exc.code), str(exc),
853 parsed_line)
854 parsing_error = True
855 else:
856 parsing_error = False
857
858 if parsing_error or self.debug:
859
860
861
862
863 try:
864 check_utf8_xml_chars(reply_xml, "CIM-XML response")
865 except ParseError:
866 raise
867 else:
868 if parsing_error:
869
870
871 raise ParseError(msg)
872
873 if self.debug:
874 pretty_reply = reply_dom.toprettyxml(indent=' ')
875 self.last_reply = re.sub(r'>( *[\r\n]+)+( *)<', r'>\n\2<',
876 pretty_reply)
877
878
879
880 tt = parse_cim(dom_to_tupletree(reply_dom))
881
882 if tt[0] != 'CIM':
883 raise ParseError('Expecting CIM element, got %s' % tt[0])
884 tt = tt[2]
885
886 if tt[0] != 'MESSAGE':
887 raise ParseError('Expecting MESSAGE element, got %s' % tt[0])
888 tt = tt[2]
889
890 if len(tt) != 1 or tt[0][0] != 'SIMPLERSP':
891 raise ParseError('Expecting one SIMPLERSP element')
892 tt = tt[0][2]
893
894 if tt[0] != 'METHODRESPONSE':
895 raise ParseError('Expecting METHODRESPONSE element, got %s' %\
896 tt[0])
897
898 if tt[1]['NAME'] != methodname:
899 raise ParseError('Expecting attribute NAME=%s, got %s' %\
900 (methodname, tt[1]['NAME']))
901 tt = tt[2]
902
903
904
905
906 if len(tt) > 0 and tt[0][0] == 'ERROR':
907 code = int(tt[0][1]['CODE'])
908 if 'DESCRIPTION' in tt[0][1]:
909 raise CIMError(code, tt[0][1]['DESCRIPTION'])
910 raise CIMError(code, 'Error code %s' % tt[0][1]['CODE'])
911
912 return tt
913
914
915
916
917
919
920 """
921 Enumerate the instance paths of instances of a class (including
922 instances of its subclasses).
923
924 This method performs the EnumerateInstanceNames CIM-XML operation.
925 If the operation succeeds, this method returns.
926 Otherwise, this method raises an exception.
927
928 :Parameters:
929
930 ClassName : string
931 Name of the class to be enumerated.
932
933 namespace : string
934 Optional: Name of the CIM namespace to be used. The value `None`
935 causes the default namespace of the connection object to be used.
936
937 Default: `None`.
938
939 :Returns:
940
941 A list of `CIMInstanceName` objects that are the enumerated
942 instance paths.
943
944 :Exceptions:
945
946 See the list of exceptions described in `WBEMConnection`.
947 """
948
949 if namespace is None:
950 namespace = self.default_namespace
951
952 result = self.imethodcall(
953 'EnumerateInstanceNames',
954 namespace,
955 ClassName=CIMClassName(ClassName),
956 **params)
957
958 names = []
959
960 if result is not None:
961 names = result[2]
962
963 for n in names:
964 setattr(n, 'namespace', namespace)
965
966 return names
967
969
970 """
971 Enumerate the instances of a class (including instances of its
972 subclasses).
973
974 This method performs the EnumerateInstances CIM-XML operation.
975 If the operation succeeds, this method returns.
976 Otherwise, this method raises an exception.
977
978 :Parameters:
979
980 ClassName : string
981 Name of the class to be enumerated.
982
983 namespace : string
984 Optional: Name of the CIM namespace to be used. The value `None`
985 causes the default namespace of the connection object to be used.
986
987 Default: `None`.
988
989 LocalOnly : `bool`
990 Optional: Controls the exclusion of inherited properties from the
991 returned instances, as follows:
992
993 * If `False`, inherited properties are not excluded.
994 * If `True`, the behavior is WBEM server specific.
995
996 Default: `True`.
997
998 This parameter has been deprecated in CIM-XML and should be set to
999 `False` by the caller.
1000
1001 DeepInheritance : `bool`
1002 Optional: Indicates that properties added by subclasses of the
1003 specified class are to be included in the returned instances.
1004 Note, the semantics of this parameter differs between instance and
1005 class level operations.
1006
1007 Default: `True`.
1008
1009 IncludeQualifiers : `bool`
1010 Optional: Indicates that qualifiers are to be included in the
1011 returned instance.
1012
1013 Default: `False`.
1014
1015 This parameter has been deprecated in CIM-XML. Clients cannot rely
1016 on it being implemented by WBEM servers.
1017
1018 IncludeClassOrigin : `bool`
1019 Optional: Indicates that class origin information is to be included
1020 on each property in the returned instances.
1021
1022 Default: `False`.
1023
1024 PropertyList : iterable of string
1025 Optional: An iterable specifying the names of the properties to be
1026 included in the returned instances. An empty iterable indicates to
1027 include no properties. A value of `None` for this parameter
1028 indicates to include all properties.
1029
1030 Default: `None`.
1031
1032 :Returns:
1033
1034 A list of `CIMInstance` objects that are representations of
1035 the enumerated instances.
1036
1037 :Exceptions:
1038
1039 See the list of exceptions described in `WBEMConnection`.
1040 """
1041
1042 if namespace is None:
1043 namespace = self.default_namespace
1044
1045 result = self.imethodcall(
1046 'EnumerateInstances',
1047 namespace,
1048 ClassName=CIMClassName(ClassName),
1049 **params)
1050
1051 instances = []
1052
1053 if result is not None:
1054 instances = result[2]
1055
1056 for i in instances:
1057 setattr(i.path, 'namespace', namespace)
1058
1059 return instances
1060
1062
1063 """
1064 Retrieve an instance.
1065
1066 This method performs the GetInstance CIM-XML operation.
1067 If the operation succeeds, this method returns.
1068 Otherwise, this method raises an exception.
1069
1070 :Parameters:
1071
1072 InstanceName : `CIMInstanceName`
1073 Instance path of the instance to be retrieved.
1074
1075 LocalOnly : `bool`
1076 Optional: Controls the exclusion of inherited properties from the
1077 returned instance, as follows:
1078
1079 * If `False`, inherited properties are not excluded.
1080 * If `True`, the behavior is WBEM server specific.
1081
1082 Default: `True`.
1083
1084 This parameter has been deprecated in CIM-XML and should be set to
1085 `False` by the caller.
1086
1087 IncludeQualifiers : `bool`
1088 Optional: Indicates that qualifiers are to be included in the
1089 returned instance.
1090
1091 Default: `False`.
1092
1093 This parameter has been deprecated in CIM-XML. Clients cannot rely
1094 on it being implemented by WBEM servers.
1095
1096 IncludeClassOrigin : `bool`
1097 Optional: Indicates that class origin information is to be included
1098 on each property in the returned instance.
1099
1100 Default: `False`.
1101
1102 PropertyList : iterable of string
1103 Optional: An iterable specifying the names of the properties to be
1104 included in the returned instances. An empty iterable indicates to
1105 include no properties. A value of `None` for this parameter
1106 indicates to include all properties.
1107
1108 Default: `None`.
1109
1110 :Returns:
1111
1112 A `CIMInstance` object that is a representation of the
1113 retrieved instance.
1114
1115 :Exceptions:
1116
1117 See the list of exceptions described in `WBEMConnection`.
1118 """
1119
1120
1121
1122 iname = InstanceName.copy()
1123 iname.host = None
1124 iname.namespace = None
1125
1126 if InstanceName.namespace is None:
1127 namespace = self.default_namespace
1128 else:
1129 namespace = InstanceName.namespace
1130
1131 result = self.imethodcall(
1132 'GetInstance',
1133 namespace,
1134 InstanceName=iname,
1135 **params)
1136
1137 instance = result[2][0]
1138 instance.path = InstanceName
1139 instance.path.namespace = namespace
1140
1141 return instance
1142
1144
1145 """
1146 Delete an instance.
1147
1148 This method performs the DeleteInstance CIM-XML operation.
1149 If the operation succeeds, this method returns.
1150 Otherwise, this method raises an exception.
1151
1152 :Parameters:
1153
1154 InstanceName : `CIMInstanceName`
1155 Instance path of the instance to be deleted.
1156
1157 :Exceptions:
1158
1159 See the list of exceptions described in `WBEMConnection`.
1160 """
1161
1162
1163
1164 iname = InstanceName.copy()
1165 iname.host = None
1166 iname.namespace = None
1167
1168 if InstanceName.namespace is None:
1169 namespace = self.default_namespace
1170 else:
1171 namespace = InstanceName.namespace
1172
1173 self.imethodcall(
1174 'DeleteInstance',
1175 namespace,
1176 InstanceName=iname,
1177 **params)
1178
1180
1181 """
1182 Create an instance.
1183
1184 This method performs the CreateInstance CIM-XML operation.
1185 If the operation succeeds, this method returns.
1186 Otherwise, this method raises an exception.
1187
1188 :Parameters:
1189
1190 NewInstance : `CIMInstance`
1191 A representation of the instance to be created.
1192
1193 The `namespace` and `classname` instance variables of this object
1194 specify CIM namespace and creation class for the new instance,
1195 respectively.
1196 An instance path specified using the `path` instance variable of
1197 this object will be ignored.
1198
1199 The `properties` instance variable of this object specifies initial
1200 property values for the new instance.
1201
1202 Instance-level qualifiers have been deprecated in CIM, so any
1203 qualifier values specified using the `qualifiers` instance variable
1204 of this object will be ignored.
1205
1206 :Returns:
1207
1208 `CIMInstanceName` object that is the instance path of the new
1209 instance.
1210
1211 :Exceptions:
1212
1213 See the list of exceptions described in `WBEMConnection`.
1214 """
1215
1216
1217
1218 if NewInstance.path is not None and \
1219 NewInstance.path.namespace is not None:
1220 namespace = NewInstance.path.namespace
1221 else:
1222 namespace = self.default_namespace
1223
1224
1225
1226
1227 instance = NewInstance.copy()
1228 instance.path = None
1229
1230 result = self.imethodcall(
1231 'CreateInstance',
1232 namespace,
1233 NewInstance=instance,
1234 **params)
1235
1236 name = result[2][0]
1237 name.namespace = namespace
1238
1239 return name
1240
1242
1243 """
1244 Modify the property values of an instance.
1245
1246 This method performs the ModifyInstance CIM-XML operation.
1247 If the operation succeeds, this method returns.
1248 Otherwise, this method raises an exception.
1249
1250 :Parameters:
1251
1252 ModifiedInstance : `CIMInstance`
1253 A representation of the modified instance. This object needs to
1254 contain any new property values and the instance path of the
1255 instance to be modified. Missing properties (relative to the class
1256 declaration) and properties provided with a value of `None` will be
1257 set to NULL. Typically, this object has been retrieved by other
1258 operations, such as GetInstance.
1259
1260 IncludeQualifiers : `bool`
1261 Optional: Indicates that qualifiers are to be modified as specified
1262 in the `ModifiedInstance` parameter.
1263
1264 Default: `True`.
1265
1266 This parameter has been deprecated in CIM-XML. Clients cannot rely
1267 on it being implemented by WBEM servers.
1268
1269 PropertyList : iterable of string
1270 Optional: An iterable specifying the names of the properties to be
1271 modified. An empty iterable indicates to modify no properties. A
1272 value of `None` for this parameter indicates to modify all
1273 properties.
1274
1275 Default: `None`.
1276
1277 :Exceptions:
1278
1279 See the list of exceptions described in `WBEMConnection`.
1280 """
1281
1282
1283
1284 if ModifiedInstance.path is None:
1285 raise ValueError(
1286 'ModifiedInstance parameter must have path attribute set')
1287
1288
1289
1290 if ModifiedInstance.path.namespace is None:
1291 namespace = self.default_namespace
1292 else:
1293 namespace = ModifiedInstance.path.namespace
1294
1295 instance = ModifiedInstance.copy()
1296 instance.path.namespace = None
1297
1298 self.imethodcall(
1299 'ModifyInstance',
1300 namespace,
1301 ModifiedInstance=instance,
1302 **params)
1303
1304 - def ExecQuery(self, QueryLanguage, Query, namespace=None):
1305
1306 """
1307 Execute a query in a namespace.
1308
1309 This method performs the ExecQuery CIM-XML operation.
1310 If the operation succeeds, this method returns.
1311 Otherwise, this method raises an exception.
1312
1313 :Parameters:
1314
1315 QueryLanguage : string
1316 Name of the query language used in the `Query` parameter.
1317
1318 Query : string
1319 Query string in the query language specified in the `QueryLanguage`
1320 parameter.
1321
1322 namespace : string
1323 Optional: Name of the CIM namespace to be used. The value `None`
1324 causes the default namespace of the connection object to be used.
1325
1326 Default: `None`.
1327
1328 :Returns:
1329
1330 A list of `CIMInstance` objects that represents the query
1331 result.
1332 These instances have their `path` instance variable set to identify
1333 their creation class and the target namespace of the query, but
1334 they are not addressable instances.
1335
1336 :Exceptions:
1337
1338 See the list of exceptions described in `WBEMConnection`.
1339 """
1340
1341 if namespace is None:
1342 namespace = self.default_namespace
1343
1344 result = self.imethodcall(
1345 'ExecQuery',
1346 namespace,
1347 QueryLanguage=QueryLanguage,
1348 Query=Query)
1349
1350 instances = []
1351
1352 if result is not None:
1353 instances = [tt[2] for tt in result[2]]
1354
1355 for i in instances:
1356 setattr(i.path, 'namespace', namespace)
1357
1358 return instances
1359
1360
1361
1362
1363
1365 """Convert string ClassName parameter to a CIMClassName."""
1366
1367 if 'ClassName' in params and \
1368 isinstance(params['ClassName'], six.string_types):
1369 params['ClassName'] = CIMClassName(params['ClassName'])
1370
1371 return params
1372
1374
1375 """
1376 Enumerate the names of subclasses of a class, or of the top-level
1377 classes in a namespace.
1378
1379 This method performs the EnumerateClassNames CIM-XML operation.
1380 If the operation succeeds, this method returns.
1381 Otherwise, this method raises an exception.
1382
1383 :Parameters:
1384
1385 namespace : string
1386 Optional: Name of the namespace in which the class names are to be
1387 enumerated.
1388 The value `None` causes the default namespace of the connection to
1389 be used.
1390
1391 Default: `None`
1392
1393 ClassName : string
1394 Optional: Name of the class whose subclasses are to be retrieved.
1395 The value `None` causes the top-level classes in the namespace to
1396 be retrieved.
1397
1398 Default: `None`
1399
1400 DeepInheritance : `bool`
1401 Optional: Indicates that all (direct and indirect) subclasses of
1402 the specified class or of the top-level classes are to be included
1403 in the result.
1404 `False` indicates that only direct subclasses of the specified
1405 class or ony top-level classes are to be included in the result.
1406
1407 Note, the semantics of this parameter differs between instance and
1408 class level operations.
1409
1410 Default: `False`.
1411
1412 :Returns:
1413
1414 A list of strings that are the class names of the enumerated
1415 classes.
1416
1417 :Exceptions:
1418
1419 See the list of exceptions described in `WBEMConnection`.
1420 """
1421
1422 params = self._map_classname_param(params)
1423
1424 if namespace is None:
1425 namespace = self.default_namespace
1426
1427 result = self.imethodcall(
1428 'EnumerateClassNames',
1429 namespace,
1430 **params)
1431
1432 if result is None:
1433 return []
1434 else:
1435 return [x.classname for x in result[2]]
1436
1438
1439 """
1440 Enumerate the subclasses of a class, or the top-level classes in a
1441 namespace.
1442
1443 This method performs the EnumerateClasses CIM-XML operation.
1444 If the operation succeeds, this method returns.
1445 Otherwise, this method raises an exception.
1446
1447 :Parameters:
1448
1449 namespace : string
1450 Optional: Name of the namespace in which the classes are to be
1451 enumerated.
1452 The value `None` causes the default namespace of the connection to
1453 be used.
1454
1455 Default: `None`
1456
1457 ClassName : string
1458 Optional: Name of the class whose subclasses are to be retrieved.
1459 The value `None` causes the top-level classes in the namespace to
1460 be retrieved.
1461
1462 Default: `None`
1463
1464 DeepInheritance : `bool`
1465 Optional: Indicates that all (direct and indirect) subclasses of
1466 the specified class or of the top-level classes are to be included
1467 in the result.
1468 `False` indicates that only direct subclasses of the specified
1469 class or ony top-level classes are to be included in the result.
1470
1471 Note, the semantics of this parameter differs between instance and
1472 class level operations.
1473
1474 Default: `False`.
1475
1476 LocalOnly : `bool`
1477 Optional: Indicates that inherited properties, methods, and
1478 qualifiers are to be excluded from the returned classes.
1479
1480 Default: `True`.
1481
1482 IncludeQualifiers : `bool`
1483 Optional: Indicates that qualifiers are to be included in the
1484 returned classes.
1485
1486 Default: `False`.
1487
1488 IncludeClassOrigin : `bool`
1489 Optional: Indicates that class origin information is to be included
1490 on each property and method in the returned classes.
1491
1492 Default: `False`.
1493
1494 :Returns:
1495
1496 A list of `CIMClass` objects that are representations of the
1497 enumerated classes.
1498
1499 :Exceptions:
1500
1501 See the list of exceptions described in `WBEMConnection`.
1502 """
1503
1504 params = self._map_classname_param(params)
1505
1506 if namespace is None:
1507 namespace = self.default_namespace
1508
1509 result = self.imethodcall(
1510 'EnumerateClasses',
1511 namespace,
1512 **params)
1513
1514 if result is None:
1515 return []
1516
1517 return result[2]
1518
1519 - def GetClass(self, ClassName, namespace=None, **params):
1520
1521 """
1522 Retrieve a class.
1523
1524 This method performs the GetClass CIM-XML operation.
1525 If the operation succeeds, this method returns.
1526 Otherwise, this method raises an exception.
1527
1528 :Parameters:
1529
1530 ClassName : string
1531 Name of the class to be retrieved.
1532
1533 namespace : string
1534 Optional: Name of the namespace of the class to be retrieved.
1535 The value `None` causes the default namespace of the connection to
1536 be used.
1537
1538 Default: `None`
1539
1540 LocalOnly : `bool`
1541 Optional: Indicates that inherited properties, methods, and
1542 qualifiers are to be excluded from the returned class.
1543
1544 Default: `True`.
1545
1546 IncludeQualifiers : `bool`
1547 Optional: Indicates that qualifiers are to be included in the
1548 returned class.
1549
1550 Default: `False`.
1551
1552 IncludeClassOrigin : `bool`
1553 Optional: Indicates that class origin information is to be included
1554 on each property and method in the returned class.
1555
1556 Default: `False`.
1557
1558 PropertyList : iterable of string
1559 Optional: An iterable specifying the names of the properties to be
1560 included in the returned class. An empty iterable indicates to
1561 include no properties. A value of `None` for this parameter
1562 indicates to include all properties.
1563
1564 Default: `None`.
1565
1566 :Returns:
1567
1568 A `CIMClass` object that is a representation of the
1569 retrieved class.
1570
1571 :Exceptions:
1572
1573 See the list of exceptions described in `WBEMConnection`.
1574 """
1575
1576 params = self._map_classname_param(params)
1577
1578 if namespace is None:
1579 namespace = self.default_namespace
1580
1581 result = self.imethodcall(
1582 'GetClass',
1583 namespace,
1584 ClassName=CIMClassName(ClassName),
1585 **params)
1586
1587 return result[2][0]
1588
1589 - def DeleteClass(self, ClassName, namespace=None, **params):
1590
1591 """
1592 Delete a class.
1593
1594 This method performs the DeleteClass CIM-XML operation.
1595 If the operation succeeds, this method returns.
1596 Otherwise, this method raises an exception.
1597
1598 :Parameters:
1599
1600 ClassName : string
1601 Name of the class to be deleted.
1602
1603 namespace : string
1604 Optional: Name of the namespace of the class to be deleted.
1605 The value `None` causes the default namespace of the connection to
1606 be used.
1607
1608 Default: `None`
1609
1610 :Exceptions:
1611
1612 See the list of exceptions described in `WBEMConnection`.
1613 """
1614
1615 params = self._map_classname_param(params)
1616
1617 if namespace is None:
1618 namespace = self.default_namespace
1619
1620 self.imethodcall(
1621 'DeleteClass',
1622 namespace,
1623 ClassName=CIMClassName(ClassName),
1624 **params)
1625
1626 - def ModifyClass(self, ModifiedClass, namespace=None, **params):
1627
1628 """
1629 Modify a class.
1630
1631 This method performs the ModifyClass CIM-XML operation.
1632 If the operation succeeds, this method returns.
1633 Otherwise, this method raises an exception.
1634
1635 :Parameters:
1636
1637 ModifiedClass : `CIMClass`
1638 A representation of the modified class. This object needs to
1639 contain any modified properties, methods and qualifiers and the
1640 class path of the class to be modified.
1641 Typically, this object has been retrieved by other operations, such
1642 as `GetClass`.
1643
1644 :Exceptions:
1645
1646 See the list of exceptions described in `WBEMConnection`.
1647 """
1648
1649 if namespace is None:
1650 namespace = self.default_namespace
1651
1652 self.imethodcall(
1653 'ModifyClass',
1654 namespace,
1655 ModifiedClass=ModifiedClass,
1656 **params)
1657
1658 - def CreateClass(self, NewClass, namespace=None, **params):
1659
1660 """
1661 Create a class.
1662
1663 This method performs the CreateClass CIM-XML operation.
1664 If the operation succeeds, this method returns.
1665 Otherwise, this method raises an exception.
1666
1667 :Parameters:
1668
1669 NewClass : `CIMClass`
1670 A representation of the class to be created. This object needs to
1671 contain any properties, methods, qualifiers, superclass name, and
1672 the class name of the class to be created.
1673 The class path in this object (`path` instance variable) will be
1674 ignored.
1675
1676 namespace : string
1677 Optional: Name of the namespace in which the class is to be
1678 created.
1679 The value `None` causes the default namespace of the connection to
1680 be used.
1681
1682 Default: `None`
1683
1684 :Exceptions:
1685
1686 See the list of exceptions described in `WBEMConnection`.
1687 """
1688
1689 if namespace is None:
1690 namespace = self.default_namespace
1691
1692 self.imethodcall(
1693 'CreateClass',
1694 namespace,
1695 NewClass=NewClass,
1696 **params)
1697
1698
1699
1700
1701
1703 """Add an object name (either a class name or an instance
1704 name) to a dictionary of parameter names."""
1705
1706 if isinstance(object_, (CIMClassName, CIMInstanceName)):
1707 params['ObjectName'] = object_.copy()
1708 params['ObjectName'].namespace = None
1709 elif isinstance(object_, six.string_types):
1710 params['ObjectName'] = CIMClassName(object_)
1711 else:
1712 raise ValueError('Expecting a classname, CIMClassName or '
1713 'CIMInstanceName object')
1714
1715 return params
1716
1718 """Convert various convenience parameters and types into their
1719 correct form for passing to the imethodcall() function."""
1720
1721
1722
1723
1724 if 'ResultClass' in params and \
1725 isinstance(params['ResultClass'], six.string_types):
1726 params['ResultClass'] = CIMClassName(params['ResultClass'])
1727
1728 if 'AssocClass' in params and \
1729 isinstance(params['AssocClass'], six.string_types):
1730 params['AssocClass'] = CIMClassName(params['AssocClass'])
1731
1732 return params
1733
1735
1736 """
1737 Retrieve the instances (or classes) associated to a source instance
1738 (or source class).
1739
1740 This method performs the Associators CIM-XML operation.
1741 If the operation succeeds, this method returns.
1742 Otherwise, this method raises an exception.
1743
1744 :Parameters:
1745
1746 ObjectName
1747 For instance level usage: The instance path of the source instance,
1748 as a `CIMInstanceName` object. If that object does not
1749 specify a namespace, the default namespace of the connection is
1750 used.
1751
1752 For class level usage: The class path of the source class, as a
1753 string or as a `CIMClassName` object.
1754 If specified as a string, the string is interpreted as a class name
1755 in the default namespace of the connection.
1756 If specified as a `CIMClassName` object that does not
1757 specify a namespace, the default namespace of the connection is
1758 used.
1759
1760 AssocClass : string or `CIMClassName`
1761 Optional: Class name of an association class, to filter the result
1762 to include only traversals of that association class (or
1763 subclasses).
1764
1765 Default: `None` (no filtering).
1766
1767 ResultClass : string or `CIMClassName`
1768 Optional: Class name of an associated class, to filter the result
1769 to include only traversals to that associated class (or
1770 subclasses).
1771
1772 Default: `None` (no filtering).
1773
1774 Role : string
1775 Optional: Role name (= property name) of the source end, to filter
1776 the result to include only traversals from that source role.
1777
1778 Default: `None` (no filtering).
1779
1780 ResultRole
1781 Optional: Role name (= property name) of the far end, to filter
1782 the result to include only traversals to that far role.
1783
1784 Default: `None` (no filtering).
1785
1786 IncludeQualifiers : `bool`
1787 Optional: Indicates that qualifiers are to be included in the
1788 returned instances (or classes).
1789
1790 Default: `False`.
1791
1792 This parameter has been deprecated in CIM-XML. Clients cannot rely
1793 on it being implemented by WBEM servers.
1794
1795 IncludeClassOrigin : `bool`
1796 Optional: Indicates that class origin information is to be included
1797 on each property or method in the returned instances (or classes).
1798
1799 Default: `False`.
1800
1801 PropertyList : iterable of string
1802 Optional: An iterable specifying the names of the properties to be
1803 included in the returned instances (or classes). An empty iterable
1804 indicates to include no properties. A value of `None` for this
1805 parameter indicates to include all properties.
1806
1807 Default: `None`.
1808
1809 :Returns:
1810
1811 For instance level usage, a list of `CIMInstance` objects
1812 that are representations of the associated instances.
1813
1814 For class level usage, a list of `CIMClass` objects
1815 that are representations the associated classes.
1816
1817 :Exceptions:
1818
1819 See the list of exceptions described in `WBEMConnection`.
1820 """
1821
1822 params = self._map_association_params(params)
1823 params = self._add_objectname_param(params, ObjectName)
1824
1825 namespace = self.default_namespace
1826
1827 if isinstance(ObjectName, CIMInstanceName) and \
1828 ObjectName.namespace is not None:
1829 namespace = ObjectName.namespace
1830
1831 result = self.imethodcall(
1832 'Associators',
1833 namespace,
1834 **params)
1835
1836 if result is None:
1837 return []
1838
1839 return [x[2] for x in result[2]]
1840
1842
1843 """
1844 Retrieve the instance paths of the instances (or class paths of the
1845 classes) associated to a source instance (or source class).
1846
1847 This method performs the AssociatorNames CIM-XML operation.
1848 If the operation succeeds, this method returns.
1849 Otherwise, this method raises an exception.
1850
1851 :Parameters:
1852
1853 ObjectName
1854 For instance level usage: The instance path of the source instance,
1855 as a `CIMInstanceName` object. If that object does not
1856 specify a namespace, the default namespace of the connection is
1857 used.
1858
1859 For class level usage: The class path of the source class, as a
1860 string or as a `CIMClassName` object.
1861 If specified as a string, the string is interpreted as a class name
1862 in the default namespace of the connection.
1863 If specified as a `CIMClassName` object that does not
1864 specify a namespace, the default namespace of the connection is
1865 used.
1866
1867 AssocClass : string or `CIMClassName`
1868 Optional: Class name of an association class, to filter the result
1869 to include only traversals of that association class (or
1870 subclasses).
1871
1872 Default: `None` (no filtering).
1873
1874 ResultClass : string or `CIMClassName`
1875 Optional: Class name of an associated class, to filter the result
1876 to include only traversals to that associated class (or
1877 subclasses).
1878
1879 Default: `None` (no filtering).
1880
1881 Role : string
1882 Optional: Role name (= property name) of the source end, to filter
1883 the result to include only traversals from that source role.
1884
1885 Default: `None` (no filtering).
1886
1887 ResultRole
1888 Optional: Role name (= property name) of the far end, to filter
1889 the result to include only traversals to that far role.
1890
1891 Default: `None` (no filtering).
1892
1893 :Returns:
1894
1895 For instance level usage, a list of `CIMInstanceName`
1896 objects that are the instance paths of the associated instances.
1897
1898 For class level usage, a list of `CIMClassName` objects
1899 that are the class paths of the associated classes.
1900
1901 :Exceptions:
1902
1903 See the list of exceptions described in `WBEMConnection`.
1904 """
1905
1906 params = self._map_association_params(params)
1907 params = self._add_objectname_param(params, ObjectName)
1908
1909 namespace = self.default_namespace
1910
1911 if isinstance(ObjectName, CIMInstanceName) and \
1912 ObjectName.namespace is not None:
1913 namespace = ObjectName.namespace
1914
1915 result = self.imethodcall(
1916 'AssociatorNames',
1917 namespace,
1918 **params)
1919
1920 if result is None:
1921 return []
1922
1923 return [x[2] for x in result[2]]
1924
1926
1927 """
1928 Retrieve the association instances (or association classes) that
1929 reference a source instance (or source class).
1930
1931 This method performs the References CIM-XML operation.
1932 If the operation succeeds, this method returns.
1933 Otherwise, this method raises an exception.
1934
1935 :Parameters:
1936
1937 ObjectName
1938 For instance level usage: The instance path of the source instance,
1939 as a `CIMInstanceName` object. If that object does not
1940 specify a namespace, the default namespace of the connection is
1941 used.
1942
1943 For class level usage: The class path of the source class, as a
1944 string or as a `CIMClassName` object.
1945 If specified as a string, the string is interpreted as a class name
1946 in the default namespace of the connection.
1947 If specified as a `CIMClassName` object that does not
1948 specify a namespace, the default namespace of the connection is
1949 used.
1950
1951 ResultClass : string or `CIMClassName`
1952 Optional: Class name of an association class, to filter the result
1953 to include only traversals of that association class (or
1954 subclasses).
1955
1956 Default: `None` (no filtering).
1957
1958 Role : string
1959 Optional: Role name (= property name) of the source end, to filter
1960 the result to include only traversals from that source role.
1961
1962 Default: `None` (no filtering).
1963
1964 IncludeQualifiers : `bool`
1965 Optional: Indicates that qualifiers are to be included in the
1966 returned instances (or classes).
1967
1968 Default: `False`.
1969
1970 This parameter has been deprecated in CIM-XML. Clients cannot rely
1971 on it being implemented by WBEM servers.
1972
1973 IncludeClassOrigin : `bool`
1974 Optional: Indicates that class origin information is to be included
1975 on each property or method in the returned instances (or classes).
1976
1977 Default: `False`.
1978
1979 PropertyList : iterable of string
1980 Optional: An iterable specifying the names of the properties to be
1981 included in the returned instances (or classes). An empty iterable
1982 indicates to include no properties. A value of `None` for this
1983 parameter indicates to include all properties.
1984
1985 Default: `None`.
1986
1987 :Returns:
1988
1989 For instance level usage, a list of `CIMInstance` objects
1990 that are representations of the referencing association instances.
1991
1992 For class level usage, a list of `CIMClass` objects
1993 that are representations the referencing association classes.
1994
1995 :Exceptions:
1996
1997 See the list of exceptions described in `WBEMConnection`.
1998 """
1999
2000 params = self._map_association_params(params)
2001 params = self._add_objectname_param(params, ObjectName)
2002
2003 namespace = self.default_namespace
2004
2005 if isinstance(ObjectName, CIMInstanceName) and \
2006 ObjectName.namespace is not None:
2007 namespace = ObjectName.namespace
2008
2009 result = self.imethodcall(
2010 'References',
2011 namespace,
2012 **params)
2013
2014 if result is None:
2015 return []
2016
2017 return [x[2] for x in result[2]]
2018
2020
2021 """
2022 Retrieve the instance paths of the association instances (or class
2023 paths of the association classes) that reference a source instance
2024 (or source class).
2025
2026 This method performs the ReferenceNames CIM-XML operation.
2027 If the operation succeeds, this method returns.
2028 Otherwise, this method raises an exception.
2029
2030 :Parameters:
2031
2032 ObjectName
2033 For instance level usage: The instance path of the source instance,
2034 as a `CIMInstanceName` object. If that object does not
2035 specify a namespace, the default namespace of the connection is
2036 used.
2037
2038 For class level usage: The class path of the source class, as a
2039 string or as a `CIMClassName` object.
2040 If specified as a string, the string is interpreted as a class name
2041 in the default namespace of the connection.
2042 If specified as a `CIMClassName` object that does not
2043 specify a namespace, the default namespace of the connection is
2044 used.
2045
2046 ResultClass : string or `CIMClassName`
2047 Optional: Class name of an association class, to filter the result
2048 to include only traversals of that association class (or
2049 subclasses).
2050
2051 Default: `None` (no filtering).
2052
2053 Role : string
2054 Optional: Role name (= property name) of the source end, to filter
2055 the result to include only traversals from that source role.
2056
2057 Default: `None` (no filtering).
2058
2059 :Returns:
2060
2061 For instance level usage, a list of `CIMInstanceName`
2062 objects that are the instance paths of the referencing association
2063 instances.
2064
2065 For class level usage, a list of `CIMClassName` objects
2066 that are the class paths of the referencing association classes.
2067
2068 :Exceptions:
2069
2070 See the list of exceptions described in `WBEMConnection`.
2071 """
2072
2073 params = self._map_association_params(params)
2074 params = self._add_objectname_param(params, ObjectName)
2075
2076 namespace = self.default_namespace
2077
2078 if isinstance(ObjectName, CIMInstanceName) and \
2079 ObjectName.namespace is not None:
2080 namespace = ObjectName.namespace
2081
2082 result = self.imethodcall(
2083 'ReferenceNames',
2084 namespace,
2085 **params)
2086
2087 if result is None:
2088 return []
2089
2090 return [x[2] for x in result[2]]
2091
2092
2093
2094
2095
2096 - def InvokeMethod(self, MethodName, ObjectName, Params=None, **params):
2097
2098 """
2099 Invoke a method on a target instance or on a target class.
2100
2101 The methods that can be invoked are static and non-static methods
2102 defined in a class (also known as *extrinsic* methods).
2103 Static methods can be invoked on instances and on classes.
2104 Non-static methods can be invoked only on instances.
2105
2106 This method performs the InvokeMethod CIM-XML operation.
2107 If the operation succeeds, this method returns.
2108 Otherwise, this method raises an exception.
2109
2110 Input parameters for the CIM method can be specified in a
2111 order-preserving way using the ``Params`` parameter, and in a
2112 order-agnostic way using the ``**params`` keyword parameters.
2113
2114 :Parameters:
2115
2116 MethodName : string
2117 Name of the method to be invoked (without parenthesis or any
2118 parameter signature).
2119
2120 ObjectName
2121 For instance level usage: The instance path of the target instance,
2122 as a `CIMInstanceName` object. If that object does not
2123 specify a namespace, the default namespace of the connection is
2124 used.
2125
2126 For class level usage: The class path of the target class, as a
2127 string or as a `CIMClassName` object.
2128 If specified as a string, the string is interpreted as a class name
2129 in the default namespace of the connection.
2130 If specified as a `CIMClassName` object that does not
2131 specify a namespace, the default namespace of the connection is
2132 used.
2133
2134 Params
2135 A list of input parameters for the CIM method.
2136
2137 Each list item represents a single input parameter for the CIM
2138 method and must be a ``tuple(name,value)``, where ``name`` is the
2139 parameter name in any lexical case, and ``value`` is the parameter
2140 value as a CIM typed value as described in `cim_types`.
2141
2142 **params
2143 Keyword parameters for the input parameters for the CIM method.
2144
2145 Each keyword parameter represents a single input parameter for the
2146 CIM method, where the key is the parameter name in any lexical
2147 case, and the value is the parameter value as a CIM typed value as
2148 described in `cim_types`.
2149
2150 The overall list of input parameters represented in the CIM-XML
2151 request message that is sent to the WBEM server is formed from
2152 the list of parameters specified in ``Params`` preserving its
2153 order, followed by the set of parameters specified in ``**params``
2154 in any order. There is no checking for duplicate parameter names
2155 in the PyWBEM client.
2156
2157
2158 :Returns:
2159
2160 A tuple of ``(returnvalue, outparams)``, where:
2161
2162 - ``returnvalue`` : Return value of the CIM method, as a CIM typed
2163 value as described in `cim_types`.
2164 - ``outparams`` : Output parameters of the CIM method, as a
2165 `NocaseDict` dictionary containing all CIM method output
2166 parameters, where the dictionary items have:
2167
2168 * a key that is the CIM parameter name, as a string.
2169 * a value that is the CIM parameter value, as a CIM typed value
2170 as described in `cim_types`.
2171
2172 :Exceptions:
2173
2174 See the list of exceptions described in `WBEMConnection`.
2175 """
2176
2177
2178
2179 obj = ObjectName
2180
2181 if isinstance(obj, six.string_types):
2182 obj = CIMClassName(obj, namespace=self.default_namespace)
2183
2184 if isinstance(obj, CIMInstanceName) and obj.namespace is None:
2185 obj = ObjectName.copy()
2186 obj.namespace = self.default_namespace
2187
2188
2189
2190 result = self.methodcall(MethodName, obj, Params, **params)
2191
2192
2193
2194 returnvalue = None
2195
2196 if len(result) > 0 and result[0][0] == 'RETURNVALUE':
2197
2198 returnvalue = tocimobj(result[0][1]['PARAMTYPE'], result[0][2])
2199 result = result[1:]
2200
2201
2202
2203 output_params = NocaseDict()
2204
2205 for p in result:
2206 if p[1] == 'reference':
2207 output_params[p[0]] = p[2]
2208 else:
2209 output_params[p[0]] = tocimobj(p[1], p[2])
2210
2211 return returnvalue, output_params
2212
2213
2214
2215
2216
2218
2219 """
2220 Enumerate qualifier declarations.
2221
2222 This method performs the EnumerateQualifiers CIM-XML operation.
2223 If the operation succeeds, this method returns.
2224 Otherwise, this method raises an exception.
2225
2226 :Parameters:
2227
2228 namespace : string
2229 Optional: Name of the namespace in which the qualifier
2230 declarations are to be enumerated.
2231 The value `None` causes the default namespace of the connection to
2232 be used.
2233
2234 :Returns:
2235
2236 A list of `CIMQualifierDeclaration` objects that are
2237 representations of the enumerated qualifier declarations.
2238
2239 :Exceptions:
2240
2241 See the list of exceptions described in `WBEMConnection`.
2242 """
2243
2244 if namespace is None:
2245 namespace = self.default_namespace
2246
2247 result = self.imethodcall(
2248 'EnumerateQualifiers',
2249 namespace,
2250 **params)
2251
2252
2253 if result is not None:
2254 qualifiers = result[2]
2255 else:
2256 qualifiers = []
2257
2258 return qualifiers
2259
2260 - def GetQualifier(self, QualifierName, namespace=None, **params):
2261
2262 """
2263 Retrieve a qualifier declaration.
2264
2265 This method performs the GetQualifier CIM-XML operation.
2266 If the operation succeeds, this method returns.
2267 Otherwise, this method raises an exception.
2268
2269 :Parameters:
2270
2271 Qualifier : string
2272 Name of the qualifier declaration to be retrieved.
2273
2274 namespace : string
2275 Optional: Name of the namespace of the qualifier declaration.
2276 The value `None` causes the default namespace of the connection to
2277 be used.
2278
2279 :Returns:
2280
2281 A `CIMQualifierDeclaration` object that is a representation
2282 of the retrieved qualifier declaration.
2283
2284 :Exceptions:
2285
2286 See the list of exceptions described in `WBEMConnection`.
2287 """
2288
2289 if namespace is None:
2290 namespace = self.default_namespace
2291
2292 result = self.imethodcall(
2293 'GetQualifier',
2294 namespace,
2295 QualifierName=QualifierName,
2296 **params)
2297
2298 if result is not None:
2299 names = result[2][0]
2300
2301 return names
2302
2303 - def SetQualifier(self, QualifierDeclaration, namespace=None, **params):
2304
2305 """
2306 Create or modify a qualifier declaration.
2307
2308 This method performs the SetQualifier CIM-XML operation.
2309 If the operation succeeds, this method returns.
2310 Otherwise, this method raises an exception.
2311
2312 :Parameters:
2313
2314 QualifierDeclaration : `CIMQualifierDeclaration`
2315 Representation of the qualifier declaration to be created or
2316 modified.
2317
2318 namespace : string
2319 Optional: Name of the namespace in which the qualifier declaration
2320 is to be created or modified.
2321 The value `None` causes the default namespace of the connection to
2322 be used.
2323
2324 :Exceptions:
2325
2326 See the list of exceptions described in `WBEMConnection`.
2327 """
2328
2329 if namespace is None:
2330 namespace = self.default_namespace
2331
2332
2333 result = self.imethodcall(
2334 'SetQualifier',
2335 namespace,
2336 QualifierDeclaration=QualifierDeclaration,
2337 **params)
2338
2340
2341 """
2342 Delete a qualifier declaration.
2343
2344 This method performs the DeleteQualifier CIM-XML operation.
2345 If the operation succeeds, this method returns.
2346 Otherwise, this method raises an exception.
2347
2348 :Parameters:
2349
2350 Qualifier : string
2351 Name of the qualifier declaration to be deleted.
2352
2353 namespace : string
2354 Optional: Name of the namespace in which the qualifier declaration
2355 is to be deleted.
2356 The value `None` causes the default namespace of the connection to
2357 be used.
2358
2359 :Exceptions:
2360
2361 See the list of exceptions described in `WBEMConnection`.
2362 """
2363
2364 if namespace is None:
2365 namespace = self.default_namespace
2366
2367 unused_result = self.imethodcall(
2368 'DeleteQualifier',
2369 namespace,
2370 QualifierName=QualifierName,
2371 **params)
2372
2374 """Determine if one class is a subclass of another class.
2375
2376 Keyword Arguments:
2377 ch -- A CIMOMHandle. Either a pycimmb.CIMOMHandle or a
2378 pywbem.WBEMConnection.
2379 ns -- Namespace.
2380 super-class -- A string containing the super class name.
2381 sub -- The subclass. This can either be a string or a pywbem.CIMClass.
2382
2383 """
2384
2385 lsuper = super_class.lower()
2386 if isinstance(sub, CIMClass):
2387 subname = sub.classname
2388 subclass = sub
2389 else:
2390 subname = sub
2391 subclass = None
2392 if subname.lower() == lsuper:
2393 return True
2394 if subclass is None:
2395 subclass = ch.GetClass(subname,
2396 ns,
2397 LocalOnly=True,
2398 IncludeQualifiers=False,
2399 PropertyList=[],
2400 IncludeClassOrigin=False)
2401 while subclass.superclass is not None:
2402 if subclass.superclass.lower() == lsuper:
2403 return True
2404 subclass = ch.GetClass(subclass.superclass,
2405 ns,
2406 LocalOnly=True,
2407 IncludeQualifiers=False,
2408 PropertyList=[],
2409 IncludeClassOrigin=False)
2410 return False
2411
2413 """ Pegasus specific Unix Domain Socket call. Specific because
2414 of the location of the file name
2415 """
2416
2417
2418 return WBEMConnection('/var/run/tog-pegasus/cimxml.socket', creds,
2419 **kwargs)
2420
2422 """ SFCB specific Unix Domain Socket call. Specific because
2423 of the location of the file name
2424 """
2425
2426
2427 return WBEMConnection('/tmp/sfcbHttpSocket', creds, **kwargs)
2428
2430 """ Pegasus specific Unix Domain Socket call. Specific because
2431 of the location of the file name
2432 """
2433
2434
2435 return WBEMConnection('/tmp/OW@LCL@APIIPC_72859_Xq47Bf_P9r761-5_J-7_Q',
2436 creds, **kwargs)
2437