Pywbem - A WBEM client and related utilities, written in pure Python¶
Pywbem is a WBEM client and WBEM indication listener and provides related WBEM client-side functionality. It is written in pure Python and runs on Python 2 and Python 3.
WBEM is a standardized approach for systems management defined by the DMTF that is used in the industry for a wide variety of systems management tasks. See WBEM Standards for more information. An important use of this approach is the SMI-S standard defined by SNIA for managing storage.
Pywbem is based on the idea that a good WBEM client should be easy to use and not necessarily require a large amount of programming knowledge. It is suitable for a large range of tasks from simply poking around to writing web and GUI applications.
The general web site for all projects of the pywbem family is: https://pywbem.github.io/.
Introduction¶
Chapter Contents
Functionality¶
The major components of pywbem are shown in this diagram:

The green components all have Python APIs for use by user applications. The yellow components are command line utilities. The blue components are not part of the pywbem or pywbemtools packages.
The pywbem components all run on the client side and communicate with a remote WBEM server using the standard CIM operations over HTTP (CIM-XML) protocol defined in the DMTF standards DSP0200 and DSP0201.
Pywbem provides the following Python APIs:
- WBEM client library - An API that supports issuing WBEM operations to a WBEM server, using the CIM operations over HTTP (CIM-XML) protocol defined in the DMTF standards DSP0200 and DSP0201.
- WBEM server library - An API that encapsulates selected functionality of a WBEM server for use by a WBEM client application, such as determining the Interop namespace and other basic information about the server, or the management profiles advertised by the server.
- WBEM indication listener - An API for creating and managing a thread-based WBEM listener that waits for indications (i.e. event notifications) emitted by a WBEM server using the CIM-XML protocol. The API supports registering callback functions that get called when indications are received by the listener.
- WBEM subscription manager - An API for viewing and managing subscriptions for indications on a WBEM server.
- MOF compiler - An API for compiling MOF files or strings into a CIM repository (e.g. on a WBEM server), or for test-compiling MOF.
- Mock WBEM server - An API for setting up a mocked WBEM server that is used instead of a real WBEM server. This allows setting up well-defined WBEM servers locally that can be used for example for prototyping or testing user applications.
Pywbem also provides a command line utility:
- mof_compiler - A MOF compiler that takes MOF files as input and compiles them into a CIM repository (e.g. on a WBEM server). See DSP0004 for a definition of MOF.
The related pywbemtools project provides this command line utility:
- pywbemcli - A client-side command line interface for a WBEM server, supporting a command line mode and an interactive (repl) mode.
Supported environments¶
Pywbem is supported in these environments:
- Operating Systems: Linux, OS-X, native Windows, UNIX-like environments under Windows (such as CygWin, MSYS2, Babun, or Gow).
- Python: 2.7, 3.4, and higher
- WBEM servers: Any WBEM server that conforms to the DMTF specifications listed in Standards conformance. WBEM servers supporting older versions of these standards are also supported, but may have limitations. See WBEM servers for more details.
Installation¶
Pywbem is a pure Python package and therefore does not have a dependency on operating system packages in addition to Python itself.
Prerequisites:
- The Python environment into which you want to install must be the current
Python environment, and must have at least the following Python packages
installed:
- setuptools
- wheel
- pip
- The Python environment into which you want to install must be the current
Python environment, and must have at least the following Python packages
installed:
Install pywbem (and its prerequisite Python packages) into the active Python environment:
$ pip install pywbem
This will also install any prerequisite Python packages.
Starting with version 1.0.0, pywbem has no OS-level prerequisite packages.
If you want to contribute to the pywbem project, you need to set up a development and test environment for pywbem. That has a larger set of Python package prerequisites and also OS-level prerequisites. Its setup is described in chapter Development.
Installing into a different Python environment¶
The examples in the previous sections install pywbem and its prerequisite Python packages using the Pip utility. By default, Pip installs these packages into the currently active Python environment. That can be the system Python, or a virtual Python. The commands shown above did not detail this, but this section does.
If you just want to use the scripts that come with pywbem, and want them to be always available without having to think about activating virtual Python environments, then installation of pywbem into the system Python environment is probably the right choice for you. If your intention is to write code against the pywbem APIs, installation into a virtual Python environment is recommended.
An additional dimension is Python 2 vs. Python 3:
- On systems where Python 2 is the default, the
python
andpip
commands operate on Python 2. There may bepython3
andpip3
commands that operate on Python 3. - On some newer systems (e.g. Ubuntu 17.04), Python 3 is the default. In that
case, the
python
andpip
commands operate on Python 3. There may bepython2
andpip2
commands that operate on Python 2.
For simplicity, the following examples show only the default commands.
To install pywbem into the currently active virtual Python environment (e.g.
myenv
), issue:(myenv)$ pip install pywbem
To install pywbem for only the current user into the currently active system Python environment, issue:
$ pip install --user pywbem
This installs the Python packages in a directory under the home directory of the current user and therefore does not require sudo permissions nor does it modify the system Python environment seen by other users.
To install pywbem for all users into the currently active system Python environment, issue:
$ sudo pip install pywbem
This installs the Python packages into a directory of the system Python installation and therefore requires sudo permissions.
Be aware that this may replace the content of existing packages when a package version is updated. Such updated packages as well as any newly installed packages are not known by your operating system installer, so the knowledge of your operating system installer is now out of sync with the actual set of packages in the system Python.
Therefore, this approach is not recommended and you should apply this approach only after you have thought about how you would maintain these Python packages in the future.
Installing a different version of pywbem¶
The examples in the previous sections install the latest version of pywbem that is released on PyPI. This section describes how different versions of pywbem can be installed.
To install the latest version of pywbem that is released on PyPI, issue:
$ pip install pywbem
To install an older released version of pywbem, Pip supports specifying a version requirement. The following example installs pywbem version 0.10.0 from PyPI:
$ pip install pywbem==0.10.0
If you need to get a certain new functionality or a new fix of pywbem that is not yet part of a version released to PyPI, Pip supports installation from a Git repository. The following example installs pywbem from the current code level in the master branch of the pywbem Git repository:
$ pip install git+https://github.com/pywbem/pywbem.git@master#egg=pywbem
Verifying the installation¶
You can verify that pywbem is installed correctly by importing the package into Python (using the Python environment you installed pywbem to):
$ python -c "import pywbem; print('ok')"
ok
In case of trouble with the installation, see the Troubleshooting section.
Prerequisite operating system packages for install¶
The installation of pywbem before its version 1.0.0 required certain operating system packages. Starting with version 1.0.0, pywbem has no dependencies on specific operating system packages (other than Python).
Note that the development of pywbem still requires a number of operating system packages. See Setting up the development environment for details.
Package version¶
Starting with pywbem 0.8.1, the version of the pywbem package can be accessed by
programs using the pywbem.__version__
variable:
-
pywbem._version.
__version__
= '1.1.4.dev1'¶ The full version of this package including any development levels, as a string.
Possible formats for this version string are:
- “M.N.P.devD”: Development level D of a not yet released version M.N.P
- “M.N.P”: A released version M.N.P
Note: For tooling reasons, the variable is shown as
pywbem._version.__version__
, but it should be used as
pywbem.__version__
.
Versions of pywbem that do not have the pywbem.__version__
variable are
most likely version 0.7.0 because that was the only version before pywbem 0.8.1
that was released to Pypi, and most likely also the only version before
pywbem 0.8.1 that was packaged as an operating system package into Linux
distributions.
The following shell command can be used to determine the version of a pywbem package installed in the current Python environment, for all versions that were released to Pypi, and independently of whether pywbem was installed as an operating system package or as a Python package:
python -c "import pywbem; print(getattr(pywbem, '__version__', None) or '0.7.0')"
Version dependent features¶
Pywbem indicates support for version dependent features to users of its API.
These are features that have been introduced at some point, and users may have a need to depend on the feature being supported (i.e. active). If a feature is supported, the corresponding attribute is True. Note that before a feature was introduced, the corresponding attribute is undefined.
The attributes listed here do not allow controlling whether a feature is active or not; they only indicate whether the feature is supported and active.
Note: For tooling reasons, these attributes are shown as
pywbem._features.XXX
, but they should be used as pywbem.XXX
.
-
pywbem._features.
PYWBEM_USES_REQUESTS
= True¶ Indicates that this version of pywbem uses the ‘requests’ Python package. This influences for example the support of CA certificates by the
WBEMConnection
class, and the exceptions that may be raised by that class.
Standards conformance¶
The pywbem client and pywbem indication listener conform to the following CIM and WBEM standards, in the version specified when following the links to the standards:
The implementation of the CIM-XML protocol in pywbem (client and listener) conforms to DSP0200 and DSP0201.
Limitations:
- The mock support of pywbem (see Mock WBEM server) does not support the
ModifyClass
operation. Note that in its implementation of the CIM-XML protocol, pywbem does support theModifyClass
operation. - The
EnumerationCount
operation is not supported by pywbem. That operation is optional for WBEM servers to support, and is hard to implement reasonably. - Multi-requests are not supported by pywbem. This is not a functional limitation though, because the use of multi-requests is entirely determined by the client: If a client does not use multi-requests, the server does not use multi-responses.
- DSP0201 version 2.4 introduced the requirement that the TYPE attribute of the KEYVALUE element must be set. The KEYVALUE element is used to represent keys in instance names, for example when the CreateInstance operation returns an instance name from the WBEM server, or when the DeleteInstance operation sends an instance name to the WBEM server. In operation requests sent to the WBEM server, pywbem sets the TYPE attribute of the KEYVALUE element for key properties of CIM types string and boolean, as required by DSP0201 version 2.4. For key properties with numeric CIM types, pywbem does not set the TYPE attribute of the KEYVALUE element in operation requests. This conforms to DSP0201 before version 2.4, but not to version 2.4. This is not expected to cause problems however, because WBEM servers that implement DSP0201 version 2.4 very likely will tolerate clients that conform to earlier versions. In operation responses received from the WBEM server, pywbem tolerates an absent TYPE attribute in KEYVALUE elements in order to accomodate WBEM servers that implement DSP0201 before version 2.4.
- The
CORRELATOR
element introduced in DSP0201 version 2.4 is not supported by pywbem.
Notes:
- The CIM-XML representation as defined in DSP0201 supports CIM methods that have a void return type. However, the CIM architecture defined in DSP0004 does not support that, and neither does pywbem.
- The CIM-XML representation as defined in DSP0201 supports references to CIM classes. However, the CIM architecture defined in DSP0004 does not support that, and neither does pywbem.
- The mock support of pywbem (see Mock WBEM server) does not support the
The CIM-XML representation of CIM objects as produced by their
tocimxml()
andtocimxmlstr()
methods conforms to the representations for these objects as defined in DSP0201.Limitations:
- The xml:lang attribute supported by DSP0201 on some CIM-XML elements that can have string values is tolerated in the CIM-XML received by pywbem, but is ignored and is not represented on the corresponding CIM objects.
The capabilities of CIM objects conform to the CIM architecture as defined in DSP0004.
The MOF as produced by the
tomof()
methods on CIM objects and as parsed by the MOF compiler conforms to the MOF syntax as defined in DSP0004.Limitations:
- The pywbem MOF compiler has the restriction that CIM instances specified in MOF that have an alias must have key properties that are either initialized in the instance, or have non-NULL default values (issue #1079).
- The pywbem MOF compiler has the restriction that an alias must be defined before it is used. In the MOF syntax defined in DSP0004, no such restriction exists (issue #1078).
- The pywbem MOF compiler does not roll back changes to qualifier declarations when it aborts (issue #990).
The WBEM URIs produced by the
to_wbem_uri()
methods ofCIMInstanceName
andCIMClassName
conform to the WBEM URI syntax as defined in DSP0207.Note that the
__str__()
methods of these two classes produce strings that are similar but not conformant to DSP0207, for historical reasons.The mechanisms for discovering the Interop namespace of a WBEM server and the management profiles advertised by a WBEM server and their central instances in the WBEM server library conform to DSP1033.
The mechanisms for subscribing for CIM indications in the WBEM indication listener conform to DSP1054.
Deprecation and compatibility policy¶
Starting with version 0.7.0, pywbem attempts to be as backwards compatible as possible.
Compatibility of pywbem is always seen from the perspective of the user of the pywbem APIs or pywbem utility commands. Thus, a backwards compatible new version of pywbem means that a user can safely upgrade to that new version without encountering compatibility issues for their code using the pywbem APIs or for their scripts using the pywbem utility commands.
Having said that, there is always the possibility that even a bug fix changes some behavior a user was dependent upon. Over time, the pywbem project has put automated regression testing in place that tests the behavior at the APIs, but such compatibility issues cannot be entirely excluded.
Pywbem uses the rules of Semantic Versioning 2.0.0 for compatibility between versions, and for deprecations. The public interface that is subject to the semantic versioning rules and specificically to its compatibility rules are the various pywbem APIs described in this documentation, and the command line interface of the pywbem utility commands.
Occasionally functionality needs to be retired, because it is flawed and a better but incompatible replacement has emerged. In pywbem, such changes are done by deprecating existing functionality, without removing it immediately. The deprecated functionality is still supported at least throughout new minor or update releases within the same major release. Eventually, a new major release may break compatibility by removing deprecated functionality.
Any changes at the pywbem APIs or utility commands that do introduce incompatibilities as defined above, are described in the Change log.
Deprecation of functionality at the pywbem APIs or utility commands is communicated to the users in multiple ways:
- It is described in the documentation of the API or utility command
- It is mentioned in the change log.
- It is raised at runtime by issuing Python warnings of type
DeprecationWarning
(see the Pythonwarnings
module).
Starting with Python 2.7, DeprecationWarning
messages are suppressed by
default. They can be shown for example in any of these ways:
- By specifying the Python command line option:
-W default
- By invoking Python with the environment variable:
PYTHONWARNINGS=default
It is recommended that users of the pywbem package run their test code with
DeprecationWarning
messages being shown, so they become aware of any use of
deprecated functionality.
Here is a summary of the deprecation and compatibility policy used by pywbem, by release type:
- New update release (M.N.U -> M.N.U+1): No new deprecations; no new functionality; backwards compatible.
- New minor release (M.N.U -> M.N+1.0): New deprecations may be added; functionality may be extended; backwards compatible.
- New major release (M.N.U -> M+1.0.0): Deprecated functionality may get removed; functionality may be extended or changed; backwards compatibility may be broken.
Python namespaces¶
The external APIs of pywbem are defined by the symbols in the pywbem
and pywbem_mock
namespaces/packages and their public sub-modules.
Sub-modules that have a leading underscore in their name are private and should not be used by users. Their content may change at any time without prior warning.
This documentation describes only the external APIs of pywbem, and omits any internal symbols and any private sub-modules.
Configuration variables¶
Pywbem supports a very limited number of configuration variables that influence certain specific behavior.
These configuration variables can be modified by the user directly after importing pywbem. For example:
import pywbem
pywbem.config.ENFORCE_INTEGER_RANGE = False
Note that the pywbem source file defining these variables should not be changed by the user. Instead, the technique shown in the example above should be used to modify the configuration variables.
-
pywbem.config.
ENFORCE_INTEGER_RANGE
= True¶ Enforce the allowable value range for CIM integer types (e.g.
Uint8
). For details, see theCIMInt
base class.- True (default): Pywbem enforces the allowable value range; Assigning
values out of range causes
ValueError
to be raised. - False: Pywbem does not enforce the allowable value range; Assigning values out of range works in pywbem. Note that a WBEM server may or may not reject such out-of-range values.
New in pywbem 0.9.
- True (default): Pywbem enforces the allowable value range; Assigning
values out of range causes
-
pywbem.config.
DEFAULT_ITER_MAXOBJECTCOUNT
= 1000¶ Default setting for the MaxObjectCount attribute for all of the
WBEMConnection
:Iter… operations. If this attribute is not specified on a request such asIterEnumerateInstances()
, this value will be used as the value for MaxObjectCount. Note that this does not necessarily optimize the performance of these operations.New in pywbem 0.10 as experimental and finalized in 0.12.
-
pywbem.config.
SEND_VALUE_NULL
= True¶ Backwards compatibility option controlling the use of VALUE.NULL for representing NULL entries in array values in CIM-XML requests sent to WBEM servers.
DSP0201 requires the use of VALUE.NULL for representing NULL entries in array values since its version 2.2 (released 01/2007). Pywbem added support for using VALUE.NULL in CIM-XML requests in its version 0.12. In case a WBEM server has not implemented support for VALUE.NULL, this config option can be used to disable the use of VALUE.NULL as a means for backwards compatibility with such WBEM servers.
Note that the config option only influences the behavior of pywbem for using VALUE.NULL in CIM-XML requests sent to a WBEM server. Regardless of the config option, pywbem will always support VALUE.NULL in CIM-XML responses the pywbem client receives from a WBEM server, and in CIM-XML requests the pywbem listener receives from a WBEM server.
- True (default): Pywbem uses VALUE.NULL in CIM-XML requests for representing NULL entries in array values.
- False: Pywbem uses VALUE with an empty value in CIM-XML requests for representing NULL entries in array values.
New in pywbem 0.12.
-
pywbem.config.
IGNORE_NULL_KEY_VALUE
= False¶ Backward compatibility option that controls creating
CIMInstanceName
objects with NULL values for keybindings.DSP0004, section 7.9 specifically forbids key properties with values that are NULL but because pywbem has always allowed this, adding the code to disallow None as a keybinding value is an incompatible change.
- True: Pywbem tolerates None as a value when keybindings are defined.
- False (default): Pywbem raises ValueError when keybindings are created where any key will have the value None.
New in pywbem 0.12.
-
pywbem.config.
AUTO_GENERATE_SFCB_UEP_HEADER
= True¶ Option that enables or disables the automatic creation of a special HTTP header field that the Small Footprint CIM Broker (SFCB) requires when invoking its special “UpdateExpiredPassword()” method. See https://sblim.sourceforge.net/wiki/index.php/SfcbExpiredPasswordUpdate for details.
- True: (default): Automatic creation is enabled, and pywbem will create
the HTTP header field
Pragma: UpdateExpiredPassword
in all CIM-XML requests that invoke a CIM method named “UpdateExpiredPassword()”. - False: Automatic creation is disabled.
New in pywbem 0.13.
- True: (default): Automatic creation is enabled, and pywbem will create
the HTTP header field
WBEM servers¶
Server-specific features¶
Pywbem supports the following features of some specific WBEM servers that are additions to the DMTF standards:
- OpenPegasus
- Pywbem supports the Interop namespace
root/PG_InterOp
that is specific to OpenPegasus. OpenPegasus also supports the standard Interop namespaces (interop
,root/interop
) but for backwards compatibility with earlier versions of OpenPegasus, pywbem supports this old Interop namespace, for example in its Interop namespace determination whose result is exposed in thepywbem.WBEMServer.interop_ns
property. - Pywbem supports the upper-case variant
EMBEDDEDOBJECT
of the respective CIM-XML attribute that is specific to some releases of OpenPegasus, in addition to the mixed-case variantEmbeddedObject
that is defined in the DSP0201 standard and that is also supported by OpenPegasus. Older releases of OpenPegasus supported only the upper-case variant. - Starting with version 1.0.0, pywbem no longer supports the Local authentication scheme of OpenPegasus, which is a password-less local authorization.
- Pywbem supports the Interop namespace
- SFCB (Small Footprint CIM Broker)
- None
- OpenWBEM
- Starting with version 1.0.0, pywbem no longer supports the OWLocal authentication scheme of OpenWBEM, which is a password-less local authorization.
WBEM server testing¶
Today the pywbem project tests primarily against current versions of the OpenPegasus WBEM server because that server is available to the project.
These tests are captured in test scripts such as
tests/manualtest/run_cimoperations.py
. Note that
generally those tests that are server-specific only run against the defined
server so that there are a number of tests that run only against the
OpenPegasus server. This includes some tests that use specific providers
in the OpenPegasus server to set up tests such as indication tests.
In addition, pywbem has automated testcases for testing against its own mock WBEM server, and against simulated CIM-XML responses.
Concepts¶
This sections defines some of the basic concepts that form the basis for Pywbem including the architecture, basic CIM/WBEM components, operations and indications.
It also defines the differences between some of the methods defined in Pywbem cim_operations, in particular, the pull operations and the iter operations.
Chapter Contents
The CIM/WBEM architecture¶
TODO: Write this section
The CIM model and CIM objects¶
TODO: Write this section
WBEM Operations: Communicating with the WBEM Server¶
TODO: Write this section
WBEM operations overview¶
TODO Write this section
Traditional operations¶
TODO - Write this section
Pull operations¶
The DMTF CIM/XML pull operations allow the WBEM client to break the monolithic instance operations for requests that deliver multiple objects into multiple requests/responses executed as a sequence of requests to limit the size of individual responses.
NOTE: The pull operations were added to pywbem in version 0.9.0.
They were created to reduce scalability issues with extremely large responses from servers for instance enumerate operations (EnumerateInstances, Associators, and References) that were causing resource problems in both clients and servers. The pull operations allow the client to break large responses up into multiple smaller responses and allowing filtering of the responses to be performed by the server.
A central concept of pulled enumeration operations is the enumeration session, which provides a context in which the operations perform their work and which determines the set of instances or instance paths to be returned. To process the operations of an enumeration session, some parameters of the open operation need to be maintained as long as the enumeration session is open. In addition, some state data about where the enumeration session is with regard to instances or instance paths already returned must be maintained.
A successful Open… operation establishes the enumeration session and returns an enumeration context (Pybbem result.context) value representing that session. This value is used as a parameter in subsequent Pull operations on that enumeration session.
In general the pull operations replace the single monolithic request/response (ex. EnumerateInstances) that returns all instances in a single response with a pattern (enumeration sequence) that is based on three operations:
- Open… to open the request enumeration session to the WBEM Server and optionally request objects be returned.
- Pull… to continue retrieving objects from the WBEM Server after a successful Open…. The client normally continues to execute pulls until an exception or end-of-sequence flag is received.
- CloseEnumeration Close an enumeration sequence before it is complete. This request is ONLY used to execute early close; when the eos flag is returned or and error is returned (if ContinueOnError is not set), the session is closed by the server.
The open… requests use the same request parameters as the traditional operations to define the basic characteristics of the corresponding traditional operation (object name, propertylists, etc) and add several more request parameters to control the flow of responses (response size, timeouts, etc.). In addition they add two new request parameters (QueryFilter and QueryFilterLanguage) to request that the server filter the responses and return only instances/paths that match the filter.
Relation to traditional operations¶
The convention for the pull operation naming is as follows:
- Prepend the traditional operation name with Open and Pull
- Suffix the pull operations that return both instances and paths with WithPath
- Change the name suffix on operations that return path information from Names to Paths to reflect that these operations are returning complete instance paths with host and namespace included. The Exec was dropped from the name for the OpenQueryInstances.
The pull operations parallel to the traditional operations as follows:
Traditional Operation | Pull Operations |
EnumerateInstances | OpenEnumerateInstances / PullInstancesWithPath |
EnumerateInstanceNames | OpenEnumerateInstancePaths / PullInstancePaths |
Associators | OpenAssociatorInstances / PullInstancesWithPath |
AssociatorNames | OpenAssociatorInstancePaths / PullInstancePaths |
References | OpenReferenceInstances / PullInstancesWithPath |
ReferenceNames | OpenReferenceInstancePaths / PullInstancePaths |
ExecQuery | OpenQueryInstances / PullInstances |
The pull operations are defined only for instances. There are NO pull operations for CIM classes, the for CIM qualifier declarations or for method invocations.
Pull operation responses¶
Each pull operation request returns a Python namedtuple result that consists of the following named components:
- eos - A boolean flag that indicates the end of the enumeration sequence. As along as this returned flag is false, the server has more objects to return. If this flag is true in a response, the server has no more objects to return and it has closed the enumeration sequence.
- context - An opaque identifier that must be returned to the server with subsequent pull requests to continue the enumeration sequence. The context received with a response within an enumeration must be returned with the next request since the context may uniquely define not only the enumeration sequence but the segement returned in the response.
- instances or paths - A list of pywbem objects returned from the server. The requests that demand instances return the instances entry in the namedtuple and those that request paths return paths in the path entry in the namedtuple.
Pull enumeration sequence code pattern¶
Generally the pattern for requesting from a server using the pull operations is as follows:
# open the enumeration sequence
result = open...(uri, ...)
... process the objects return in result.xx
# while more objects exist in the server, loop to pull objects
while not result.eos
result = pull...(result.context, <MaxObjectCount>, ...)
... process the objects return in result.xx
The user opens the request with the open request and if that is successful, and does not return the end-of-sequence flag the result (eos) executed the pull request to continue receiving objects within the enumeration sequence. Each pull request MUST include the enumeration context from the previous response (context in the result tuple).
The pull sequence may be terminated by executing a [CloseEnumeration()](https://pywbem.readthedocs.io/en/latest/client.html#pyw bem.WBEMConnection.CloseEnumerate) to terminate the pull sequence. However, this is optional and used only to close pull sequences before the eos has been received.
Common Pull Operation Request Input Arguments¶
The following are the request arguments that are common across all of the Pull requests.
Open requests¶
- FilterQuery Language and FilterQuery - These input parameters specify a filter query that acts as an additional restricting filter on the set of enumerated instances/paths returned. WBEM servers must support filter queries in pulled enumerations and must support the DMTF Filter Query Language(FQL, see DMTF DSP0212) as a query language. If a WBEM server accepts a request with the FilterQuery parameter defined it MUST filter the response. NOTE: The query and query language defined for the OpenQueryInstances is NOT FQL but the same query languages defined for the execQuery request.
- OperationTimeout - Determines the minimum time the WBEM server shall maintain the opened enumeration session after the last Open or Pull operation (unless the enumeration session is closed during the last operation). If the operation timeout is exceeded, the WBEM server may close the enumeration session at any time, releasing any resources allocated to the enumeration session. An OperationTimeout of 0 means that there is no operation timeout. That is, the enumeration session is never closed based on time. If OperationTimeout is NULL, the WBEM server shall choose an operation timeout.
- ContinueOnError - This input parameter, if true, requests a continuation on error, which is the ability to resume an enumeration session successfully after a Pull operation returns an error. If a WBEM server does not support continuation on error and ContinueOnError is true, it shall return a failure with the status code CIM_ERR_CONTINUATION_ON_ERROR_NOT_SUPPORTED. Most servers today do not support ContinueOnError.
- MaxObjectCount - Defines the maximum number of instances or instance paths that the open operation can return. Any uint32 number is valid, including 0. The WBEM server may deliver any number of instances or instance paths up to MaxObjectCount but shall not deliver more than MaxObjectCount elements. The default for this is zero so that the WBEM server does not deliver objects in the response unless a MaxObjectCount is specifically defined. The WBEM server may limit the maximum size of this request parameter.
Pull requests¶
- Context - This is the EnumerationContext defined in the specification. It is an opaque string returned from the previous open or pull for this enumeration sequence as part of the result tuple (result.context).
- MaxObjectCount - This required input parameter defines the maximum number of instances or instance paths that may be returned by this Pull operation. Any uint32 number is valid, including 0. The WBEM server may deliver any number of instances or instance paths up to MaxObjectCount but shall not deliver more than MaxObjectCount. The WBEM client may use a MaxObjectCount value of 0 to restart the operation timeout for the enumeration session when it does not need to not retrieve any instances or instance paths.
Close request¶
- Context - This is the EnumerationContext defined in the specification. It is an opaque string returned from the previous open or pull for this enumeration sequence as part of the result tuple (result.context).
Differences from traditional operations¶
The pull operations differ from the traditional operations in the several ways:
- They allow filtering the response in the WBEM Server which can represent a significant resource saving if only selected instances from a large response are really required.
- They limit the amount of memory used by the server since the server need not process the complete request before returning information to the client
- They limit the memory used by the client since it can define the maximum size of any response.
- They allow the client to terminate an enumeration early with the CloseEnumeration.
- They allow the server and client to receive partial responses in that the client receives potentially an error response on each segment of the response, not the overall response.
- They provide a more consistent inclusion of the path component in the responses.
Iter operations¶
The iterable operation extensions (short: iter operations) are a set of methods added to [pywbem.WBEMConnection](https://pywbem.readthedocs.io/en/latest/client.html# pywbem.WBEMConnection) class in pywbem version 0.10.0 to simplify the use of the pull vs. traditional operations.
These are specific to PyWBEM.
Why the iter operations exist¶
The iter operations provide:
1. An interface that is the same whether the user is executing the pull operations or their equivalent traditional operations.
2. An interface that use the Python iterator paradigm to get instances or instance paths in place of lists or tuples as for the pull operations and traditional operations.
3. An interface that allows the user to utilize pull operations or traditional operations with just an attribute change in WBEMConnection.
4. An interface that automatically attempts to use pull operations and if a particular WBEM server does not support them falls back to the equivalent traditional operations so the user does not need to worry about whether the server supports the pull operations or if they are required for memory optimization.
Comparison table¶
The traditional operations and their equivalent pull operations are covered by the new iter operations as follows:
Traditional Operation | Pull Operations | Iter Operation |
EnumerateInstances | OpenEnumerateInstances / PullInstancesWithPath | IterEnumerateInstances |
EnumerateInstanceNames | OpenEnumerateInstancePaths / PullInstancePaths | IterEnumerateInstancePaths |
Associators | OpenAssociatorInstances / PullInstancesWithPath | IterAssociatorInstances |
AssociatorNames | OpenAssociatorInstancePaths / PullInstancePaths | IterAssociatorInstancePaths |
References | OpenReferenceInstances / PullInstancesWithPath | IterReferenceInstances |
ReferenceNames | OpenReferenceInstancePaths / PullInstancePaths | IterReferenceInstancePaths |
ExecQuery | OpenQueryInstances / PullInstances | IterQueryInstances |
The methods for the iter operations use the same arguments as the Open… methods of the pull operations, with exceptions noted in section :ref: Differences between iter operations and pull operations.
The general pattern for use of the iter operations is:
try:
iterator = Iter...(...)
for object in iterator:
<process the object>
except Error as er:
# NOTE: objects may be received before an exception, because in each call
# the server returns either objects or error. However, generally the
# first error terminates the whole sequence.
These operations use the Python iterator paradigm so that the for-loop processes CIM objects as they are received via the pull operations or via the traditional operations if the server does not support pull operations.
Internal processing in the iter operations¶
The iter operations try to use the existing pull operations or traditional operations and lay a layer over them to determine if the pull operations can be used and to manage the iteration. The paradigm for the implementation of each of these operations is generally as follows (showing an operation returning instances as an example, and omitting the logic that closes the pull operation):
# psuedo code pattern for iter function internal processing
if <use_pull_for_this_operation is try or true>:
try:
result = Open...(...)
<use_pull_for_this_operation = true>
for inst in result.instances:
yield inst
while not result.eos:
result = PullInstancesWithPath(...)
for inst in result.instances:
yield inst
return
except CIMError as ce:
if <use_pull_for_this_operation is try> and
ce.status_code != "CIM_ERR_NOT_SUPPORTED":
<use_pull_for_this_operation = false>
else:
raise
<check for unsupported parameters when using traditional operations>
instances = <traditional-operation>(...)
for inst in instances:
<fix up path in instance>
yield inst
Forcing pull vs. traditional operations¶
A parameter (use_pull_operations) has been added to the [pywbem.WBEMConnection](https://pywbem.readthedocs.io/en/latest/client.html# pywbem.WBEMConnection) constructor to optionally force the use of either the pull operations or the traditional operations.
- If use_pull_operations is True only the pull operations will be executed and if this fails for any reason including CIM_ERR_NOT_SUPPORTED, the exception will be returned.
- If use_pull_operations is False only the traditional operations will be executed and if this fails for any reason, the exception will be returned.
- The default is None. In this case, first the pull operation will be attempted. If the first request (Open…) returns CIM_ERR_NOT_SUPPORTED, the corresponding traditional operation will be attempted.
Thus, the iter operations can be used to execute exclusively the traditional operations by simply setting use_pull_operations=False.
conn = pywbem.WBEMConnection(server, (username, password),
default_namespace=namespace,
no_verification=True,
use_pull_operations=False)
.._Differences between iter operations and pull operations:
Differences between iter operations and pull operations¶
Use of FilterQuery¶
Since the traditional operations did not incorporate the query filters into their input parameters, if a query filter is included in the request and the request is passed to a traditional operation, the request will be refused and an exception generated. This is because the specification for the FilterQuery states that the server must return filtered responses and there is no way to do that with the traditional operations.
Paths in returned instances¶
The requirements on paths in returned instances differ between pull and traditional operations. The iter operations have been defined to be in line with the requirements on paths for pull operations, and the implementation of the iter operations acts to bring the path in returned instances in line with the requirements of the pull operations, if it uses the traditional operation. Thus, the iter operation always returns a complete path in any returned instances.
Use of MaxObjectCount argument¶
The MaxObjectCount argument is somewhat more limited than if the pull operations are used directly in that:
- It is the same value for open and pull requests.
- The mechanism to delay responses (setting MaxObjectCount=0 and executing a Pull…() method) cannot be used so the interoperation timeout must be sufficient for the client to complete its processing.
Receiving returned objects before an exception¶
In general the pull operations receive either objects or error for each request (open or pull). Since these operations may be called to get objects from the server the iterator may receive objects before an exception is executed. In general, unless the ContinueOnError flag is set, the enumeration sequence will terminate after the first error and that error is an indication that not all objects were received from the server. If the traditional enumerate function is called by the Iter…() method, either objects or an error are received, never both.
Closing an Iter operation before it is complete¶
An iter operation may be closed before the processing from the server is complete by executing the close() function on the iterator:
inst_iterator = conn.IterEnumerateInstances(classname,
MaxObjectCount=max_obj_cnt)
for inst in inst_iterator:
if <instance fails some test>
inst_iterator.close()
else:
<process the instance>
Note that if the operation executed was the traditional operation rather than the pull operation, the close() will do nothing since the response instances are received as a single block. If the enumeration sequence is already complete, this call will also be ignored.
WBEM indications and subscriptions¶
TODO: Section on indications and subscriptions
WBEM Management Profiles¶
TODO: Create this section describing profiles, why there exist and very generally how to use them
Tutorial¶
This section contains a few short tutorials about using pywbem. It is intended to be enough to get people up and going who already know a bit about WBEM and CIM.
The tutorials in this section are Jupyter Notebooks, and are shown using the online Jupyter Notebook Viewer. This allows viewing the tutorials without having Jupyter Notebook installed locally.
Table of Jupyter tutorials¶
In order to view a tutorial, just click on a link in this table:
Tutorial | Short description |
---|---|
connections.ipynb | Making connections to a WBEM server |
datamodel.ipynb | Representation of CIM objects in Python |
enuminsts.ipynb | EnumerateInstances |
enuminstnames.ipynb | EnumerateInstanceNames |
getinstance.ipynb | GetInstance |
createdeleteinst.ipynb | CreateInstance + DeleteInstance |
modifyinstance.ipynb | ModifyInstance |
invokemethod.ipynb | InvokeMethod |
pulloperations.ipynb | The Pull Operations |
iterablecimoperations.ipynb | The Iterable Operation Extensions |
wbemserverclass.ipynb | Pywbem WBEMServer Class |
subscriptionmanager.ipynb | Subscription Manager |
pywbemmock.ipynb | Using the pywbem_mock module |
For the following topics, tutorials are not yet available:
- ExecQuery
- Association Operations
- Class Operations
- Qualifier Operations
- WBEMListener
Executing code in the tutorials¶
You cannot directly modify or execute the code in the tutorials using the Jupyter Notebook Viewer, though. In order to do that, the Jupyter Notebook Viewer provides a download button at the top right corner of the page.
You must have Jupyter Notebook installed, preferrably in a virtual Python environment, and you must have pywbem installed.
To see a list of your downloaded notebook files, start Jupyter Notebook as follows:
jupyter notebook --notebook-dir={your-notebook-dir}
WBEM client library¶
The WBEM client library API of pywbem supports issuing WBEM operations to a WBEM server, using the CIM operations over HTTP (CIM-XML) protocol defined in the DMTF standards DSP0200 and DSP0201.
A number of these topics apply also to the other APIs of the pywbem package.
Chapter Contents
WBEM operations¶
Objects of the WBEMConnection
class represent a connection to
a WBEM server.
All WBEM operations defined in DSP0200 can be issued across this connection.
Each method of this class corresponds directly to a WBEM operation.
WBEMConnection method | Purpose |
---|---|
EnumerateInstances() |
Enumerate the instances of a class (including instances of its subclasses) |
EnumerateInstanceNames() |
Enumerate the instance paths of instances of a class (including instances of its subclasses). |
GetInstance() |
Retrieve an instance |
ModifyInstance() |
Modify the property values of an instance |
CreateInstance() |
Create an instance |
DeleteInstance() |
Delete an instance |
Associators() |
Retrieve the instances (or classes) associated to a source instance (or source class) |
AssociatorNames() |
Retrieve the instance paths of the instances (or classes) associated to a source instance (or source class) |
References() |
Retrieve the association instances (or association classes) that reference a source instance (or source class) |
ReferenceNames() |
Retrieve the instance paths of the association instances (or association classes) that reference a source instance (or source class) |
InvokeMethod() |
Invoke a method on a target instance or on a target class |
ExecQuery() |
Execute a query in a namespace |
IterEnumerateInstances() |
Iterator API that uses either OpenEnumerateInstances and PullInstancesWithPath or EnumerateInstances depending on the attributes and existence of pull operations in the server. |
IterEnumerateInstancePaths() |
Iterator API that uses either OpenEnumerateInstances and PullInstancesWithPath or EnumerateInstances depending on the attributes and existence of pull operations in the server. |
IterAssociatorInstances() |
Iterator API that uses either OpenAssociatorInstances and PullInstancesWithPath or Associators depending on the attributes and existence of pull operations in the server. |
IterAssociatorInstancePaths() |
Iterator API that uses either OpenAssociatorInstances and PullInstancesWithPath or Associators depending on the attributes and existence of pull operations in the server. |
IterReferenceInstances() |
Iterator API that uses either OpenReferenceInstances and PullInstancesWithPath or References depending on the attributes and existence of pull operations in the server. |
IterReferenceInstancePaths() |
Iterator API that uses either OpenReferenceInstances and PullInstancesWithPath or References depending on the attributes and existence of pull operations in the server. |
IterQueryInstances() |
Iterator API that uses either OpenQueryInstances and PullInstances or ExecQuery depending on the attributes and existence of pull operations in the server. |
OpenEnumerateInstances() |
Open enumeration session to retrieve instances of of a class (including instances of its subclass) |
OpenEnumerateInstancePaths() |
Open enumeration session to retrieve instances of a class (including instances of its subclass) |
OpenAssociatorInstances() |
Open enumeration session to retrieve the instances associated to a source instance |
OpenAssociatorInstancePaths() |
Open enumeration session to retrieve the instances associated to a source instance |
OpenReferenceInstances() |
Open enumeration session to retrieve the instances that reference a source instance |
OpenReferenceInstancePaths() |
Open enumeration session to retrieve the instances that reference a source instance |
OpenQueryInstances() |
Open query request to retrieve instances defined by the query parameter in a namespace |
PullInstancesWithPath() |
Continue enumeration session opened with OpenEnumerateInstances, OpenAssociatorInstances, or OpenReferenceinstances |
PullInstancePaths() |
Continue enumeration session opened with OpenEnumerateInstancePaths, OpenAssociatorInstancePaths, or OpenReferenceInstancePaths |
PullInstances() |
Continue enumeration of enumeration session opened with OpenQueryInstances |
CloseEnumeration() |
Close an enumeration session in process. |
EnumerateClasses() |
Enumerate the subclasses of a class, or the top-level classes in a namespace |
EnumerateClassNames() |
Enumerate the names of subclasses of a class, or of the top-level classes in a namespace |
GetClass() |
Retrieve a class |
ModifyClass() |
Modify a class |
CreateClass() |
Create a class |
DeleteClass() |
Delete a class |
EnumerateQualifiers() |
Enumerate qualifier declarations |
GetQualifier() |
Retrieve a qualifier declaration |
SetQualifier() |
Create or modify a qualifier declaration |
DeleteQualifier() |
Delete a qualifier declaration |
NOTE: The method EnumerationCount is to be deprecated from the DMTF specs and has not been implemented by any WBEM servers so was not implemented in pywbem.
WBEMConnection¶
-
class
pywbem.
WBEMConnection
(url, creds=None, default_namespace=None, x509=None, ca_certs=None, no_verification=False, timeout=None, use_pull_operations=False, stats_enabled=False, proxies=None)[source]¶ A client’s connection to a WBEM server. This is the main class of the WBEM client library API.
The connection object knows a default CIM namespace, which is used when no namespace is specified on subsequent WBEM 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 WBEM operation performs an independent, state-less HTTP/HTTPS request. Usage of the requests Python package causes the underlying resources such as sockets to be pooled, though.
The
WBEMConnection
class supports connection through HTTP and SOCKS proxies, by utilizing the proxy support in the requests Python package.After creating a
WBEMConnection
object, various methods may be called on the object, which cause WBEM operations to be issued to the WBEM server. See WBEM operations for a list of these methods.CIM elements such as instances or classes are represented as Python objects (see CIM objects). The caller does not need to know about the CIM-XML encoding of CIM elements and protocol payload that is used underneath (It should be possible to use a different WBEM protocol 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
attribute of the connection object. This may be useful in debugging: If a problem occurs, you can examine thelast_request
andlast_reply
attributes 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 thelast_raw_request
andlast_raw_reply
attributes of the connection object.WBEMConnection objects can record the operations performed by calling
WBEMConnection
methods that interact with a WBEM server using operation recorders, at the level of method calls and returns, and at the level of CIM-XML requests and responses. TheLogOperationRecorder
class records the operations in the Python logging facility. This recorder is activated through the connection parameter ofconfigure_logger()
. TheTestClientRecorder
class records the operations in a file in the YAML format suitable for the test_client.py unit test program. Theadd_operation_recorder()
method is used to add an operation recorder to a connection, and theoperation_recorders
property is used to retrieve the current operation recorders of a connection.The methods of this class may raise the following exceptions:
Exceptions indicating operational errors:
ConnectionError
- A connection with the WBEM server could not be established or broke down.AuthError
- Authentication failed with the WBEM server.TimeoutError
- The WBEM server did not respond in time and the client timed out.
Such exceptions can typically be resolved by the client user or server admin.
Exceptions indicating server-side issues:
HTTPError
- HTTP error (bad status code) received from WBEM server.CIMXMLParseError
- The response from the WBEM server cannot be parsed because it is invalid CIM-XML (for example, a required attribute is missing on an XML element).XMLParseError
- The response from the WBEM server cannot be parsed because it is invalid XML (for example, invalid characters or UTF-8 sequences, or ill-formed XML).
Such exceptions nearly always indicate an issue with the implementation of the WBEM server.
Other exceptions:
CIMError
- The WBEM server returned an error response with a CIM status code.
Depending on the nature of the request, and on the CIM status code, the reason may be a client user error (e.g. incorrect class name) or a server side issue (e.g. some internal error in the server).
Exceptions indicating programming errors (in pywbem or by the user):
TypeError
KeyError
ValueError
AttributeError
- … possibly others …
Exceptions indicating programming errors should not happen. If you think the reason such an exception is raised lies in pywbem, report a bug.
Parameters: - url (string) –
URL of the WBEM server, in the format:
[{scheme}://]{host}[:{port}]
Possibly present trailing path segments in the URL are ignored.
The following URL schemes are supported:
http
: Causes HTTP to be used (default).https
: Causes HTTPS to be used.
The host can be specified in any of the usual formats:
- a short or fully qualified DNS hostname
- a literal (= dotted) IPv4 address
- a literal IPv6 address, formatted as defined in RFC3986
with the extensions for zone identifiers as defined in
RFC6874, supporting
-
(minus) for the delimiter before the zone ID string, as an additional choice to%25
.
If no port is specified in the URL, it defaults to:
- Port 5988 for URL scheme
http
- Port 5989 for URL scheme
https
Examples for some URL formats:
"https://10.11.12.13:6989"
: Use HTTPS to port 6989 on host 10.11.12.13"https://mysystem.acme.org"
: Use HTTPS to port 5989 on host mysystem.acme.org"10.11.12.13"
: Use HTTP to port 5988 on host 10.11.12.13"http://[2001:db8::1234]:15988"
: Use HTTP to port 15988 on host 2001:db8::1234"http://[::ffff.10.11.12.13]"
: Use HTTP to port 5988 on host ::ffff.10.11.12.13 (an IPv4-mapped IPv6 address)"http://[2001:db8::1234%25eth0]"
or"http://[2001:db8::1234-eth0]"
: Use HTTP to port 5988 to host 2001:db8::1234 (a link-local IPv6 address) using zone identifier eth0
- creds (
tuple()
of userid, password) –Credentials for HTTP authentication with the WBEM server, as a tuple(userid, password), with:
- userid (string): Userid for authenticating with the WBEM server.
- password (string): Password for that userid.
If None, the client will not generate
Authorization
headers in the HTTP request. Otherwise, the client will generate anAuthorization
header using HTTP Basic Authentication.See Authentication types for an overview.
- default_namespace (string) –
Default CIM namespace for this connection.
Leading and trailing slash characters will be stripped. The lexical case will be preserved.
If None, the default namespace of the connection will be set to the built-in default namespace
"root/cimv2"
.The default namespace of the connection is used if no namespace or a namespace of None is specified for an operation.
- x509 (
dict
) –X.509 client certificate and key file to be presented to the WBEM server during the TLS/SSL handshake.
This parameter is ignored when HTTP is used.
If None, no client certificate is presented to the server, resulting in TLS/SSL 1-way authentication to be used.
Otherwise, the client certificate is presented to the server, resulting in TLS/SSL 2-way authentication to be used. This parameter must be a dictionary containing the following two items:
"cert_file"
(string): The file path of a file containing an X.509 client certificate. Required. If the file does not exist,IOError
will be raised."key_file"
(string): The file path of a file containing the private key belonging to the public key that is part of the X.509 certificate file. Optional; if omitted or None, the private key must be in the file specified with"cert_file"
. If specified but the file does not exist,IOError
will be raised.
See Authentication types for an overview.
- ca_certs (string) –
Selects the CA certificates (trusted certificates) for verifying the X.509 server certificate returned by the WBEM server.
This parameter is ignored when HTTP is used or when the no_verification parameter is set to disable verification.
The parameter value must be one of:
- string: A path to a file containing one or more CA
certificates in PEM format. See the description of CAfile in
the OpenSSL SSL_CTX_load_verify_locations function for
details. If the file does not exist,
IOError
will be raised. - string: A path to a directory with files each of which
contains one CA certificate in PEM format. See the description
of CApath in the OpenSSL SSL_CTX_load_verify_locations
function for details. If the directory does not exist,
IOError
will be raised. - None (default): Use the certificates provided by the certifi Python package. This package provides the certificates from the Mozilla Included CA Certificate List.
- string: A path to a file containing one or more CA
certificates in PEM format. See the description of CAfile in
the OpenSSL SSL_CTX_load_verify_locations function for
details. If the file does not exist,
- no_verification (
bool
) –Disables verification of the X.509 server certificate returned by the WBEM server during TLS/SSL handshake, and disables verification of the hostname.
If True, verification is disabled; otherwise, verification is enabled.
This parameter is ignored when HTTP is used.
Disabling the verification of the server certificate is insecure and should be avoided!
- timeout (number) –
Timeout in seconds, for requests sent to the server.
New in pywbem 0.8.
If the server did not respond within the timeout duration, the socket for the connection will be closed, causing a
TimeoutError
to be raised.A value of None means that the connection uses the standard timeout behavior of Python sockets, which can be between several minutes and much longer. Because this is somewhat unpredictable, it is recommended to specify a value for the timeout.
A value of
0
means the timeout is very short, and does not really make any sense.Note that not all situations can be handled within this timeout, so for some issues, operations may take longer before raising an exception.
- use_pull_operations (
bool
) –Controls the use of pull operations in any Iter…() methods.
New in pywbem 0.11 as experimental and finalized in 0.13.
None means that the Iter…() methods will attempt a pull operation first, and if the WBEM server does not support it, will use a traditional operation from then on, on this connection. This detection is performed for each pull operation separately, in order to accomodate WBEM servers that support only some of the pull operations. This will work on any WBEM server whether it supports no, some, or all pull operations.
True means that the Iter…() methods will only use pull operations. If the WBEM server does not support pull operations, a
CIMError
with status code CIM_ERR_NOT_SUPPORTED will be raised.False (default) means that the Iter…() methods will only use traditional operations.
- stats_enabled (
bool
) –Initial enablement status for maintaining statistics about the WBEM operations executed via this connection.
New in pywbem 0.11 as experimental, renamed from `enable_stats` and finalized in 0.12.
See the WBEM operation statistics section for details.
- proxies (
dict
) –Dictionary with the URLs of HTTP or SOCKS proxies to use for the connection to the WBEM server.
New in pywbem 1.0
None (the default) causes the use of direct connections without using a proxy.
This parameter is passed on to the proxies parameter of the requests package. See the Proxy support section for details.
Methods
AssociatorNames
Retrieve the instance paths of the instances associated to a source instance, or the class paths of the classes associated to a source class. Associators
Retrieve the instances associated to a source instance, or the classes associated to a source class. CloseEnumeration
Close an open enumeration session, causing an early termination of an incomplete enumeration session. CreateClass
Create a class in a namespace. CreateInstance
Create an instance in a namespace. DeleteClass
Delete a class. DeleteInstance
Delete an instance. DeleteQualifier
Delete a qualifier type (= qualifier declaration). EnumerateClassNames
Enumerate the names of subclasses of a class, or of the top-level classes in a namespace. EnumerateClasses
Enumerate the subclasses of a class, or the top-level classes in a namespace. EnumerateInstanceNames
Enumerate the instance paths of instances of a class (including instances of its subclasses) in a namespace. EnumerateInstances
Enumerate the instances of a class (including instances of its subclasses) in a namespace. EnumerateQualifiers
Enumerate the qualifier types (= qualifier declarations) in a namespace. ExecQuery
Execute a query in a namespace. GetClass
Retrieve a class. GetInstance
Retrieve an instance. GetQualifier
Retrieve a qualifier type (= qualifier declaration). InvokeMethod
Invoke a method on a target instance or on a target class. IterAssociatorInstancePaths
Retrieve the instance paths of the instances associated to a source instance, using the Python generator idiom to return the result. IterAssociatorInstances
Retrieve the instances associated to a source instance, using the Python generator idiom to return the result. IterEnumerateInstancePaths
Enumerate the instance paths of instances of a class (including instances of its subclasses) in a namespace, using the Python generator idiom to return the result. IterEnumerateInstances
Enumerate the instances of a class (including instances of its subclasses) in a namespace, using the Python generator idiom to return the result. IterQueryInstances
Execute a query in a namespace, using the Python generator idiom to return the result. IterReferenceInstancePaths
Retrieve the instance paths of the association instances that reference a source instance, using the Python generator idiom to return the result. IterReferenceInstances
Retrieve the association instances that reference a source instance, using the Python generator idiom to return the result. ModifyClass
Modify a class. ModifyInstance
Modify the property values of an instance. OpenAssociatorInstancePaths
Open an enumeration session to retrieve the instance paths of the instances associated to a source instance. OpenAssociatorInstances
Open an enumeration session to retrieve the instances associated to a source instance. OpenEnumerateInstancePaths
Open an enumeration session to enumerate the instance paths of instances of a class (including instances of its subclasses) in a namespace. OpenEnumerateInstances
Open an enumeration session to enumerate the instances of a class (including instances of its subclasses) in a namespace. OpenQueryInstances
Open an enumeration session to execute a query in a namespace and to retrieve the instances representing the query result. OpenReferenceInstancePaths
Open an enumeration session to retrieve the instance paths of the association instances that reference a source instance. OpenReferenceInstances
Open an enumeration session to retrieve the association instances that reference a source instance. PullInstancePaths
Retrieve the next set of instance paths from an open enumeration session. PullInstances
Retrieve the next set of instances (without instance paths) from an open enumeration session. PullInstancesWithPath
Retrieve the next set of instances (with instance paths) from an open enumeration session. ReferenceNames
Retrieve the instance paths of the association instances that reference a source instance, or the class paths of the association classes that reference a source class. References
Retrieve the association instances that reference a source instance, or the association classes that reference a source class. SetQualifier
Create or modify a qualifier type (= qualifier declaration) in a namespace. add_operation_recorder
Experimental: Add an operation recorder to this connection. is_subclass
Return boolean indicating whether a class is a (direct or indirect) subclass of a superclass, or the same class, in the specified namespace. operation_recorder_reset
Experimental: Low-level method used by the operation-specific methods of this class. operation_recorder_stage_pywbem_args
Experimental: Low-level method used by the operation-specific methods of this class. operation_recorder_stage_result
Experimental: Low-level method used by the operation-specific methods of this class. Attributes
ca_certs
Selects the CA certificates (trusted certificates) for verifying the X.509 server certificate returned by the WBEM server. conn_id
Connection ID (a unique ID) of this connection. creds
Credentials for HTTP authentication with the WBEM server. debug
Boolean indicating that debug is enabled for this connection. default_namespace
Name of the CIM namespace to be used by default (if no namespace is specified for an operation). host
Normalized host and port number of the WBEM server, in the format host:port
.last_operation_time
Elapsed time of the last operation that was executed via this connection in seconds or None. last_raw_reply
CIM-XML data of the last response received from the WBEM server on this connection, formatted as it was received (=raw). last_raw_request
CIM-XML data of the last request sent to the WBEM server on this connection, formatted as it was sent (=raw). last_reply
CIM-XML data of the last response received from the WBEM server on this connection, formatted as prettified XML. last_reply_len
The size of the HTTP body in the CIM-XML response of the last operation, in Bytes. last_request
CIM-XML data of the last request sent to the WBEM server on this connection, formatted as prettified XML. last_request_len
The size of the HTTP body in the CIM-XML request of the last operation, in Bytes. last_server_response_time
Server-measured response time of the last request, or None. no_verification
Boolean indicating that verifications are disabled for this connection. operation_recorder_enabled
Experimental: Enablement status for all operation recorders of the connection. operation_recorders
Experimental: The operation recorders of this connection. proxies
Dictionary with the URLs of HTTP or SOCKS proxies to use for the connection to the WBEM server. scheme
Normalized scheme of the URL of the WBEM server, for example ‘http’ or ‘https’. statistics
Statistics for this connection. stats_enabled
Statistics enablement status for this connection. timeout
Timeout in seconds, for requests sent to the server. url
Normalized URL of the WBEM server. use_pull_operations
Boolean indicating that the client should attempt the use of pull operations in any Iter…() methods. x509
X.509 client certificate and key file to be presented to the WBEM server during the TLS/SSL handshake. Details
-
url
¶ Normalized URL of the WBEM server.
The scheme is in lower case and the default scheme (http) has been applied. Default port numbers (5988 for http and 5989 for https) have been applied. For IPv6 addresses, the host has been normalized to RFC6874 URI syntax. Trailing path segments have been removed.
For examples, see the description of the same-named init parameter of
this class
.Changed in pywbem 1.0: The URL is now normalized.
Type: unicode string
-
scheme
¶ Normalized scheme of the URL of the WBEM server, for example ‘http’ or ‘https’.
The scheme is in lower case and the default scheme (http) has been applied.
New in pywbem 1.0.
Type: unicode string
-
host
¶ Normalized host and port number of the WBEM server, in the format
host:port
.Default port numbers (5988 for http and 5989 for https) have been applied. For IPv6 addresses, the host has been normalized to RFC6874 URI syntax.
This value is used as the host portion of CIM namespace paths in any objects returned from the WBEM server that did not specify a CIM namespace path.
New in pywbem 0.11. Changed in pywbem 1.0: The host is now normalized and the port is always present.
Type: unicode string
-
creds
¶ Credentials for HTTP authentication with the WBEM server.
For details, see the description of the same-named init parameter of
this class
.Type: tuple()
-
default_namespace
¶ Name of the CIM namespace to be used by default (if no namespace is specified for an operation).
For details, see the description of the same-named init parameter of
this class
.This attribute is settable.
Type: unicode string
-
x509
¶ X.509 client certificate and key file to be presented to the WBEM server during the TLS/SSL handshake.
For details, see the description of the same-named init parameter of
this class
.Type: dict
-
ca_certs
¶ Selects the CA certificates (trusted certificates) for verifying the X.509 server certificate returned by the WBEM server.
For details, see the description of the same-named init parameter of
this class
.Type: string
-
no_verification
¶ Boolean indicating that verifications are disabled for this connection.
For details, see the description of the same-named init parameter of
this class
.Type: bool
-
timeout
¶ Timeout in seconds, for requests sent to the server.
New in pywbem 0.8.
For details, see the description of the same-named init parameter of
this class
.Type: number
-
operation_recorders
¶ - Experimental: The operation recorders of this connection.
New in pywbem 0.12 as experimental.
Type: Tuple of BaseOperationRecorder
subclass objects
-
operation_recorder_enabled
¶ Experimental: Enablement status for all operation recorders of the connection.
New in pywbem 0.11 as experimental
This is a writeable property; setting this property will change the operation recorder enablement status accordingly for all operation recorders of the connection.
Reading this property returns True if one or more operation recorders of the connection are enabled. Otherwise it returns False, also when the connection has no operation recorders.
Type: bool
-
stats_enabled
¶ Statistics enablement status for this connection.
New in pywbem 0.11 as experimental and finalized in 0.12.
This is a writeable property; setting this property will change the statistics enablement status accordingly.
The statistics enablement status can also be set when creating a connection, through the
stats_enabled
init argument ofWBEMConnection
.Type: bool
-
proxies
¶ Dictionary with the URLs of HTTP or SOCKS proxies to use for the connection to the WBEM server.
New in pywbem 1.0
This attribute is not settable. The dictionary content should not be modified (and such modifications would have no effect).
See the Proxy support section for details.
Type: dict
-
statistics
¶ Statistics for this connection.
New in pywbem 0.11 as experimental and finalized in 0.12.
Statistics are disabled by default and can be enabled via the
stats_enabled
argument when creating a connection object, or later via modifying thestats_enabled
property on this connection object. See the WBEM operation statistics section for more details.Type: Statistics
-
last_operation_time
¶ Elapsed time of the last operation that was executed via this connection in seconds or None.
New in pywbem 0.11 as experimental and finalized in 0.12.
This time is available only subsequent to the execution of an operation on this connection, and if the statistics are enabled on this connection. Otherwise, the value is None.
Type: float
-
last_server_response_time
¶ Server-measured response time of the last request, or None.
New in pywbem 0.11 as experimental and finalized in 0.12.
This time is optionally returned from the server in the HTTP header of the response. This time is available only subsequent to the execution of an operation on this connection if the WBEMServerResponseTime is received from the WBEM server. Otherwise, the value is None.
Type: float
-
use_pull_operations
¶ Boolean indicating that the client should attempt the use of pull operations in any Iter…() methods.
New in pywbem 0.11 as experimental and finalized in 0.13.
This property reflects the intent of the user as specified in the same-named init parameter of
this class
. This property is not updated with the status of actually using pull operations. That status is maintained internally for each pull operation separately to accomodate WBEM servers that support only some of the pull operations.Type: bool
-
debug
¶ Boolean indicating that debug is enabled for this connection.
When enabled (value True), the prettified last CIM-XML request and response will be stored in the following properties of this class:
When disabled (value False), these properties will be None.
This attribute is writeable. The initial value of this attribute is False.
Note that the following properties will be set regardless of whether debug is enabled for this connection:
Type: bool
-
last_request
¶ CIM-XML data of the last request sent to the WBEM server on this connection, formatted as prettified XML.
This property is only set when debug is enabled (see
debug
), and is None otherwise.Prior to sending the very first request on this connection object, this property is None.
Type: unicode string
-
last_raw_request
¶ CIM-XML data of the last request sent to the WBEM server on this connection, formatted as it was sent (=raw).
Prior to sending the very first request on this connection object, this property is None.
As of pywbem 0.13, this property is set independently of whether debug is enabled (see
debug
).Type: unicode string
-
last_reply
¶ CIM-XML data of the last response received from the WBEM server on this connection, formatted as prettified XML.
This property is only set when debug is enabled (see
debug
), and is None otherwise.This property is set to None in the WBEM operation methods of this class before the request is sent to the WBEM server, and is set to the prettified response when the response has been received from the WBEM server and XML parsed. If the XML parsing fails, this property will be None, but the
last_raw_reply
property does not depend on XML parsing and will already have been set at that point.Prior to sending the very first request on this connection object, this property is None.
Type: unicode string
-
last_raw_reply
¶ CIM-XML data of the last response received from the WBEM server on this connection, formatted as it was received (=raw).
This property is set to None in the WBEM operation methods of this class before the request is sent to the WBEM server, and is set to the prettified response when the response has been received from the WBEM server, and before XML parsing takes place.
Prior to sending the very first request on this connection object, this property is None.
As of pywbem 0.13, this property is set independently of whether debug is enabled (see
debug
).Type: unicode string
-
last_request_len
¶ The size of the HTTP body in the CIM-XML request of the last operation, in Bytes.
Prior to sending the very first request on this connection object, this property is 0.
This property is set independently of whether debug is enabled (see
debug
).Type: int
-
last_reply_len
¶ The size of the HTTP body in the CIM-XML response of the last operation, in Bytes.
This property is set to 0 in the WBEM operation methods of this class before the request is sent to the WBEM server, and is set to the size when the response has been received from the WBEM server, and before XML parsing takes place.
Prior to sending the very first request on this connection object, this property is 0.
This property is set independently of whether debug is enabled (see
debug
).Type: int
-
conn_id
¶ Connection ID (a unique ID) of this connection.
The value for this property is created when the
WBEMConnection
object is created and remains constant throughout the life of that object.The connection ID is part of each log entry output to uniquely identify the
WBEMConnection
object responsible for that log. It also part of the logger name for the “pywbem.api” and “pywbem.http” loggers that create log entries so that logging can be defined separately for different connections.Type: connection id
-
__str__
()[source]¶ Return a short representation of the
WBEMConnection
object for human consumption.
-
__repr__
()[source]¶ Return a representation of the
WBEMConnection
object with all attributes (except for the password in the credentials) that is suitable for debugging.
-
add_operation_recorder
(operation_recorder)[source]¶ Experimental: Add an operation recorder to this connection.
New in pywbem 0.12 as experimental.
If the connection already has a recorder with the same class, the request to add the recorder is ignored.
Parameters: operation_recorder (
BaseOperationRecorder
subclass object) – The operation recorder to be added. Must not be None.Raises: ValueError
– Operation recorder must not be None.ValueError
– Cannot add the same recorder class multiple times.
-
operation_recorder_reset
(pull_op=False)[source]¶ Experimental: Low-level method used by the operation-specific methods of this class.
New in pywbem 0.9 as experimental.
It resets the operation processing state of all recorders of this connection, to be ready for processing a new operation call.
-
operation_recorder_stage_pywbem_args
(method, **kwargs)[source]¶ Experimental: Low-level method used by the operation-specific methods of this class.
New in pywbem 0.9 as experimental.
It forwards the operation method name and arguments to all recorders of this connection.
-
operation_recorder_stage_result
(ret, exc)[source]¶ Experimental: Low-level method used by the operation-specific methods of this class.
New in pywbem 0.9 as experimental.
It forwards the operation results including exceptions that were raised, to all recorders of this connection, and causes the forwarded information to be recorded by all recorders of this connection.
-
EnumerateInstances
(ClassName, namespace=None, LocalOnly=None, DeepInheritance=None, IncludeQualifiers=None, IncludeClassOrigin=None, PropertyList=None)[source]¶ Enumerate the instances of a class (including instances of its subclasses) in a namespace.
This method performs the EnumerateInstances operation (see DSP0200). See WBEM operations for a list of all methods performing such operations.
If the operation succeeds, this method returns. Otherwise, this method raises an exception.
Parameters: - ClassName (string or
CIMClassName
) – Name of the class to be enumerated (case independent). If specified as aCIMClassName
object, its host attribute will be ignored. - namespace (string) –
Name of the CIM namespace to be used (case independent).
Leading and trailing slash characters will be stripped. The lexical case will be preserved.
If None, the namespace of the ClassName parameter will be used, if specified as a
CIMClassName
object. If that is also None, the default namespace of the connection will be used. - LocalOnly (
bool
) –Controls the exclusion of inherited properties from the returned instances, as follows:
- If False, inherited properties are not excluded.
- If True, inherited properties are basically excluded, but the behavior may be WBEM server specific.
- If None, this parameter is not passed to the WBEM server, and causes the server-implemented default to be used. DSP0200 defines that the server-implemented default is True.
This parameter has been deprecated in DSP0200 and should be set to False by the caller.
- DeepInheritance (
bool
) –Indicates that properties added by subclasses of the specified class are to be included in the returned instances, as follows:
- If False, properties added by subclasses are not included.
- If True, properties added by subclasses are included.
- If None, this parameter is not passed to the WBEM server, and causes the server-implemented default to be used. DSP0200 defines that the server-implemented default is True.
Note, the semantics of the DeepInheritance parameter in
EnumerateClasses()
andEnumerateClassNames()
is different. - IncludeQualifiers (
bool
) –Indicates that qualifiers are to be included in the returned instances, as follows:
- If False, qualifiers are not included.
- If True, qualifiers are included if the WBEM server implements support for this parameter.
- If None, this parameter is not passed to the WBEM server, and causes the server-implemented default to be used. DSP0200 defines that the server-implemented default is False.
This parameter has been deprecated in DSP0200. Clients cannot rely on qualifiers to be returned in this operation.
- IncludeClassOrigin (
bool
) –Indicates that class origin information is to be included on each property in the returned instances, as follows:
- If False, class origin information is not included.
- If True, class origin information is included.
- If None, this parameter is not passed to the WBEM server, and causes the server-implemented default to be used. DSP0200 defines that the server-implemented default is False.
This parameter has been deprecated in DSP0200. WBEM servers may either implement this parameter as specified, or may treat any specified value as False.
- PropertyList (string or iterable of string) –
An iterable specifying the names of the properties (or a string that defines a single property) to be included in the returned instances (case independent).
An empty iterable indicates to include no properties.
If None, all properties are included.
Returns: A list of
CIMInstance
objects that are representations of the enumerated instances.The path attribute of each
CIMInstance
object is aCIMInstanceName
object with its attributes set as follows:- classname: Name of the creation class of the instance.
- keybindings: Keybindings of the instance.
- namespace: Name of the CIM namespace containing the instance.
- host: None, indicating the WBEM server is unspecified.
Raises: Exceptions described in
WBEMConnection
.- ClassName (string or
-
EnumerateInstanceNames
(ClassName, namespace=None)[source]¶ Enumerate the instance paths of instances of a class (including instances of its subclasses) in a namespace.
This method performs the EnumerateInstanceNames operation (see DSP0200). See WBEM operations for a list of all methods performing such operations.
If the operation succeeds, this method returns. Otherwise, this method raises an exception.
Parameters: - ClassName (string or
CIMClassName
) – Name of the class to be enumerated (case independent). If specified as aCIMClassName
object, its host attribute will be ignored. - namespace (string) –
Name of the CIM namespace to be used (case independent).
Leading and trailing slash characters will be stripped. The lexical case will be preserved.
If None, the namespace of the ClassName parameter will be used, if specified as a
CIMClassName
object. If that is also None, the default namespace of the connection will be used.
Returns: A list of
CIMInstanceName
objects that are the enumerated instance paths, with its attributes set as follows:- classname: Name of the creation class of the instance.
- keybindings: Keybindings of the instance.
- namespace: Name of the CIM namespace containing the instance.
- host: None, indicating the WBEM server is unspecified.
Raises: Exceptions described in
WBEMConnection
.- ClassName (string or
-
GetInstance
(InstanceName, LocalOnly=None, IncludeQualifiers=None, IncludeClassOrigin=None, PropertyList=None)[source]¶ Retrieve an instance.
This method performs the GetInstance operation (see DSP0200). See WBEM operations for a list of all methods performing such operations.
If the operation succeeds, this method returns. Otherwise, this method raises an exception.
Parameters: - InstanceName (
CIMInstanceName
) – The instance path of the instance to be retrieved. If this object does not specify a namespace, the default namespace of the connection is used. Its host attribute will be ignored. - LocalOnly (
bool
) –Controls the exclusion of inherited properties from the returned instance, as follows:
- If False, inherited properties are not excluded.
- If True, inherited properties are basically excluded, but the behavior may be WBEM server specific.
- If None, this parameter is not passed to the WBEM server, and causes the server-implemented default to be used. DSP0200 defines that the server-implemented default is True.
This parameter has been deprecated in DSP0200 and should be set to False by the caller.
- IncludeQualifiers (
bool
) –Indicates that qualifiers are to be included in the returned instance, as follows:
- If False, qualifiers are not included.
- If True, qualifiers are included if the WBEM server implements support for this parameter.
- If None, this parameter is not passed to the WBEM server, and causes the server-implemented default to be used. DSP0200 defines that the server-implemented default is False.
This parameter has been deprecated in DSP0200. Clients cannot rely on qualifiers to be returned in this operation.
- IncludeClassOrigin (
bool
) –Indicates that class origin information is to be included on each property in the returned instance, as follows:
- If False, class origin information is not included.
- If True, class origin information is included.
- If None, this parameter is not passed to the WBEM server, and causes the server-implemented default to be used. DSP0200 defines that the server-implemented default is False.
This parameter has been deprecated in DSP0200. WBEM servers may either implement this parameter as specified, or may treat any specified value as False.
- PropertyList (string or iterable of string) –
An iterable specifying the names of the properties (or a string that defines a single property) to be included in the returned instance (case independent).
An empty iterable indicates to include no properties.
If None, all properties are included.
Returns: A
CIMInstance
object that is a representation of the retrieved instance. Its path attribute is aCIMInstanceName
object with its attributes set as follows:- classname: Name of the creation class of the instance.
- keybindings: Keybindings of the instance.
- namespace: Name of the CIM namespace containing the instance.
- host: None, indicating the WBEM server is unspecified.
Raises: Exceptions described in
WBEMConnection
.- InstanceName (
-
ModifyInstance
(ModifiedInstance, IncludeQualifiers=None, PropertyList=None)[source]¶ Modify the property values of an instance.
This method performs the ModifyInstance operation (see DSP0200). See WBEM operations for a list of all methods performing such operations.
The PropertyList parameter determines the set of properties that are designated to be modified (see its description for details).
The properties provided in the ModifiedInstance parameter specify the new property values for the properties that are designated to be modified.
Pywbem sends the property values provided in the ModifiedInstance parameter to the WBEM server as provided; it does not add any default values for properties not provided but designated to be modified, nor does it reduce the properties by those not designated to be modified.
The properties that are actually modified by the WBEM server as a result of this operation depend on a number of things:
The WBEM server will reject modification requests for key properties and for properties that are not exposed by the creation class of the target instance.
The WBEM server may consider some properties as read-only, as a result of requirements at the CIM modeling level (schema or management profiles), or as a result of an implementation decision.
Note that the WRITE qualifier on a property is not a safe indicator as to whether the property can actually be modified. It is an expression at the level of the CIM schema that may or may not be considered in DMTF management profiles or in implementations. Specifically, a qualifier value of True on a property does not guarantee modifiability of the property, and a value of False does not prevent modifiability.
The WBEM server may detect invalid new values or conflicts resulting from the new property values and may reject modification of a property for such reasons.
If the WBEM server rejects modification of a property for any reason, it will cause this operation to fail and will not modify any property on the target instance. If this operation succeeds, all properties designated to be modified have their new values (see the description of the ModifiedInstance parameter for details on how the new values are determined).
Note that properties (including properties not designated to be modified) may change their values as an indirect result of this operation. For example, a property that was not designated to be modified may be derived from another property that was modified, and may show a changed value due to that.
If the operation succeeds, this method returns. Otherwise, this method raises an exception.
Parameters: - ModifiedInstance (
CIMInstance
) –A representation of the modified instance, also indicating its instance path.
The path attribute of this object identifies the instance to be modified. Its keybindings attribute is required. If its namespace attribute is None, the default namespace of the connection will be used. Its host attribute will be ignored.
The classname attribute of the instance path and the classname attribute of the instance must specify the same class name.
The properties defined in this object specify the new property values (including None for NULL). If a property is designated to be modified but is not specified in this object, the WBEM server will use the default value of the property declaration if specified (including None), and otherwise may update the property to any value (including None).
Typically, this object has been retrieved by other operations, such as
GetInstance()
. - IncludeQualifiers (
bool
) –Indicates that qualifiers are to be modified as specified in the ModifiedInstance parameter, as follows:
- If False, qualifiers not modified.
- If True, qualifiers are modified if the WBEM server implements support for this parameter.
- If None, this parameter is not passed to the WBEM server, and causes the server-implemented default to be used. DSP0200 defines that the server-implemented default is True.
This parameter has been deprecated in DSP0200. Clients cannot rely on qualifiers to be modified.
- PropertyList (string or iterable of string) –
This parameter defines which properties are designated to be modified.
This parameter is an iterable specifying the names of the properties, or a string that specifies a single property name. In all cases, the property names are matched case insensitively. The specified properties are designated to be modified. Properties not specified are not designated to be modified.
An empty iterable indicates that no properties are designated to be modified.
If None, DSP0200 states that the properties with values different from the current values in the instance are designated to be modified, but for all practical purposes this is equivalent to stating that all properties exposed by the instance are designated to be modified.
Raises: Exceptions described in
WBEMConnection
.
-
CreateInstance
(NewInstance, namespace=None)[source]¶ Create an instance in a namespace.
This method performs the CreateInstance operation (see DSP0200). See WBEM operations for a list of all methods performing such operations.
If the operation succeeds, this method returns. Otherwise, this method raises an exception.
The creation class for the new instance is taken from the classname attribute of the NewInstance parameter.
The namespace for the new instance is taken from these sources, in decreasing order of priority:
- namespace parameter of this method, if not None,
- namespace in path attribute of the NewInstance parameter, if not None,
- default namespace of the connection.
Parameters: - NewInstance (
CIMInstance
) –A representation of the CIM instance to be created.
The classname attribute of this object specifies the creation class for the new instance.
Apart from utilizing its namespace, the path attribute is ignored.
The properties attribute of this object specifies initial property values for the new CIM instance.
Instance-level qualifiers have been deprecated in CIM, so any qualifier values specified using the qualifiers attribute of this object will be ignored.
- namespace (string) –
Name of the CIM namespace to be used (case independent).
New in pywbem 0.9.
If None, defaults to the namespace in the path attribute of the NewInstance parameter, or to the default namespace of the connection.
Leading and trailing slash characters will be stripped. The lexical case will be preserved.
Returns: A
CIMInstanceName
object that is the instance path of the new instance, with classname, keybindings and namespace set.Raises: Exceptions described in
WBEMConnection
.
-
DeleteInstance
(InstanceName)[source]¶ Delete an instance.
This method performs the DeleteInstance operation (see DSP0200). See WBEM operations for a list of all methods performing such operations.
If the operation succeeds, this method returns. Otherwise, this method raises an exception.
Parameters: InstanceName ( CIMInstanceName
) – The instance path of the instance to be deleted. If this object does not specify a namespace, the default namespace of the connection is used. Its host attribute will be ignored.Raises: Exceptions described in WBEMConnection
.
-
Associators
(ObjectName, AssocClass=None, ResultClass=None, Role=None, ResultRole=None, IncludeQualifiers=None, IncludeClassOrigin=None, PropertyList=None)[source]¶ Retrieve the instances associated to a source instance, or the classes associated to a source class.
This method performs the Associators operation (see DSP0200). See WBEM operations for a list of all methods performing such operations.
If the operation succeeds, this method returns. Otherwise, this method raises an exception.
Parameters: - ObjectName –
The object path of the source object, selecting instance-level or class-level use of this operation, as follows:
- For selecting instance-level use: The instance path of the
source instance, as a
CIMInstanceName
object. If this object does not specify a namespace, the default namespace of the connection is used. Its host attribute will be ignored. - For selecting class-level use: The class path of the source
class, as a string or
CIMClassName
object:If specified as a string, the string is interpreted as a class name in the default namespace of the connection (case independent).
If specified as a
CIMClassName
object, its host attribute will be ignored. If this object does not specify a namespace, the default namespace of the connection is used.
- For selecting instance-level use: The instance path of the
source instance, as a
- AssocClass (string or
CIMClassName
) –Class name of an association class (case independent), to filter the result to include only traversals of that association class (or subclasses). If specified as a
CIMClassName
object, its host and namespace attributes will be ignored.None means that no such filtering is peformed.
- ResultClass (string or
CIMClassName
) –Class name of an associated class (case independent), to filter the result to include only traversals to that associated class (or subclasses). If specified as a
CIMClassName
object, its host and namespace attributes will be ignored.None means that no such filtering is peformed.
- Role (string) –
Role name (= property name) of the source end (case independent), to filter the result to include only traversals from that source role.
None means that no such filtering is peformed.
- ResultRole (string) –
Role name (= property name) of the far end (case independent), to filter the result to include only traversals to that far role.
None means that no such filtering is peformed.
- IncludeQualifiers (
bool
) –Indicates that qualifiers are to be included in the returned instances (or classes), as follows:
- If False, qualifiers are not included.
- If True, qualifiers are included if the WBEM server implements support for this parameter.
- If None, this parameter is not passed to the WBEM server, and causes the server-implemented default to be used. DSP0200 defines that the server-implemented default is False.
This parameter has been deprecated in DSP0200. Clients cannot rely on qualifiers to be returned in this operation.
- IncludeClassOrigin (
bool
) –Indicates that class origin information is to be included on each property or method in the returned instances (or classes), as follows:
- If False, class origin information is not included.
- If True, class origin information is included.
- If None, this parameter is not passed to the WBEM server, and causes the server-implemented default to be used. DSP0200 defines that the server-implemented default is False.
This parameter has been deprecated in DSP0200 for instance-level use. WBEM servers may either implement this parameter as specified, or may treat any specified value as False.
- PropertyList (string or iterable of string) –
An iterable specifying the names of the properties (or a string that defines a single property) to be included in the returned instances (or classes) (case independent).
An empty iterable indicates to include no properties.
If None, all properties are included.
Returns: The returned list of objects depend on the usage:
For instance-level use: A list of
CIMInstance
objects that are representations of the associated instances.The path attribute of each
CIMInstance
object is aCIMInstanceName
object with its attributes set as follows:- classname: Name of the creation class of the instance.
- keybindings: Keybindings of the instance.
- namespace: Name of the CIM namespace containing the instance.
- host: Host and optionally port of the WBEM server containing the CIM namespace, or None if the server did not return host information.
For class-level use: A list of
tuple()
of (classpath, class) objects that are representations of the associated classes.Each tuple represents one class and has these items:
- classpath (
CIMClassName
): The class path of the class, with its attributes set as follows:- classname: Name of the class.
- namespace: Name of the CIM namespace containing the class.
- host: Host and optionally port of the WBEM server containing the CIM namespace, or None if the server did not return host information.
- class (
CIMClass
): The representation of the class, with its path attribute set to the classpath tuple item.
- classpath (
Raises: Exceptions described in
WBEMConnection
.- ObjectName –
-
AssociatorNames
(ObjectName, AssocClass=None, ResultClass=None, Role=None, ResultRole=None)[source]¶ Retrieve the instance paths of the instances associated to a source instance, or the class paths of the classes associated to a source class.
This method performs the AssociatorNames operation (see DSP0200). See WBEM operations for a list of all methods performing such operations.
If the operation succeeds, this method returns. Otherwise, this method raises an exception.
Parameters: - ObjectName –
The object path of the source object, selecting instance-level or class-level use of this operation, as follows:
- For selecting instance-level use: The instance path of the
source instance, as a
CIMInstanceName
object. If this object does not specify a namespace, the default namespace of the connection is used. Its host attribute will be ignored. - For selecting class-level use: The class path of the source
class, as a string or
CIMClassName
object:If specified as a string, the string is interpreted as a class name in the default namespace of the connection (case independent).
If specified as a
CIMClassName
object, its host attribute will be ignored. If this object does not specify a namespace, the default namespace of the connection is used.
- For selecting instance-level use: The instance path of the
source instance, as a
- AssocClass (string or
CIMClassName
) –Class name of an association class (case independent), to filter the result to include only traversals of that association class (or subclasses). If specified as a
CIMClassName
object, its host and namespace attributes will be ignored.None means that no such filtering is peformed.
- ResultClass (string or
CIMClassName
) –Class name of an associated class (case independent), to filter the result to include only traversals to that associated class (or subclasses). If specified as a
CIMClassName
object, its host and namespace attributes will be ignored.None means that no such filtering is peformed.
- Role (string) –
Role name (= property name) of the source end (case independent), to filter the result to include only traversals from that source role.
None means that no such filtering is peformed.
- ResultRole (string) –
Role name (= property name) of the far end (case independent), to filter the result to include only traversals to that far role.
None means that no such filtering is peformed.
Returns: The returned list of objects depend on the usage:
- For instance-level use: A list of
CIMInstanceName
objects that are the instance paths of the associated instances, with their attributes set as follows:- classname: Name of the creation class of the instance.
- keybindings: Keybindings of the instance.
- namespace: Name of the CIM namespace containing the instance.
- host: Host and optionally port of the WBEM server containing the CIM namespace, or None if the server did not return host information.
- For class-level use: A list of
CIMClassName
objects that are the class paths of the associated classes, with their attributes set as follows:- classname: Name of the class.
- namespace: Name of the CIM namespace containing the class.
- host: Host and optionally port of the WBEM server containing the CIM namespace, or None if the server did not return host information.
Raises: Exceptions described in
WBEMConnection
.- ObjectName –
-
References
(ObjectName, ResultClass=None, Role=None, IncludeQualifiers=None, IncludeClassOrigin=None, PropertyList=None)[source]¶ Retrieve the association instances that reference a source instance, or the association classes that reference a source class.
This method performs the References operation (see DSP0200). See WBEM operations for a list of all methods performing such operations.
If the operation succeeds, this method returns. Otherwise, this method raises an exception.
Parameters: - ObjectName –
The object path of the source object, selecting instance-level or class-level use of this operation, as follows:
- For selecting instance-level use: The instance path of the
source instance, as a
CIMInstanceName
object. If this object does not specify a namespace, the default namespace of the connection is used. Its host attribute will be ignored. - For selecting class-level use: The class path of the source
class, as a string or
CIMClassName
object:If specified as a string, the string is interpreted as a class name in the default namespace of the connection (case independent).
If specified as a
CIMClassName
object, its host attribute will be ignored. If this object does not specify a namespace, the default namespace of the connection is used.
- For selecting instance-level use: The instance path of the
source instance, as a
- ResultClass (string or
CIMClassName
) –Class name of an association class (case independent), to filter the result to include only traversals of that association class (or subclasses). If specified as a
CIMClassName
object, its host and namespace attributes will be ignored.None means that no such filtering is peformed.
- Role (string) –
Role name (= property name) of the source end (case independent), to filter the result to include only traversals from that source role.
None means that no such filtering is peformed.
- IncludeQualifiers (
bool
) –Indicates that qualifiers are to be included in the returned instances (or classes), as follows:
- If False, qualifiers are not included.
- If True, qualifiers are included if the WBEM server implements support for this parameter.
- If None, this parameter is not passed to the WBEM server, and causes the server-implemented default to be used. DSP0200 defines that the server-implemented default is False.
This parameter has been deprecated in DSP0200. Clients cannot rely on qualifiers to be returned in this operation.
- IncludeClassOrigin (
bool
) –Indicates that class origin information is to be included on each property or method in the returned instances (or classes), as follows:
- If False, class origin information is not included.
- If True, class origin information is included.
- If None, this parameter is not passed to the WBEM server, and causes the server-implemented default to be used. DSP0200 defines that the server-implemented default is False.
This parameter has been deprecated in DSP0200 for instance-level use. WBEM servers may either implement this parameter as specified, or may treat any specified value as False.
- PropertyList (string or iterable of string) –
An iterable specifying the names of the properties (or a string that defines a single property) to be included in the returned instances (or classes) (case independent).
An empty iterable indicates to include no properties.
If None, all properties are included.
Returns: The returned list of objects depend on the usage:
For instance-level use: A list of
CIMInstance
objects that are representations of the referencing association instances.The path attribute of each
CIMInstance
object is aCIMInstanceName
object with its attributes set as follows:- classname: Name of the creation class of the instance.
- keybindings: Keybindings of the instance.
- namespace: Name of the CIM namespace containing the instance.
- host: Host and optionally port of the WBEM server containing the CIM namespace, or None if the server did not return host information.
For class-level use: A list of
tuple()
of (classpath, class) objects that are representations of the referencing association classes.Each tuple represents one class and has these items:
- classpath (
CIMClassName
): The class path of the class, with its attributes set as follows:- classname: Name of the class.
- namespace: Name of the CIM namespace containing the class.
- host: Host and optionally port of the WBEM server containing the CIM namespace, or None if the server did not return host information.
- class (
CIMClass
): The representation of the class, with its path attribute set to the classpath tuple item.
- classpath (
Raises: Exceptions described in
WBEMConnection
.- ObjectName –
-
ReferenceNames
(ObjectName, ResultClass=None, Role=None)[source]¶ Retrieve the instance paths of the association instances that reference a source instance, or the class paths of the association classes that reference a source class.
This method performs the ReferenceNames operation (see DSP0200). See WBEM operations for a list of all methods performing such operations.
If the operation succeeds, this method returns. Otherwise, this method raises an exception.
Parameters: - ObjectName –
The object path of the source object, selecting instance-level or class-level use of this operation, as follows:
- For selecting instance-level use: The instance path of the
source instance, as a
CIMInstanceName
object. If this object does not specify a namespace, the default namespace of the connection is used. Its host attribute will be ignored. - For selecting class-level use: The class path of the source
class, as a string or
CIMClassName
object:If specified as a string, the string is interpreted as a class name in the default namespace of the connection (case independent).
If specified as a
CIMClassName
object, its host attribute will be ignored. If this object does not specify a namespace, the default namespace of the connection is used.
- For selecting instance-level use: The instance path of the
source instance, as a
- ResultClass (string or
CIMClassName
) –Class name of an association class (case independent), to filter the result to include only traversals of that association class (or subclasses). If specified as a
CIMClassName
object, its host and namespace attributes will be ignored.None means that no such filtering is peformed.
- Role (string) –
Role name (= property name) of the source end (case independent), to filter the result to include only traversals from that source role.
None means that no such filtering is peformed.
Returns: The returned list of objects depend on the usage:
- For instance-level use: A list of
CIMInstanceName
objects that are the instance paths of the referencing association instances, with their attributes set as follows:- classname: Name of the creation class of the instance.
- keybindings: Keybindings of the instance.
- namespace: Name of the CIM namespace containing the instance.
- host: Host and optionally port of the WBEM server containing the CIM namespace, or None if the server did not return host information.
- For class-level use: A list of
CIMClassName
objects that are the class paths of the referencing association classes, with their attributes set as follows:- classname: Name of the class.
- namespace: Name of the CIM namespace containing the class.
- host: Host and optionally port of the WBEM server containing the CIM namespace, or None if the server did not return host information.
Raises: Exceptions described in
WBEMConnection
.- ObjectName –
-
InvokeMethod
(MethodName, ObjectName, Params=None, **params)[source]¶ Invoke a method on a target instance or on a target class.
The methods that can be invoked are static and non-static methods defined in a class (also known as extrinsic methods). Static methods can be invoked on instances and on classes. Non-static methods can be invoked only on instances.
This method performs the extrinsic method invocation operation (see DSP0200). See WBEM operations for a list of all methods performing such operations.
If the operation succeeds, this method returns. Otherwise, this method raises an exception.
Input parameters for the CIM method can be specified using the Params parameter, and using keyword parameters. The overall list of input parameters is formed from the list of parameters specified in Params (preserving their order), followed by the set of keyword parameters (not preserving their order). There is no checking for duplicate parameter names.
Parameters: - MethodName (string) – Name of the method to be invoked (case independent).
- ObjectName –
The object path of the target object, as follows:
- For instance-level use: The instance path of the target
instance, as a
CIMInstanceName
object. If this object does not specify a namespace, the default namespace of the connection is used. Its host attribute will be ignored. - For class-level use: The class path of the target class, as a
string or
CIMClassName
object:If specified as a string, the string is interpreted as a class name in the default namespace of the connection (case independent).
If specified as a
CIMClassName
object, its host attribute will be ignored. If this object does not specify a namespace, the default namespace of the connection is used.
- For instance-level use: The instance path of the target
instance, as a
- Params (iterable) –
An iterable of input parameter values for the CIM method. Each item in the iterable is a single parameter value and can be any of:
CIMParameter
representing a parameter value. The name, value, type and embedded_object attributes of this object are used.- tuple of name, value, with:
- name (string): Parameter name (case independent)
- value (CIM data type): Parameter value
- **params –
Each keyword parameter is an additional input parameter value for the CIM method, with:
- key (string): Parameter name (case independent)
- value (CIM data type): Parameter value
Returns: A
tuple()
of (returnvalue, outparams), with these tuple items:- returnvalue (CIM data type): Return value of the CIM method.
- outparams (NocaseDict):
Dictionary with all provided output parameters of the CIM method,
with:
- key (unicode string): Parameter name, preserving its lexical case
- value (CIM data type): Parameter value
Raises: Exceptions described in
WBEMConnection
.
-
ExecQuery
(QueryLanguage, Query, namespace=None)[source]¶ Execute a query in a namespace.
This method performs the ExecQuery operation (see DSP0200). See WBEM operations for a list of all methods performing such operations.
If the operation succeeds, this method returns. Otherwise, this method raises an exception.
Parameters: - QueryLanguage (string) – Name of the query language used in the Query parameter, e.g. “DMTF:CQL” for CIM Query Language, and “WQL” for WBEM Query Language.
- Query (string) – Query string in the query language specified in the QueryLanguage parameter.
- namespace (string) –
Name of the CIM namespace to be used (case independent).
Leading and trailing slash characters will be stripped. The lexical case will be preserved.
If None, the default namespace of the connection object will be used.
Returns: A list of
CIMInstance
objects that represents the query result.These instances have their path attribute set to identify their creation class and the target namespace of the query, but they are not addressable instances.
Raises: Exceptions described in
WBEMConnection
.
-
IterEnumerateInstances
(ClassName, namespace=None, LocalOnly=None, DeepInheritance=None, IncludeQualifiers=None, IncludeClassOrigin=None, PropertyList=None, FilterQueryLanguage=None, FilterQuery=None, OperationTimeout=None, ContinueOnError=None, MaxObjectCount=1000)[source]¶ Enumerate the instances of a class (including instances of its subclasses) in a namespace, using the Python generator idiom to return the result.
New in pywbem 0.10 as experimental and finalized in 0.12.
This method uses the corresponding pull operations if supported by the WBEM server or otherwise the corresponding traditional operation. This method is an alternative to using the pull operations directly, that frees the user of having to know whether the WBEM server supports pull operations.
This method is a generator function that retrieves instances from the WBEM server and returns them one by one (using
yield
) when the caller iterates through the returned generator object. The number of instances that are retrieved from the WBEM server in one request (and thus need to be materialized in this method) is up to the MaxObjectCount parameter if the corresponding pull operations are used, or the complete result set all at once if the corresponding traditional operation is used.By default, this method attempts to perform the corresponding pull operations (
OpenEnumerateInstances()
andPullInstancesWithPath()
). If these pull operations are not supported by the WBEM server, this method falls back to using the corresponding traditional operation (EnumerateInstances()
). Whether the WBEM server supports these pull operations is remembered in theWBEMConnection
object (by operation type), and avoids unnecessary attempts to try these pull operations on that connection in the future. The use_pull_operations init parameter ofWBEMConnection
can be used to control the preference for always using pull operations, always using traditional operations, or using pull operations if supported by the WBEM server (the default).This method provides all of the controls of the corresponding pull operations except for the ability to set different response sizes on each request; the response size (defined by the MaxObjectCount parameter) is the same for all pull operations in the enumeration session.
In addition, some functionality is only available if the corresponding pull operations are used by this method:
Filtering is not supported for the corresponding traditional operation so that setting the FilterQuery or FilterQueryLanguage parameters will be rejected if the corresponding traditional operation is used by this method.
Note that this limitation is not a disadvantage compared to using the corresponding pull operations directly, because in both cases, the WBEM server must support the pull operations and their filtering capability in order for the filtering to work.
Setting the ContinueOnError parameter to True will be rejected if the corresponding traditional operation is used by this method.
The enumeration session that is opened with the WBEM server when using pull operations is closed automatically when the returned generator object is exhausted, or when the generator object is closed using its
close()
method (which may also be called before the generator is exhausted).Parameters: - ClassName (string or
CIMClassName
) – Name of the class to be enumerated (case independent). If specified as aCIMClassName
object, its namespace attribute will be used as a default namespace as described for the namespace parameter, and its host attribute will be ignored. - namespace (string) –
Name of the CIM namespace to be used (case independent).
Leading and trailing slash characters will be stripped. The lexical case will be preserved.
If None, the namespace of the ClassName parameter will be used, if specified as a
CIMClassName
object. If that is also None, the default namespace of the connection will be used. - LocalOnly (
bool
) –Controls the exclusion of inherited properties from the returned instances, as follows:
- If False, inherited properties are not excluded.
- If True, the behavior depends on the underlying operation: If pull operations are used, inherited properties are not excluded. If traditional operations are used, inherited properties are basically excluded, but the behavior may be WBEM server specific.
- If None, the behavior depends on the underlying operation: If pull operations are used, inherited properties are not excluded. If traditional operations are used, this parameter is not passed to the WBEM server, and causes the server-implemented default to be used. DSP0200 defines that the server-implemented default is True, i.e. to exclude inherited properties.
DSP0200 has deprecated this parameter for the traditional operation and does not support it for the pull operation.
This parameter should be set to False by the caller.
- DeepInheritance (
bool
) –Indicates that properties added by subclasses of the specified class are to be included in the returned instances, as follows:
- If False, properties added by subclasses are not included.
- If True, properties added by subclasses are included.
- If None, this parameter is not passed to the WBEM server, and causes the server-implemented default to be used. DSP0200 defines that the server-implemented default is True.
Note, the semantics of the DeepInheritance parameter in
EnumerateClasses()
andEnumerateClassNames()
is different. - IncludeQualifiers (
bool
) –Indicates that qualifiers are to be included in the returned instances, as follows:
- If False, qualifiers are not included.
- If True, qualifiers are included if this method uses traditional operations and the WBEM server implements support for this parameter.
- If None, this parameter is not passed to the WBEM server, and causes the server-implemented default to be used. DSP0200 defines that the server-implemented default is False.
If this method uses pull operations, this parameter will be ignored, not passed to the WBEM server, and the returned instances will not contain any qualifiers. If this method uses traditional operations, clients cannot rely on returned instances containing qualifiers, as described in DSP0200.
- IncludeClassOrigin (
bool
) –Indicates that class origin information is to be included on each property in the returned instances, as follows:
- If False, class origin information is not included.
- If True, class origin information is included.
- If None, this parameter is not passed to the WBEM server, and causes the server-implemented default to be used. DSP0200 defines that the server-implemented default is False.
This parameter has been deprecated in DSP0200. WBEM servers may either implement this parameter as specified, or may treat any specified value as False.
- PropertyList (string or iterable of string) –
An iterable specifying the names of the properties (or a string that defines a single property) to be included in the returned instances (case independent).
An empty iterable indicates to include no properties.
If None, all properties are included.
- FilterQueryLanguage (string) –
The name of the filter query language used for the FilterQuery parameter. The DMTF-defined Filter Query Language (see DSP0212) is specified as “DMTF:FQL”.
If this parameter is not None and the traditional operation is used by this method,
ValueError
will be raised. - FilterQuery (string) –
The filter query in the query language defined by the FilterQueryLanguage parameter.
If this parameter is not None and the traditional operation is used by this method,
ValueError
will be raised. - OperationTimeout (
Uint32
) –Minimum time in seconds the WBEM Server shall maintain an open enumeration session after a previous Open or pull request is sent to the client. Once this timeout time has expired, the WBEM server may close the enumeration session.
- If not None, this parameter is sent to the WBEM server as the
proposed timeout for the enumeration session. A value of 0
indicates that the server is expected to never time out. The
server may reject the proposed value, causing a
CIMError
to be raised with status codeCIM_ERR_INVALID_OPERATION_TIMEOUT
. - If None, this parameter is not passed to the WBEM server, and causes the server-implemented default timeout to be used.
- If not None, this parameter is sent to the WBEM server as the
proposed timeout for the enumeration session. A value of 0
indicates that the server is expected to never time out. The
server may reject the proposed value, causing a
- ContinueOnError (
bool
) –Indicates to the WBEM server to continue sending responses after an error response has been sent.
- If True, the server is to continue sending responses after
sending an error response. Not all servers support continuation
on error; a server that does not support it must send an error
response if True was specified, causing
CIMError
to be raised with status codeCIM_ERR_CONTINUATION_ON_ERROR_NOT_SUPPORTED
. If the corresponding traditional operation is used by this method,ValueError
will be raised. - If False, the server is requested to close the enumeration after sending an error response.
- If None, this parameter is not passed to the WBEM server, and causes the server-implemented default behaviour to be used. DSP0200 defines that the server-implemented default is False.
- If True, the server is to continue sending responses after
sending an error response. Not all servers support continuation
on error; a server that does not support it must send an error
response if True was specified, causing
- MaxObjectCount (
Uint32
) –Maximum number of instances the WBEM server may return for each of the open and pull requests issued during the iterations over the returned generator object.
- If positive, the WBEM server is to return no more than the specified number of instances.
- Zero is not allowed; it would mean that zero instances are to be returned for open and all pull requests issued to the server.
- The default is defined as a system config variable.
- None is not allowed.
The choice of MaxObjectCount is client/server dependent but choices between 100 and 1000 typically do not have a significant impact on either memory or overall efficiency.
Raises: - Exceptions described in
WBEMConnection
. ValueError
– Invalid parameters provided.
Returns: A generator object that iterates the resulting CIM instances. These instances include an instance path that has its host and namespace components set.
Return type: generator iterating
CIMInstance
Example:
insts_generator = conn.IterEnumerateInstances('CIM_Blah') for inst in insts_generator: # close if a particular property value found if inst.get('thisPropertyName') == 0 insts_generator.close() break else: print('instance {0}'.format(inst.tomof()))
-
IterEnumerateInstancePaths
(ClassName, namespace=None, FilterQueryLanguage=None, FilterQuery=None, OperationTimeout=None, ContinueOnError=None, MaxObjectCount=1000)[source]¶ Enumerate the instance paths of instances of a class (including instances of its subclasses) in a namespace, using the Python generator idiom to return the result.
New in pywbem 0.10 as experimental and finalized in 0.12.
This method uses the corresponding pull operations if supported by the WBEM server or otherwise the corresponding traditional operation.
This method is an alternative to using the pull operations directly, that frees the user of having to know whether the WBEM server supports pull operations.
This method is a generator function that retrieves instance paths from the WBEM server and returns them one by one (using
yield
) when the caller iterates through the returned generator object. The number of instance paths that are retrieved from the WBEM server in one request (and thus need to be materialized in this method) is up to the MaxObjectCount parameter if the corresponding pull operations are used, or the complete result set all at once if the corresponding traditional operation is used.By default, this method attempts to perform the corresponding pull operations (
OpenEnumerateInstancePaths()
andPullInstancePaths()
). If these pull operations are not supported by the WBEM server, this method falls back to using the corresponding traditional operation (EnumerateInstanceNames()
). Whether the WBEM server supports these pull operations is remembered in theWBEMConnection
object (by operation type), and avoids unnecessary attempts to try these pull operations on that connection in the future. The use_pull_operations init parameter ofWBEMConnection
can be used to control the preference for always using pull operations, always using traditional operations, or using pull operations if supported by the WBEM server (the default).This method provides all of the controls of the corresponding pull operations except for the ability to set different response sizes on each request; the response size (defined by the MaxObjectCount parameter) is the same for all pull operations in the enumeration session.
In addition, some functionality is only available if the corresponding pull operations are used by this method:
Filtering is not supported for the corresponding traditional operation so that setting the FilterQuery or FilterQueryLanguage parameters will be rejected if the corresponding traditional operation is used by this method.
Note that this limitation is not a disadvantage compared to using the corresponding pull operations directly, because in both cases, the WBEM server must support the pull operations and their filtering capability in order for the filtering to work.
Setting the ContinueOnError parameter to True will be rejected if the corresponding traditional operation is used by this method.
The enumeration session that is opened with the WBEM server when using pull operations is closed automatically when the returned generator object is exhausted, or when the generator object is closed using its
close()
method (which may also be called before the generator is exhausted).Parameters: - ClassName (string or
CIMClassName
) – Name of the class to be enumerated (case independent). If specified as aCIMClassName
object, its namespace attribute will be used as a default namespace as described for the namespace parameter, and its host attribute will be ignored. - namespace (string) –
Name of the CIM namespace to be used (case independent).
Leading and trailing slash characters will be stripped. The lexical case will be preserved.
If None, the namespace of the ClassName parameter will be used, if specified as a
CIMClassName
object. If that is also None, the default namespace of the connection will be used. - FilterQueryLanguage (string) –
The name of the filter query language used for the FilterQuery parameter. The DMTF-defined Filter Query Language (see DSP0212) is specified as “DMTF:FQL”.
If this parameter is not None and the traditional operation is used by this method,
ValueError
will be raised.Not all WBEM servers support filtering for this operation because it returns instance paths and the act of the server filtering requires that it generate instances just for that purpose and then discard them.
- FilterQuery (string) –
The filter query in the query language defined by the FilterQueryLanguage parameter.
If this parameter is not None and the traditional operation is used by this method,
ValueError
will be raised. - OperationTimeout (
Uint32
) –Minimum time in seconds the WBEM Server shall maintain an open enumeration session after a previous Open or Pull request is sent to the client. Once this timeout time has expired, the WBEM server may close the enumeration session.
- If not None, this parameter is sent to the WBEM server as the
proposed timeout for the enumeration session. A value of 0
indicates that the server is expected to never time out. The
server may reject the proposed value, causing a
CIMError
to be raised with status codeCIM_ERR_INVALID_OPERATION_TIMEOUT
. - If None, this parameter is not passed to the WBEM server, and causes the server-implemented default timeout to be used.
- If not None, this parameter is sent to the WBEM server as the
proposed timeout for the enumeration session. A value of 0
indicates that the server is expected to never time out. The
server may reject the proposed value, causing a
- ContinueOnError (
bool
) –Indicates to the WBEM server to continue sending responses after an error response has been sent.
- If True, the server is to continue sending responses after
sending an error response. Not all servers support continuation
on error; a server that does not support it must send an error
response if True was specified, causing
CIMError
to be raised with status codeCIM_ERR_CONTINUATION_ON_ERROR_NOT_SUPPORTED
. If the corresponding traditional operation is used by this method,ValueError
will be raised. - If False, the server is requested to close the enumeration after sending an error response.
- If None, this parameter is not passed to the WBEM server, and causes the server-implemented default behaviour to be used. DSP0200 defines that the server-implemented default is False.
- If True, the server is to continue sending responses after
sending an error response. Not all servers support continuation
on error; a server that does not support it must send an error
response if True was specified, causing
- MaxObjectCount (
Uint32
) –Maximum number of instances the WBEM server may return for each of the open and pull requests issued during the iterations over the returned generator object.
- If positive, the WBEM server is to return no more than the specified number of instance paths.
- Zero is not allowed; it would mean that zero paths are to be returned for every request issued.
- The default is defined as a system config variable.
- None is not allowed.
The choice of MaxObjectCount is client/server dependent but choices between 100 and 1000 typically do not have a significant impact on either memory or overall efficiency.
Raises: Exceptions described in
WBEMConnection
.Returns: A generator object that iterates the resulting CIM instance paths. These instance paths have their host and namespace components set.
Return type: generator iterating
CIMInstanceName
Example:
paths_generator = conn.IterEnumerateInstancePaths('CIM_Blah') for path in paths_generator: print('path {0}'.format(path))
-
IterAssociatorInstances
(InstanceName, AssocClass=None, ResultClass=None, Role=None, ResultRole=None, IncludeQualifiers=None, IncludeClassOrigin=None, PropertyList=None, FilterQueryLanguage=None, FilterQuery=None, OperationTimeout=None, ContinueOnError=None, MaxObjectCount=1000)[source]¶ Retrieve the instances associated to a source instance, using the Python generator idiom to return the result.
New in pywbem 0.10 as experimental and finalized in 0.12.
This method uses the corresponding pull operations if supported by the WBEM server or otherwise the corresponding traditional operation. This method is an alternative to using the pull operations directly, that frees the user of having to know whether the WBEM server supports pull operations.
This method is a generator function that retrieves instances from the WBEM server and returns them one by one (using
yield
) when the caller iterates through the returned generator object. The number of instances that are retrieved from the WBEM server in one request (and thus need to be materialized in this method) is up to the MaxObjectCount parameter if the corresponding pull operations are used, or the complete result set all at once if the corresponding traditional operation is used.By default, this method attempts to perform the corresponding pull operations (
OpenAssociatorInstances()
andPullInstancesWithPath()
). If these pull operations are not supported by the WBEM server, this method falls back to using the corresponding traditional operation (Associators()
). Whether the WBEM server supports these pull operations is remembered in theWBEMConnection
object (by operation type), and avoids unnecessary attempts to try these pull operations on that connection in the future. The use_pull_operations init parameter ofWBEMConnection
can be used to control the preference for always using pull operations, always using traditional operations, or using pull operations if supported by the WBEM server (the default).This method provides all of the controls of the corresponding pull operations except for the ability to set different response sizes on each request; the response size (defined by the MaxObjectCount parameter) is the same for all pull operations in the enumeration session.
In addition, some functionality is only available if the corresponding pull operations are used by this method:
Filtering is not supported for the corresponding traditional operation so that setting the FilterQuery or FilterQueryLanguage parameters will be rejected if the corresponding traditional operation is used by this method.
Note that this limitation is not a disadvantage compared to using the corresponding pull operations directly, because in both cases, the WBEM server must support the pull operations and their filtering capability in order for the filtering to work.
Setting the ContinueOnError parameter to True will be rejected if the corresponding traditional operation is used by this method.
The enumeration session that is opened with the WBEM server when using pull operations is closed automatically when the returned generator object is exhausted, or when the generator object is closed using its
close()
method (which may also be called before the generator is exhausted).Parameters: - InstanceName (
CIMInstanceName
) – The instance path of the source instance. If this object does not specify a namespace, the default namespace of the connection is used. Its host attribute will be ignored. - AssocClass (string or
CIMClassName
) –Class name of an association class (case independent), to filter the result to include only traversals of that association class (or subclasses). If specified as a
CIMClassName
object, its host and namespace attributes will be ignored.None means that no such filtering is peformed.
- ResultClass (string or
CIMClassName
) –Class name of an associated class (case independent), to filter the result to include only traversals to that associated class (or subclasses). If specified as a
CIMClassName
object, its host and namespace attributes will be ignored.None means that no such filtering is peformed.
- Role (string) –
Role name (= property name) of the source end (case independent), to filter the result to include only traversals from that source role.
None means that no such filtering is peformed.
- ResultRole (string) –
Role name (= property name) of the far end (case independent), to filter the result to include only traversals to that far role.
None means that no such filtering is peformed.
- IncludeQualifiers (
bool
) –Indicates that qualifiers are to be included in the returned instances, as follows:
- If False, qualifiers are not included.
- If True, qualifiers are included if this method uses traditional operations and the WBEM server implements support for this parameter.
- If None, this parameter is not passed to the WBEM server, and causes the server-implemented default to be used. DSP0200 defines that the server-implemented default is False.
If this method uses pull operations, this parameter will be ignored and the returned instances will not contain any qualifiers. If this method uses traditional operations, clients cannot rely on returned instances containing qualifiers, as described in DSP0200.
- IncludeClassOrigin (
bool
) –Indicates that class origin information is to be included on each property or method in the returned instances, as follows:
- If False, class origin information is not included.
- If True, class origin information is included.
- If None, this parameter is not passed to the WBEM server, and causes the server-implemented default to be used. DSP0200 defines that the server-implemented default is False.
This parameter has been deprecated in DSP0200. WBEM servers may either implement this parameter as specified, or may treat any specified value as False.
- PropertyList (string or iterable of string) –
An iterable specifying the names of the properties (or a string that defines a single property) to be included in the returned instances (case independent).
An empty iterable indicates to include no properties.
If None, all properties are included.
- FilterQueryLanguage (string) –
The name of the filter query language used for the FilterQuery parameter. The DMTF-defined Filter Query Language (see DSP0212) is specified as “DMTF:FQL”.
If this parameter is not None and the traditional operation is used by this method,
ValueError
will be raised. - FilterQuery (string) –
The filter query in the query language defined by the FilterQueryLanguage parameter.
If this parameter is not None and the traditional operation is used by this method,
ValueError
will be raised. - OperationTimeout (
Uint32
) –Minimum time in seconds the WBEM Server shall maintain an open enumeration session after a previous Open or Pull request is sent to the client. Once this timeout time has expired, the WBEM server may close the enumeration session.
- If not None, this parameter is sent to the WBEM server as the
proposed timeout for the enumeration session. A value of 0
indicates that the server is expected to never time out. The
server may reject the proposed value, causing a
CIMError
to be raised with status codeCIM_ERR_INVALID_OPERATION_TIMEOUT
. - If None, this parameter is not passed to the WBEM server, and causes the server-implemented default timeout to be used.
Many WBEM servers do not support this request attribute so that setting it to True is NOT recommended except in special cases.
If this parameter is True and the traditional operation is used by this method,
ValueError
will be raised. - If not None, this parameter is sent to the WBEM server as the
proposed timeout for the enumeration session. A value of 0
indicates that the server is expected to never time out. The
server may reject the proposed value, causing a
- ContinueOnError (
bool
) –Indicates to the WBEM server to continue sending responses after an error response has been sent.
- If True, the server is to continue sending responses after
sending an error response. Not all servers support continuation
on error; a server that does not support it must send an error
response if True was specified, causing
CIMError
to be raised with status codeCIM_ERR_CONTINUATION_ON_ERROR_NOT_SUPPORTED
. If the corresponding traditional operation is used by this method,ValueError
will be raised. - If False, the server is requested to close the enumeration after sending an error response.
- If None, this parameter is not passed to the WBEM server, and causes the server-implemented default behaviour to be used. DSP0200 defines that the server-implemented default is False.
- If True, the server is to continue sending responses after
sending an error response. Not all servers support continuation
on error; a server that does not support it must send an error
response if True was specified, causing
- MaxObjectCount (
Uint32
) –Maximum number of instances the WBEM server may return for each of the open and pull requests issued during the iterations over the returned generator object.
- If positive, the WBEM server is to return no more than the specified number of instances.
- Zero is not allowed; it would mean that zero instances are to be returned for open and all pull requests issued to the server.
- The default is defined as a system config variable.
- None is not allowed.
Returns: A generator object that iterates the resulting CIM instances. These instances include an instance path that has its host and namespace components set.
Return type: generator iterating
CIMInstance
Raises: Exceptions described in
WBEMConnection
.Example:
insts_generator = conn.IterAssociatorInstances('CIM_Blah.key=1',...) for inst in insts_generator: # close if a particular property value found if inst.get('thisPropertyName') == 0 insts_generator.close() break else: print('instance {0}'.format(inst.tomof()))
-
IterAssociatorInstancePaths
(InstanceName, AssocClass=None, ResultClass=None, Role=None, ResultRole=None, FilterQueryLanguage=None, FilterQuery=None, OperationTimeout=None, ContinueOnError=None, MaxObjectCount=1000)[source]¶ Retrieve the instance paths of the instances associated to a source instance, using the Python generator idiom to return the result.
New in pywbem 0.10 as experimental and finalized in 0.12.
This method uses the corresponding pull operations if supported by the WBEM server or otherwise the corresponding traditional operation. This method is an alternative to using the pull operations directly, that frees the user of having to know whether the WBEM server supports pull operations.
This method is a generator function that retrieves instance paths from the WBEM server and returns them one by one (using
yield
) when the caller iterates through the returned generator object. The number of instance paths that are retrieved from the WBEM server in one request (and thus need to be materialized in this method) is up to the MaxObjectCount parameter if the corresponding pull operations are used, or the complete result set all at once if the corresponding traditional operation is used.By default, this method attempts to perform the corresponding pull operations (
OpenAssociatorInstancePaths()
andPullInstancePaths()
). If these pull operations are not supported by the WBEM server, this method falls back to using the corresponding traditional operation (AssociatorNames()
). Whether the WBEM server supports these pull operations is remembered in theWBEMConnection
object (by operation type), and avoids unnecessary attempts to try these pull operations on that connection in the future. The use_pull_operations init parameter ofWBEMConnection
can be used to control the preference for always using pull operations, always using traditional operations, or using pull operations if supported by the WBEM server (the default).This method provides all of the controls of the corresponding pull operations except for the ability to set different response sizes on each request; the response size (defined by the MaxObjectCount parameter) is the same for all pull operations in the enumeration session.
In addition, some functionality is only available if the corresponding pull operations are used by this method:
Filtering is not supported for the corresponding traditional operation so that setting the FilterQuery or FilterQueryLanguage parameters will be rejected if the corresponding traditional operation is used by this method.
Note that this limitation is not a disadvantage compared to using the corresponding pull operations directly, because in both cases, the WBEM server must support the pull operations and their filtering capability in order for the filtering to work.
Setting the ContinueOnError parameter to True will be rejected if the corresponding traditional operation is used by this method.
The enumeration session that is opened with the WBEM server when using pull operations is closed automatically when the returned generator object is exhausted, or when the generator object is closed using its
close()
method (which may also be called before the generator is exhausted).Parameters: - InstanceName (
CIMInstanceName
) – The instance path of the source instance. If this object does not specify a namespace, the default namespace of the connection is used. Its host attribute will be ignored. - AssocClass (string or
CIMClassName
) –Class name of an association class (case independent), to filter the result to include only traversals of that association class (or subclasses). If specified as a
CIMClassName
object, its host and namespace attributes will be ignored.None means that no such filtering is peformed.
- ResultClass (string or
CIMClassName
) –Class name of an associated class (case independent), to filter the result to include only traversals to that associated class (or subclasses). If specified as a
CIMClassName
object, its host and namespace attributes will be ignored.None means that no such filtering is peformed.
- Role (string) –
Role name (= property name) of the source end (case independent), to filter the result to include only traversals from that source role.
None means that no such filtering is peformed.
- ResultRole (string) –
Role name (= property name) of the far end (case independent), to filter the result to include only traversals to that far role.
None means that no such filtering is peformed.
- FilterQueryLanguage (string) –
The name of the filter query language used for the FilterQuery parameter. The DMTF-defined Filter Query Language (see DSP0212) is specified as “DMTF:FQL”.
If this parameter is not None and the traditional operation is used by this method,
ValueError
will be raised.Not all WBEM servers support filtering for this operation because it returns instance paths and the act of the server filtering requires that it generate instances just for that purpose and then discard them.
- FilterQuery (string) –
The filter query in the query language defined by the FilterQueryLanguage parameter.
If this parameter is not None and the traditional operation is used by this method,
ValueError
will be raised. - OperationTimeout (
Uint32
) –Minimum time in seconds the WBEM Server shall maintain an open enumeration session after a previous Open or Pull request is sent to the client. Once this timeout time has expired, the WBEM server may close the enumeration session.
- If not None, this parameter is sent to the WBEM server as the
proposed timeout for the enumeration session. A value of 0
indicates that the server is expected to never time out. The
server may reject the proposed value, causing a
CIMError
to be raised with status codeCIM_ERR_INVALID_OPERATION_TIMEOUT
. - If None, this parameter is not passed to the WBEM server, and causes the server-implemented default timeout to be used.
- If not None, this parameter is sent to the WBEM server as the
proposed timeout for the enumeration session. A value of 0
indicates that the server is expected to never time out. The
server may reject the proposed value, causing a
- ContinueOnError (
bool
) –Indicates to the WBEM server to continue sending responses after an error response has been sent.
- If True, the server is to continue sending responses after
sending an error response. Not all servers support continuation
on error; a server that does not support it must send an error
response if True was specified, causing
CIMError
to be raised with status codeCIM_ERR_CONTINUATION_ON_ERROR_NOT_SUPPORTED
. If the corresponding traditional operation is used by this method,ValueError
will be raised. - If False, the server is requested to close the enumeration after sending an error response.
- If None, this parameter is not passed to the WBEM server, and causes the server-implemented default behaviour to be used. DSP0200 defines that the server-implemented default is False.
- If True, the server is to continue sending responses after
sending an error response. Not all servers support continuation
on error; a server that does not support it must send an error
response if True was specified, causing
- MaxObjectCount (
Uint32
) –Maximum number of instances the WBEM server may return for each of the open and pull requests issued during the iterations over the returned generator object.
- If positive, the WBEM server is to return no more than the specified number of instances.
- Zero is not allowed; it would mean that zero instances are to be returned for open and all pull requests issued to the server.
- The default is defined as a system config variable.
- None is not allowed.
Returns: A generator object that iterates the resulting CIM instance paths. These instance paths have their host and namespace components set.
Return type: generator iterating
CIMInstanceName
Raises: Exceptions described in
WBEMConnection
.Example:
paths_generator = conn.IterAssociatorInstancePaths('CIM_Blah') for path in paths_generator: print('path {0}'.format(path))
-
IterReferenceInstances
(InstanceName, ResultClass=None, Role=None, IncludeQualifiers=None, IncludeClassOrigin=None, PropertyList=None, FilterQueryLanguage=None, FilterQuery=None, OperationTimeout=None, ContinueOnError=None, MaxObjectCount=1000)[source]¶ Retrieve the association instances that reference a source instance, using the Python generator idiom to return the result.
New in pywbem 0.10 as experimental and finalized in 0.12.
This method uses the corresponding pull operations if supported by the WBEM server or otherwise the corresponding traditional operation. This method is an alternative to using the pull operations directly, that frees the user of having to know whether the WBEM server supports pull operations.
This method is a generator function that retrieves instances from the WBEM server and returns them one by one (using
yield
) when the caller iterates through the returned generator object. The number of instances that are retrieved from the WBEM server in one request (and thus need to be materialized in this method) is up to the MaxObjectCount parameter if the corresponding pull operations are used, or the complete result set all at once if the corresponding traditional operation is used.By default, this method attempts to perform the corresponding pull operations (
OpenReferenceInstances()
andPullInstancesWithPath()
). If these pull operations are not supported by the WBEM server, this method falls back to using the corresponding traditional operation (References()
). Whether the WBEM server supports these pull operations is remembered in theWBEMConnection
object (by operation type), and avoids unnecessary attempts to try these pull operations on that connection in the future. The use_pull_operations init parameter ofWBEMConnection
can be used to control the preference for always using pull operations, always using traditional operations, or using pull operations if supported by the WBEM server (the default).This method provides all of the controls of the corresponding pull operations except for the ability to set different response sizes on each request; the response size (defined by the MaxObjectCount parameter) is the same for all pull operations in the enumeration session.
In addition, some functionality is only available if the corresponding pull operations are used by this method:
Filtering is not supported for the corresponding traditional operation so that setting the FilterQuery or FilterQueryLanguage parameters will be rejected if the corresponding traditional operation is used by this method.
Note that this limitation is not a disadvantage compared to using the corresponding pull operations directly, because in both cases, the WBEM server must support the pull operations and their filtering capability in order for the filtering to work.
Setting the ContinueOnError parameter to True will be rejected if the corresponding traditional operation is used by this method.
The enumeration session that is opened with the WBEM server when using pull operations is closed automatically when the returned generator object is exhausted, or when the generator object is closed using its
close()
method (which may also be called before the generator is exhausted).Parameters: - InstanceName (
CIMInstanceName
) – The instance path of the source instance. If this object does not specify a namespace, the default namespace of the connection is used. Its host attribute will be ignored. - ResultClass (string or
CIMClassName
) –Class name of an association class (case independent), to filter the result to include only traversals of that association class (or subclasses). If specified as a
CIMClassName
object, its host and namespace attributes will be ignored.None means that no such filtering is peformed.
- Role (string) –
Role name (= property name) of the source end (case independent), to filter the result to include only traversals from that source role.
None means that no such filtering is peformed.
- IncludeQualifiers (
bool
) –Indicates that qualifiers are to be included in the returned instances, as follows:
- If False, qualifiers are not included.
- If True, qualifiers are included if this method uses traditional operations and the WBEM server implements support for this parameter.
- If None, this parameter is not passed to the WBEM server, and causes the server-implemented default to be used. DSP0200 defines that the server-implemented default is False.
If this method uses pull operations, this parameter will be ignored and the returned instances will not contain any qualifiers. If this method uses traditional operations, clients cannot rely on returned instances containing qualifiers, as described in DSP0200.
- IncludeClassOrigin (
bool
) –Indicates that class origin information is to be included on each property or method in the returned instances, as follows:
- If False, class origin information is not included.
- If True, class origin information is included.
- If None, this parameter is not passed to the WBEM server, and causes the server-implemented default to be used. DSP0200 defines that the server-implemented default is False.
This parameter has been deprecated in DSP0200. WBEM servers may either implement this parameter as specified, or may treat any specified value as False.
- PropertyList (string or iterable of string) –
An iterable specifying the names of the properties (or a string that defines a single property) to be included in the returned instances (case independent).
An empty iterable indicates to include no properties.
If None, all properties are included.
- FilterQueryLanguage (string) –
The name of the filter query language used for the FilterQuery parameter. The DMTF-defined Filter Query Language (see DSP0212) is specified as “DMTF:FQL”.
If this parameter is not None and the traditional operation is used by this method,
ValueError
will be raised. - FilterQuery (string) –
The filter query in the query language defined by the FilterQueryLanguage parameter.
If this parameter is not None and the traditional operation is used by this method,
ValueError
will be raised. - OperationTimeout (
Uint32
) –Minimum time in seconds the WBEM Server shall maintain an open enumeration session after a previous Open or Pull request is sent to the client. Once this timeout time has expired, the WBEM server may close the enumeration session.
- If not None, this parameter is sent to the WBEM server as the
proposed timeout for the enumeration session. A value of 0
indicates that the server is expected to never time out. The
server may reject the proposed value, causing a
CIMError
to be raised with status codeCIM_ERR_INVALID_OPERATION_TIMEOUT
. - If None, this parameter is not passed to the WBEM server, and causes the server-implemented default timeout to be used.
- If not None, this parameter is sent to the WBEM server as the
proposed timeout for the enumeration session. A value of 0
indicates that the server is expected to never time out. The
server may reject the proposed value, causing a
- ContinueOnError (
bool
) –Indicates to the WBEM server to continue sending responses after an error response has been sent.
- If True, the server is to continue sending responses after
sending an error response. Not all servers support continuation
on error; a server that does not support it must send an error
response if True was specified, causing
CIMError
to be raised with status codeCIM_ERR_CONTINUATION_ON_ERROR_NOT_SUPPORTED
. If the corresponding traditional operation is used by this method,ValueError
will be raised. - If False, the server is requested to close the enumeration after sending an error response.
- If None, this parameter is not passed to the WBEM server, and causes the server-implemented default behaviour to be used. DSP0200 defines that the server-implemented default is False.
- If True, the server is to continue sending responses after
sending an error response. Not all servers support continuation
on error; a server that does not support it must send an error
response if True was specified, causing
- MaxObjectCount (
Uint32
) –Maximum number of instances the WBEM server may return for each of the open and pull requests issued during the iterations over the returned generator object.
- If positive, the WBEM server is to return no more than the specified number of instances.
- Zero is not allowed; it would mean that zero instances are to be returned for open and all pull requests issued to the server.
- The default is defined as a system config variable.
- None is not allowed.
Returns: A generator object that iterates the resulting CIM instances. These instances include an instance path that has its host and namespace components set.
Return type: generator iterating
CIMInstance
Raises: Exceptions described in
WBEMConnection
.Example:
insts_generator = conn.IterReferenceInstances('CIM_Blah.key=1', ...) for inst in insts_generator: # close if a particular property value found if inst.get('thisPropertyName') == 0 insts_generator.close() break else: print('instance {0}'.format(inst.tomof()))
-
IterReferenceInstancePaths
(InstanceName, ResultClass=None, Role=None, FilterQueryLanguage=None, FilterQuery=None, OperationTimeout=None, ContinueOnError=None, MaxObjectCount=1000)[source]¶ Retrieve the instance paths of the association instances that reference a source instance, using the Python generator idiom to return the result.
New in pywbem 0.10 as experimental and finalized in 0.12.
This method uses the corresponding pull operations if supported by the WBEM server or otherwise the corresponding traditional operation. This method is an alternative to using the pull operations directly, that frees the user of having to know whether the WBEM server supports pull operations.
This method is a generator function that retrieves instance paths from the WBEM server and returns them one by one (using
yield
) when the caller iterates through the returned generator object. The number of instance paths that are retrieved from the WBEM server in one request (and thus need to be materialized in this method) is up to the MaxObjectCount parameter if the corresponding pull operations are used, or the complete result set all at once if the corresponding traditional operation is used.By default, this method attempts to perform the corresponding pull operations (
OpenReferenceInstancePaths()
andPullInstancePaths()
). If these pull operations are not supported by the WBEM server, this method falls back to using the corresponding traditional operation (ReferenceNames()
). Whether the WBEM server supports these pull operations is remembered in theWBEMConnection
object (by operation type), and avoids unnecessary attempts to try these pull operations on that connection in the future. The use_pull_operations init parameter ofWBEMConnection
can be used to control the preference for always using pull operations, always using traditional operations, or using pull operations if supported by the WBEM server (the default).This method provides all of the controls of the corresponding pull operations except for the ability to set different response sizes on each request; the response size (defined by the MaxObjectCount parameter) is the same for all pull operations in the enumeration session.
In addition, some functionality is only available if the corresponding pull operations are used by this method:
Filtering is not supported for the corresponding traditional operation so that setting the FilterQuery or FilterQueryLanguage parameters will be rejected if the corresponding traditional operation is used by this method.
Note that this limitation is not a disadvantage compared to using the corresponding pull operations directly, because in both cases, the WBEM server must support the pull operations and their filtering capability in order for the filtering to work.
Setting the ContinueOnError parameter to True will be rejected if the corresponding traditional operation is used by this method.
The enumeration session that is opened with the WBEM server when using pull operations is closed automatically when the returned generator object is exhausted, or when the generator object is closed using its
close()
method (which may also be called before the generator is exhausted).Parameters: - InstanceName (
CIMInstanceName
) – The instance path of the source instance. If this object does not specify a namespace, the default namespace of the connection is used. Its host attribute will be ignored. - ResultClass (string or
CIMClassName
) –Class name of an association class (case independent), to filter the result to include only traversals of that association class (or subclasses). If specified as a
CIMClassName
object, its host and namespace attributes will be ignored.None means that no such filtering is peformed.
- Role (string) –
Role name (= property name) of the source end (case independent), to filter the result to include only traversals from that source role.
None means that no such filtering is peformed.
- FilterQueryLanguage (string) –
The name of the filter query language used for the FilterQuery parameter. The DMTF-defined Filter Query Language (see DSP0212) is specified as “DMTF:FQL”.
If this parameter is not None and the traditional operation is used by this method,
ValueError
will be raised.Not all WBEM servers support filtering for this operation because it returns instance paths and the act of the server filtering requires that it generate instances just for that purpose and then discard them.
- FilterQuery (string) –
The filter query in the query language defined by the FilterQueryLanguage parameter.
If this parameter is not None and the traditional operation is used by this method,
ValueError
will be raised. - OperationTimeout (
Uint32
) –Minimum time in seconds the WBEM Server shall maintain an open enumeration session after a previous Open or Pull request is sent to the client. Once this timeout time has expired, the WBEM server may close the enumeration session.
- If not None, this parameter is sent to the WBEM server as the
proposed timeout for the enumeration session. A value of 0
indicates that the server is expected to never time out. The
server may reject the proposed value, causing a
CIMError
to be raised with status codeCIM_ERR_INVALID_OPERATION_TIMEOUT
. - If None, this parameter is not passed to the WBEM server, and causes the server-implemented default timeout to be used.
- If not None, this parameter is sent to the WBEM server as the
proposed timeout for the enumeration session. A value of 0
indicates that the server is expected to never time out. The
server may reject the proposed value, causing a
- ContinueOnError (
bool
) –Indicates to the WBEM server to continue sending responses after an error response has been sent.
- If True, the server is to continue sending responses after
sending an error response. Not all servers support continuation
on error; a server that does not support it must send an error
response if True was specified, causing
CIMError
to be raised with status codeCIM_ERR_CONTINUATION_ON_ERROR_NOT_SUPPORTED
. If the corresponding traditional operation is used by this method,ValueError
will be raised. - If False, the server is requested to close the enumeration after sending an error response.
- If None, this parameter is not passed to the WBEM server, and causes the server-implemented default behaviour to be used. DSP0200 defines that the server-implemented default is False.
- If True, the server is to continue sending responses after
sending an error response. Not all servers support continuation
on error; a server that does not support it must send an error
response if True was specified, causing
- MaxObjectCount (
Uint32
) –Maximum number of instances the WBEM server may return for each of the open and pull requests issued during the iterations over the returned generator object.
- If positive, the WBEM server is to return no more than the specified number of instances.
- Zero is not allowed; it would mean that zero instances are to be returned for open and all pull requests issued to the server.
- The default is defined as a system config variable.
- None is not allowed.
Returns: A generator object that iterates the resulting CIM instance paths. These instance paths have their host and namespace components set.
Return type: generator iterating
CIMInstanceName
Raises: Exceptions described in
WBEMConnection
.Example:
paths_generator = conn.IterReferenceInstancePaths('CIM_Blah') for path in paths_generator: print('path {0}'.format(path))
-
IterQueryInstances
(FilterQueryLanguage, FilterQuery, namespace=None, ReturnQueryResultClass=None, OperationTimeout=None, ContinueOnError=None, MaxObjectCount=1000)[source]¶ Execute a query in a namespace, using the Python generator idiom to return the result.
New in pywbem 0.10 as experimental and finalized in 0.12.
This method uses the corresponding pull operations if supported by the WBEM server or otherwise the corresponding traditional operation. This method is an alternative to using the pull operations directly, that frees the user of having to know whether the WBEM server supports pull operations.
Other than the other Iter…() methods, this method does not return a generator object directly, but as a property of the returned object. The reason for this design is the additionally returned query result class. The generator property in the returned object is a generator object that returns the instances in the query result one by one (using
yield
) when the caller iterates through the generator object. This design causes the entire query result to be materialized, even if pull operations are used.By default, this method attempts to perform the corresponding pull operations (
OpenQueryInstances()
andPullInstances()
). If these pull operations are not supported by the WBEM server, this method falls back to using the corresponding traditional operation (ExecQuery()
). Whether the WBEM server supports these pull operations is remembered in theWBEMConnection
object (by operation type), and avoids unnecessary attempts to try these pull operations on that connection in the future. The use_pull_operations init parameter ofWBEMConnection
can be used to control the preference for always using pull operations, always using traditional operations, or using pull operations if supported by the WBEM server (the default).This method provides all of the controls of the corresponding pull operations except for the ability to set different response sizes on each request; the response size (defined by the MaxObjectCount parameter) is the same for all pull operations in the enumeration session.
In addition, some functionality is only available if the corresponding pull operations are used by this method:
- Setting the ContinueOnError parameter to True will be rejected if the corresponding traditional operation is used by this method.
The enumeration session that is opened with the WBEM server when using pull operations is closed automatically when the returned generator object is exhausted, or when the generator object is closed using its
close()
method (which may also be called before the generator is exhausted).Parameters: - QueryLanguage (string) – Name of the query language used in the Query parameter, e.g. “DMTF:CQL” for CIM Query Language, and “WQL” for WBEM Query Language. Because this is not a filter query, “DMTF:FQL” is not a valid query language for this request.
- Query (string) – Query string in the query language specified in the QueryLanguage parameter.
- namespace (string) –
Name of the CIM namespace to be used (case independent).
Leading and trailing slash characters will be stripped. The lexical case will be preserved.
If None, the default namespace of the connection object will be used.
- ReturnQueryResultClass (
bool
) –Controls whether a class definition describing the returned instances will be returned.
None will cause the server to use its default of False.
None will cause the server to use its default of False.
- OperationTimeout (
Uint32
) –Minimum time in seconds the WBEM Server shall maintain an open enumeration session after a previous Open or Pull request is sent to the client. Once this timeout time has expired, the WBEM server may close the enumeration session.
- If not None, this parameter is sent to the WBEM server as the
proposed timeout for the enumeration session. A value of 0
indicates that the server is expected to never time out. The
server may reject the proposed value, causing a
CIMError
to be raised with status codeCIM_ERR_INVALID_OPERATION_TIMEOUT
. - If None, this parameter is not passed to the WBEM server, and causes the server-implemented default timeout to be used.
- If not None, this parameter is sent to the WBEM server as the
proposed timeout for the enumeration session. A value of 0
indicates that the server is expected to never time out. The
server may reject the proposed value, causing a
- ContinueOnError (
bool
) –Indicates to the WBEM server to continue sending responses after an error response has been sent.
- If True, the server is to continue sending responses after
sending an error response. Not all servers support continuation
on error; a server that does not support it must send an error
response if True was specified, causing
CIMError
to be raised with status codeCIM_ERR_CONTINUATION_ON_ERROR_NOT_SUPPORTED
. If the corresponding traditional operation is used by this method,ValueError
will be raised. - If False, the server is requested to close the enumeration after sending an error response.
- If None, this parameter is not passed to the WBEM server, and causes the server-implemented default behaviour to be used. DSP0200 defines that the server-implemented default is False.
- If True, the server is to continue sending responses after
sending an error response. Not all servers support continuation
on error; a server that does not support it must send an error
response if True was specified, causing
- MaxObjectCount (
Uint32
) –Maximum number of instances the WBEM server may return for each of the open and pull requests issued during the iterations over the returned generator object.
- If positive, the WBEM server is to return no more than the specified number of instances.
- Zero is not allowed; it would mean that zero instances are to be returned for open and all pull requests issued to the server.
- The default is defined as a system config variable.
- None is not allowed.
Returns: An object with the following properties:
query_result_class (
CIMClass
):The query result class, if requested via the ReturnQueryResultClass parameter.
None, if a query result class was not requested.
generator (generator iterating
CIMInstance
):A generator object that iterates the CIM instances representing the query result. These instances do not have an instance path set.
Return type: IterQueryInstancesReturn
Raises: Exceptions described in
WBEMConnection
.Example:
result = conn.IterQueryInstances( 'DMTF:CQL', 'SELECT FROM * where pl > 2') for inst in result.generator: print('instance {0}'.format(inst.tomof()))
-
OpenEnumerateInstances
(ClassName, namespace=None, DeepInheritance=None, IncludeClassOrigin=None, PropertyList=None, FilterQueryLanguage=None, FilterQuery=None, OperationTimeout=None, ContinueOnError=None, MaxObjectCount=None)[source]¶ Open an enumeration session to enumerate the instances of a class (including instances of its subclasses) in a namespace.
New in pywbem 0.9.
The incorrectly supported parameters `LocalOnly` and `IncludeQualifiers` were removed in pywbem 1.0.0.
This method performs the OpenEnumerateInstances operation (see DSP0200). See WBEM operations for a list of all methods performing such operations.
If the operation succeeds, this method returns enumeration session status and optionally instances. Otherwise, this method raises an exception.
Use the
PullInstancesWithPath()
method to retrieve the next set of instances or theCloseEnumeration()
method to close the enumeration session before it is exhausted.Parameters: - ClassName (string or
CIMClassName
) – Name of the class to be enumerated (case independent). If specified as aCIMClassName
object, its namespace attribute will be used as a default namespace as described for the namespace parameter, and its host attribute will be ignored. - namespace (string) –
Name of the CIM namespace to be used (case independent).
Leading and trailing slash characters will be stripped. The lexical case will be preserved.
If None, the namespace of the ClassName parameter will be used, if specified as a
CIMClassName
object. If that is also None, the default namespace of the connection will be used. - DeepInheritance (
bool
) –Indicates that properties added by subclasses of the specified class are to be included in the returned instances, as follows:
- If False, properties added by subclasses are not included.
- If True, properties added by subclasses are included.
- If None, this parameter is not passed to the WBEM server, and causes the server-implemented default to be used. DSP0200 defines that the server-implemented default is True.
Note, the semantics of the DeepInheritance parameter in
EnumerateClasses()
andEnumerateClassNames()
is different. - IncludeClassOrigin (
bool
) –Indicates that class origin information is to be included on each property in the returned instances, as follows:
- If False, class origin information is not included.
- If True, class origin information is included.
- If None, this parameter is not passed to the WBEM server, and causes the server-implemented default to be used. DSP0200 defines that the server-implemented default is False.
This parameter has been deprecated in DSP0200. WBEM servers may either implement this parameter as specified, or may treat any specified value as False.
- PropertyList (string or iterable of string) –
An iterable specifying the names of the properties (or a string that defines a single property) to be included in the returned instances (case independent).
An empty iterable indicates to include no properties.
If None, all properties are included.
- FilterQueryLanguage (string) – The name of the filter query language used for the FilterQuery parameter. The DMTF-defined Filter Query Language (see DSP0212) is specified as “DMTF:FQL”.
- FilterQuery (string) – The filter query in the query language defined by the FilterQueryLanguage parameter.
- OperationTimeout (
Uint32
) –Minimum time in seconds the WBEM Server shall maintain an open enumeration session after a previous Open or Pull request is sent to the client. Once this timeout time has expired, the WBEM server may close the enumeration session.
- If not None, this parameter is sent to the WBEM server as the
proposed timeout for the enumeration session. A value of 0
indicates that the server is expected to never time out. The
server may reject the proposed value, causing a
CIMError
to be raised with status codeCIM_ERR_INVALID_OPERATION_TIMEOUT
. - If None, this parameter is not passed to the WBEM server, and causes the server-implemented default timeout to be used.
- If not None, this parameter is sent to the WBEM server as the
proposed timeout for the enumeration session. A value of 0
indicates that the server is expected to never time out. The
server may reject the proposed value, causing a
- ContinueOnError (
bool
) –Indicates to the WBEM server to continue sending responses after an error response has been sent.
- If True, the server is to continue sending responses after
sending an error response. Not all servers support continuation
on error; a server that does not support it must send an error
response if True was specified, causing
CIMError
to be raised with status codeCIM_ERR_CONTINUATION_ON_ERROR_NOT_SUPPORTED
. - If False, the server is requested to close the enumeration after sending an error response.
- If None, this parameter is not passed to the WBEM server, and causes the server-implemented default behaviour to be used. DSP0200 defines that the server-implemented default is False.
- If True, the server is to continue sending responses after
sending an error response. Not all servers support continuation
on error; a server that does not support it must send an error
response if True was specified, causing
- MaxObjectCount (
Uint32
) –Maximum number of instances the WBEM server may return for this request.
- If positive, the WBEM server is to return no more than the specified number of instances.
- If zero, the WBEM server is to return no instances. This may be used by a client to leave the handling of any returned instances to a loop of Pull operations.
- If None, this parameter is not passed to the WBEM server, and causes the server-implemented default behaviour to be used. DSP0200 defines that the server-implemented default is to return zero instances.
Returns: A
namedtuple()
object containing the following named items:instances (
list
ofCIMInstance
): Representations of the retrieved instances.The path attribute of each
CIMInstance
object is aCIMInstanceName
object with its attributes set as follows:- classname: Name of the creation class of the instance.
- keybindings: Keybindings of the instance.
- namespace: Name of the CIM namespace containing the instance.
- host: Host and optionally port of the WBEM server containing the CIM namespace.
eos (
bool
): Indicates whether the enumeration session is exhausted after this operation:- If True, the enumeration session is exhausted, and the server has closed the enumeration session.
- If False, the enumeration session is not exhausted and the context item is the context object for the next operation on the enumeration session.
context (
tuple()
of server_context, namespace): A context object identifying the open enumeration session, including its current enumeration state, and the namespace. This object must be supplied with the next pull or close operation for this enumeration session.The tuple items are:
- server_context (string): Enumeration context string returned by the server if the session is not exhausted, or None otherwise. This string is opaque for the client.
- namespace (string): Name of the CIM namespace that was used for this operation.
NOTE: This inner tuple hides the need for a CIM namespace on subsequent operations in the enumeration session. CIM operations always require target namespace, but it never makes sense to specify a different one in subsequent operations on the same enumeration session.
Raises: Exceptions described in
WBEMConnection
.Example:
max_object_count = 100 rslt_tuple = conn.OpenEnumerateInstances( 'CIM_Blah', MaxObjectCount=max_object_count) insts = rslt_tuple.paths while not rslt_tuple.eos: rslt_tuple = conn.PullInstancesWithPath(rslt_tupl.context, max_object_count) insts.extend(rslt_tupl.paths) for inst in insts: print('instance {0}'.format(inst.tomof()))
- ClassName (string or
-
OpenEnumerateInstancePaths
(ClassName, namespace=None, FilterQueryLanguage=None, FilterQuery=None, OperationTimeout=None, ContinueOnError=None, MaxObjectCount=None)[source]¶ Open an enumeration session to enumerate the instance paths of instances of a class (including instances of its subclasses) in a namespace.
New in pywbem 0.9.
This method performs the OpenEnumerateInstancePaths operation (see DSP0200). See WBEM operations for a list of all methods performing such operations.
If the operation succeeds, this method returns status on the enumeration session and optionally instance paths. Otherwise, this method raises an exception.
Use the
PullInstancePaths()
method to retrieve the next set of instance paths or theCloseEnumeration()
method to close the enumeration session before it is exhausted.Parameters: - ClassName (string or
CIMClassName
) – Name of the class to be enumerated (case independent). If specified as aCIMClassName
object, its namespace attribute will be used as a default namespace as described for the namespace parameter, and its host attribute will be ignored. - namespace (string) –
Name of the CIM namespace to be used (case independent).
Leading and trailing slash characters will be stripped. The lexical case will be preserved.
If None, the namespace of the ClassName parameter will be used, if specified as a
CIMClassName
object. If that is also None, the default namespace of the connection will be used. - FilterQueryLanguage (string) –
The name of the filter query language used for the FilterQuery parameter. The DMTF-defined Filter Query Language (see DSP0212) is specified as “DMTF:FQL”.
Not all WBEM servers support filtering for this operation because it returns instance paths and the act of the server filtering requires that it generate instances just for that purpose and then discard them.
- FilterQuery (string) – The filter query in the query language defined by the FilterQueryLanguage parameter.
- OperationTimeout (
Uint32
) –Minimum time in seconds the WBEM Server shall maintain an open enumeration session after a previous Open or Pull request is sent to the client. Once this timeout time has expired, the WBEM server may close the enumeration session.
- If not None, this parameter is sent to the WBEM server as the
proposed timeout for the enumeration session. A value of 0
indicates that the server is expected to never time out. The
server may reject the proposed value, causing a
CIMError
to be raised with status codeCIM_ERR_INVALID_OPERATION_TIMEOUT
. - If None, this parameter is not passed to the WBEM server, and causes the server-implemented default timeout to be used.
- If not None, this parameter is sent to the WBEM server as the
proposed timeout for the enumeration session. A value of 0
indicates that the server is expected to never time out. The
server may reject the proposed value, causing a
- ContinueOnError (
bool
) –Indicates to the WBEM server to continue sending responses after an error response has been sent.
- If True, the server is to continue sending responses after
sending an error response. Not all servers support continuation
on error; a server that does not support it must send an error
response if True was specified, causing
CIMError
to be raised with status codeCIM_ERR_CONTINUATION_ON_ERROR_NOT_SUPPORTED
. - If False, the server is requested to close the enumeration after sending an error response.
- If None, this parameter is not passed to the WBEM server, and causes the server-implemented default behaviour to be used. DSP0200 defines that the server-implemented default is False.
- If True, the server is to continue sending responses after
sending an error response. Not all servers support continuation
on error; a server that does not support it must send an error
response if True was specified, causing
- MaxObjectCount (
Uint32
) –Maximum number of instances the WBEM server may return for this request.
- If positive, the WBEM server is to return no more than the specified number of instances.
- If zero, the WBEM server is to return no instances. This may be used by a client to leave the handling of any returned instances to a loop of Pull operations.
- If None, this parameter is not passed to the WBEM server, and causes the server-implemented default behaviour to be used. DSP0200 defines that the server-implemented default is to return zero instances.
Returns: A
namedtuple()
object containing the following named items:paths (
list
ofCIMInstanceName
): Representations of the retrieved instance paths, with their attributes set as follows:- classname: Name of the creation class of the instance.
- keybindings: Keybindings of the instance.
- namespace: Name of the CIM namespace containing the instance.
- host: Host and optionally port of the WBEM server containing the CIM namespace.
eos (
bool
): Indicates whether the enumeration session is exhausted after this operation:- If True, the enumeration session is exhausted, and the server has closed the enumeration session.
- If False, the enumeration session is not exhausted and the context item is the context object for the next operation on the enumeration session.
context (
tuple()
of server_context, namespace): A context object identifying the open enumeration session, including its current enumeration state, and the namespace. This object must be supplied with the next pull or close operation for this enumeration session.The tuple items are:
- server_context (string): Enumeration context string returned by the server if the session is not exhausted, or None otherwise. This string is opaque for the client.
- namespace (string): Name of the CIM namespace that was used for this operation.
NOTE: This inner tuple hides the need for a CIM namespace on subsequent operations in the enumeration session. CIM operations always require target namespace, but it never makes sense to specify a different one in subsequent operations on the same enumeration session.
Raises: Exceptions described in
WBEMConnection
.Example:
max_object_count = 100 rslt_tuple = conn.OpenEnumerateInstancePaths( 'CIM_Blah', MaxObjectCount=max_object_count) paths = rslt_tuple.paths while not rslt_tuple.eos: rslt_tuple = conn.PullInstancePaths(rslt_tupl.context, max_object_count) paths.extend(rslt_tupl.paths) for path in paths: print('path {0}'.format(path))
- ClassName (string or
-
OpenAssociatorInstances
(InstanceName, AssocClass=None, ResultClass=None, Role=None, ResultRole=None, IncludeClassOrigin=None, PropertyList=None, FilterQueryLanguage=None, FilterQuery=None, OperationTimeout=None, ContinueOnError=None, MaxObjectCount=None)[source]¶ Open an enumeration session to retrieve the instances associated to a source instance.
New in pywbem 0.9.
The incorrectly supported parameter `IncludeQualifiers` was removed in pywbem 1.0.0.
This method does not support retrieving classes.
This method performs the OpenAssociatorInstances operation (see DSP0200). See WBEM operations for a list of all methods performing such operations.
If the operation succeeds, this method returns enumeration session status and optionally instances. Otherwise, this method raises an exception.
Use the
PullInstancesWithPath()
method to retrieve the next set of instances or theCloseEnumeration()
method to close the enumeration session before it is exhausted.Parameters: - InstanceName (
CIMInstanceName
) – The instance path of the source instance. If this object does not specify a namespace, the default namespace of the connection is used. Its host attribute will be ignored. - AssocClass (string or
CIMClassName
) –Class name of an association class (case independent), to filter the result to include only traversals of that association class (or subclasses). If specified as a
CIMClassName
object, its host and namespace attributes will be ignored.None means that no such filtering is peformed.
- ResultClass (string or
CIMClassName
) –Class name of an associated class (case independent), to filter the result to include only traversals to that associated class (or subclasses). If specified as a
CIMClassName
object, its host and namespace attributes will be ignored.None means that no such filtering is peformed.
- Role (string) –
Role name (= property name) of the source end (case independent), to filter the result to include only traversals from that source role.
None means that no such filtering is peformed.
- ResultRole (string) –
Role name (= property name) of the far end (case independent), to filter the result to include only traversals to that far role.
None means that no such filtering is peformed.
- IncludeClassOrigin (
bool
) –Indicates that class origin information is to be included on each property or method in the returned instances, as follows:
- If False, class origin information is not included.
- If True, class origin information is included.
- If None, this parameter is not passed to the WBEM server, and causes the server-implemented default to be used. DSP0200 defines that the server-implemented default is False.
This parameter has been deprecated in DSP0200. WBEM servers may either implement this parameter as specified, or may treat any specified value as False.
- PropertyList (string or iterable of string) –
An iterable specifying the names of the properties (or a string that defines a single property) to be included in the returned instances (case independent).
An empty iterable indicates to include no properties.
If None, all properties are included.
- FilterQueryLanguage (string) – The name of the filter query language used for the FilterQuery parameter. The DMTF-defined Filter Query Language (see DSP0212) is specified as “DMTF:FQL”.
- FilterQuery (string) – The filter query in the query language defined by the FilterQueryLanguage parameter.
- OperationTimeout (
Uint32
) –Minimum time in seconds the WBEM Server shall maintain an open enumeration session after a previous Open or Pull request is sent to the client. Once this timeout time has expired, the WBEM server may close the enumeration session.
- If not None, this parameter is sent to the WBEM server as the
proposed timeout for the enumeration session. A value of 0
indicates that the server is expected to never time out. The
server may reject the proposed value, causing a
CIMError
to be raised with status codeCIM_ERR_INVALID_OPERATION_TIMEOUT
. - If None, this parameter is not passed to the WBEM server, and causes the server-implemented default timeout to be used.
- If not None, this parameter is sent to the WBEM server as the
proposed timeout for the enumeration session. A value of 0
indicates that the server is expected to never time out. The
server may reject the proposed value, causing a
- ContinueOnError (
bool
) –Indicates to the WBEM server to continue sending responses after an error response has been sent.
- If True, the server is to continue sending responses after
sending an error response. Not all servers support continuation
on error; a server that does not support it must send an error
response if True was specified, causing
CIMError
to be raised with status codeCIM_ERR_CONTINUATION_ON_ERROR_NOT_SUPPORTED
. - If False, the server is requested to close the enumeration after sending an error response.
- If None, this parameter is not passed to the WBEM server, and causes the server-implemented default behaviour to be used. DSP0200 defines that the server-implemented default is False.
- If True, the server is to continue sending responses after
sending an error response. Not all servers support continuation
on error; a server that does not support it must send an error
response if True was specified, causing
- MaxObjectCount (
Uint32
) –Maximum number of instances the WBEM server may return for this request.
- If positive, the WBEM server is to return no more than the specified number of instances.
- If zero, the WBEM server is to return no instances. This may be used by a client to leave the handling of any returned instances to a loop of Pull operations.
- If None, this parameter is not passed to the WBEM server, and causes the server-implemented default behaviour to be used. DSP0200 defines that the server-implemented default is to return zero instances.
Returns: A
namedtuple()
object containing the following named items:instances (
list
ofCIMInstance
): Representations of the retrieved instances.The path attribute of each
CIMInstance
object is aCIMInstanceName
object with its attributes set as follows:- classname: Name of the creation class of the instance.
- keybindings: Keybindings of the instance.
- namespace: Name of the CIM namespace containing the instance.
- host: Host and optionally port of the WBEM server containing the CIM namespace.
eos (
bool
): Indicates whether the enumeration session is exhausted after this operation:- If True, the enumeration session is exhausted, and the server has closed the enumeration session.
- If False, the enumeration session is not exhausted and the context item is the context object for the next operation on the enumeration session.
context (
tuple()
of server_context, namespace): A context object identifying the open enumeration session, including its current enumeration state, and the namespace. This object must be supplied with the next pull or close operation for this enumeration session.The tuple items are:
- server_context (string): Enumeration context string returned by the server if the session is not exhausted, or None otherwise. This string is opaque for the client.
- namespace (string): Name of the CIM namespace that was used for this operation.
NOTE: This inner tuple hides the need for a CIM namespace on subsequent operations in the enumeration session. CIM operations always require target namespace, but it never makes sense to specify a different one in subsequent operations on the same enumeration session.
Raises: Exceptions described in
WBEMConnection
.- InstanceName (
-
OpenAssociatorInstancePaths
(InstanceName, AssocClass=None, ResultClass=None, Role=None, ResultRole=None, FilterQueryLanguage=None, FilterQuery=None, OperationTimeout=None, ContinueOnError=None, MaxObjectCount=None)[source]¶ Open an enumeration session to retrieve the instance paths of the instances associated to a source instance.
New in pywbem 0.9.
This method does not support retrieving classes.
This method performs the OpenAssociatorInstancePaths operation (see DSP0200). See WBEM operations for a list of all methods performing such operations.
If the operation succeeds, this method returns enumeration session status and optionally instance paths. Otherwise, this method raises an exception.
Use the
PullInstancePaths()
method to retrieve the next set of instance paths or theCloseEnumeration()
method to close the enumeration session before it is exhausted.Parameters: - InstanceName (
CIMInstanceName
) – The instance path of the source instance. If this object does not specify a namespace, the default namespace of the connection is used. Its host attribute will be ignored. - AssocClass (string or
CIMClassName
) –Class name of an association class (case independent), to filter the result to include only traversals of that association class (or subclasses). If specified as a
CIMClassName
object, its host and namespace attributes will be ignored.None means that no such filtering is peformed.
- ResultClass (string or
CIMClassName
) –Class name of an associated class (case independent), to filter the result to include only traversals to that associated class (or subclasses). If specified as a
CIMClassName
object, its host and namespace attributes will be ignored.None means that no such filtering is peformed.
- Role (string) –
Role name (= property name) of the source end (case independent), to filter the result to include only traversals from that source role.
None means that no such filtering is peformed.
- ResultRole (string) –
Role name (= property name) of the far end (case independent), to filter the result to include only traversals to that far role.
None means that no such filtering is peformed.
- FilterQueryLanguage (string) –
The name of the filter query language used for the FilterQuery parameter. The DMTF-defined Filter Query Language (see DSP0212) is specified as “DMTF:FQL”.
Not all WBEM servers support filtering for this operation because it returns instance paths and the act of the server filtering requires that it generate instances just for that purpose and then discard them.
- FilterQuery (string) – The filter query in the query language defined by the FilterQueryLanguage parameter.
- OperationTimeout (
Uint32
) –Minimum time in seconds the WBEM Server shall maintain an open enumeration session after a previous Open or Pull request is sent to the client. Once this timeout time has expired, the WBEM server may close the enumeration session.
- If not None, this parameter is sent to the WBEM server as the
proposed timeout for the enumeration session. A value of 0
indicates that the server is expected to never time out. The
server may reject the proposed value, causing a
CIMError
to be raised with status codeCIM_ERR_INVALID_OPERATION_TIMEOUT
. - If None, this parameter is not passed to the WBEM server, and causes the server-implemented default timeout to be used.
- If not None, this parameter is sent to the WBEM server as the
proposed timeout for the enumeration session. A value of 0
indicates that the server is expected to never time out. The
server may reject the proposed value, causing a
- ContinueOnError (
bool
) –Indicates to the WBEM server to continue sending responses after an error response has been sent.
- If True, the server is to continue sending responses after
sending an error response. Not all servers support continuation
on error; a server that does not support it must send an error
response if True was specified, causing
CIMError
to be raised with status codeCIM_ERR_CONTINUATION_ON_ERROR_NOT_SUPPORTED
. - If False, the server is requested to close the enumeration after sending an error response.
- If None, this parameter is not passed to the WBEM server, and causes the server-implemented default behaviour to be used. DSP0200 defines that the server-implemented default is False.
- If True, the server is to continue sending responses after
sending an error response. Not all servers support continuation
on error; a server that does not support it must send an error
response if True was specified, causing
- MaxObjectCount (
Uint32
) –Maximum number of instances the WBEM server may return for this request.
- If positive, the WBEM server is to return no more than the specified number of instances.
- If zero, the WBEM server is to return no instances. This may be used by a client to leave the handling of any returned instances to a loop of Pull operations.
- If None, this parameter is not passed to the WBEM server, and causes the server-implemented default behaviour to be used. DSP0200 defines that the server-implemented default is to return zero instances.
Returns: A
namedtuple()
object containing the following named items:paths (
list
ofCIMInstanceName
): Representations of the retrieved instance paths, with their attributes set as follows:- classname: Name of the creation class of the instance.
- keybindings: Keybindings of the instance.
- namespace: Name of the CIM namespace containing the instance.
- host: Host and optionally port of the WBEM server containing the CIM namespace.
eos (
bool
): Indicates whether the enumeration session is exhausted after this operation:- If True, the enumeration session is exhausted, and the server has closed the enumeration session.
- If False, the enumeration session is not exhausted and the context item is the context object for the next operation on the enumeration session.
context (
tuple()
of server_context, namespace): A context object identifying the open enumeration session, including its current enumeration state, and the namespace. This object must be supplied with the next pull or close operation for this enumeration session.The tuple items are:
- server_context (string): Enumeration context string returned by the server if the session is not exhausted, or None otherwise. This string is opaque for the client.
- namespace (string): Name of the CIM namespace that was used for this operation.
NOTE: This inner tuple hides the need for a CIM namespace on subsequent operations in the enumeration session. CIM operations always require target namespace, but it never makes sense to specify a different one in subsequent operations on the same enumeration session.
Raises: Exceptions described in
WBEMConnection
.- InstanceName (
-
OpenReferenceInstances
(InstanceName, ResultClass=None, Role=None, IncludeClassOrigin=None, PropertyList=None, FilterQueryLanguage=None, FilterQuery=None, OperationTimeout=None, ContinueOnError=None, MaxObjectCount=None)[source]¶ Open an enumeration session to retrieve the association instances that reference a source instance.
New in pywbem 0.9.
The incorrectly supported parameter `IncludeQualifiers` was removed in pywbem 1.0.0.
This method does not support retrieving classes.
This method performs the OpenReferenceInstances operation (see DSP0200). See WBEM operations for a list of all methods performing such operations.
If the operation succeeds, this method returns enumeration session status and optionally instances. Otherwise, this method raises an exception.
Use the
PullInstancesWithPath()
method to retrieve the next set of instances or theCloseEnumeration()
method to close the enumeration session before it is exhausted.Parameters: - InstanceName (
CIMInstanceName
) – The instance path of the source instance. If this object does not specify a namespace, the default namespace of the connection is used. Its host attribute will be ignored. - ResultClass (string or
CIMClassName
) –Class name of an association class (case independent), to filter the result to include only traversals of that association class (or subclasses). If specified as a
CIMClassName
object, its host and namespace attributes will be ignored.None means that no such filtering is peformed.
- Role (string) –
Role name (= property name) of the source end (case independent), to filter the result to include only traversals from that source role.
None means that no such filtering is peformed.
- IncludeClassOrigin (
bool
) –Indicates that class origin information is to be included on each property or method in the returned instances, as follows:
- If False, class origin information is not included.
- If True, class origin information is included.
- If None, this parameter is not passed to the WBEM server, and causes the server-implemented default to be used. DSP0200 defines that the server-implemented default is False.
This parameter has been deprecated in DSP0200. WBEM servers may either implement this parameter as specified, or may treat any specified value as False.
- PropertyList (string or iterable of string) –
An iterable specifying the names of the properties (or a string that defines a single property) to be included in the returned instances (case independent).
An empty iterable indicates to include no properties.
If None, all properties are included.
- FilterQueryLanguage (string) – The name of the filter query language used for the FilterQuery parameter. The DMTF-defined Filter Query Language (see DSP0212) is specified as “DMTF:FQL”.
- FilterQuery (string) – The filter query in the query language defined by the FilterQueryLanguage parameter.
- OperationTimeout (
Uint32
) –Minimum time in seconds the WBEM Server shall maintain an open enumeration session after a previous Open or Pull request is sent to the client. Once this timeout time has expired, the WBEM server may close the enumeration session.
- If not None, this parameter is sent to the WBEM server as the
proposed timeout for the enumeration session. A value of 0
indicates that the server is expected to never time out. The
server may reject the proposed value, causing a
CIMError
to be raised with status codeCIM_ERR_INVALID_OPERATION_TIMEOUT
. - If None, this parameter is not passed to the WBEM server, and causes the server-implemented default timeout to be used.
- If not None, this parameter is sent to the WBEM server as the
proposed timeout for the enumeration session. A value of 0
indicates that the server is expected to never time out. The
server may reject the proposed value, causing a
- ContinueOnError (
bool
) –Indicates to the WBEM server to continue sending responses after an error response has been sent.
- If True, the server is to continue sending responses after
sending an error response. Not all servers support continuation
on error; a server that does not support it must send an error
response if True was specified, causing
CIMError
to be raised with status codeCIM_ERR_CONTINUATION_ON_ERROR_NOT_SUPPORTED
. - If False, the server is requested to close the enumeration after sending an error response.
- If None, this parameter is not passed to the WBEM server, and causes the server-implemented default behaviour to be used. DSP0200 defines that the server-implemented default is False.
- If True, the server is to continue sending responses after
sending an error response. Not all servers support continuation
on error; a server that does not support it must send an error
response if True was specified, causing
- MaxObjectCount (
Uint32
) –Maximum number of instances the WBEM server may return for this request.
- If positive, the WBEM server is to return no more than the specified number of instances.
- If zero, the WBEM server is to return no instances. This may be used by a client to leave the handling of any returned instances to a loop of Pull operations.
- If None, this parameter is not passed to the WBEM server, and causes the server-implemented default behaviour to be used. DSP0200 defines that the server-implemented default is to return zero instances.
Returns: A
namedtuple()
object containing the following named items:instances (
list
ofCIMInstance
): Representations of the retrieved instances.The path attribute of each
CIMInstance
object is aCIMInstanceName
object with its attributes set as follows:- classname: Name of the creation class of the instance.
- keybindings: Keybindings of the instance.
- namespace: Name of the CIM namespace containing the instance.
- host: Host and optionally port of the WBEM server containing the CIM namespace.
eos (
bool
): Indicates whether the enumeration session is exhausted after this operation:- If True, the enumeration session is exhausted, and the server has closed the enumeration session.
- If False, the enumeration session is not exhausted and the context item is the context object for the next operation on the enumeration session.
context (
tuple()
of server_context, namespace): A context object identifying the open enumeration session, including its current enumeration state, and the namespace. This object must be supplied with the next pull or close operation for this enumeration session.The tuple items are:
- server_context (string): Enumeration context string returned by the server if the session is not exhausted, or None otherwise. This string is opaque for the client.
- namespace (string): Name of the CIM namespace that was used for this operation.
NOTE: This inner tuple hides the need for a CIM namespace on subsequent operations in the enumeration session. CIM operations always require target namespace, but it never makes sense to specify a different one in subsequent operations on the same enumeration session.
Raises: Exceptions described in
WBEMConnection
.- InstanceName (
-
OpenReferenceInstancePaths
(InstanceName, ResultClass=None, Role=None, FilterQueryLanguage=None, FilterQuery=None, OperationTimeout=None, ContinueOnError=None, MaxObjectCount=None)[source]¶ Open an enumeration session to retrieve the instance paths of the association instances that reference a source instance.
New in pywbem 0.9.
This method does not support retrieving classes.
This method performs the OpenReferenceInstancePaths operation (see DSP0200). See WBEM operations for a list of all methods performing such operations.
If the operation succeeds, this method returns enumeration session status and optionally instance paths. Otherwise, this method raises an exception.
Use the
PullInstancePaths()
method to retrieve the next set of instance paths or theCloseEnumeration()
method to close the enumeration session before it is exhausted.Parameters: - InstanceName (
CIMInstanceName
) – The instance path of the source instance. If this object does not specify a namespace, the default namespace of the connection is used. Its host attribute will be ignored. - ResultClass (string or
CIMClassName
) –Class name of an association class (case independent), to filter the result to include only traversals of that association class (or subclasses). If specified as a
CIMClassName
object, its host and namespace attributes will be ignored.None means that no such filtering is peformed.
- Role (string) –
Role name (= property name) of the source end (case independent), to filter the result to include only traversals from that source role.
None means that no such filtering is peformed.
- FilterQueryLanguage (string) –
The name of the filter query language used for the FilterQuery parameter. The DMTF-defined Filter Query Language (see DSP0212) is specified as “DMTF:FQL”.
Not all WBEM servers support filtering for this operation because it returns instance paths and the act of the server filtering requires that it generate instances just for that purpose and then discard them.
- FilterQuery (string) – The filter query in the query language defined by the FilterQueryLanguage parameter.
- OperationTimeout (
Uint32
) –Minimum time in seconds the WBEM Server shall maintain an open enumeration session after a previous Open or Pull request is sent to the client. Once this timeout time has expired, the WBEM server may close the enumeration session.
- If not None, this parameter is sent to the WBEM server as the
proposed timeout for the enumeration session. A value of 0
indicates that the server is expected to never time out. The
server may reject the proposed value, causing a
CIMError
to be raised with status codeCIM_ERR_INVALID_OPERATION_TIMEOUT
. - If None, this parameter is not passed to the WBEM server, and causes the server-implemented default timeout to be used.
- If not None, this parameter is sent to the WBEM server as the
proposed timeout for the enumeration session. A value of 0
indicates that the server is expected to never time out. The
server may reject the proposed value, causing a
- ContinueOnError (
bool
) –Indicates to the WBEM server to continue sending responses after an error response has been sent.
- If True, the server is to continue sending responses after
sending an error response. Not all servers support continuation
on error; a server that does not support it must send an error
response if True was specified, causing
CIMError
to be raised with status codeCIM_ERR_CONTINUATION_ON_ERROR_NOT_SUPPORTED
. - If False, the server is requested to close the enumeration after sending an error response.
- If None, this parameter is not passed to the WBEM server, and causes the server-implemented default behaviour to be used. DSP0200 defines that the server-implemented default is False.
- If True, the server is to continue sending responses after
sending an error response. Not all servers support continuation
on error; a server that does not support it must send an error
response if True was specified, causing
- MaxObjectCount (
Uint32
) –Maximum number of instances the WBEM server may return for this request.
- If positive, the WBEM server is to return no more than the specified number of instances.
- If zero, the WBEM server is to return no instances. This may be used by a client to leave the handling of any returned instances to a loop of Pull operations.
- If None, this parameter is not passed to the WBEM server, and causes the server-implemented default behaviour to be used. DSP0200 defines that the server-implemented default is to return zero instances.
Returns: A
namedtuple()
object containing the following named items:paths (
list
ofCIMInstanceName
): Representations of the retrieved instance paths, with their attributes set as follows:- classname: Name of the creation class of the instance.
- keybindings: Keybindings of the instance.
- namespace: Name of the CIM namespace containing the instance.
- host: Host and optionally port of the WBEM server containing the CIM namespace.
eos (
bool
): Indicates whether the enumeration session is exhausted after this operation:- If True, the enumeration session is exhausted, and the server has closed the enumeration session.
- If False, the enumeration session is not exhausted and the context item is the context object for the next operation on the enumeration session.
context (
tuple()
of server_context, namespace): A context object identifying the open enumeration session, including its current enumeration state, and the namespace. This object must be supplied with the next pull or close operation for this enumeration session.The tuple items are:
- server_context (string): Enumeration context string returned by the server if the session is not exhausted, or None otherwise. This string is opaque for the client.
- namespace (string): Name of the CIM namespace that was used for this operation.
NOTE: This inner tuple hides the need for a CIM namespace on subsequent operations in the enumeration session. CIM operations always require target namespace, but it never makes sense to specify a different one in subsequent operations on the same enumeration session.
Raises: Exceptions described in
WBEMConnection
.- InstanceName (
-
OpenQueryInstances
(FilterQueryLanguage, FilterQuery, namespace=None, ReturnQueryResultClass=None, OperationTimeout=None, ContinueOnError=None, MaxObjectCount=None)[source]¶ Open an enumeration session to execute a query in a namespace and to retrieve the instances representing the query result.
New in pywbem 0.9.
This method performs the OpenQueryInstances operation (see DSP0200). See WBEM operations for a list of all methods performing such operations.
If the operation succeeds, this method returns enumeration session status and optionally CIM instances representing the query result. Otherwise, this method raises an exception.
Use the
PullInstances()
method to retrieve the next set of instances or theCloseEnumeration()
method to close the enumeration session before it is exhausted.Parameters: - FilterQueryLanguage (string) – Name of the query language used in the FilterQuery parameter, e.g. “DMTF:CQL” for CIM Query Language, and “WQL” for WBEM Query Language. Because this is not a filter query, “DMTF:FQL” is not a valid query language for this request.
- FilterQuery (string) – Query string in the query language specified in the FilterQueryLanguage parameter.
- namespace (string) –
Name of the CIM namespace to be used (case independent).
Leading and trailing slash characters will be stripped. The lexical case will be preserved.
If None, the default namespace of the connection object will be used.
- ReturnQueryResultClass (
bool
) –Controls whether a class definition describing the returned instances will be returned.
None will cause the server to use its default of False.
- OperationTimeout (
Uint32
) –Minimum time in seconds the WBEM Server shall maintain an open enumeration session after a previous Open or Pull request is sent to the client. Once this timeout time has expired, the WBEM server may close the enumeration session.
- If not None, this parameter is sent to the WBEM server as the
proposed timeout for the enumeration session. A value of 0
indicates that the server is expected to never time out. The
server may reject the proposed value, causing a
CIMError
to be raised with status codeCIM_ERR_INVALID_OPERATION_TIMEOUT
. - If None, this parameter is not passed to the WBEM server, and causes the server-implemented default timeout to be used.
- If not None, this parameter is sent to the WBEM server as the
proposed timeout for the enumeration session. A value of 0
indicates that the server is expected to never time out. The
server may reject the proposed value, causing a
- ContinueOnError (
bool
) –Indicates to the WBEM server to continue sending responses after an error response has been sent.
- If True, the server is to continue sending responses after
sending an error response. Not all servers support continuation
on error; a server that does not support it must send an error
response if True was specified, causing
CIMError
to be raised with status codeCIM_ERR_CONTINUATION_ON_ERROR_NOT_SUPPORTED
. - If False, the server is requested to close the enumeration after sending an error response.
- If None, this parameter is not passed to the WBEM server, and causes the server-implemented default behaviour to be used. DSP0200 defines that the server-implemented default is False.
- If True, the server is to continue sending responses after
sending an error response. Not all servers support continuation
on error; a server that does not support it must send an error
response if True was specified, causing
- MaxObjectCount (
Uint32
) –Maximum number of instances the WBEM server may return for this request.
- If positive, the WBEM server is to return no more than the specified number of instances.
- If zero, the WBEM server is to return no instances. This may be used by a client to leave the handling of any returned instances to a loop of Pull operations.
- If None, this parameter is not passed to the WBEM server, and causes the server-implemented default behaviour to be used. DSP0200 defines that the server-implemented default is to return zero instances.
Returns: A
namedtuple()
object containing the following named items:instances (
list
ofCIMInstance
): Representations of the retrieved instances.The path attribute of each
CIMInstance
object is None, because query results are not addressable CIM instances.eos (
bool
): Indicates whether the enumeration session is exhausted after this operation:- If True, the enumeration session is exhausted, and the server has closed the enumeration session.
- If False, the enumeration session is not exhausted and the context item is the context object for the next operation on the enumeration session.
context (
tuple()
of server_context, namespace): A context object identifying the open enumeration session, including its current enumeration state, and the namespace. This object must be supplied with the next pull or close operation for this enumeration session.The tuple items are:
- server_context (string): Enumeration context string returned by the server if the session is not exhausted, or None otherwise. This string is opaque for the client.
- namespace (string): Name of the CIM namespace that was used for this operation.
NOTE: The inner tuple hides the need for a CIM namespace on subsequent operations in the enumeration session. CIM operations always require target namespace, but it never makes sense to specify a different one in subsequent operations on the same enumeration session.
query_result_class (
CIMClass
): If the ReturnQueryResultClass parameter is True, this tuple item contains a class definition that defines the properties of each row (instance) of the query result. Otherwise, None.
Raises: Exceptions described in
WBEMConnection
.
-
PullInstancesWithPath
(context, MaxObjectCount)[source]¶ Retrieve the next set of instances (with instance paths) from an open enumeration session.
New in pywbem 0.9.
This operation can only be used on enumeration sessions that have been opened by one of the following methods:
This method performs the PullInstancesWithPath operation (see DSP0200). See WBEM operations for a list of all methods performing such operations.
If the operation succeeds, this method returns enumeration session status and optionally instances. Otherwise, this method raises an exception.
Parameters: - context (
tuple()
of server_context, namespace) –A context object identifying the open enumeration session, including its current enumeration state, and the namespace. This object must have been returned by the previous open or pull operation for this enumeration session.
The tuple items are:
- MaxObjectCount (
Uint32
) –Maximum number of instances the WBEM server shall return for this request. This parameter is required for each Pull request.
- If positive, the WBEM server is to return no more than the specified number of instances.
- If zero, the WBEM server is to return no instances. This may be used by a client to reset the interoperation timer
- None is not allowed.
Returns: A
namedtuple()
object containing the following named items:instances (
list
ofCIMInstance
): Representations of the retrieved instances.The path attribute of each
CIMInstance
object is aCIMInstanceName
object with its attributes set as follows:- classname: Name of the creation class of the instance.
- keybindings: Keybindings of the instance.
- namespace: Name of the CIM namespace containing the instance.
- host: Host and optionally port of the WBEM server containing the CIM namespace.
eos (
bool
): Indicates whether the enumeration session is exhausted after this operation:- If True, the enumeration session is exhausted, and the server has closed the enumeration session.
- If False, the enumeration session is not exhausted and the context item is the context object for the next operation on the enumeration session.
context (
tuple()
of server_context, namespace): A context object identifying the open enumeration session, including its current enumeration state, and the namespace. This object must be supplied with the next pull or close operation for this enumeration session.The tuple items are:
- server_context (string): Enumeration context string returned by the server if the session is not exhausted, or None otherwise. This string is opaque for the client.
- namespace (string): Name of the CIM namespace that was used for this operation.
NOTE: This inner tuple hides the need for a CIM namespace on subsequent operations in the enumeration session. CIM operations always require target namespace, but it never makes sense to specify a different one in subsequent operations on the same enumeration session.
Raises: Exceptions described in
WBEMConnection
.- context (
-
PullInstancePaths
(context, MaxObjectCount)[source]¶ Retrieve the next set of instance paths from an open enumeration session.
New in pywbem 0.9.
This operation can only be used on enumeration sessions that have been opened by one of the following methods:
This method performs the PullInstancePaths operation (see DSP0200). See WBEM operations for a list of all methods performing such operations.
If the operation succeeds, this method returns enumeration session status and optionally instance paths. Otherwise, this method raises an exception.
Parameters: - context (
tuple()
of server_context, namespace) –A context object identifying the open enumeration session, including its current enumeration state, and the namespace. This object must have been returned by the previous open or pull operation for this enumeration session.
The tuple items are:
- MaxObjectCount (
Uint32
) –Maximum number of instances the WBEM server shall return for this request. This parameter is required for each Pull request.
- If positive, the WBEM server is to return no more than the specified number of instances.
- If zero, the WBEM server is to return no instances. This may be used by a client to reset the interoperation timer.
- None is not allowed.
Returns: A
namedtuple()
object containing the following named items:paths (
list
ofCIMInstanceName
): Representations of the retrieved instance paths, with their attributes set as follows:- classname: Name of the creation class of the instance.
- keybindings: Keybindings of the instance.
- namespace: Name of the CIM namespace containing the instance.
- host: Host and optionally port of the WBEM server containing the CIM namespace.
eos (
bool
): Indicates whether the enumeration session is exhausted after this operation:- If True, the enumeration session is exhausted, and the server has closed the enumeration session.
- If False, the enumeration session is not exhausted and the context item is the context object for the next operation on the enumeration session.
context (
tuple()
of server_context, namespace): A context object identifying the open enumeration session, including its current enumeration state, and the namespace. This object must be supplied with the next pull or close operation for this enumeration session.The tuple items are:
- server_context (string): Enumeration context string returned by the server if the session is not exhausted, or None otherwise. This string is opaque for the client.
- namespace (string): Name of the CIM namespace that was used for this operation.
NOTE: This inner tuple hides the need for a CIM namespace on subsequent operations in the enumeration session. CIM operations always require target namespace, but it never makes sense to specify a different one in subsequent operations on the same enumeration session.
Raises: Exceptions described in
WBEMConnection
.- context (
-
PullInstances
(context, MaxObjectCount)[source]¶ Retrieve the next set of instances (without instance paths) from an open enumeration session.
New in pywbem 0.9.
This operation can only be used on enumeration sessions that have been opened by one of the following methods:
This method performs the PullInstances operation (see DSP0200). See WBEM operations for a list of all methods performing such operations.
If the operation succeeds, this method returns enumeration session status and optionally instances. Otherwise, this method raises an exception.
Parameters: - context (
tuple()
of server_context, namespace) –A context object identifying the open enumeration session, including its current enumeration state, and the namespace. This object must have been returned by the previous open or pull operation for this enumeration session.
The tuple items are:
- MaxObjectCount (
Uint32
) –Maximum number of instances the WBEM server shall return for this request. This parameter is required for each Pull request.
- If positive, the WBEM server is to return no more than the specified number of instances.
- If zero, the WBEM server is to return no instances. This may be used by a client to reset the interoperation timer.
- None is not allowed.
Returns: A
namedtuple()
object containing the following named items:instances (
list
ofCIMInstance
): Representations of the retrieved instances.The path attribute of each
CIMInstance
object is None, because this operation does not return instance paths.eos (
bool
): Indicates whether the enumeration session is exhausted after this operation:- If True, the enumeration session is exhausted, and the server has closed the enumeration session.
- If False, the enumeration session is not exhausted and the context item is the context object for the next operation on the enumeration session.
context (
tuple()
of server_context, namespace): A context object identifying the open enumeration session, including its current enumeration state, and the namespace. This object must be supplied with the next pull or close operation for this enumeration session.The tuple items are:
- server_context (string): Enumeration context string returned by the server if the session is not exhausted, or None otherwise. This string is opaque for the client.
- namespace (string): Name of the CIM namespace that was used for this operation.
NOTE: This inner tuple hides the need for a CIM namespace on subsequent operations in the enumeration session. CIM operations always require target namespace, but it never makes sense to specify a different one in subsequent operations on the same enumeration session.
Raises: Exceptions described in
WBEMConnection
.- context (
-
CloseEnumeration
(context)[source]¶ Close an open enumeration session, causing an early termination of an incomplete enumeration session.
New in pywbem 0.9.
This method performs the CloseEnumeration operation (see DSP0200). See WBEM operations for a list of all methods performing such operations.
The enumeration session must still be open when this operation is performed.
If the operation succeeds, this method returns. Otherwise, it raises an exception.
Parameters: context ( tuple()
of server_context, namespace) –A context object identifying the open enumeration session, including its current enumeration state, and the namespace. This object must have been returned by the previous open or pull operation for this enumeration session.
The tuple items are:
Raises: Exceptions described in WBEMConnection
.
-
EnumerateClasses
(namespace=None, ClassName=None, DeepInheritance=None, LocalOnly=None, IncludeQualifiers=None, IncludeClassOrigin=None)[source]¶ Enumerate the subclasses of a class, or the top-level classes in a namespace.
This method performs the EnumerateClasses operation (see DSP0200). See WBEM operations for a list of all methods performing such operations.
If the operation succeeds, this method returns. Otherwise, this method raises an exception.
Parameters: - namespace (string) –
Name of the namespace in which the classes are to be enumerated (case independent).
Leading and trailing slash characters will be stripped. The lexical case will be preserved.
If None, the namespace of the ClassName parameter will be used, if specified as a
CIMClassName
object. If that is also None, the default namespace of the connection will be used. - ClassName (string or
CIMClassName
) –Name of the class whose subclasses are to be retrieved (case independent). If specified as a
CIMClassName
object, its host attribute will be ignored.If None, the top-level classes in the namespace will be retrieved.
- DeepInheritance (
bool
) –Indicates that all (direct and indirect) subclasses of the specified class or of the top-level classes are to be included in the result, as follows:
- If False, only direct subclasses of the specified class or only top-level classes are included in the result.
- If True, all direct and indirect subclasses of the specified class or the top-level classes and all of their direct and indirect subclasses are included in the result.
- If None, this parameter is not passed to the WBEM server, and causes the server-implemented default to be used. DSP0200 defines that the server-implemented default is False.
Note, the semantics of the DeepInheritance parameter in
EnumerateInstances()
is different. - LocalOnly (
bool
) –Indicates that inherited properties, methods, and qualifiers are to be excluded from the returned classes, as follows.
- If False, inherited elements are not excluded.
- If True, inherited elements are excluded.
- If None, this parameter is not passed to the WBEM server, and causes the server-implemented default to be used. DSP0200 defines that the server-implemented default is True.
- IncludeQualifiers (
bool
) –Indicates that qualifiers are to be included in the returned classes, as follows:
- If False, qualifiers are not included.
- If True, qualifiers are included.
- If None, this parameter is not passed to the WBEM server, and causes the server-implemented default to be used. DSP0200 defines that the server-implemented default is True.
- IncludeClassOrigin (
bool
) –Indicates that class origin information is to be included on each property and method in the returned classes, as follows:
- If False, class origin information is not included.
- If True, class origin information is included.
- If None, this parameter is not passed to the WBEM server, and causes the server-implemented default to be used. DSP0200 defines that the server-implemented default is False.
Returns: A list of
CIMClass
objects that are representations of the enumerated classes, with their path attributes set.Raises: Exceptions described in
WBEMConnection
.- namespace (string) –
-
EnumerateClassNames
(namespace=None, ClassName=None, DeepInheritance=None)[source]¶ Enumerate the names of subclasses of a class, or of the top-level classes in a namespace.
This method performs the EnumerateClassNames operation (see DSP0200). See WBEM operations for a list of all methods performing such operations.
If the operation succeeds, this method returns. Otherwise, this method raises an exception.
Parameters: - namespace (string) –
Name of the namespace in which the class names are to be enumerated (case independent).
Leading and trailing slash characters will be stripped. The lexical case will be preserved.
If None, the namespace of the ClassName parameter will be used, if specified as a
CIMClassName
object. If that is also None, the default namespace of the connection will be used. - ClassName (string or
CIMClassName
) –Name of the class whose subclasses are to be retrieved (case independent). If specified as a
CIMClassName
object, its host attribute will be ignored.If None, the top-level classes in the namespace will be retrieved.
- DeepInheritance (
bool
) –Indicates that all (direct and indirect) subclasses of the specified class or of the top-level classes are to be included in the result, as follows:
- If False, only direct subclasses of the specified class or only top-level classes are included in the result.
- If True, all direct and indirect subclasses of the specified class or the top-level classes and all of their direct and indirect subclasses are included in the result.
- If None, this parameter is not passed to the WBEM server, and causes the server-implemented default to be used. DSP0200 defines that the server-implemented default is False.
Note, the semantics of the DeepInheritance parameter in
EnumerateInstances()
is different.
Returns: A list of unicode string objects that are the class names of the enumerated classes.
Raises: Exceptions described in
WBEMConnection
.- namespace (string) –
-
GetClass
(ClassName, namespace=None, LocalOnly=None, IncludeQualifiers=None, IncludeClassOrigin=None, PropertyList=None)[source]¶ Retrieve a class.
This method performs the GetClass operation (see DSP0200). See WBEM operations for a list of all methods performing such operations.
If the operation succeeds, this method returns. Otherwise, this method raises an exception.
Parameters: - ClassName (string or
CIMClassName
) – Name of the class to be retrieved (case independent). If specified as aCIMClassName
object, its host attribute will be ignored. - namespace (string) –
Name of the namespace of the class to be retrieved (case independent).
Leading and trailing slash characters will be stripped. The lexical case will be preserved.
If None, the namespace of the ClassName parameter will be used, if specified as a
CIMClassName
object. If that is also None, the default namespace of the connection will be used. - LocalOnly (
bool
) –Indicates that inherited properties, methods, and qualifiers are to be excluded from the returned class, as follows.
- If False, inherited elements are not excluded.
- If True, inherited elements are excluded.
- If None, this parameter is not passed to the WBEM server, and causes the server-implemented default to be used. DSP0200 defines that the server-implemented default is True.
- IncludeQualifiers (
bool
) –Indicates that qualifiers are to be included in the returned class, as follows:
- If False, qualifiers are not included.
- If True, qualifiers are included.
- If None, this parameter is not passed to the WBEM server, and causes the server-implemented default to be used. DSP0200 defines that the server-implemented default is True.
- IncludeClassOrigin (
bool
) –Indicates that class origin information is to be included on each property and method in the returned class, as follows:
- If False, class origin information is not included.
- If True, class origin information is included.
- If None, this parameter is not passed to the WBEM server, and causes the server-implemented default to be used. DSP0200 defines that the server-implemented default is False.
- PropertyList (string or iterable of string) –
An iterable specifying the names of the properties (or a string that defines a single property) to be included in the returned class (case independent).
An empty iterable indicates to include no properties.
If None, all properties are included.
Returns: A
CIMClass
object that is a representation of the retrieved class, with its path attribute set.Raises: Exceptions described in
WBEMConnection
.- ClassName (string or
-
ModifyClass
(ModifiedClass, namespace=None)[source]¶ Modify a class.
This method performs the ModifyClass operation (see DSP0200). See WBEM operations for a list of all methods performing such operations.
If the operation succeeds, this method returns. Otherwise, this method raises an exception.
Parameters: - ModifiedClass (
CIMClass
) –A representation of the modified class.
The properties, methods and qualifiers defined in this object specify what is to be modified.
Typically, this object has been retrieved by other operations, such as
GetClass()
. - namespace (string) –
Name of the namespace in which the class is to be modified (case independent).
Leading and trailing slash characters will be stripped. The lexical case will be preserved.
If None, the default namespace of the connection object will be used.
Raises: Exceptions described in
WBEMConnection
.- ModifiedClass (
-
CreateClass
(NewClass, namespace=None)[source]¶ Create a class in a namespace.
This method performs the CreateClass operation (see DSP0200). See WBEM operations for a list of all methods performing such operations.
If the operation succeeds, this method returns. Otherwise, this method raises an exception.
Parameters: - NewClass (
CIMClass
) –A representation of the class to be created.
The properties, methods and qualifiers defined in this object specify how the class is to be created.
Its path attribute is ignored.
- namespace (string) –
Name of the namespace in which the class is to be created (case independent).
Leading and trailing slash characters will be stripped. The lexical case will be preserved.
If None, the default namespace of the connection object will be used.
Raises: Exceptions described in
WBEMConnection
.- NewClass (
-
DeleteClass
(ClassName, namespace=None)[source]¶ Delete a class.
This method performs the DeleteClass operation (see DSP0200). See WBEM operations for a list of all methods performing such operations.
If the operation succeeds, this method returns. Otherwise, this method raises an exception.
Parameters: - ClassName (string or
CIMClassName
) – Name of the class to be deleted (case independent). If specified as aCIMClassName
object, its host attribute will be ignored. - namespace (string) –
Name of the namespace of the class to be deleted (case independent).
Leading and trailing slash characters will be stripped. The lexical case will be preserved.
If None, the namespace of the ClassName parameter will be used, if specified as a
CIMClassName
object. If that is also None, the default namespace of the connection will be used.
Raises: Exceptions described in
WBEMConnection
.- ClassName (string or
-
EnumerateQualifiers
(namespace=None)[source]¶ Enumerate the qualifier types (= qualifier declarations) in a namespace.
This method performs the EnumerateQualifiers operation (see DSP0200). See WBEM operations for a list of all methods performing such operations.
If the operation succeeds, this method returns. Otherwise, this method raises an exception.
Parameters: namespace (string) – Name of the namespace in which the qualifier declarations are to be enumerated (case independent).
Leading and trailing slash characters will be stripped. The lexical case will be preserved.
If None, the default namespace of the connection object will be used.
Returns: A list of CIMQualifierDeclaration
objects that are representations of the enumerated qualifier declarations.Raises: Exceptions described in WBEMConnection
.
-
GetQualifier
(QualifierName, namespace=None)[source]¶ Retrieve a qualifier type (= qualifier declaration).
This method performs the GetQualifier operation (see DSP0200). See WBEM operations for a list of all methods performing such operations.
If the operation succeeds, this method returns. Otherwise, this method raises an exception.
Parameters: - QualifierName (string) – Name of the qualifier declaration to be retrieved (case independent).
- namespace (string) –
Name of the namespace of the qualifier declaration (case independent).
Leading and trailing slash characters will be stripped. The lexical case will be preserved.
If None, the default namespace of the connection object will be used.
Returns: A
CIMQualifierDeclaration
object that is a representation of the retrieved qualifier declaration.Raises: Exceptions described in
WBEMConnection
.
-
SetQualifier
(QualifierDeclaration, namespace=None)[source]¶ Create or modify a qualifier type (= qualifier declaration) in a namespace.
This method performs the SetQualifier operation (see DSP0200). See WBEM operations for a list of all methods performing such operations.
If the operation succeeds, this method returns. Otherwise, this method raises an exception.
Parameters: - QualifierDeclaration (
CIMQualifierDeclaration
) – Representation of the qualifier declaration to be created or modified. - namespace (string) –
Name of the namespace in which the qualifier declaration is to be created or modified (case independent).
Leading and trailing slash characters will be stripped. The lexical case will be preserved.
If None, the default namespace of the connection object will be used.
Raises: Exceptions described in
WBEMConnection
.- QualifierDeclaration (
-
DeleteQualifier
(QualifierName, namespace=None)[source]¶ Delete a qualifier type (= qualifier declaration).
This method performs the DeleteQualifier operation (see DSP0200). See WBEM operations for a list of all methods performing such operations.
If the operation succeeds, this method returns. Otherwise, this method raises an exception.
Parameters: - QualifierName (string) – Name of the qualifier declaration to be deleted (case independent).
- namespace (string) –
Name of the namespace in which the qualifier declaration is to be deleted (case independent).
Leading and trailing slash characters will be stripped. The lexical case will be preserved.
If None, the default namespace of the connection object will be used.
Raises: Exceptions described in
WBEMConnection
.
-
is_subclass
(namespace, klass, superclass)[source]¶ Return boolean indicating whether a class is a (direct or indirect) subclass of a superclass, or the same class, in the specified namespace.
This test is done by starting at the class and walking its superclasses up to the root.
Parameters: Returns: Boolean indicating whether the class is a (direct or indirect) subclass of the superclass, or the same class.
Return type: Raises:
CIM objects¶
CIM objects are local representations of CIM instances, classes, properties, etc., as Python objects. They are used as input to and output from WBEM operations:
CIM object | Purpose |
---|---|
CIMInstanceName |
Instance path of a CIM instance |
CIMInstance |
CIM instance |
CIMClassName |
Name of a CIM class, optionally with class path |
CIMClass |
CIM class |
CIMProperty |
CIM property, both as property value in a CIM instance and as property declaration in a CIM class |
CIMMethod |
CIM method declaration in a CIM class |
CIMParameter |
CIM parameter, both as a parameter value in a method invocation and as a parameter declaration in a CIM method declaration in a CIM class |
CIMQualifier |
CIM qualifier value |
CIMQualifierDeclaration |
CIM qualifier type/declaration |
Putting CIM objects in sets¶
Using sets for holding the result of WBEM operations is not uncommon, because that allows comparison of results without regard to the (undefined) order in which the objects are returned.
CIM objects are mutable and unchanged-hashable. This requires some caution when putting them in sets, or using them in any other way that relies on their hash values.
The caution that is needed is that the public attributes, and therefore the state of the CIM objects, must not change as long as they are a member of a set, or used in any other way that relies on their hash values.
The following example shows what happens if a CIM object is modified while being a member of a set:
import pywbem
s = set()
# Create CIM object c1 and show its identity and hash value:
c1 = pywbem.CIMClass('C')
print(id(c1), hash(c1)) # (140362966049680, -7623128493967117119)
# Add c1 to the set and verify the set content:
s.add(c1)
print([id(c) for c in s]) # [140362966049680]
# Modify the c1 object; it now has changed its hash value:
c1.superclass = 'B'
print(id(c1), hash(c1)) # (140362966049680, 638672161836520435)
# Create a CIM object c2 with the same attribute values as c1, and show
# that they compare equal and that c2 has the same hash value as c1 now has:
c2 = pywbem.CIMClass('C', superclass='B')
print(c1 == c2) # True
print(id(c2), hash(c2)) # (140362970983696, 638672161836520435)
# Add c2 to the set and verify the set content:
s.add(c2)
print([id(c) for c in s]) # [140362966049680, 140362970983696] !!
At the end, the set contains both objects even though they have the same hash value. This is not what one would expect from set types.
The reason is that at the time the object c1 was added to the set, it had a different hash value, and the set uses the hash value it found at insertion time of its member for identifying the object. When the second object is added, it finds it has a yet unknown hash value, and adds it.
While the set type in this particular Python implementation was able to still look up the first member object even though its hash value has changed meanwhile, other collection types or other Python implementations may not be as forgiving and may not even be able to look up the object once its hash value has changed.
Therefore, always make sure that the public attributes of CIM objects that are put into a set remain unchanged while the object is in the set. The same applies to any other usage of CIM objects that relies on their hash values.
Order of CIM child objects¶
CIM objects have zero or more lists of child objects. For example, a CIM class (the parent object) has a list of CIM properties, CIM methods and CIM qualifiers (the child objects).
In pywbem, the parent CIM object allows initializing each list of child objects
via an init parameter. For example, the CIMClass
init method
has a parameter named properties
that allows specifying the CIM properties
of the CIM class.
Once the parent CIM object exists, each list of child objects can be modified
via a settable attribute. For example, the CIMClass
class has
a properties
attribute for its list of CIM properties.
For such attributes and init parameters that specify lists of child objects, pywbem supports a number of different ways the child objects can be specified.
Some of these ways preserve the order of child objects and some don’t.
This section uses CIM properties in CIM classes as an example, but it applies to all kinds of child objects in CIM objects.
The possible input objects for the properties
init parameter
and for the properties
attribute of
CIMClass
is described in the type
properties input object, and must be one of these objects:
- iterable of
CIMProperty
- iterable of tuple(key, value)
OrderedDict
with key and valuedict
with key and value (will not preserve order)
The keys are always the property names, and the values are always
CIMProperty
objects (at least when initializing classes).
Even though the OrderedDict
class preserves the order
of its items, intializing the dictionary with keyword arguments causes the
order of items to be lost before the dictionary is even initialized (before
Python 3.6). The only way to initialize a dictionary without loosing order of
items is by providing a list of tuples(key,value).
The following examples work but loose the order of properties in the class:
# Examples where order of properties in class is not as specified:
# Using an OrderedDict object, initialized with keyword arguments
# (before Python 3.6):
c1_props = OrderedDict(
Prop1=CIMProperty('Prop1', value='abc'),
Prop2=CIMProperty('Prop2', value=None, type='string'),
)
# Using a dict object, initialized with keyword arguments (This time
# specified using key:value notation):
c1_props = {
'Prop1': CIMProperty('Prop1', value='abc'),
'Prop2': CIMProperty('Prop2', value=None, type='string'),
}
# Using a dict object, initialized with list of tuple(key,value):
c1_props = dict([
('Prop1', CIMProperty('Prop1', value='abc')),
('Prop2', CIMProperty('Prop2', value=None, type='string')),
])
# Any of the above objects can be used to initialize the class properties:
c1 = CIMClass('CIM_Foo', properties=c1_props)
The following examples all preserve the order of properties in the class:
# Examples where order of properties in class is as specified:
# Using a list of CIMProperty objects (starting with pywbem 0.12):
c1_props = [
CIMProperty('Prop1', value='abc'),
CIMProperty('Prop2', value=None, type='string'),
]
# Using an OrderedDict object, initialized with list of tuple(key,value):
c1_props = OrderedDict([
('Prop1', CIMProperty('Prop1', value='abc')),
('Prop2', CIMProperty('Prop2', value=None, type='string')),
])
# Using a list of tuple(key,value):
c1_props = [
('Prop1', CIMProperty('Prop1', value='abc')),
('Prop2', CIMProperty('Prop2', value=None, type='string')),
]
# Any of the above objects can be used to initialize the class properties:
c1 = CIMClass('CIM_Foo', properties=c1_props)
NocaseDict¶
Class NocaseDict
is a dictionary implementation with case-insensitive but
case-preserving keys, and with preservation of the order of its items.
It is used for lists of child objects of CIM objects (e.g. the list of CIM properties in a CIM class, or the list of CIM parameters in a CIM method).
Users of pywbem will notice NocaseDict
objects only as a result of pywbem
functions. Users cannot create NocaseDict
objects.
Except for the case-insensitivity of its keys, it behaves like the built-in
OrderedDict
. Therefore, NocaseDict
is not
described in detail in this documentation.
CIMInstanceName¶
-
class
pywbem.
CIMInstanceName
(classname, keybindings=None, host=None, namespace=None)[source]¶ A CIM instance path (aka CIM instance name).
A CIM instance path references a CIM instance in a CIM namespace in a WBEM server. Namespace and WBEM server may be unspecified.
Two objects of this class compare equal if their public attributes compare equal. Objects of this class are unchanged-hashable, with the hash value being based on its public attributes. Therefore, objects of this class can be used as members in a set (or as dictionary keys) only during periods in which their public attributes remain unchanged.
Parameters: - classname (string) –
Name of the creation class of the referenced instance.
Must not be None.
The lexical case of the string is preserved. Object comparison and hash value calculation are performed case-insensitively.
- keybindings (keybindings input object) – Keybindings for the instance path (that is, the key property values of the referenced instance).
- host (string) –
Host and optionally port of the WBEM server containing the CIM namespace of the referenced instance.
The format of the string must be:
host[:port]
The host can be specified in any of the usual formats:
- a short or fully qualified DNS hostname
- a literal (= dotted) IPv4 address
- a literal IPv6 address, formatted as defined in RFC3986
with the extensions for zone identifiers as defined in
RFC6874, supporting
-
(minus) for the delimiter before the zone ID string, as an additional choice to%25
.
None means that the WBEM server is unspecified, and the
host
attribute will also be None.The lexical case of the string is preserved. Object comparison and hash value calculation are performed case-insensitively.
- namespace (string) –
Name of the CIM namespace containing the referenced instance.
None means that the namespace is unspecified, and the
namespace
attribute will also be None.Leading and trailing slash characters will be stripped. The lexical case of the string is preserved. Object comparison and hash value calculation are performed case-insensitively.
Raises: ValueError
– An error in the provided argument values.ValueError
– A keybinding value is None and the config variable pywbem.config.IGNORE_NULL_KEY_VALUE is FalseTypeError
– An error in the provided argument types.
Methods
copy
Return a new CIMInstanceName
object that is a copy of this CIM instance path.from_instance
Return a new CIMInstanceName
object from the key property values in a CIM instance and the key property definitions in a CIM class.from_wbem_uri
Return a new CIMInstanceName
object from the specified WBEM URI string.get
Return the value of a particular keybinding of this CIM instance path, or a default value. has_key
Return a boolean indicating whether this CIM instance path has a particular keybinding. items
Return the keybinding items as a tuple (name, value) of this CIM instance path. iteritems
Return an iterator through the keybinding items of this CIM instance path, where each item is a tuple of keybinding name and value. iterkeys
Return an iterator through the keybinding names of this CIM instance path. itervalues
Return an iterator through the keybinding values of this CIM instance path. keys
Return the keybinding names of this CIM instance path. to_wbem_uri
Return the (untyped) WBEM URI string of this CIM instance path. tocimxml
Return the CIM-XML representation of this CIM instance path, as an object of an appropriate subclass of Element. tocimxmlstr
Return the CIM-XML representation of this CIM instance path, as a unicode string. update
Update the keybindings of this CIM instance path. values
Return the keybinding values of this CIM instance path. Attributes
classname
Class name of this CIM instance path, identifying the creation class of the referenced instance. host
Host and optionally port of this CIM instance path, identifying the WBEM server of the referenced instance. keybindings
Keybindings of this CIM instance path, identifying the key properties of the referenced instance. namespace
Namespace name of this CIM instance path, identifying the namespace of the referenced instance. Details
-
classname
¶ Class name of this CIM instance path, identifying the creation class of the referenced instance.
Will not be None.
This attribute is settable. For details, see the description of the same-named init parameter of
this class
.Type: unicode string
-
keybindings
¶ Keybindings of this CIM instance path, identifying the key properties of the referenced instance.
Will not be None.
Each dictionary item specifies one keybinding, with:
- key (unicode string): Keybinding name. Its lexical case was preserved.
- value (CIM data type or number): Keybinding value.
None is not allowed by default, consistent with DSP0004.
This default behavior can be changed via the config variable
pywbem.config.IGNORE_NULL_KEY_VALUE
.
The order of keybindings in the instance path is preserved.
The keybinding name may be None in objects of this class that are created by pywbem, in the special case a WBEM server has returned an instance path with an unnamed keybinding (i.e. a KEYVALUE or VALUE.REFERENCE element without a parent KEYBINDINGS element). This is allowed as per DSP0201. When creating objects of this class, it is not allowed to specify unnamed keybindings, i.e. the keybinding name must not be None.
This attribute is settable; setting it will cause the current keybindings to be replaced with the new keybindings. For details, see the description of the same-named init parameter of
this class
.When setting a keybinding value, it will be preserved whether the input value was a CIM data type, a number or None. If the input value was a CIM data type, the CIM type of the keybinding value is known and this will cause the TYPE attribute in the KEYVALUE element of the CIM-XML representation to be present.
The keybindings can also be accessed and manipulated one by one because the attribute value is a modifiable dictionary. The provided input value must be specified as a CIM data type or as number:
instpath = CIMInstanceName(...) v1 = "abc" # must be a CIM data type or Python number type instpath.keybindings['k1'] = v1 # Set "k1" to v1 (add if needed) v1 = instpath.keybindings['k1'] # Access value of "k1" del instpath.keybindings['k1'] # Delete "k1" from the inst. path
In addition, the keybindings can be accessed and manipulated one by one by using the entire
CIMInstanceName
object like a dictionary. Again, the provided input value must be specified as a CIM data type or as number:instpath = CIMInstanceName(...) v2 = 42 # must be a CIM data type or Python number type instpath['k2'] = v2 # Set "k2" to v2 (add if needed) v2 = instpath['k2'] # Access value of "k2" del instpath['k2'] # Delete "k2" from the instance path
Type: NocaseDict
-
namespace
¶ Namespace name of this CIM instance path, identifying the namespace of the referenced instance.
None means that the namespace is unspecified.
This attribute is settable. For details, see the description of the same-named init parameter of
this class
.Type: unicode string
-
host
¶ Host and optionally port of this CIM instance path, identifying the WBEM server of the referenced instance.
For details about the string format, see the same-named init parameter of
this class
.None means that the host and port are unspecified.
This attribute is settable. For details, see the description of the same-named init parameter.
Type: unicode string
-
__eq__
(other)[source]¶ Equality test function for two
CIMInstanceName
objects.The equality is based on their public attributes, in descending precedence:
- host
- namespace
- classname
- keybindings
The equality test takes into account any case insensitivities described for these attributes.
Raises TypeError’, if the `other object is not a
CIMInstanceName
object.
-
__str__
()[source]¶ Return the WBEM URI string of this CIM instance path.
The returned WBEM URI string is in the historical format returned by
to_wbem_uri()
.For new code, it is recommended that the standard format is used; it is returned by
to_wbem_uri()
as the default format.Examples (for the historical format):
With host and namespace:
//acme.com/cimv2/test:CIM_RegisteredProfile.InstanceID="acme.1"
Without host but with namespace:
cimv2/test:CIM_RegisteredProfile.InstanceID="acme.1"
Without host and without namespace:
CIM_RegisteredProfile.InstanceID="acme.1"
-
__repr__
()[source]¶ Return a string representation of this CIM instance path, that is suitable for debugging.
The key bindings will be ordered by their names in the result.
-
copy
()[source]¶ Return a new
CIMInstanceName
object that is a copy of this CIM instance path.This is a middle-deep copy; any mutable types in attributes except the following are copied, so besides these exceptions, modifications of the original object will not affect the returned copy, and vice versa. The following mutable types are not copied and are therefore shared between original and copy:
- Any mutable object types (see CIM data types) in the
keybindings
dictionary (but not the dictionary object itself)
Note that the Python functions
copy.copy()
andcopy.deepcopy()
can be used to create completely shallow or completely deep copies of objects of this class.- Any mutable object types (see CIM data types) in the
-
update
(*args, **kwargs)[source]¶ Update the keybindings of this CIM instance path.
Existing keybindings will be updated, and new keybindings will be added.
Parameters: - *args (list) – Keybindings for updating the keybindings of the instance path,
specified as positional arguments. Each positional argument must
be a tuple (key, value), where key and value are described for
setting the
keybindings
property. - **kwargs (dict) – Keybindings for updating the keybindings of the instance path,
specified as keyword arguments. The name and value of the keyword
arguments are described as key and value for setting the
keybindings
property.
- *args (list) – Keybindings for updating the keybindings of the instance path,
specified as positional arguments. Each positional argument must
be a tuple (key, value), where key and value are described for
setting the
-
has_key
(key)[source]¶ Return a boolean indicating whether this CIM instance path has a particular keybinding.
Parameters: key (string) – Name of the keybinding (in any lexical case). Returns: Boolean indicating whether this CIM instance path has the keybinding. Return type: bool
-
get
(key, default=None)[source]¶ Return the value of a particular keybinding of this CIM instance path, or a default value.
New in pywbem 0.8.
Parameters: - key (string) – Name of the keybinding (in any lexical case).
- default (CIM data type) – Default value that is returned if a keybinding with the specified name does not exist in the instance path.
Returns: Value of the keybinding, or the default value.
Return type:
-
keys
()[source]¶ Return the keybinding names of this CIM instance path.
The type of the returned object is consistent with the behavior of the corresponding method of the built-in dict class: On Python 2, a list is returned; on Python 3, a dictionary view is returned.
The keybinding names have their original lexical case and the order of keybindings is preserved.
-
values
()[source]¶ Return the keybinding values of this CIM instance path.
The type of the returned object is consistent with the behavior of the corresponding method of the built-in dict class: On Python 2, a list is returned; on Python 3, a dictionary view is returned.
The order of keybindings is preserved.
-
items
()[source]¶ Return the keybinding items as a tuple (name, value) of this CIM instance path.
The type of the returned object is consistent with the behavior of the corresponding method of the built-in dict class: On Python 2, a list is returned; on Python 3, a dictionary view is returned.
The keybinding names have their original lexical case and the order of keybindings is preserved.
-
iterkeys
()[source]¶ Return an iterator through the keybinding names of this CIM instance path.
The keybinding names have their original lexical case, and the order of keybindings is preserved.
Deprecated: This method is deprecated on Python 3 and will be removed in a future version of pywbem, consistent with the built-in dict class on Python 3. Use the
keys()
method instead.
-
itervalues
()[source]¶ Return an iterator through the keybinding values of this CIM instance path.
The order of keybindings is preserved.
Deprecated: This method is deprecated on Python 3 and will be removed in a future version of pywbem, consistent with the built-in dict class on Python 3. Use the
values()
method instead.
-
iteritems
()[source]¶ Return an iterator through the keybinding items of this CIM instance path, where each item is a tuple of keybinding name and value.
The keybinding names have their original lexical case, and the order of keybindings is preserved.
Deprecated: This method is deprecated on Python 3 and will be removed in a future version of pywbem, consistent with the built-in dict class on Python 3. Use the
items()
method instead.
-
tocimxml
(ignore_host=False, ignore_namespace=False)[source]¶ Return the CIM-XML representation of this CIM instance path, as an object of an appropriate subclass of Element.
If the instance path has no namespace specified or if ignore_namespace is True, the returned CIM-XML representation is an INSTANCENAME element consistent with DSP0201.
Otherwise, if the instance path has no host specified or if ignore_host is True, the returned CIM-XML representation is a LOCALINSTANCEPATH element consistent with DSP0201.
Otherwise, the returned CIM-XML representation is a INSTANCEPATH element consistent with DSP0201.
The order of keybindings in the returned CIM-XML representation is preserved from the
CIMInstanceName
object.CIMInstanceName
objects without keybindings cause a UserWarning to be issued, because this is invalid according to DSP0004 (section 7.7.5).Parameters: Returns: The CIM-XML representation, as an object of an appropriate subclass of Element.
-
tocimxmlstr
(indent=None, ignore_host=False, ignore_namespace=False)[source]¶ Return the CIM-XML representation of this CIM instance path, as a unicode string.
New in pywbem 0.9.
For the returned CIM-XML representation, see
tocimxml()
.Parameters: - indent (string or integer) –
None indicates that a single-line version of the XML should be returned, without any whitespace between the XML elements.
Other values indicate that a prettified, multi-line version of the XML should be returned. A string value specifies the indentation string to be used for each level of nested XML elements. An integer value specifies an indentation string of so many blanks.
- ignore_host (
bool
) – Ignore the host of the instance path, even if a host is specified. - ignore_namespace (
bool
) – Ignore the namespace and host of the instance path, even if a namespace and/or host is specified.
Returns: The CIM-XML representation of the value, as a unicode string.
- indent (string or integer) –
-
static
from_wbem_uri
(wbem_uri)[source]¶ Return a new
CIMInstanceName
object from the specified WBEM URI string.New in pywbem 0.12.
The WBEM URI string must be a CIM instance path in untyped WBEM URI format, as defined in DSP0207, with these extensions:
- DSP0207 restricts the namespace types (URI schemes) to be one
of
http
,https
,cimxml-wbem
, orcimxml-wbems
. Pywbem tolerates any namespace type, but issues aUserWarning
if it is not one of the namespace types defined in DSP0207. - DSP0207 requires a slash before the namespace name. For local WBEM URIs (no namespace type, no authority), that slash is the first character of the WBEM URI. For historical reasons, pywbem tolerates a missing leading slash for local WBEM URIs. Note that pywbem requires the slash (consistent with DSP0207) when the WBEM URI is not local.
- DSP0207 requires a colon before the class name. For historical reasons, pywbem tolerates a missing colon before the class name, if it would have been the first character of the string.
- DSP0207 requires datetime values in keybindings to be
surrounded by double quotes. For historical reasons, pywbem tolerates
datetime values that are not surrounded by double quotes, but issues
a
UserWarning
. - DSP0207 does not allow the special float values INF, -INF, and NaN in WBEM URIs (according to realValue in DSP0004). However, the CIM-XML protocol supports representation of these special values, so to be on the safe side, pywbem supports these special values as keybindings in WBEM URIs.
Keybindings that are references are supported, recursively.
CIM instance paths in the typed WBEM URI format defined in DSP0207 are not supported.
The untyped WBEM URI format defined in DSP0207 has the following limitations when interpreting a WBEM URI string:
- It cannot distinguish string-typed keys with a value that is a datetime value from datetime-typed keys with such a value. Pywbem treats such values as datetime-typed keys.
- It cannot distinguish string-typed keys with a value that is a WBEM URI from reference-typed keys with such a value. Pywbem treats such values as reference-typed keys.
Examples:
https://jdd:test@acme.com:5989/cimv2/test:CIM_RegisteredProfile.InstanceID="acme.1" //jdd:test@acme.com:5989/cimv2/test:CIM_RegisteredProfile.InstanceID="acme.1" /cimv2/test:CIM_RegisteredProfile.InstanceID="acme.1" cimv2/test:CIM_RegisteredProfile.InstanceID="acme.1" /:CIM_RegisteredProfile.InstanceID="acme.1" :CIM_RegisteredProfile.InstanceID="acme.1" CIM_RegisteredProfile.InstanceID="acme.1" http://acme.com/root/cimv2:CIM_ComputerSystem.CreationClassName="ACME_CS",Name="sys1" /:CIM_SubProfile.Main="/:CIM_RegisteredProfile.InstanceID="acme.1"",Sub="/:CIM_RegisteredProfile.InstanceID="acme.2""
Parameters: wbem_uri (string) – WBEM URI for an instance path. Returns: The instance path created from the specified WBEM URI string. Return type: CIMInstanceName
Raises: ValueError
– Invalid WBEM URI format for an instance path. This includes typed WBEM URIs.- DSP0207 restricts the namespace types (URI schemes) to be one
of
-
to_wbem_uri
(format='standard')[source]¶ Return the (untyped) WBEM URI string of this CIM instance path.
The returned WBEM URI contains its components as follows:
- it does not contain a namespace type (URI scheme).
- it contains an authority (host) component according to the
host
attribute, if that is not None. Otherwise, it does not contain the authority component. - it contains a namespace component according to the
namespace
attribute, if that is not None. Otherwise, it does not contain the namespace component. - it contains a class name component according to the
classname
attribute. - it contains keybindings according to the
keybindings
attribute, with the order of keybindings in alphabetical order of the keybinding names, and the lexical case of keybinding names preserved (except when using the format “canonical”).
Note that when you do not want some of these components to show up in the resulting WBEM URI string, you can set them to None before calling this method.
Except when using the format “canonical”, this method should not be used to compare instance paths for equality: DSP0004 defines defines several components of an instance path to be compared case insensitively, including the names of keybindings. In addition, it defines that the order of keybindings in instance paths does not matter for the comparison. Therefore, two instance paths that are considered equal according to DSP0004 may not have equal WBEM URI strings as returned by this method.
Instead, equality of instance paths represented by
CIMInstanceName
objects should be determined by using the==
operator, which performs the comparison conformant to DSP0004. If you have WBEM URI strings without the correspondingCIMInstanceName
object, such an object can be created by using the static methodfrom_wbem_uri()
.Parameters: format (string) – Format for the generated WBEM URI string, using one of the following values:
"standard"
- Standard format that is conformant to untyped WBEM URIs for instance paths defined in DSP0207. The order of keybindings is in alphabetical order of the original keybinding names."canonical"
- Like"standard"
, except that the following items have been converted to lower case: host, namespace, classname, and the names of any keybindings. The order of keybindings is in alphabetical order of the lower-cased keybinding names. This format guarantees that two instance paths that are considered equal according to DSP0004 result in equal WBEM URI strings. Therefore, the returned WBEM URI is suitable to be used as a key in dictionaries of CIM instances."cimobject"
- Format for the CIMObject header field in CIM-XML messages for representing instance paths (used internally, see DSP0200)."historical"
- Historical format for WBEM URIs (used by__str__()
; should not be used by new code). The historical format has the following differences to the standard format:- If the host component is not present, the slash after the host is also omitted. In the standard format, that slash is always present.
- If the namespace component is not present, the colon after the namespace is also omitted. In the standard format, that colon is always present.
Keybindings that are references use the specified format recursively.
Examples:
With host and namespace, standard format:
//ACME.com/cimv2/Test:CIM_RegisteredProfile.InstanceID="Acme.1"
With host and namespace, canonical format:
//acme.com/cimv2/test:cim_registeredprofile.instanceid="Acme.1"
Without host but with namespace, standard format:
/cimv2/Test:CIM_RegisteredProfile.InstanceID="Acme.1"
Without host but with namespace, canonical format:
/cimv2/test:cim_registeredprofile.instanceid="Acme.1"
Without host and without namespace, standard format:
/:CIM_RegisteredProfile.InstanceID="Acme.1"
Returns: Untyped WBEM URI of the CIM instance path, in the specified format.
Return type: Raises: TypeError
– Invalid type in keybindingsValueError
– Invalid format argument
-
static
from_instance
(class_, instance, namespace=None, host=None, strict=False)[source]¶ Return a new
CIMInstanceName
object from the key property values in a CIM instance and the key property definitions in a CIM class.If the strict parameter is False, and a property value does not exist in the instance that entry is not included in the constructed CIMInstanceName
If the strict parameter is True all key properties in the class_ must exist in the instance or a ValueError exception is raised.
Parameters: - class_ (
CIMClass
) –The CIM class with the key properties.
In strict mode, that class and the instance must contain all key properties that are required to create the
CIMInstanceName
object. Thus, for example, if the class were retrieved from a server, generally, the LocalOnly parameter in the request should be False to assure that superclass properties are retrieved and IncludeQualifiers parameter should be set to True to assure that qualifiers are retrieved.In non-strict mode, that class and instance may have missing key properties. Any missing key properties will result in missing key bindings in the created
CIMInstanceName
object.The specified class does not need to be the creation class of the instance. Thus, it could be a superclass as long as it has the required key properties.
- instance (
CIMInstance
) – The CIM instance with the key property values. - namespace (string) – Namespace to include in the created
CIMInstanceName
or None. - host (string) – Host name to include in created
CIMInstanceName
or None. - strict (
bool
) – Strict mode (see description of class_ parameter).
Returns: CIMInstanceName
built from the key properties in the class_ parameter using the key property values in the instance parameter.Return type: Raises: ValueError
– The strict attribute is True and a key property does not exist in the instance.- class_ (
- classname (string) –
CIMInstance¶
-
class
pywbem.
CIMInstance
(classname, properties=None, qualifiers=None, path=None)[source]¶ A representation of a CIM instance in a CIM namespace in a WBEM server, optionally including its instance path.
Two objects of this class compare equal if their public attributes compare equal. Objects of this class are unchanged-hashable, with the hash value being based on its public attributes. Therefore, objects of this class can be used as members in a set (or as dictionary keys) only during periods in which their public attributes remain unchanged.
Parameters: - classname (string) –
Name of the creation class for the instance.
Must not be None.
The lexical case of the string is preserved. Object comparison and hash value calculation are performed case-insensitively.
- properties (properties input object) –
The property values for the instance.
Deprecated: Providing key property values will cause the corresponding keybindings in the instance path (if set) to be updated accordingly. This behavior has been deprecated in pywbem 1.1.0 and will be removed in a future version of pywbem.
- qualifiers (qualifiers input object) –
The qualifiers for the instance.
Note that DSP0200 has deprecated the presence of qualifiers on CIM instances.
- path (
CIMInstanceName
) –Instance path for the instance.
The provided object will be copied before being stored in the
CIMInstance
object.None means that the instance path is unspecified, and the
path
attribute will also be None.
Raises: ValueError
– classname is None, a property or qualifier name is None, or a property or qualifier name does not match its dictionary key.TypeError
– a numeric Python type was used for a property or qualifier value.
Methods
copy
Return a new CIMInstance
object that is a copy of this CIM instance.from_class
Return a new CIMInstance
object from specified key property values and from the key property definitions in a class.get
Return the value of a particular property of this CIM instance, or a default value. has_key
Return a boolean indicating whether this CIM instance has a particular property. items
Return the properties of this CIM instance, where each item is a tuple of property name and value (the value
attribute of theCIMProperty
object).iteritems
Return an iterator through the properties of this CIM instance, where each item is a tuple of property name and value. iterkeys
Return an iterator through the property names of this CIM instance. itervalues
Return an iterator through the property values of this CIM instance. keys
Return the property names of this CIM instance. tocimxml
Return the CIM-XML representation of this CIM instance, as an object of an appropriate subclass of Element. tocimxmlstr
Return the CIM-XML representation of this CIM instance, as a unicode string. tomof
Return a MOF string with the specification of this CIM instance. update
Update the properties of this CIM instance. update_existing
Update the values of already existing properties of this CIM instance. values
Return the property values (the value
attribute of theCIMProperty
object) of this CIM instance.Attributes
classname
Name of the creation class of this CIM instance. path
Instance path of this CIM instance. properties
Properties of this CIM instance. qualifiers
Qualifiers (qualifier values) of this CIM instance. Details
-
classname
¶ Name of the creation class of this CIM instance.
Will not be None.
This attribute is settable. For details, see the description of the same-named init parameter of
this class
.Type: unicode string
-
properties
¶ Properties of this CIM instance.
Will not be None.
Each dictionary item specifies one property value, with:
- key (unicode string): Property name. Its lexical case was preserved.
- value (
CIMProperty
): Property value.
The order of properties in the CIM instance is preserved.
This attribute is settable; setting it will cause the current CIM properties to be replaced with the new properties.
Deprecated: Updating a key property will cause the corresponding keybinding in the instance path (if set) to be updated accordingly. This behavior has been deprecated in pywbem 1.1.0 and will be removed in a future version of pywbem.
For details, see the description of the same-named init parameter. Note that the property value may be specified as a CIM data type or as a
CIMProperty
object.The CIM property values can also be accessed and manipulated one by one because the attribute value is a modifiable dictionary. In that case, the provided input value must be a
CIMProperty
object. A corresponding keybinding in the instance path (if set) will not (!) be updated in this case:inst = CIMInstance(...) p1 = CIMProperty('p1', ...) # must be CIMProperty inst.properties['p1'] = p1 # Set "p1" to p1 (add if needed) p1 = inst.properties['p1'] # Access "p1" del inst.properties['p1'] # Delete "p1" from the instance
In addition, the CIM properties can be accessed and manipulated one by one by using the entire
CIMInstance
object like a dictionary. In that case, the provided input value may be specified as a CIM data type or as aCIMProperty
object:inst = CIMInstance(...) p2 = Uint32(...) # may be CIM data type or CIMProperty inst['p2'] = p2 # Set "p2" to p2 (add if needed) p2 = inst['p2'] # Access "p2" del inst['p2'] # Delete "p2" from the instance
Type: NocaseDict
-
qualifiers
¶ Qualifiers (qualifier values) of this CIM instance.
Will not be None.
Each dictionary item specifies one qualifier value, with:
- key (unicode string): Qualifier name. Its lexical case was preserved.
- value (
CIMQualifier
): Qualifier value.
The order of qualifiers in the CIM instance is preserved.
This attribute is settable; setting it will cause the current qualifiers to be replaced with the new qualifiers. For details, see the description of the same-named init parameter of
this class
.The qualifier values can also be accessed and manipulated one by one because the attribute value is a modifiable dictionary.
Note that DSP0200 has deprecated the presence of qualifier values on CIM instances.
Type: NocaseDict
-
path
¶ Instance path of this CIM instance.
None means that the instance path is unspecified.
This attribute is settable. For details, see the description of the same-named init parameter of
this class
.Type: CIMInstanceName
-
__eq__
(other)[source]¶ Equality test function for two
CIMInstance
objects.The equality is based on some of their public attributes, in descending precedence:
- classname
- path
- properties
- qualifiers
The equality test takes into account any case insensitivities described for these attributes.
Raises TypeError’, if the `other object is not a
CIMInstance
object.
-
__str__
()[source]¶ Return a short string representation of this CIM instance, for human consumption.
-
__repr__
()[source]¶ Return a string representation of this CIM instance, that is suitable for debugging.
The properties and qualifiers will be ordered by their names in the result.
-
copy
()[source]¶ Return a new
CIMInstance
object that is a copy of this CIM instance.This is a middle-deep copy; any mutable types in attributes except the following are copied, so besides these exceptions, modifications of the original object will not affect the returned copy, and vice versa. The following mutable types are not copied and are therefore shared between original and copy:
- The
CIMProperty
objects in theproperties
dictionary (but not the dictionary object itself) - The
CIMQualifier
objects in thequalifiers
dictionary (but not the dictionary object itself)
Note that the Python functions
copy.copy()
andcopy.deepcopy()
can be used to create completely shallow or completely deep copies of objects of this class.- The
-
update
(*args, **kwargs)[source]¶ Update the properties of this CIM instance.
Existing properties will be updated, and new properties will be added.
Parameters: - *args (list) – Properties for updating the properties of the instance, specified
as positional arguments. Each positional argument must be a tuple
(key, value), where key and value are described for setting the
properties
property. - **kwargs (dict) – Properties for updating the properties of the instance, specified
as keyword arguments. The name and value of the keyword arguments
are described as key and value for setting the
properties
property.
- *args (list) – Properties for updating the properties of the instance, specified
as positional arguments. Each positional argument must be a tuple
(key, value), where key and value are described for setting the
-
update_existing
(*args, **kwargs)[source]¶ Update the values of already existing properties of this CIM instance.
From the specified new properties, only properties that already exist in the instance will be updated. New properties will not be added to the instance; they will be ignored without further notice.
Parameters: - *args (list) –
New properties, specified as positional arguments. Each positional argument must be one of:
- an iterable of tuple (name, value), where each tuple specifies the name of the property to be updated and its new value.
- an object with an
items()
method that iterates through tuple (name, value), where each tuple specifies the name of the property to be updated and its new value.Examples of such objects are
CIMInstanceName
(where its keybindings will be used as new properties) orCIMInstance
(where its properties will be used as new properties).
- **kwargs (dict) – New properties, specified as keyword arguments. Each keyword argument specifies one new property, where the argument name is the name of the property to be updated and the argument value is its new value.
- *args (list) –
-
has_key
(key)[source]¶ Return a boolean indicating whether this CIM instance has a particular property.
Parameters: key (string) – Name of the property (in any lexical case). Returns: Boolean indicating whether the instance has the property. Return type: bool
-
get
(key, default=None)[source]¶ Return the value of a particular property of this CIM instance, or a default value.
New in pywbem 0.8.
Parameters: - key (string) – Name of the property (in any lexical case).
- default (CIM data type) – Default value that is returned if a property with the specified name does not exist in the instance.
Returns: Value of the property, or the default value.
Return type:
-
keys
()[source]¶ Return the property names of this CIM instance.
The type of the returned object is consistent with the behavior of the corresponding method of the built-in dict class: On Python 2, a list is returned; on Python 3, a dictionary view is returned.
The property names have their original lexical case, and the order of properties is preserved.
-
values
()[source]¶ Return the property values (the
value
attribute of theCIMProperty
object) of this CIM instance.The type of the returned object is consistent with the behavior of the corresponding method of the built-in dict class: On Python 2, a list is returned; on Python 3, a dictionary view is returned.
The order of properties is preserved.
-
items
()[source]¶ Return the properties of this CIM instance, where each item is a tuple of property name and value (the
value
attribute of theCIMProperty
object).The type of the returned object is consistent with the behavior of the corresponding method of the built-in dict class: On Python 2, a list is returned; on Python 3, a dictionary view is returned.
The property names have their original lexical case, and the order of properties is preserved.
-
iterkeys
()[source]¶ Return an iterator through the property names of this CIM instance.
The property names have their original lexical case, and the order of properties is preserved.
Deprecated: This method is deprecated on Python 3 and will be removed in a future version of pywbem, consistent with the built-in dict class on Python 3. Use the
keys()
method instead.
-
itervalues
()[source]¶ Return an iterator through the property values of this CIM instance.
The property values are the
value
attributes of theCIMProperty
objects.The order of properties is preserved.
Deprecated: This method is deprecated on Python 3 and will be removed in a future version of pywbem, consistent with the built-in dict class on Python 3. Use the
values()
method instead.
-
iteritems
()[source]¶ Return an iterator through the properties of this CIM instance, where each item is a tuple of property name and value.
The property values are the
value
attributes of theCIMProperty
objects.The property names have their original lexical case, and the order of properties is preserved.
Deprecated: This method is deprecated on Python 3 and will be removed in a future version of pywbem, consistent with the built-in dict class on Python 3. Use the
items()
method instead.
-
tocimxml
(ignore_path=False)[source]¶ Return the CIM-XML representation of this CIM instance, as an object of an appropriate subclass of Element.
If the instance has no instance path specified or if ignore_path is True, the returned CIM-XML representation is an INSTANCE element consistent with DSP0201. This is the required element for representing embedded instances.
Otherwise, if the instance path of the instance has no namespace specified, the returned CIM-XML representation is an VALUE.NAMEDINSTANCE element consistent with DSP0201.
Otherwise, if the instance path of the instance has no host specified, the returned CIM-XML representation is a VALUE.OBJECTWITHLOCALPATH element consistent with DSP0201.
Otherwise, the returned CIM-XML representation is a VALUE.INSTANCEWITHPATH element consistent with DSP0201.
The order of properties and qualifiers in the returned CIM-XML representation is preserved from the
CIMInstance
object.Parameters: ignore_path ( bool
) – Ignore the path of the instance, even if a path is specified.Returns: The CIM-XML representation, as an object of an appropriate subclass of Element.
-
tocimxmlstr
(indent=None, ignore_path=False)[source]¶ Return the CIM-XML representation of this CIM instance, as a unicode string.
New in pywbem 0.9.
For the returned CIM-XML representation, see
tocimxml()
.Parameters: - indent (string or integer) –
None indicates that a single-line version of the XML should be returned, without any whitespace between the XML elements.
Other values indicate that a prettified, multi-line version of the XML should be returned. A string value specifies the indentation string to be used for each level of nested XML elements. An integer value specifies an indentation string of so many blanks.
- ignore_path (
bool
) – Ignore the path of the instance, even if a path is specified.
Returns: The CIM-XML representation of the object, as a unicode string.
- indent (string or integer) –
-
tomof
(maxline=80)[source]¶ Return a MOF string with the specification of this CIM instance.
The returned MOF string conforms to the
instanceDeclaration
ABNF rule defined in DSP0004, with the following limitations:- Pywbem does not support instance aliases, so the returned MOF string does not define an alias name for the instance.
- Even though pywbem supports qualifiers on
CIMInstance
objects, and onCIMProperty
objects that are used as property values within an instance, the returned MOF string does not contain any qualifier values on the instance or on its property values.
The order of properties and qualifiers is preserved.
Parameters: maxline (integer) – Maximum line length. Returns: MOF string. Return type: unicode string
-
static
from_class
(klass, namespace=None, property_values=None, include_missing_properties=True, include_path=True, include_class_origin=False)[source]¶ Return a new
CIMInstance
object from specified key property values and from the key property definitions in a class.The properties in the returned instance do not have any qualifiers.
Parameters: - klass (
CIMClass
) – CIMClass from which the instance will be constructed. This class must include qualifiers and should include properties from any superclasses in the model insure it includes all properties that are to be built into the instance, in particular any key properties if the include+path parameter is True. Seefrom_class()
for further requirements on the class. - namespace (string) – Namespace to be included in the path component of the returned CIMInstance if include_path parameter is True.
- property_values (
dict
or NocaseDict) – Dictionary containing name/value pairs where the names are the names of properties in the class and the properties are the property values to be set into the instance properties. The values must match the type defined for the property in the class. If a property is in the property_values dictionary but not in the class a ValueError exception is raised. Not all properties in the class need to be defined in property_values. - include_missing_properties –
Determines if properties not in the property_values parameter are included in the instance.
If True all properties from the class are included in the new instance including those not defined in property_values parameter with with the default value defined in the class if one is defined, or otherwise None”.
If False only properties in the property_values parameter are included in the new instance.
Returns: A CIM instance created from klass and property_values parameters with the defined properties and optionally the path component set.
No qualifiers are included in the returned instance and the existence of the class origin attribute depends on the include_class_origin parameter.
All other attributes of each property are the same as the corresponding class property.
Return type: Raises: ValueError
– Conflicts between the class properties and- property_values parameter or the instance does
- not include all key properties defined in the class.
TypeError
– Mismatch between types of the property values in- property_values parameter and the property type in the
- corresponding class property
- klass (
- classname (string) –
CIMClassName¶
-
class
pywbem.
CIMClassName
(classname, host=None, namespace=None)[source]¶ A CIM class path (aka CIM class name).
A CIM class path references a CIM class in a CIM namespace in a WBEM server. Namespace and WBEM server may be unspecified.
Two objects of this class compare equal if their public attributes compare equal. Objects of this class are unchanged-hashable, with the hash value being based on its public attributes. Therefore, objects of this class can be used as members in a set (or as dictionary keys) only during periods in which their public attributes remain unchanged.
Parameters: - classname (string) –
Class name of the referenced class.
Must not be None.
The lexical case of the string is preserved. Object comparison and hash value calculation are performed case-insensitively.
- host (string) –
Host and optionally port of the WBEM server containing the CIM namespace of the referenced class.
The format of the string must be:
host[:port]
The host can be specified in any of the usual formats:
- a short or fully qualified DNS hostname
- a literal (= dotted) IPv4 address
- a literal IPv6 address, formatted as defined in RFC3986
with the extensions for zone identifiers as defined in
RFC6874, supporting
-
(minus) for the delimiter before the zone ID string, as an additional choice to%25
.
None means that the WBEM server is unspecified, and the
host
attribute will also be None.The lexical case of the string is preserved. Object comparison and hash value calculation are performed case-insensitively.
- namespace (string) –
Name of the CIM namespace containing the referenced class.
None means that the namespace is unspecified, and the
namespace
attribute will also be None.Leading and trailing slash characters will be stripped. The lexical case of the string is preserved. Object comparison and hash value calculation are performed case-insensitively.
Raises: ValueError
– classname is None.Methods
copy
Return a new CIMClassName
object that is a copy of this CIM class path.from_wbem_uri
Return a new CIMClassName
object from the specified WBEM URI string.to_wbem_uri
Return the (untyped) WBEM URI string of this CIM class path. tocimxml
Return the CIM-XML representation of this CIM class path, as an object of an appropriate subclass of Element. tocimxmlstr
Return the CIM-XML representation of this CIM class path, as a unicode string. Attributes
classname
Class name of this CIM class path, identifying the referenced class. host
Host and optionally port of this CIM class path, identifying the WBEM server of the referenced class. namespace
Namespace name of this CIM class path, identifying the namespace of the referenced class. Details
-
classname
¶ Class name of this CIM class path, identifying the referenced class.
Will not be None.
This attribute is settable. For details, see the description of the same-named init parameter of
this class
.Type: unicode string
-
namespace
¶ Namespace name of this CIM class path, identifying the namespace of the referenced class.
None means that the namespace is unspecified.
This attribute is settable. For details, see the description of the same-named init parameter of
this class
.Type: unicode string
-
host
¶ Host and optionally port of this CIM class path, identifying the WBEM server of the referenced class.
For details about the string format, see the same-named init parameter of
this class
.None means that the host and port are unspecified.
This attribute is settable. For details, see the description of the same-named init parameter.
Type: unicode string
-
copy
()[source]¶ Return a new
CIMClassName
object that is a copy of this CIM class path.Objects of this class have no mutable types in any attributes, so modifications of the original object will not affect the returned copy, and vice versa.
Note that the Python functions
copy.copy()
andcopy.deepcopy()
can be used to create completely shallow or completely deep copies of objects of this class.
-
__eq__
(other)[source]¶ Equality test function for two
CIMClassName
objects.The equality is based on their public attributes, in descending precedence:
- host
- namespace
- classname
The equality test takes into account any case insensitivities described for these attributes.
Raises TypeError’, if the `other object is not a
CIMClassName
object.
-
__str__
()[source]¶ Return a WBEM URI string of this CIM class path.
The returned WBEM URI string is in the historical format returned by
to_wbem_uri()
.For new code, it is recommended that the standard format is used; it is returned by
to_wbem_uri()
as the default format.If you want to access the class name, use the
classname
attribute, instead of relying on the coincidence that the historical format of a WBEM URI without host and namespace happens to be the class name.Examples (for the historical format):
With host and namespace:
//acme.com/cimv2/test:CIM_RegisteredProfile
Without host but with namespace:
cimv2/test:CIM_RegisteredProfile
Without host and without namespace:
CIM_RegisteredProfile
-
__repr__
()[source]¶ Return a string representation of this CIM class path, that is suitable for debugging.
-
tocimxml
(ignore_host=False, ignore_namespace=False)[source]¶ Return the CIM-XML representation of this CIM class path, as an object of an appropriate subclass of Element.
If the class path has no namespace specified or if ignore_namespace is True, the returned CIM-XML representation is a CLASSNAME element consistent with DSP0201.
Otherwise, if the class path has no host specified or if ignore_host is True, the returned CIM-XML representation is a LOCALCLASSPATH element consistent with DSP0201.
Otherwise, the returned CIM-XML representation is a CLASSPATH element consistent with DSP0201.
Parameters: Returns: The CIM-XML representation, as an object of an appropriate subclass of Element.
-
tocimxmlstr
(indent=None, ignore_host=False, ignore_namespace=False)[source]¶ Return the CIM-XML representation of this CIM class path, as a unicode string.
New in pywbem 0.9.
For the returned CIM-XML representation, see
tocimxml()
.Parameters: - indent (string or integer) –
None indicates that a single-line version of the XML should be returned, without any whitespace between the XML elements.
Other values indicate that a prettified, multi-line version of the XML should be returned. A string value specifies the indentation string to be used for each level of nested XML elements. An integer value specifies an indentation string of so many blanks.
- ignore_host (
bool
) – Ignore the host of the class path, even if a host is specified. - ignore_namespace (
bool
) – Ignore the namespace and host of the class path, even if a namespace and/or host is specified.
Returns: The CIM-XML representation of the object, as a unicode string.
- indent (string or integer) –
-
static
from_wbem_uri
(wbem_uri)[source]¶ Return a new
CIMClassName
object from the specified WBEM URI string.New in pywbem 0.12.
The WBEM URI string must be a CIM class path in untyped WBEM URI format, as defined in DSP0207, with these extensions:
- DSP0207 restricts the namespace types (URI schemes) to be one
of
http
,https
,cimxml-wbem
, orcimxml-wbems
. Pywbem tolerates any namespace type, but issues aUserWarning
if it is not one of the namespace types defined in DSP0207. - DSP0207 requires a slash before the namespace name. For local WBEM URIs (no namespace type, no authority), that slash is the first character of the WBEM URI. For historical reasons, pywbem tolerates a missing leading slash for local WBEM URIs. Note that pywbem requires the slash (consistent with DSP0207) when the WBEM URI is not local.
- DSP0207 requires a colon before the class name. For historical reasons, pywbem tolerates a missing colon before the class name, if it would have been the first character of the string.
CIM class paths in the typed WBEM URI format defined in DSP0207 are not supported.
Examples:
https://jdd:test@acme.com:5989/cimv2/test:CIM_RegisteredProfile http://acme.com/root/cimv2:CIM_ComputerSystem http:/root/cimv2:CIM_ComputerSystem /root/cimv2:CIM_ComputerSystem root/cimv2:CIM_ComputerSystem /:CIM_ComputerSystem :CIM_ComputerSystem CIM_ComputerSystem
Parameters: wbem_uri (string) – WBEM URI for a class path. Returns: The class path created from the specified WBEM URI string. Return type: CIMClassName
Raises: ValueError
– Invalid WBEM URI format for a class path. This includes typed WBEM URIs.- DSP0207 restricts the namespace types (URI schemes) to be one
of
-
to_wbem_uri
(format='standard')[source]¶ Return the (untyped) WBEM URI string of this CIM class path.
The returned WBEM URI contains its components as follows:
- it does not contain a namespace type (URI scheme).
- it contains an authority (host) component according to the
host
attribute, if that is not None. Otherwise, it does not contain the authority component. - it contains a namespace component according to the
namespace
attribute, if that is not None. Otherwise, it does not contain the namespace component. - it contains a class name component according to the
classname
attribute.
Note that when you do not want some of these components to show up in the resulting WBEM URI string, you can set them to None before calling this method.
Except when using the format “canonical”, this method should not be used to compare class paths for equality: DSP0004 defines several components of a class path to be compared case insensitively. All WBEM URI formats returned by this method except for the format “canonical” return a WBEM URI string that preserves the lexical case of any components. Therefore, two class paths that are considered equal according to DSP0004 may not have equal WBEM URI strings as as returned by this method.
Instead, equality of class paths represented by
CIMClassName
objects should be determined by using the==
operator, which performs the comparison conformant to DSP0004. If you have WBEM URI strings without the correspondingCIMClassName
object, such an object can be created by using the static methodfrom_wbem_uri()
.Parameters: format (string) – Format for the generated WBEM URI string, using one of the following values:
"standard"
- Standard format that is conformant to untyped WBEM URIs for class paths defined in DSP0207."canonical"
- Like"standard"
, except that the following items have been converted to lower case: host, namespace, and classname. This format guarantees that two class paths that are considered equal according to DSP0004 result in equal WBEM URI strings. Therefore, the returned WBEM URI is suitable to be used as a key in dictionaries of CIM classes."cimobject"
- Format for the CIMObject header field in CIM-XML messages for representing class paths (used internally, see DSP0200)."historical"
- Historical format for WBEM URIs (used by__str__()
; should not be used by new code). The historical format has the following differences to the standard format:- If the host component is not present, the slash after the host is also omitted. In the standard format, that slash is always present.
- If the namespace component is not present, the colon after the namespace is also omitted. In the standard format, that colon is always present.
Examples:
With host and namespace, standard format:
//ACME.com/cimv2/Test:CIM_RegisteredProfile
With host and namespace, canonical format:
//acme.com/cimv2/test:cim_registeredprofile
Without host but with namespace, standard format:
/cimv2/Test:CIM_RegisteredProfile
Without host but with namespace, canonical format:
/cimv2/test:cim_registeredprofile
Without host and without namespace, standard format:
/:CIM_RegisteredProfile
Returns: Untyped WBEM URI of the CIM class path, in the specified format. Return type: unicode string Raises: ValueError
– Invalid format
- classname (string) –
CIMClass¶
-
class
pywbem.
CIMClass
(classname, properties=None, methods=None, superclass=None, qualifiers=None, path=None)[source]¶ A representation of a CIM class in a CIM namespace in a WBEM server, optionally including its class path.
Two objects of this class compare equal if their public attributes compare equal. Objects of this class are unchanged-hashable, with the hash value being based on its public attributes. Therefore, objects of this class can be used as members in a set (or as dictionary keys) only during periods in which their public attributes remain unchanged.
Parameters: - classname (string) –
Class name of the class.
Must not be None.
The lexical case of the string is preserved. Object comparison and hash value calculation are performed case-insensitively.
- properties (properties input object) – The property declarations for the class.
- methods (methods input object) – The method declarations for the class.
- superclass (string) –
Name of the superclass for the class.
None means that the class is a top-level class, and the
superclass
attribute will also be None.The lexical case of the string is preserved. Object comparison and hash value calculation are performed case-insensitively.
- qualifiers (qualifiers input object) – The qualifiers for the class.
- path (
CIMClassName
) –Class path for the class.
New in pywbem 0.11.
The provided object will be copied before being stored in the
CIMClass
object.None means that the instance path is unspecified, and the
path
attribute will also be None.This parameter has been added in pywbem 0.11 as a convenience for the user in order so that
CIMClass
objects can be self-contained w.r.t. their class path.
Raises: ValueError
– classname is None, a property, method or qualifier name is None, or a property, method or qualifier name does not match its dictionary key.TypeError
– a numeric Python type was used for a qualifier value.
Methods
copy
Return a new CIMClass
object that is a copy of this CIM class.tocimxml
Return the CIM-XML representation of this CIM class, as an object of an appropriate subclass of Element. tocimxmlstr
Return the CIM-XML representation of this CIM class, as a unicode string. tomof
Return a MOF string with the declaration of this CIM class. Attributes
classname
Class name of this CIM class. methods
Methods (declarations) of this CIM class. path
Class path of this CIM class. properties
Properties (declarations) of this CIM class. qualifiers
Qualifiers (qualifier values) of this CIM class. superclass
Class name of the superclass of this CIM class. Details
-
classname
¶ Class name of this CIM class.
Will not be None.
This attribute is settable. For details, see the description of the same-named init parameter of
this class
.Type: unicode string
-
superclass
¶ Class name of the superclass of this CIM class.
None means that the class is a top-level class.
This attribute is settable. For details, see the description of the same-named init parameter of
this class
.Type: unicode string
-
properties
¶ Properties (declarations) of this CIM class.
Will not be None.
Each dictionary item specifies one property declaration, with:
- key (unicode string): Property name. Its lexical case was preserved.
- value (
CIMProperty
): Property declaration.
The order of properties in the CIM class is preserved.
This attribute is settable; setting it will cause the current CIM properties to be replaced with the new properties. For details, see the description of the same-named init parameter of
this class
.The CIM properties can also be accessed and manipulated one by one because the attribute value is a modifiable dictionary. The provided input value must be a
CIMProperty
object:cls = CIMClass(...) p1 = CIMProperty('p1', ...) # must be a CIMProperty cls.properties['p1'] = p1 # Set "p1" to p1 (add if needed) p1 = cls.properties['p1'] # Access "p1" del cls.properties['p1'] # Delete "p1" from the class
Type: NocaseDict
-
methods
¶ Methods (declarations) of this CIM class.
Will not be None.
Each dictionary item specifies one method, with:
- key (unicode string): Method name. Its lexical case was preserved.
- value (
CIMMethod
): Method declaration.
The order of methods in the CIM class is preserved.
This attribute is settable; setting it will cause the current CIM methods to be replaced with the new methods. For details, see the description of the same-named init parameter of
this class
.The CIM methods can also be accessed and manipulated one by one because the attribute value is a modifiable dictionary. The provided input value must be a
CIMMethod
object:cls = CIMClass(...) m1 = CIMMethod('m1', ...) # must be a CIMMethod cls.methods['m1'] = m1 # Set "m1" to m1 (add if needed) m1 = cls.methods['m1'] # Access "m1" del cls.methods['m1'] # Delete "m1" from the class
Type: NocaseDict
-
qualifiers
¶ Qualifiers (qualifier values) of this CIM class.
Will not be None.
Each dictionary item specifies one qualifier value, with:
- key (unicode string): Qualifier name. Its lexical case was preserved.
- value (
CIMQualifier
): Qualifier value.
The order of qualifiers in the CIM class is preserved.
This attribute is settable; setting it will cause the current qualifiers to be replaced with the new qualifiers. For details, see the description of the same-named init parameter of
this class
.The qualifier values can also be accessed and manipulated one by one because the attribute value is a modifiable dictionary. The provided input value may be specified as a CIM data type or as a
CIMQualifier
object:cls = CIMClass(...) q1 = Uint32(...) # may be CIM data type or CIMQualifier cls.qualifiers['q1'] = q1 # Set "q1" to q1 (add if needed) q1 = cls.qualifiers['q1'] # Access "q1" del cls.qualifiers['q1'] # Delete "q1" from the class
Type: NocaseDict
-
path
¶ Class path of this CIM class.
New in pywbem 0.11.
None means that the class path is unspecified.
This attribute has been added in pywbem 0.11 as a convenience for the user in order so that
CIMClass
objects can be self-contained w.r.t. their class path.This attribute will be set in in any
CIMClass
objects returned byWBEMConnection
methods, based on information in the response from the WBEM server.This attribute is settable. For details, see the description of the same-named init parameter of
this class
.Type: CIMClassName
-
__eq__
(other)[source]¶ Equality test function for two
CIMClass
objects.The equality is based on their public attributes, in descending precedence:
- classname
- superclass
- qualifiers
- properties
- methods
- path
The equality test takes into account any case insensitivities described for these attributes.
Raises TypeError’, if the `other object is not a
CIMClass
object.
-
__repr__
()[source]¶ Return a string representation of this CIM class, that is suitable for debugging.
The order of properties, method and qualifiers will be preserved in the result.
-
copy
()[source]¶ Return a new
CIMClass
object that is a copy of this CIM class.This is a middle-deep copy; any mutable types in attributes except the following are copied, so besides these exceptions, modifications of the original object will not affect the returned copy, and vice versa. The following mutable types are not copied and are therefore shared between original and copy:
- The
CIMProperty
objects in theproperties
dictionary (but not the dictionary object itself) - The
CIMMethod
objects in themethods
dictionary (but not the dictionary object itself) - The
CIMQualifier
objects in thequalifiers
dictionary (but not the dictionary object itself)
Note that the Python functions
copy.copy()
andcopy.deepcopy()
can be used to create completely shallow or completely deep copies of objects of this class.- The
-
tocimxml
()[source]¶ Return the CIM-XML representation of this CIM class, as an object of an appropriate subclass of Element.
The returned CIM-XML representation is a CLASS element consistent with DSP0201. This is the required element for representing embedded classes.
If the class has a class path specified, it will be ignored.
The order of properties, methods, parameters, and qualifiers in the returned CIM-XML representation is preserved from the
CIMClass
object.Returns: The CIM-XML representation, as an object of an appropriate subclass of Element.
-
tocimxmlstr
(indent=None)[source]¶ Return the CIM-XML representation of this CIM class, as a unicode string.
New in pywbem 0.9.
For the returned CIM-XML representation, see
tocimxml()
.Parameters: indent (string or integer) – None indicates that a single-line version of the XML should be returned, without any whitespace between the XML elements.
Other values indicate that a prettified, multi-line version of the XML should be returned. A string value specifies the indentation string to be used for each level of nested XML elements. An integer value specifies an indentation string of so many blanks.
Returns: The CIM-XML representation of the object, as a unicode string.
-
tomof
(maxline=80)[source]¶ Return a MOF string with the declaration of this CIM class.
The returned MOF string conforms to the
classDeclaration
ABNF rule defined in DSP0004.The order of properties, methods, parameters, and qualifiers is preserved.
The
path
attribute of this object will not be included in the returned MOF string.Consistent with that, class path information is not included in the returned MOF string.
Returns: MOF string. Return type: unicode string
- classname (string) –
CIMProperty¶
-
class
pywbem.
CIMProperty
(name, value, type=None, class_origin=None, array_size=None, propagated=None, is_array=None, reference_class=None, qualifiers=None, embedded_object=None)[source]¶ A CIM property (value or declaration).
This object can be used in a
CIMInstance
object for representing a property value, or in aCIMClass
object for representing a property declaration.For property values in CIM instances:
- The value attribute is the actual value of the property.
- Qualifiers are not allowed.
For property declarations in CIM classes:
- The value attribute is the default value of the property declaration.
- Qualifiers are allowed.
Scalar (=non-array) properties may have a value of NULL (= None), any primitive CIM data type, reference type, and string type with embedded instance or embedded object.
Array properties may be Null or may have elements with a value of NULL, any primitive CIM data type, and string type with embedded instance or embedded object. Reference types are not allowed in property arrays in CIM, as per DSP0004.
Two objects of this class compare equal if their public attributes compare equal. Objects of this class are unchanged-hashable, with the hash value being based on its public attributes. Therefore, objects of this class can be used as members in a set (or as dictionary keys) only during periods in which their public attributes remain unchanged.
The init method infers optional parameters that are not specified (for example, it infers type from the Python type of value and other information). If the specified parameters are inconsistent, an exception is raised. If an optional parameter is needed for some reason, an exception is raised.
Parameters: - name (string) –
Name of the property.
Must not be None.
The lexical case of the string is preserved. Object comparison and hash value calculation are performed case-insensitively.
- value (CIM data type or other suitable types) –
Value of the property.
The property value is interpreted as an actual property value when the CIM property is used in a CIM instance, and as default value when the CIM property is used in a CIM class.
None means that the property is Null, and the same-named attribute in the
CIMProperty
object will also be None.The specified value will be converted to a CIM data type using the rules documented in the description of
cimvalue()
, taking into account the type parameter. - type (string) –
Name of the CIM data type of the property (e.g.
"uint8"
).None will cause the type to be inferred from the value parameter, raising
ValueError
if it cannot be inferred (for example when value is None or a Python integer).ValueError
is raised if the type is not a valid CIM data type (see CIM data types). - class_origin (string) –
The CIM class origin of the property (the name of the most derived class that defines or overrides the property in the class hierarchy of the class owning the property).
None means that class origin information is not available, and
class_origin
attribute will also be None.The lexical case of the string is preserved. Object comparison and hash value calculation are performed case-insensitively.
- array_size (integer) –
The size of the array property, for fixed-size arrays.
None means that the array property has variable size, and
array_size
attribute will also be None. - propagated (
bool
) –If not None, specifies whether the property declaration has been propagated from a superclass, or the property value has been propagated from the creation class.
None means that propagation information is not available, and
propagated
attribute will also be None. - is_array (
bool
) –A boolean indicating whether the property is an array (True) or a scalar (False).
If None, the
is_array
attribute will be inferred from the value parameter. If the value parameter is None, a scalar is assumed. - reference_class (string) –
For reference properties, the name of the class referenced by the property, or None indicating that the referenced class is unspecified.
For non-reference properties, must be None.
The lexical case of the string is preserved. Object comparison and hash value calculation are performed case-insensitively.
Note: Prior to pywbem 0.11, the corresponding attribute was inferred from the creation class name of a referenced instance. This was incorrect and has been fixed in pywbem 0.11.
- qualifiers (qualifiers input object) – The qualifiers for the property declaration. Has no meaning for property values.
- embedded_object (string) –
A string value indicating the kind of embedded object represented by the property value. Has no meaning for property declarations.
For details about the possible values, see the corresponding attribute.
None means that the value is unspecified, causing the same-named attribute in the
CIMProperty
object to be inferred. An exception is raised if it cannot be inferred.False means the property value is not an embedded object, and is stored as None.
Examples:
# a string property: CIMProperty("MyString", "abc") # a uint8 property: CIMProperty("MyNum", 42, "uint8") # a uint8 property: CIMProperty("MyNum", Uint8(42)) # a uint8 array property: CIMProperty("MyNumArray", [1, 2, 3], "uint8") # a reference property: CIMProperty("MyRef", CIMInstanceName("Foo")) # an embedded object property containing a class: CIMProperty("MyEmbObj", CIMClass("Foo")) # an embedded object property containing an instance: CIMProperty("MyEmbObj", CIMInstance("Foo"), embedded_object="object") # an embedded instance property: CIMProperty("MyEmbInst", CIMInstance("Foo")) # a string property that is Null: CIMProperty("MyString", None, "string") # a uint8 property that is Null: CIMProperty("MyNum", None, "uint8") # a reference property that is Null: CIMProperty("MyRef", None, "reference", reference_class="MyClass") # an embedded object property that is Null: CIMProperty("MyEmbObj", None, "string", embedded_object="object") # an embedded instance property that is Null: CIMProperty("MyEmbInst", None, "string", embedded_object="instance")
Methods
copy
Return a new CIMProperty
object that is a copy of this CIM property.tocimxml
Return the CIM-XML representation of this CIM property, as an object of an appropriate subclass of Element. tocimxmlstr
Return the CIM-XML representation of this CIM property, as a unicode string. tomof
Return a MOF string with the declaration of this CIM property for use in a CIM class, or the specification of this CIM property for use in a CIM instance. Attributes
array_size
The size of the fixed-size array of this CIM property. class_origin
The class origin of this CIM property, identifying the most derived class that defines or overrides the property in the class hierarchy of the class owning the property. embedded_object
A string value indicating the kind of embedded object represented by this CIM property value. is_array
Boolean indicating that this CIM property is an array (as opposed to a scalar). name
Name of this CIM property. propagated
Boolean indicating that the property declaration has been propagated from a superclass, or that the property value has been propagated from the creation class. qualifiers
Qualifiers (qualifier values) of this CIM property declaration. reference_class
The name of the class referenced by this CIM reference property. type
Name of the CIM data type of this CIM property. value
Value of this CIM property. Details
-
name
¶ Name of this CIM property.
Will not be None.
This attribute is settable. For details, see the description of the same-named init parameter of
this class
.Type: unicode string
-
value
¶ Value of this CIM property.
The property value is interpreted as an actual property value when this CIM property is used in a CIM instance, and as default value when this CIM property is used in a CIM class.
None means that the value is Null.
This attribute is settable. For details, see the description of the same-named init parameter of
this class
.Type: CIM data type
-
type
¶ Name of the CIM data type of this CIM property.
Example:
"uint8"
Will not be None.
This attribute is settable. For details, see the description of the same-named init parameter of
this class
.Type: unicode string
-
reference_class
¶ The name of the class referenced by this CIM reference property.
Will be None for non-reference properties or if the referenced class is unspecified in reference properties.
Note that in CIM instances returned from a WBEM server, DSP0201 recommends this attribute not to be set. For CIM classes returned from a WBEM server, DSP0201 requires this attribute to be set.
This attribute is settable. For details, see the description of the same-named init parameter of
this class
.Type: unicode string
-
embedded_object
¶ A string value indicating the kind of embedded object represented by this CIM property value.
Has no meaning for CIM property declarations.
The following values are defined for this parameter:
"instance"
: The property is declared with theEmbeddedInstance
qualifier, indicating that the property value is an embedded instance of the class specified as the value of theEmbeddedInstance
qualifier. The property value must be aCIMInstance
object, or None."object"
: The property is declared with theEmbeddedObject
qualifier, indicating that the property value is an embedded object (instance or class) of which the class name is not known. The property value must be aCIMInstance
orCIMClass
object, or None.- None, for properties not representing embedded objects.
This attribute is settable. For details, see the description of the same-named init parameter of
this class
.Type: unicode string
-
is_array
¶ Boolean indicating that this CIM property is an array (as opposed to a scalar).
Will not be None.
This attribute is settable. For details, see the description of the same-named init parameter of
this class
.Type: bool
-
array_size
¶ The size of the fixed-size array of this CIM property.
None means that the array has variable size, or that the property is a scalar.
This attribute is settable. For details, see the description of the same-named init parameter of
this class
.Type: integer
-
class_origin
¶ The class origin of this CIM property, identifying the most derived class that defines or overrides the property in the class hierarchy of the class owning the property.
None means that class origin information is not available.
This attribute is settable. For details, see the description of the same-named init parameter of
this class
.Type: unicode string
-
propagated
¶ Boolean indicating that the property declaration has been propagated from a superclass, or that the property value has been propagated from the creation class.
None means that propagation information is not available.
This attribute is settable. For details, see the description of the same-named init parameter of
this class
.Type: bool
-
qualifiers
¶ Qualifiers (qualifier values) of this CIM property declaration.
Will not be None.
Each dictionary item specifies one qualifier value, with:
- key (unicode string): Qualifier name. Its lexical case was preserved.
- value (
CIMQualifier
): Qualifier value.
The order of qualifiers in the property is preserved.
This attribute is settable; setting it will cause the current qualifiers to be replaced with the new qualifiers. For details, see the description of the same-named init parameter of
this class
.The qualifier values can also be accessed and manipulated one by one because the attribute value is a modifiable dictionary. The provided input value may be specified as a CIM data type or as a
CIMQualifier
object:prop = CIMProperty(...) q1 = CIMQualifier('q1', ...) # may be CIM data type or CIMQualifier prop.qualifiers['q1'] = q1 # Set "q1" to q1 (add if needed) q1 = prop.qualifiers['q1'] # Access "q1" del prop.qualifiers['q1'] # Delete "q1" from the class
Type: NocaseDict
-
copy
()[source]¶ Return a new
CIMProperty
object that is a copy of this CIM property.This is a middle-deep copy; any mutable types in attributes except the following are copied, so besides these exceptions, modifications of the original object will not affect the returned copy, and vice versa. The following mutable types are not copied and are therefore shared between original and copy:
- The
CIMQualifier
objects in thequalifiers
dictionary (but not the dictionary object itself)
Note that the Python functions
copy.copy()
andcopy.deepcopy()
can be used to create completely shallow or completely deep copies of objects of this class.- The
-
__str__
()[source]¶ Return a short string representation of this CIM property, for human consumption.
-
__repr__
()[source]¶ Return a string representation of this CIM property, that is suitable for debugging.
The order of qualifiers will be preserved in the result.
-
tocimxml
()[source]¶ Return the CIM-XML representation of this CIM property, as an object of an appropriate subclass of Element.
The returned CIM-XML representation is a PROPERTY, PROPERTY.REFERENCE, or PROPERTY.ARRAY element dependent on the property type, and consistent with DSP0201. Note that array properties cannot be of reference type.
The order of qualifiers in the returned CIM-XML representation is preserved from the
CIMProperty
object.Returns: The CIM-XML representation, as an object of an appropriate subclass of Element.
-
tocimxmlstr
(indent=None)[source]¶ Return the CIM-XML representation of this CIM property, as a unicode string.
New in pywbem 0.9.
For the returned CIM-XML representation, see
tocimxml()
.Parameters: indent (string or integer) – None indicates that a single-line version of the XML should be returned, without any whitespace between the XML elements.
Other values indicate that a prettified, multi-line version of the XML should be returned. A string value specifies the indentation string to be used for each level of nested XML elements. An integer value specifies an indentation string of so many blanks.
Returns: The CIM-XML representation of the object, as a unicode string.
-
tomof
(is_instance=True, indent=0, maxline=80, line_pos=0)[source]¶ Return a MOF string with the declaration of this CIM property for use in a CIM class, or the specification of this CIM property for use in a CIM instance.
New in pywbem 0.9.
Even though pywbem supports qualifiers on
CIMProperty
objects that are used as property values within an instance, the returned MOF string for property values in instances does not contain any qualifier values.The order of qualifiers is preserved.
Parameters: Returns: MOF string.
Return type:
-
__eq__
(other)[source]¶ Equality test function for two
CIMProperty
objects.The equality is based on their public attributes, in descending precedence:
- name
- value
- type
- reference_class
- embedded_object
- is_array
- array_size
- propagated
- class_origin
- qualifiers
The equality test takes into account any case insensitivities described for these attributes.
Raises TypeError’, if the `other object is not a
CIMProperty
object.
CIMMethod¶
-
class
pywbem.
CIMMethod
(name=None, return_type=None, parameters=None, class_origin=None, propagated=None, qualifiers=None)[source]¶ A method (declaration) in a CIM class.
Two objects of this class compare equal if their public attributes compare equal. Objects of this class are unchanged-hashable, with the hash value being based on its public attributes. Therefore, objects of this class can be used as members in a set (or as dictionary keys) only during periods in which their public attributes remain unchanged.
The init method stores the input parameters as-is and does not infer unspecified parameters from the others (like
CIMProperty
does).Parameters: - name (string) –
Name of this CIM method (just the method name, without class name or parenthesis).
Must not be None.
The lexical case of the string is preserved. Object comparison and hash value calculation are performed case-insensitively.
- return_type (string) –
Name of the CIM data type of the method return type (e.g.
"uint32"
).Must not be None or
"reference"
.ValueError
is raised if the type is None,"reference"
, or not a valid CIM data type (see CIM data types).Support for void return types: Pywbem also does not support void return types, consistent with the CIM architecture and MOF syntax (see DSP0004). Note that void return types could be represented in CIM-XML (see DSP0201).
Support for reference return types: Pywbem does not support reference return types of methods. The CIM architecture and MOF syntax support reference return types, and the CIM-XML protocol supports the invocation of methods with reference return types. However, CIM-XML does not support the representation of class declarations with methods that have reference return types.
Support for array return types: Pywbem does not support array return types of methods, consistent with the CIM architecture, MOF syntax and CIM-XML.
- parameters (parameters input object) – Parameter declarations for the method.
- class_origin (string) –
The CIM class origin of the method (the name of the most derived class that defines or overrides the method in the class hierarchy of the class owning the method).
None means that class origin information is not available, and the
class_origin
attribute will also be None.The lexical case of the string is preserved. Object comparison and hash value calculation are performed case-insensitively.
- propagated (
bool
) –If not None, specifies whether the method has been propagated from a superclass.
None means that propagation information is not available, and the the
propagated
attribute will also be None. - qualifiers (qualifiers input object) – The qualifiers for the method.
Methods
copy
Return a new CIMMethod
object that is a copy of this CIM method.tocimxml
Return the CIM-XML representation of this CIM method, as an object of an appropriate subclass of Element. tocimxmlstr
Return the CIM-XML representation of this CIM method, as a unicode string. tomof
Return a MOF string with the declaration of this CIM method for use in a CIM class declaration. Attributes
class_origin
The class origin of this CIM method, identifying the most derived class that defines or overrides the method in the class hierarchy of the class owning the method. name
Name of this CIM method. parameters
Parameters of this CIM method. propagated
Boolean indicating that this CIM method has been propagated from a superclass. qualifiers
Qualifiers (qualifier values) of this CIM method. return_type
Name of the CIM data type of the return type of this CIM method. Details
-
name
¶ Name of this CIM method.
Will not be None.
This attribute is settable. For details, see the description of the same-named init parameter of
this class
.Type: unicode string
-
return_type
¶ Name of the CIM data type of the return type of this CIM method.
Example:
"uint32"
Will not be None or
"reference"
.This attribute is settable. For details, see the description of the same-named init parameter of
this class
.Type: unicode string
-
class_origin
¶ The class origin of this CIM method, identifying the most derived class that defines or overrides the method in the class hierarchy of the class owning the method.
None means that class origin information is not available.
This attribute is settable. For details, see the description of the same-named init parameter of
this class
.Type: unicode string
-
propagated
¶ Boolean indicating that this CIM method has been propagated from a superclass.
None means that propagation information is not available.
This attribute is settable. For details, see the description of the same-named init parameter of
this class
.Type: bool
-
parameters
¶ Parameters of this CIM method.
Will not be None.
Each dictionary item specifies one parameter, with:
- key (unicode string): Parameter name. Its lexical case was preserved.
- value (
CIMParameter
): Parameter declaration.
The order of parameters in the method is preserved.
This attribute is settable; setting it will cause the current parameters to be replaced with the new parameters. For details, see the description of the same-named init parameter of
this class
.The parameters can also be accessed and manipulated one by one because the attribute value is a modifiable dictionary. The provided input value must be a
CIMParameter
object:meth = CIMMethod(...) p1 = CIMParameter('p1', ...) # must be a CIMParameter meth.parameters['p1'] = p1 # Set "p1" to p1 (add if needed) p1 = meth.parameters['p1'] # Access "p1" del meth.parameters['p1'] # Delete "p1" from the class
Type: NocaseDict
-
qualifiers
¶ Qualifiers (qualifier values) of this CIM method.
Will not be None.
Each dictionary item specifies one qualifier value, with:
- key (unicode string): Qualifier name. Its lexical case was preserved.
- value (
CIMQualifier
): Qualifier value.
The order of qualifiers in the method is preserved.
This attribute is settable; setting it will cause the current qualifiers to be replaced with the new qualifiers. For details, see the description of the same-named init parameter of
this class
.The qualifier values can also be accessed and manipulated one by one because the attribute value is a modifiable dictionary. The provided input value may be specified as a CIM data type or as a
CIMQualifier
object:meth = CIMMethod(...) q1 = "..." # may be CIM data type or CIMQualifier meth.qualifiers['q1'] = q1 # Set "q1" to q1 (add if needed) q1 = meth.qualifiers['q1'] # Access "q1" del meth.qualifiers['q1'] # Delete "q1" from the class
Type: NocaseDict
-
__eq__
(other)[source]¶ Equality test function for two
CIMMethod
objects.The equality is based on their public attributes, in descending precedence:
- name
- qualifiers
- parameters
- return_type
- class_origin
- propagated
The equality test takes into account any case insensitivities described for these attributes.
Raises TypeError’, if the `other object is not a
CIMMethod
object.
-
__repr__
()[source]¶ Return a string representation of this CIM method, that is suitable for debugging.
The order of parameters and qualifiers will be preserved in the result.
-
copy
()[source]¶ Return a new
CIMMethod
object that is a copy of this CIM method.This is a middle-deep copy; any mutable types in attributes except the following are copied, so besides these exceptions, modifications of the original object will not affect the returned copy, and vice versa. The following mutable types are not copied and are therefore shared between original and copy:
- The
CIMParameter
objects in theparameters
dictionary (but not the dictionary object itself) - The
CIMQualifier
objects in thequalifiers
dictionary (but not the dictionary object itself)
Note that the Python functions
copy.copy()
andcopy.deepcopy()
can be used to create completely shallow or completely deep copies of objects of this class.- The
-
tocimxml
()[source]¶ Return the CIM-XML representation of this CIM method, as an object of an appropriate subclass of Element.
The returned CIM-XML representation is a METHOD element consistent with DSP0201.
The order of parameters and qualifiers in the returned CIM-XML representation is preserved from the
CIMMethod
object.Returns: The CIM-XML representation, as an object of an appropriate subclass of Element.
-
tocimxmlstr
(indent=None)[source]¶ Return the CIM-XML representation of this CIM method, as a unicode string.
New in pywbem 0.9.
For the returned CIM-XML representation, see
tocimxml()
.Parameters: indent (string or integer) – None indicates that a single-line version of the XML should be returned, without any whitespace between the XML elements.
Other values indicate that a prettified, multi-line version of the XML should be returned. A string value specifies the indentation string to be used for each level of nested XML elements. An integer value specifies an indentation string of so many blanks.
Returns: The CIM-XML representation of the object, as a unicode string.
-
tomof
(indent=0, maxline=80)[source]¶ Return a MOF string with the declaration of this CIM method for use in a CIM class declaration.
The order of parameters and qualifiers is preserved.
Parameters: indent (integer) – Number of spaces to indent each line of the returned string, counted in the line with the method name. Returns: MOF string. Return type: unicode string
- name (string) –
CIMParameter¶
-
class
pywbem.
CIMParameter
(name, type, reference_class=None, is_array=None, array_size=None, qualifiers=None, value=None, embedded_object=None)[source]¶ A CIM parameter (value or declaration).
This object can be used as parameter value in the
InvokeMethod()
operation, and as a parameter declaration in aCIMMethod
object.For parameter values in method invocations:
- The value attribute is the actual value of the parameter.
- Qualifiers are not allowed.
For parameter declarations in method declarations:
- The value attribute is ignored.
- Qualifiers are allowed.
Scalar (=non-array) parameters and items in array parameters may have a value of NULL (= None), any primitive CIM data type, reference type, or string type with embedded instance or embedded object.
Two objects of this class compare equal if their public attributes compare equal. Objects of this class are unchanged-hashable, with the hash value being based on its public attributes. Therefore, objects of this class can be used as members in a set (or as dictionary keys) only during periods in which their public attributes remain unchanged.
The init method stores the input parameters as-is and does not infer unspecified parameters from the others (like
CIMProperty
does).Parameters: - name (string) –
Name of this CIM parameter.
Must not be None.
The lexical case of the string is preserved. Object comparison and hash value calculation are performed case-insensitively.
- type (string) –
Name of the CIM data type of this CIM parameter.
Example:
"uint8"
Must not be None.
ValueError
is raised if the type is None or not a valid CIM data type (see CIM data types). - reference_class (string) –
For reference parameters, the name of the class referenced by the parameter, or None indicating that the referenced class is unspecified.
For non-reference parameters, must be None.
The lexical case of the string is preserved. Object comparison and hash value calculation are performed case-insensitively.
- is_array (
bool
) –A boolean indicating whether the parameter is an array (True) or a scalar (False).
If None, the
is_array
attribute will be inferred from the value parameter. If the value parameter is None, a scalar is assumed. - array_size (integer) –
The size of the array parameter, for fixed-size arrays.
None means that the array parameter has variable size, and the
array_size
attribute will also be None. - qualifiers (qualifiers input object) – The qualifiers for the parameter.
- value –
The value of the CIM method parameter for the method invocation. Has no meaning for parameter declarations.
The specified value will be converted to a CIM data type using the rules documented in the description of
cimvalue()
, taking into account the type parameter. - embedded_object (string) –
A string value indicating the kind of embedded object represented by the parameter value (i.e. the value parameter). Has no meaning for parameter declarations.
For details about the possible values, see the corresponding attribute.
None means that the value is unspecified, causing the same-named attribute in the
CIMParameter
object to be inferred from the parameter value (i.e. the value parameter). An exception is raised if it cannot be inferred.False means the parameter value is not an embedded object, and is stored as None.
Methods
copy
Return a new CIMParameter
object that is a copy of this CIM parameter.tocimxml
Return the CIM-XML representation of this CIM parameter, as an object of an appropriate subclass of Element. tocimxmlstr
Return the CIM-XML representation of this CIM parameter, as a unicode string. tomof
Return a MOF string with the declaration of this CIM parameter for use in a CIM method declaration. Attributes
array_size
The size of the fixed-size array of this CIM parameter. embedded_object
A string value indicating the kind of embedded object represented by this CIM parameter value. is_array
Boolean indicating that this CIM parameter is an array (as opposed to a scalar). name
Name of this CIM parameter. qualifiers
Qualifiers (qualifier values) of this CIM parameter. reference_class
The name of the class referenced by this CIM reference parameter. type
Name of the CIM data type of this CIM parameter. value
The value of this CIM parameter for the method invocation. Details
-
name
¶ Name of this CIM parameter.
Will not be None.
This attribute is settable. For details, see the description of the same-named init parameter of
this class
.Type: unicode string
-
type
¶ Name of the CIM data type of this CIM parameter.
Example:
"uint8"
Will not be None.
This attribute is settable. For details, see the description of the same-named init parameter of
this class
.Type: unicode string
-
reference_class
¶ The name of the class referenced by this CIM reference parameter.
Will be None for non-reference parameters or if the referenced class is unspecified in reference parameters.
This attribute is settable. For details, see the description of the same-named init parameter of
this class
.Type: unicode string
-
is_array
¶ Boolean indicating that this CIM parameter is an array (as opposed to a scalar).
Will not be None.
This attribute is settable. For details, see the description of the same-named init parameter of
this class
.Type: bool
-
array_size
¶ The size of the fixed-size array of this CIM parameter.
None means that the array has variable size, or that the parameter is a scalar.
This attribute is settable. For details, see the description of the same-named init parameter of
this class
.Type: integer
-
qualifiers
¶ Qualifiers (qualifier values) of this CIM parameter.
Will not be None.
Each dictionary item specifies one qualifier value, with:
- key (unicode string): Qualifier name. Its lexical case was preserved.
- value (
CIMQualifier
): Qualifier value.
The order of qualifiers in the parameter is preserved.
This attribute is settable; setting it will cause the current qualifiers to be replaced with the new qualifiers. For details, see the description of the same-named init parameter of
this class
.The qualifier values can also be accessed and manipulated one by one because the attribute value is a modifiable dictionary. The provided input value may be specified as a CIM data type or as a
CIMQualifier
object:parm = CIMParameter(...) q1 = True # may be CIM data type or CIMQualifier parm.qualifiers['q1'] = q1 # Set "q1" to q1 (add if needed) q1 = parm.qualifiers['q1'] # Access "q1" del parm.qualifiers['q1'] # Delete "q1" from the class
Type: NocaseDict
-
value
¶ The value of this CIM parameter for the method invocation.
Has no meaning for parameter declarations.
This attribute is settable. For details, see the description of the same-named init parameter of
this class
.
-
embedded_object
¶ A string value indicating the kind of embedded object represented by this CIM parameter value.
Has no meaning for CIM parameter declarations.
The following values are defined for this parameter:
"instance"
: The parameter is declared with theEmbeddedInstance
qualifier, indicating that the parameter value is an embedded instance of the class specified as the value of theEmbeddedInstance
qualifier. The property value must be aCIMInstance
object, or None."object"
: The parameter is declared with theEmbeddedObject
qualifier, indicating that the parameter value is an embedded object (instance or class) of which the class name is not known. The parameter value must be aCIMInstance
orCIMClass
object, or None.- None, for parameters not representing embedded objects.
This attribute is settable. For details, see the description of the same-named init parameter of
this class
.Type: unicode string
-
__eq__
(other)[source]¶ Equality test function for two
CIMParameter
objects.The equality is based on their public attributes, in descending precedence:
- name
- type
- reference_class
- is_array
- array_size
- qualifiers
- value
- embedded_object
The equality test takes into account any case insensitivities described for these attributes.
Raises TypeError’, if the `other object is not a
CIMParameter
object.
-
__str__
()[source]¶ Return a short string representation of this CIM parameter, for human consumption.
-
__repr__
()[source]¶ Return a string representation of this CIM parameter, that is suitable for debugging.
The order of qualifiers will be preserved in the result.
-
copy
()[source]¶ Return a new
CIMParameter
object that is a copy of this CIM parameter.This is a middle-deep copy; any mutable types in attributes except the following are copied, so besides these exceptions, modifications of the original object will not affect the returned copy, and vice versa. The following mutable types are not copied and are therefore shared between original and copy:
- The
CIMQualifier
objects in thequalifiers
dictionary (but not the dictionary object itself)
Note that the Python functions
copy.copy()
andcopy.deepcopy()
can be used to create completely shallow or completely deep copies of objects of this class.- The
-
tocimxml
(as_value=False)[source]¶ Return the CIM-XML representation of this CIM parameter, as an object of an appropriate subclass of Element.
The returned CIM-XML representation can be created either as a parameter declaration for use in a method declaration, or as a parameter value for use in a method invocation.
If a parameter value is to be returned, the returned CIM-XML representation is a PARAMVALUE element with child elements dependent on the parameter type, and consistent with DSP0201.
If a parameter declaration is to be returned, the returned CIM-XML representation is a PARAMETER, PARAMETER.REFERENCE, PARAMETER.ARRAY, or PARAMETER.REFARRAY element dependent on the parameter type, and consistent with DSP0201.
The order of qualifiers in the returned CIM-XML representation of a parameter declaration is preserved from the
CIMParameter
object.Parameters: as_value (bool) – If True, return the object as a parameter value. Otherwise, return the object as a parameter declaration. Returns: The CIM-XML representation, as an object of an appropriate subclass of Element.
-
tocimxmlstr
(indent=None, as_value=False)[source]¶ Return the CIM-XML representation of this CIM parameter, as a unicode string.
New in pywbem 0.9.
The returned CIM-XML representation can be created either as a parameter declaration for use in a method declaration, or as a parameter value for use in a method invocation.
For the returned CIM-XML representation, see
tocimxml()
.Parameters: - indent (string or integer) –
None indicates that a single-line version of the XML should be returned, without any whitespace between the XML elements.
Other values indicate that a prettified, multi-line version of the XML should be returned. A string value specifies the indentation string to be used for each level of nested XML elements. An integer value specifies an indentation string of so many blanks.
- as_value (bool) – If True, return the object as a parameter value. Otherwise, return the object as a parameter declaration.
Returns: The CIM-XML representation of the object, as a unicode string.
- indent (string or integer) –
-
tomof
(indent=0, maxline=80)[source]¶ Return a MOF string with the declaration of this CIM parameter for use in a CIM method declaration.
The object is always interpreted as a parameter declaration; so the
value
andembedded_object
attributes are ignored.The order of qualifiers is preserved.
Parameters: indent (integer) – Number of spaces to indent each line of the returned string, counted in the line with the parameter name. Returns: MOF string. Return type: unicode string
CIMQualifier¶
-
class
pywbem.
CIMQualifier
(name, value, type=None, propagated=None, overridable=None, tosubclass=None, toinstance=None, translatable=None)[source]¶ A CIM qualifier value.
A qualifier represents metadata on a class, method, property, etc., and specifies information such as a documentation string or whether a property is a key.
CIMQualifier
objects can be used to represent the qualifier values that are specified on a CIM element (e.g. on a CIM class). In that case, thepropagated
property is always False, and the effective values of applicable but unspecified qualifiers need to be determined by users, by considering the default value of the corresponding qualifier type, the propagation and override flavors of the qualifier, and the qualifier values that have been specified in the class ancestry of the CIM element in question.CIMQualifier
objects can also be used to represent the effective values of all applicable qualifiers on a CIM element, including those that have not been specified, e.g. in the MOF declaration of the CIM element. In this case, theCIMQualifier
objects for qualifier values that are specified in MOF represent the specified values, and theirpropagated
property is False. TheCIMQualifier
objects for qualifier values that are not specified in MOF represent the effective values, and theirpropagated
property is True.Whether a set of
CIMQualifier
objects on a CIM object represents just the specified qualifiers or all applicable qualifiers needs to be known from the context.CIMQualifier
has properties that represent qualifier flavors (tosubclass
,toinstance
,overridable
, andtranslatable
). If any of these flavor properties is not None, the qualifier value represented by theCIMQualifier
object implicitly defines a qualifier type. Implicitly defined qualifier types have been deprecated in DSP0004. The implicitly defined qualifier type is conceptual and is not materialized as aCIMQualifierDeclaration
object.Two objects of this class compare equal if their public attributes compare equal. Objects of this class are unchanged-hashable, with the hash value being based on its public attributes. Therefore, objects of this class can be used as members in a set (or as dictionary keys) only during periods in which their public attributes remain unchanged.
The init method infers optional parameters that are not specified (for example, it infers type from the Python type of value and other information). If the specified parameters are inconsistent, an exception is raised. If an optional parameter is needed for some reason, an exception is raised.
Parameters: - name (string) –
Name of the qualifier.
Must not be None.
The lexical case of the string is preserved. Object comparison and hash value calculation are performed case-insensitively.
- value (CIM data type or other suitable types) –
Value of the qualifier.
None means that the qualifier is Null, and the same-named attribute in the
CIMQualifier
object will also be None.The specified value will be converted to a CIM data type using the rules documented in the description of
cimvalue()
, taking into account the type parameter. - type (string) –
Name of the CIM data type of the qualifier (e.g.
"uint8"
).None will cause the type to be inferred from the value parameter, raising
ValueError
if it cannot be inferred (for example when value is None or a Python integer).ValueError
is raised if the type is not a valid CIM data type (see CIM data types). - propagated (
bool
) –If not None, specifies whether the qualifier value has been propagated from a superclass.
None means that this information is not available, and the
propagated
attribute will also be None. - overridable (
bool
) –If not None, specifies whether the qualifier value is overridable in subclasses.
None means that this information is not available, and the
overridable
attribute will also be None. - tosubclass (
bool
) –If not None, specifies whether the qualifier value propagates to subclasses.
None means that this information is not available, and the
tosubclass
attribute will also be None. - toinstance (
bool
) –If not None, specifies whether the qualifier value propagates to instances.
None means that this information is not available, and the
toinstance
attribute will also be None.Note that DSP0200 has deprecated the presence of qualifier values on CIM instances.
- translatable (
bool
) –If not None, specifies whether the qualifier is translatable.
None means that this information is not available, and the
translatable
attribute will also be None.
Examples:
# a string qualifier: CIMQualifier("MyString", "abc") # a uint8 qualifier: CIMQualifier("MyNum", 42, "uint8") # a uint8 qualifier: CIMQualifier("MyNum", Uint8(42)) # a uint8 array qualifier: CIMQualifier("MyNumArray", [1, 2, 3], "uint8") # a string qualifier that is Null: CIMQualifier("MyString", None, "string") # a uint8 qualifier that is Null: CIMQualifier("MyNum", None, "uint8")
Methods
copy
Return a new CIMQualifier
object that is a copy of this CIM qualifier.tocimxml
Return the CIM-XML representation of this CIM qualifier, as an object of an appropriate subclass of Element. tocimxmlstr
Return the CIM-XML representation of this CIM qualifier, as a unicode string. tomof
Return a MOF string with the specification of this CIM qualifier as a qualifier value. Attributes
name
Name of this CIM qualifier. overridable
If not None, causes an implicit qualifier type to be defined for this qualifier that has the specified flavor. propagated
Boolean indicating that the qualifier value has been propagated from a superclass. toinstance
If not None, causes an implicit qualifier type to be defined for this qualifier that has the specified flavor. tosubclass
If not None, causes an implicit qualifier type to be defined for this qualifier that has the specified flavor. translatable
If not None, causes an implicit qualifier type to be defined for this qualifier that has the specified flavor. type
Name of the CIM data type of this CIM qualifier. value
Value of this CIM qualifier. Details
-
name
¶ Name of this CIM qualifier.
Will not be None.
This attribute is settable. For details, see the description of the same-named init parameter of
this class
.Type: unicode string
-
type
¶ Name of the CIM data type of this CIM qualifier.
Example:
"uint8"
Will not be None.
This attribute is settable. For details, see the description of the same-named init parameter of
this class
.Type: unicode string
-
value
¶ Value of this CIM qualifier.
None means that the value is Null.
For CIM data types string and char16, this attribute will be a unicode string, even when specified as a byte string.
This attribute is settable. For details, see the description of the same-named init parameter of
this class
.Type: CIM data type
-
propagated
¶ Boolean indicating that the qualifier value has been propagated from a superclass.
None means that propagation information is not available.
This attribute is settable. For details, see the description of the same-named init parameter of
this class
.Type: bool
-
tosubclass
¶ If not None, causes an implicit qualifier type to be defined for this qualifier that has the specified flavor.
If True, specifies the ToSubclass flavor (the qualifier value propagates to subclasses); if False specifies the Restricted flavor (the qualifier values does not propagate to subclasses).
None means that this information is not available.
This attribute is settable. For details, see the description of the same-named init parameter of
this class
.Type: bool
-
toinstance
¶ If not None, causes an implicit qualifier type to be defined for this qualifier that has the specified flavor.
If True specifies the ToInstance flavor(the qualifier value propagates to instances. If False, specifies that qualifier values do not propagate to instances. There is no flavor corresponding to toinstance=False.
None means that this information is not available.
Note that DSP0200 has deprecated the presence of qualifier values on CIM instances.
This attribute is settable. For details, see the description of the same-named init parameter of
this class
.Type: bool
-
overridable
¶ If not None, causes an implicit qualifier type to be defined for this qualifier that has the specified flavor.
If True, specifies the EnableOverride flavor(the qualifier value is overridable in subclasses); if False specifies the DisableOverride flavor(the qualifier value is not overridable in subclasses).
None means that this information is not available.
This attribute is settable. For details, see the description of the same-named init parameter of
this class
.Type: bool
-
translatable
¶ If not None, causes an implicit qualifier type to be defined for this qualifier that has the specified flavor.
If True, specifies the Translatable flavor (the qualifier is translatable); if False specifies that the qualfier is not translatable. There is no flavor corresponding to translatable=False.
None means that this information is not available.
This attribute is settable. For details, see the description of the same-named init parameter of
this class
.Type: bool
-
__eq__
(other)[source]¶ Equality test function for two
CIMQualifier
objects.The equality is based on their public attributes, in descending precedence:
- name
- type
- value
- propagated
- overridable
- tosubclass
- toinstance
- translatable
The equality test takes into account any case insensitivities described for these attributes.
Raises TypeError’, if the `other object is not a
CIMQualifier
object.
-
__str__
()[source]¶ Return a short string representation of this CIM qualifier, for human consumption.
-
__repr__
()[source]¶ Return a string representation of this CIM qualifier, that is suitable for debugging.
-
copy
()[source]¶ Return a new
CIMQualifier
object that is a copy of this CIM qualifier.Objects of this class have no mutable types in any attributes, so modifications of the original object will not affect the returned copy, and vice versa.
Note that the Python functions
copy.copy()
andcopy.deepcopy()
can be used to create completely shallow or completely deep copies of objects of this class.
-
tocimxml
()[source]¶ Return the CIM-XML representation of this CIM qualifier, as an object of an appropriate subclass of Element.
The returned CIM-XML representation is a QUALIFIER element consistent with DSP0201.
Returns: The CIM-XML representation, as an object of an appropriate subclass of Element.
-
tocimxmlstr
(indent=None)[source]¶ Return the CIM-XML representation of this CIM qualifier, as a unicode string.
New in pywbem 0.9.
For the returned CIM-XML representation, see
tocimxml()
.Parameters: indent (string or integer) – None indicates that a single-line version of the XML should be returned, without any whitespace between the XML elements.
Other values indicate that a prettified, multi-line version of the XML should be returned. A string value specifies the indentation string to be used for each level of nested XML elements. An integer value specifies an indentation string of so many blanks.
Returns: The CIM-XML representation of the object, as a unicode string.
-
tomof
(indent=3, maxline=80, line_pos=0)[source]¶ Return a MOF string with the specification of this CIM qualifier as a qualifier value.
The items of array values are tried to keep on the same line. If the generated line would exceed the maximum MOF line length, the value is split into multiple lines, on array item boundaries, and/or within long strings on word boundaries.
If a string value (of a scalar value, or of an array item) is split into multiple lines, the first line of the value is put onto a line on its own.
Parameters: indent (integer) – For a multi-line result, the number of spaces to indent each line except the first line (on which the qualifier name appears). For a single-line result, ignored. Returns: MOF string. Return type: unicode string
- name (string) –
CIMQualifierDeclaration¶
-
class
pywbem.
CIMQualifierDeclaration
(name, type, value=None, is_array=False, array_size=None, scopes=None, overridable=None, tosubclass=None, toinstance=None, translatable=None)[source]¶ A CIM qualifier type is the declaration of a qualifier and defines the attributes of qualifier name, qualifier type, value, scopes, and flavors for the qualifier.
The scope of a qualifer determines the kinds of schema elements on which it can be specified.
Value specifies the default value for the qualifier.
Flavors specify certain characteristics of the qualifier such as its value propagation from the ancestry of the qualified element and its translatability.
Flavors attributes must be specifically set on construction of the
CIMQualifierDeclaration
or they will be set to None. This differs from the DMTF specification DSP0004 where default values are defined as follows:Because None is allowed as a value for the flavors attributes in constructing a
CIMQualifierDeclaration
, the user must insure that any flavor which has the value None is set to its default value if required for subsequent processing.The pywbem MOF compiler supplies all of the flavor values so that those which were not specified in the MOF are set to the DMTF defined default values.
Two objects of this class compare equal if their public attributes compare equal. Objects of this class are unchanged-hashable, with the hash value being based on its public attributes. Therefore, objects of this class can be used as members in a set (or as dictionary keys) only during periods in which their public attributes remain unchanged.
Parameters: - name (string) –
Name of the qualifier.
Must not be None.
The lexical case of the string is preserved. Object comparison and hash value calculation are performed case-insensitively.
- type (string) –
Name of the CIM data type of the qualifier (e.g.
"uint8"
).Must not be None.
ValueError
is raised if the type is None or not a valid CIM data type (see CIM data types). - value (CIM data type or other suitable types) –
Default value of the qualifier.
None means a default value of Null, and the
value
attribute will also be None.The specified value will be converted to a CIM data type using the rules documented in the description of
cimvalue()
, taking into account the type parameter. - is_array (
bool
) –A boolean indicating whether the qualifier is an array (True) or a scalar (False).
If None, the
is_array
attribute will be inferred from the value parameter. If the value parameter is None, a scalar is assumed. - array_size (integer) –
The size of the array qualifier, for fixed-size arrays.
None means that the array qualifier has variable size, and the
array_size
attribute will also be None. - scopes (
dict
or NocaseDict) –Scopes of the qualifier.
A shallow copy of the provided dictionary will be stored in the
CIMQualifierDeclaration
object.Each dictionary item specifies one scope value, with:
- key (string): Scope name, in upper case.
Must not be None.
- value (
bool
): Scope value, specifying whether the qualifier has that scope (i.e. can be applied to a CIM element of that kind).
Valid scope names are “CLASS”, “ASSOCIATION”, “REFERENCE”, “PROPERTY”, “METHOD”, “PARAMETER”, “INDICATION”, and “ANY”.
None is interpreted as an empty set of scopes.
For details about the dictionary items, see the corresponding attribute.
- key (string): Scope name, in upper case.
- overridable (
bool
) –If not None, defines the flavor that defines whether the qualifier value is overridable in subclasses.
None means that this information is not available, and the
overridable
attribute will also be None. - tosubclass (
bool
) –If not None, specifies the flavor that defines whether the qualifier value propagates to subclasses.
None means that this information is not available, and the
tosubclass
attribute will also be None. - toinstance (
bool
) –If not None, specifies the flavor that defines whether the qualifier value propagates to instances.
None means that this information is not available, and the
toinstance
attribute will also be None.Note that DSP0200 has deprecated the presence of qualifier values on CIM instances and this flavor is not defined in DSP0004
- translatable (
bool
) –If not None, specifies the flavor that defines whether the qualifier is translatable.
None means that this information is not available, and the
translatable
attribute will also be None.
Methods
copy
Return a new CIMQualifierDeclaration
object that is a copy of this CIM qualifier type.tocimxml
Return the CIM-XML representation of this CIM qualifier type, as an object of an appropriate subclass of Element. tocimxmlstr
Return the CIM-XML representation of this CIM qualifier type, as a unicode string. tomof
Return a MOF string with the declaration of this CIM qualifier type. Attributes
array_size
The size of the fixed-size array of this CIM qualifier type. is_array
Boolean indicating that this CIM qualifier type is an array (as opposed to a scalar). name
Name of this CIM qualifier type. overridable
If True, specifies the EnableOverride flavor (the qualifier value is overridable in subclasses); if False specifies the DisableOverride flavor (the qualifier value is not overridable in subclasses). scopes
Scopes of this CIM qualifier type. toinstance
If True, specifies the ToInstance flavor. tosubclass
If True specifies the ToSubclass flavor (the qualifier value propagates to subclasses); if False specifies the Restricted flavor (the qualifier value does not propagate to subclasses). translatable
If True, specifies the Translatable flavor. type
Name of the CIM data type of this CIM qualifier type. value
Default value of this CIM qualifier type. Details
-
name
¶ Name of this CIM qualifier type.
Will not be None.
This attribute is settable. For details, see the description of the same-named init parameter of
this class
.Type: unicode string
-
type
¶ Name of the CIM data type of this CIM qualifier type.
Example:
"uint8"
.Will not be None.
This attribute is settable. For details, see the description of the same-named init parameter of
this class
.Type: unicode string
-
value
¶ Default value of this CIM qualifier type.
None means that the value is Null.
For CIM data types string and char16, this attribute will be a unicode string, even when specified as a byte string.
This attribute is settable. For details, see the description of the same-named init parameter of
this class
.Type: CIM data type
-
is_array
¶ Boolean indicating that this CIM qualifier type is an array (as opposed to a scalar).
Will not be None.
This attribute is settable. For details, see the description of the same-named init parameter of
this class
.Type: bool
-
array_size
¶ The size of the fixed-size array of this CIM qualifier type.
None means that the array has variable size (or that the qualifier type is not an array).
This attribute is settable. For details, see the description of the same-named init parameter of
this class
.Type: integer
-
scopes
¶ Scopes of this CIM qualifier type.
Each dictionary item specifies one scope value, with:
- key (unicode string): Scope name, in upper case.
- value (
bool
): Scope value, specifying whether the qualifier has that scope (i.e. can be applied to a CIM element of that kind).
Valid scope names are “CLASS”, “ASSOCIATION”, “INDICATION”, “PROPERTY”, “REFERENCE”, “METHOD”, “PARAMETER”, and “ANY”.
Will not be None.
This attribute is settable. For details, see the description of the same-named init parameter of
this class
.Type: NocaseDict
-
tosubclass
¶ If True specifies the ToSubclass flavor (the qualifier value propagates to subclasses); if False specifies the Restricted flavor (the qualifier value does not propagate to subclasses).
None means that this information is not available.
This attribute is settable. For details, see the description of the same-named init parameter of
this class
.Type: bool
-
toinstance
¶ If True, specifies the ToInstance flavor. This flavor specifies that the qualifier value propagates to instances. If False, specifies that qualifier values do not propagate to instances. There is no flavor corresponding to toinstance=False.
None means that this information is not available.
Note that DSP0200 has deprecated the presence of qualifier values on CIM instances.
This attribute is settable. For details, see the description of the same-named init parameter of
this class
.Type: bool
-
overridable
¶ If True, specifies the EnableOverride flavor (the qualifier value is overridable in subclasses); if False specifies the DisableOverride flavor (the qualifier value is not overridable in subclasses).
None means that this information is not available.
This attribute is settable. For details, see the description of the same-named init parameter of
this class
.Type: bool
-
translatable
¶ If True, specifies the Translatable flavor. This flavor specifies that the qualifier is translatable. If False, specifies that the qualfier is not translatable. There is no flavor corresponding to translatable=False.
None means that this information is not available.
This attribute is settable. For details, see the description of the same-named init parameter of
this class
.Type: bool
-
__eq__
(other)[source]¶ Equality test function for two
CIMQualifierDeclaration
objects.The equality is based on their public attributes, in descending precedence:
- name
- type
- value
- is_array
- array_size
- scopes
- overridable
- tosubclass
- toinstance
- translatable
The equality test takes into account any case insensitivities described for these attributes.
Raises TypeError’, if the `other object is not a
CIMQualifierDeclaration
object.
-
__str__
()[source]¶ Return a short string representation of this CIM qualifier type, for human consumption.
-
__repr__
()[source]¶ Return a string representation of this CIM qualifier type, that is suitable for debugging.
The scopes will be ordered by their names in the result.
-
copy
()[source]¶ Return a new
CIMQualifierDeclaration
object that is a copy of this CIM qualifier type.Objects of this class have no mutable types in any attributes, so modifications of the original object will not affect the returned copy, and vice versa.
Note that the Python functions
copy.copy()
andcopy.deepcopy()
can be used to create completely shallow or completely deep copies of objects of this class.
-
tocimxml
()[source]¶ Return the CIM-XML representation of this CIM qualifier type, as an object of an appropriate subclass of Element.
The returned CIM-XML representation is a QUALIFIER.DECLARATION element consistent with DSP0201.
Returns: The CIM-XML representation, as an object of an appropriate subclass of Element.
-
tocimxmlstr
(indent=None)[source]¶ Return the CIM-XML representation of this CIM qualifier type, as a unicode string.
New in pywbem 0.9.
For the returned CIM-XML representation, see
tocimxml()
.Parameters: indent (string or integer) – None indicates that a single-line version of the XML should be returned, without any whitespace between the XML elements.
Other values indicate that a prettified, multi-line version of the XML should be returned. A string value specifies the indentation string to be used for each level of nested XML elements. An integer value specifies an indentation string of so many blanks.
Returns: The CIM-XML representation of the object, as a unicode string.
-
tomof
(maxline=80)[source]¶ Return a MOF string with the declaration of this CIM qualifier type.
The returned MOF string conforms to the
qualifierDeclaration
ABNF rule defined in DSP0004.Qualifier flavors are included in the returned MOF string only when the information is available (i.e. the value of the corresponding attribute is not None).
Because DSP0004 does not support instance qualifiers, and thus does not define a flavor keyword for the
toinstance
attribute, that flavor is not included in the returned MOF string.Returns: MOF string. Return type: unicode string
- name (string) –
CIM data types¶
Python classes for representing values of CIM data types, and related conversion functions.
The following table shows how CIM data types are represented in Python. Note that some basic CIM data types are represented with built-in Python types.
CIM data type | Python type |
---|---|
boolean | bool |
char16 | string
or Char16 |
string | string |
string (EmbeddedInstance) | CIMInstance |
string (EmbeddedObject) | CIMInstance
or CIMClass |
datetime | CIMDateTime |
reference | CIMInstanceName |
uint8 | Uint8 |
uint16 | Uint16 |
uint32 | Uint32 |
uint64 | Uint64 |
sint8 | Sint8 |
sint16 | Sint16 |
sint32 | Sint32 |
sint64 | Sint64 |
real32 | Real32 |
real64 | Real64 |
[] (array) | list |
The CIM NULL value is represented with Python None which can be used for any CIM typed value to represent NULL.
Note that init methods of pywbem classes that take CIM typed values as input
may support Python types in addition to those shown above. For example, the
CIMProperty
class represents property values of CIM datetime
type internally as CIMDateTime
objects, but its init method
accepts datetime.timedelta
objects, datetime.datetime
objects, string, in addition to
CIMDateTime
objects.
-
class
pywbem.
CIMType
[source]¶ Base type for all CIM data types defined in this package.
Methods
Attributes
cimtype
The name of the CIM datatype, as a string. Details
-
cimtype
= None¶ The name of the CIM datatype, as a string. See CIM data types for details.
-
-
class
pywbem.
CIMDateTime
(dtarg)[source]¶ A value of CIM data type datetime.
The object represents either a timezone-aware point in time, or a time interval.
Two objects of this class compare equal if their public attributes compare equal. Objects of this class are immutable and hashable, with the hash value being based on their public attributes.
Parameters: dtarg – The value from which the object is initialized, as one of the following types:
- A string object will be interpreted as CIM datetime format (see DSP0004) and will result in a point in time or a time interval. The use of asterisk characters in the value is supported according to the rules defined in DSP0004 (e.g. “20180911124613.128***:000”).
- A
datetime.datetime
object will result in a point in time. If thedatetime.datetime
object is timezone-aware (seeMinutesFromUTC
), the specified timezone will be used. Otherwise, a default timezone of UTC will be assumed. - A
datetime.timedelta
object will result in a time interval. - Another
CIMDateTime
object will be copied.
Methods
fromtimestamp
Factory method that returns a new CIMDateTime
object from a POSIX timestamp value and optional timezone information.get_local_utcoffset
Return the timezone offset of the current local timezone as +/- minutes from UTC. now
Factory method that returns a new CIMDateTime
object representing the current date and time.Attributes
cimtype
The name of the CIM datatype "datetime"
datetime
The point in time represented by this object, as a datetime.datetime
object.is_interval
A boolean indicating whether this object represents a time interval (True) or a point in time (False). minutes_from_utc
The timezone offset of this point in time object as +/- minutes from UTC. precision
Precision of the time interval or point in time represented by this object, if the datetime input string contained asterisk characters. timedelta
The time interval represented by this object, as a datetime.timedelta
object.Details
-
cimtype
= 'datetime'¶ The name of the CIM datatype
"datetime"
-
minutes_from_utc
¶ The timezone offset of this point in time object as +/- minutes from UTC.
A positive value of the timezone offset indicates minutes east of UTC, and a negative value indicates minutes west of UTC.
0, if this object represents a time interval.
-
datetime
¶ The point in time represented by this object, as a
datetime.datetime
object.None if this object represents a time interval.
-
timedelta
¶ The time interval represented by this object, as a
datetime.timedelta
object.None if this object represents a point in time.
-
precision
¶ Precision of the time interval or point in time represented by this object, if the datetime input string contained asterisk characters.
The precision is the 0-based index of the first asterisk character in the datetime input string, or None if there were no asterisk characters. For example, the precision of the timestamp value “201809121230**.******+000” is 12.
-
is_interval
¶ A boolean indicating whether this object represents a time interval (True) or a point in time (False).
-
static
get_local_utcoffset
()[source]¶ Return the timezone offset of the current local timezone as +/- minutes from UTC.
A positive value indicates minutes east of UTC, and a negative value indicates minutes west of UTC.
-
classmethod
now
(tzi=None)[source]¶ Factory method that returns a new
CIMDateTime
object representing the current date and time.The optional timezone information is used to convert the CIM datetime value into the desired timezone. That does not change the point in time that is represented by the value, but it changes the value of the
hhmmss
components of the CIM datetime value to compensate for changes in the timezone offset component.Parameters: tzi ( MinutesFromUTC
) – Timezone information. None means that the current local timezone is used.Returns: A new CIMDateTime
object representing the current date and time.
-
classmethod
fromtimestamp
(ts, tzi=None)[source]¶ Factory method that returns a new
CIMDateTime
object from a POSIX timestamp value and optional timezone information.A POSIX timestamp value is the number of seconds since “the epoch”, i.e. 1970-01-01 00:00:00 UTC. Thus, a POSIX timestamp value is unambiguous w.r.t. the timezone, but it is not timezone-aware.
The optional timezone information is used to convert the CIM datetime value into the desired timezone. That does not change the point in time that is represented by the value, but it changes the value of the
hhmmss
components of the CIM datetime value to compensate for changes in the timezone offset component.Parameters: - ts (integer) – POSIX timestamp value.
- tzi (
MinutesFromUTC
) – Timezone information. None means that the current local timezone is used.
Returns: A new
CIMDateTime
object representing the specified point in time.
-
class
pywbem.
MinutesFromUTC
(offset)[source]¶ Timezone information (an implementation of
datetime.tzinfo
) that represents a fixed offset in +/- minutes from UTC and is thus suitable for the CIM datetime data type.Objects of this class are needed in order to make
datetime.datetime
objects timezone-aware, in order to be useable as input data to the timezone-awareCIMDateTime
type.They are also used to provide timezone information to
now()
andfromtimestamp()
Example:
from datetime import datetime from time import time import pywbem # Create a timezone-aware datetime object (for CEDT = UTC+2h), and # convert that to CIM datetime: dt = datetime(year=2016, month=3, day=31, hour=19, minute=30, second=40, microsecond=654321, tzinfo=pywbem.MinutesFromUTC(120)) cim_dt = pywbem.CIMDateTime(dt) # Convert a POSIX timestamp value to CIM datetime (for EST = UTC-5h): posix_ts = time() # seconds since the epoch, not timezone-aware cim_dt = pywbem.CIMDateTime.fromtimestamp(posix_ts, pywbem.MinutesFromUTC(-300))
Parameters: offset (integer) – Timezone offset to be represented in the CIM datetime value in +/- minutes from UTC.
This is the offset of local time to UTC (including DST offset), where a positive value indicates minutes east of UTC, and a negative value indicates minutes west of UTC.
Methods
dst
An implementation of the corresponding base class method, (see datetime.tzinfo.dst()
for its description), which needs to return the offset caused by DST, as adatetime.timedelta
object.fromutc
datetime in UTC -> datetime in local time. tzname
An implementation of the corresponding base class method, (see datetime.tzinfo.tzname()
for its description), which needs to return the name of the timezone of the specified datetime object.utcoffset
An implementation of the corresponding base class method (see datetime.tzinfo.utcoffset()
for its description), which needs to return the offset of local time to UTC (including DST offset), as adatetime.timedelta
object.Attributes
Details
-
utcoffset
(dt)[source]¶ An implementation of the corresponding base class method (see
datetime.tzinfo.utcoffset()
for its description), which needs to return the offset of local time to UTC (including DST offset), as adatetime.timedelta
object. This method is called by the Python datetime classes, and a pywbem user normally does not have to deal with it.This implementation returns the offset used to initialize the object, for any specified dt parameter.
-
dst
(dt)[source]¶ An implementation of the corresponding base class method, (see
datetime.tzinfo.dst()
for its description), which needs to return the offset caused by DST, as adatetime.timedelta
object. This method is called by the Python datetime classes, and a pywbem user normally does not have to deal with it.This implementation returns an offset of 0 (indicating that DST is not in effect), for any specified dt parameter, because CIM datetime values do not represent DST information.
-
tzname
(dt)[source]¶ An implementation of the corresponding base class method, (see
datetime.tzinfo.tzname()
for its description), which needs to return the name of the timezone of the specified datetime object.This implementation returns the timezone offset formatted as a signed HH:MM string, where positive values are east of UTC.
-
-
class
pywbem.
Char16
[source]¶ A value of CIM data type char16.
This class is derived from unicode string.
Normally, values of CIM data type char16 are represented using unicode string objects. This class can be used to represent values of CIM data type char16 when it matters to distinguish them from values of CIM data type string. The only situation where that matters is for keybindings, because that allows properly setting the TYPE attribute on KEYVALUE elements when creating the CIM-XML representation for a keybinding.
Methods
capitalize
Return a capitalized version of the string. casefold
Return a version of the string suitable for caseless comparisons. center
Return a centered string of length width. count
Return the number of non-overlapping occurrences of substring sub in string S[start:end]. encode
Encode the string using the codec registered for encoding. endswith
Return True if S ends with the specified suffix, False otherwise. expandtabs
Return a copy where all tab characters are expanded using spaces. find
Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end]. format
Return a formatted version of S, using substitutions from args and kwargs. format_map
Return a formatted version of S, using substitutions from mapping. index
Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end]. isalnum
Return True if the string is an alpha-numeric string, False otherwise. isalpha
Return True if the string is an alphabetic string, False otherwise. isascii
Return True if all characters in the string are ASCII, False otherwise. isdecimal
Return True if the string is a decimal string, False otherwise. isdigit
Return True if the string is a digit string, False otherwise. isidentifier
Return True if the string is a valid Python identifier, False otherwise. islower
Return True if the string is a lowercase string, False otherwise. isnumeric
Return True if the string is a numeric string, False otherwise. isprintable
Return True if the string is printable, False otherwise. isspace
Return True if the string is a whitespace string, False otherwise. istitle
Return True if the string is a title-cased string, False otherwise. isupper
Return True if the string is an uppercase string, False otherwise. join
Concatenate any number of strings. ljust
Return a left-justified string of length width. lower
Return a copy of the string converted to lowercase. lstrip
Return a copy of the string with leading whitespace removed. maketrans
Return a translation table usable for str.translate(). partition
Partition the string into three parts using the given separator. replace
Return a copy with all occurrences of substring old replaced by new. rfind
Return the highest index in S where substring sub is found, such that sub is contained within S[start:end]. rindex
Return the highest index in S where substring sub is found, such that sub is contained within S[start:end]. rjust
Return a right-justified string of length width. rpartition
Partition the string into three parts using the given separator. rsplit
Return a list of the words in the string, using sep as the delimiter string. rstrip
Return a copy of the string with trailing whitespace removed. split
Return a list of the words in the string, using sep as the delimiter string. splitlines
Return a list of the lines in the string, breaking at line boundaries. startswith
Return True if S starts with the specified prefix, False otherwise. strip
Return a copy of the string with leading and trailing whitespace removed. swapcase
Convert uppercase characters to lowercase and lowercase characters to uppercase. title
Return a version of the string where each word is titlecased. translate
Replace each character in the string using the given translation table. upper
Return a copy of the string converted to uppercase. zfill
Pad a numeric string with zeros on the left, to fill a field of the given width. Attributes
cimtype
The name of the CIM datatype "char16"
Details
-
cimtype
= 'char16'¶ The name of the CIM datatype
"char16"
-
-
class
pywbem.
CIMInt
[source]¶ Base type for CIM integer data types. Derived from
CIMType
andint
(for Python 3) orlong
(for Python 2).This class has a concept of a valid range for the represented integer, based upon the capability of the CIM data type as defined in DSP0004. The additional constraints defined by possible MinValue or MaxValue qualifiers are not taken into account at this level.
The valid value range is enforced when an instance of a subclass of this class (e.g.
Uint8
) is created. Values outside of the valid range raise aValueError
. The enforcement of the valid value range can be disabled via the configuration variableENFORCE_INTEGER_RANGE
.Two objects of subclasses of this base class compare equal if their numeric values compare equal. Objects of this class are immutable and hashable, with the hash value being based on its numeric value.
Instances of subclasses of this class can be initialized with the usual input arguments supported by integer, for example:
>>> pywbem.Uint8(42) Uint8(cimtype='uint8', 42) >>> pywbem.Uint8('42') Uint8(cimtype='uint8', 42) >>> pywbem.Uint8('2A', 16) Uint8(cimtype='uint8', 42) >>> pywbem.Uint8('100', 16) Traceback (most recent call last): . . . ValueError: Integer value 256 is out of range for CIM datatype uint8 >>> pywbem.Uint8(100, 10) Traceback (most recent call last): . . . TypeError: int() can't convert non-string with explicit base
Methods
bit_length
Number of bits necessary to represent self in binary. conjugate
Returns self, the complex conjugate of any int. from_bytes
Return the integer represented by the given array of bytes. to_bytes
Return an array of bytes representing an integer. Attributes
cimtype
The name of the CIM datatype, as a string. denominator
the denominator of a rational number in lowest terms imag
the imaginary part of a complex number maxvalue
The maximum valid value for the integer, according to the capabilities of its CIM data type. minvalue
The minimum valid value for the integer, according to the capabilities of its CIM data type. numerator
the numerator of a rational number in lowest terms real
the real part of a complex number Details
-
minvalue
= None¶ The minimum valid value for the integer, according to the capabilities of its CIM data type. See CIM data types for a list of CIM integer data types.
-
maxvalue
= None¶ The maximum valid value for the integer, according to the capabilities of its CIM data type. See CIM data types for a list of CIM integer data types.
-
-
class
pywbem.
Uint8
[source]¶ A value of CIM data type uint8. Derived from
CIMInt
.For details on CIM integer data types, see
CIMInt
.Methods
bit_length
Number of bits necessary to represent self in binary. conjugate
Returns self, the complex conjugate of any int. from_bytes
Return the integer represented by the given array of bytes. to_bytes
Return an array of bytes representing an integer. Attributes
cimtype
The name of the CIM datatype denominator
the denominator of a rational number in lowest terms imag
the imaginary part of a complex number maxvalue
The maximum valid value for the CIM datatype minvalue
The minimum valid value for the CIM datatype numerator
the numerator of a rational number in lowest terms real
the real part of a complex number Details
-
cimtype
= 'uint8'¶ The name of the CIM datatype
-
minvalue
= 0¶ The minimum valid value for the CIM datatype
-
maxvalue
= 255¶ The maximum valid value for the CIM datatype
-
-
class
pywbem.
Sint8
[source]¶ A value of CIM data type sint8. Derived from
CIMInt
.For details on CIM integer data types, see
CIMInt
.Methods
bit_length
Number of bits necessary to represent self in binary. conjugate
Returns self, the complex conjugate of any int. from_bytes
Return the integer represented by the given array of bytes. to_bytes
Return an array of bytes representing an integer. Attributes
cimtype
The name of the CIM datatype denominator
the denominator of a rational number in lowest terms imag
the imaginary part of a complex number maxvalue
The maximum valid value for the CIM datatype minvalue
The minimum valid value for the CIM datatype numerator
the numerator of a rational number in lowest terms real
the real part of a complex number Details
-
cimtype
= 'sint8'¶ The name of the CIM datatype
-
minvalue
= -128¶ The minimum valid value for the CIM datatype
-
maxvalue
= 127¶ The maximum valid value for the CIM datatype
-
-
class
pywbem.
Uint16
[source]¶ A value of CIM data type uint16. Derived from
CIMInt
.For details on CIM integer data types, see
CIMInt
.Methods
bit_length
Number of bits necessary to represent self in binary. conjugate
Returns self, the complex conjugate of any int. from_bytes
Return the integer represented by the given array of bytes. to_bytes
Return an array of bytes representing an integer. Attributes
cimtype
The name of the CIM datatype denominator
the denominator of a rational number in lowest terms imag
the imaginary part of a complex number maxvalue
The maximum valid value for the CIM datatype minvalue
The minimum valid value for the CIM datatype numerator
the numerator of a rational number in lowest terms real
the real part of a complex number Details
-
cimtype
= 'uint16'¶ The name of the CIM datatype
-
minvalue
= 0¶ The minimum valid value for the CIM datatype
-
maxvalue
= 65535¶ The maximum valid value for the CIM datatype
-
-
class
pywbem.
Sint16
[source]¶ A value of CIM data type sint16. Derived from
CIMInt
.For details on CIM integer data types, see
CIMInt
.Methods
bit_length
Number of bits necessary to represent self in binary. conjugate
Returns self, the complex conjugate of any int. from_bytes
Return the integer represented by the given array of bytes. to_bytes
Return an array of bytes representing an integer. Attributes
cimtype
The name of the CIM datatype denominator
the denominator of a rational number in lowest terms imag
the imaginary part of a complex number maxvalue
The maximum valid value for the CIM datatype minvalue
The minimum valid value for the CIM datatype numerator
the numerator of a rational number in lowest terms real
the real part of a complex number Details
-
cimtype
= 'sint16'¶ The name of the CIM datatype
-
minvalue
= -32768¶ The minimum valid value for the CIM datatype
-
maxvalue
= 32767¶ The maximum valid value for the CIM datatype
-
-
class
pywbem.
Uint32
[source]¶ A value of CIM data type uint32. Derived from
CIMInt
.For details on CIM integer data types, see
CIMInt
.Methods
bit_length
Number of bits necessary to represent self in binary. conjugate
Returns self, the complex conjugate of any int. from_bytes
Return the integer represented by the given array of bytes. to_bytes
Return an array of bytes representing an integer. Attributes
cimtype
The name of the CIM datatype denominator
the denominator of a rational number in lowest terms imag
the imaginary part of a complex number maxvalue
The maximum valid value for the CIM datatype minvalue
The minimum valid value for the CIM datatype numerator
the numerator of a rational number in lowest terms real
the real part of a complex number Details
-
cimtype
= 'uint32'¶ The name of the CIM datatype
-
minvalue
= 0¶ The minimum valid value for the CIM datatype
-
maxvalue
= 4294967295¶ The maximum valid value for the CIM datatype
-
-
class
pywbem.
Sint32
[source]¶ A value of CIM data type sint32. Derived from
CIMInt
.For details on CIM integer data types, see
CIMInt
.Methods
bit_length
Number of bits necessary to represent self in binary. conjugate
Returns self, the complex conjugate of any int. from_bytes
Return the integer represented by the given array of bytes. to_bytes
Return an array of bytes representing an integer. Attributes
cimtype
The name of the CIM datatype denominator
the denominator of a rational number in lowest terms imag
the imaginary part of a complex number maxvalue
The maximum valid value for the CIM datatype minvalue
The minimum valid value for the CIM datatype numerator
the numerator of a rational number in lowest terms real
the real part of a complex number Details
-
cimtype
= 'sint32'¶ The name of the CIM datatype
-
minvalue
= -2147483648¶ The minimum valid value for the CIM datatype
-
maxvalue
= 2147483647¶ The maximum valid value for the CIM datatype
-
-
class
pywbem.
Uint64
[source]¶ A value of CIM data type uint64. Derived from
CIMInt
.For details on CIM integer data types, see
CIMInt
.Methods
bit_length
Number of bits necessary to represent self in binary. conjugate
Returns self, the complex conjugate of any int. from_bytes
Return the integer represented by the given array of bytes. to_bytes
Return an array of bytes representing an integer. Attributes
cimtype
The name of the CIM datatype denominator
the denominator of a rational number in lowest terms imag
the imaginary part of a complex number maxvalue
The maximum valid value for the CIM datatype minvalue
The minimum valid value for the CIM datatype numerator
the numerator of a rational number in lowest terms real
the real part of a complex number Details
-
cimtype
= 'uint64'¶ The name of the CIM datatype
-
minvalue
= 0¶ The minimum valid value for the CIM datatype
-
maxvalue
= 18446744073709551615¶ The maximum valid value for the CIM datatype
-
-
class
pywbem.
Sint64
[source]¶ A value of CIM data type sint64. Derived from
CIMInt
.For details on CIM integer data types, see
CIMInt
.Methods
bit_length
Number of bits necessary to represent self in binary. conjugate
Returns self, the complex conjugate of any int. from_bytes
Return the integer represented by the given array of bytes. to_bytes
Return an array of bytes representing an integer. Attributes
cimtype
The name of the CIM datatype denominator
the denominator of a rational number in lowest terms imag
the imaginary part of a complex number maxvalue
The maximum valid value for the CIM datatype minvalue
The minimum valid value for the CIM datatype numerator
the numerator of a rational number in lowest terms real
the real part of a complex number Details
-
cimtype
= 'sint64'¶ The name of the CIM datatype
-
minvalue
= -9223372036854775808¶ The minimum valid value for the CIM datatype
-
maxvalue
= 9223372036854775807¶ The maximum valid value for the CIM datatype
-
-
class
pywbem.
CIMFloat
[source]¶ Base type for real (floating point) CIM data types.
Two objects of subclasses of this base class compare equal if their numeric values compare equal. Objects of this class are immutable and hashable, with the hash value being based on its numeric value.
Note that equality comparison of floating point numbers in Python (and in almost any programming language) comes with some surprises. See “Floating Point Arithmetic: Issues and Limitations” for details, and specifically “Comparing Floating Point Numbers, 2012 Edition” on the topic of equality comparison. The same issues apply to hash values that are based on the numeric value of floating point numbers. Therefore, it is not recommended to perform equality comparison of objects of subclasses of this class, or to use them as dictionary keys or as members in sets.
Methods
as_integer_ratio
Return integer ratio. conjugate
Return self, the complex conjugate of any float. fromhex
Create a floating-point number from a hexadecimal string. hex
Return a hexadecimal representation of a floating-point number. is_integer
Return True if the float is an integer. Attributes
cimtype
The name of the CIM datatype, as a string. imag
the imaginary part of a complex number real
the real part of a complex number Details
-
class
pywbem.
Real32
[source]¶ A value of CIM data type real32. Derived from
CIMFloat
.It is not recommended to perform equality comparison on objects of this class, or to use them as dictionary keys or as members in sets. See
CIMFloat
for details.Methods
as_integer_ratio
Return integer ratio. conjugate
Return self, the complex conjugate of any float. fromhex
Create a floating-point number from a hexadecimal string. hex
Return a hexadecimal representation of a floating-point number. is_integer
Return True if the float is an integer. Attributes
cimtype
The name of the CIM datatype imag
the imaginary part of a complex number real
the real part of a complex number Details
-
cimtype
= 'real32'¶ The name of the CIM datatype
-
-
class
pywbem.
Real64
[source]¶ A value of CIM data type real64. Derived from
CIMFloat
.It is not recommended to perform equality comparison on objects of this class, or to use them as dictionary keys or as members in sets. See
CIMFloat
for details.Methods
as_integer_ratio
Return integer ratio. conjugate
Return self, the complex conjugate of any float. fromhex
Create a floating-point number from a hexadecimal string. hex
Return a hexadecimal representation of a floating-point number. is_integer
Return True if the float is an integer. Attributes
cimtype
The name of the CIM datatype imag
the imaginary part of a complex number real
the real part of a complex number Details
-
cimtype
= 'real64'¶ The name of the CIM datatype
-
Conversion functions¶
This section describes conversion functions related to CIM objects and CIM data types:
Function | Purpose |
---|---|
tocimxml() |
Return the CIM-XML representation of a CIM object or CIM data typed value as an Element object. |
tocimxmlstr() |
Return the CIM-XML representation of a CIM object or CIM data typed value as a unicode string. |
cimvalue() |
Return a CIM data typed value from a Python value. |
cimtype() |
Return the CIM data type name of a CIM data typed value. |
type_from_name() |
Return the Python type object for a CIM data type name. |
-
pywbem.
tocimxml
(value)[source]¶ Return the CIM-XML representation of the input object, as an object of an appropriate subclass of Element.
The returned CIM-XML representation is consistent with DSP0201.
Parameters: value (CIM object, CIM data type, number, datetime.datetime
, or tuple/list thereof) – The input object. Must not be None.Returns: The CIM-XML representation, as an object of an appropriate subclass of Element. Raises: ValueError
– Invalid input value.
-
pywbem.
tocimxmlstr
(value, indent=None)[source]¶ Return the CIM-XML representation of the CIM object or CIM data type, as a unicode string.
New in pywbem 0.9.
The returned CIM-XML representation is consistent with DSP0201.
Parameters: - value (CIM object or CIM data type or Element) – The CIM object or CIM data type to be converted to CIM-XML, or an Element object that already is the CIM-XML representation.
- indent (string or integer) –
None indicates that a single-line version of the XML should be returned, without any whitespace between the XML elements.
Other values indicate that a prettified, multi-line version of the XML should be returned. A string value specifies the indentation string to be used for each level of nested XML elements. An integer value specifies an indentation string of so many blanks.
Returns: The CIM-XML representation of the value, as a unicode string.
-
pywbem.
cimvalue
(value, type)[source]¶ Return a CIM data type representing the specified value in the specified CIM type.
New in pywbem 0.12.
This function guarantees that the returned object is a valid CIM data type. If the input parameters are not sufficient to construct a CIM data type, an exception is raised.
If the provided value is already a CIM data type (or None), the input value is returned.
Otherwise, the value is converted to a CIM data type as described below.
If the provided value is a list, a new list is returned with this function being invoked recursively on the items of the input list.
Embedded objects and embedded instances are not handled by this function.
Parameters: - type (string) –
The CIM data type name for the CIM object. See CIM data types for valid type names.
If value is a list, type must specify the CIM data type name of an item in the list.
- value (CIM data type and other suitable types) –
The value to be represented as a CIM object.
If None, the returned object will be None.
The following other suitable types are supported (in addition to the respective CIM data type):
- If type is
'string'
or'char16'
:- Objects of type byte string; they will be converted to unicode string.
- If type specifies one of the CIM integer data types (e.g.
'uint8'
): - If type specifies one of the CIM float data types (e.g.
'real32'
): - If type is
'boolean'
:- Any object. The value is converted to bool using the standard Python truth testing procedure.
- If type is
'datetime'
:- Any object supported as an init parameter for
CIMDateTime
.
- Any object supported as an init parameter for
- If type is
'reference'
:- string. The string must be an untyped WBEM URI representing an instance path (see DSP0207).
CIMInstanceName
. An instance path.CIMClassName
. A class path.
- If type is
Returns: A CIM data type object, representing the specified value and type.
Raises: ValueError
– An input parameter has an invalid value.TypeError
– An input parameter has an invalid Python type.
- type (string) –
-
pywbem.
cimtype
(obj)[source]¶ Return the CIM data type name of a CIM typed object, as a string.
For an array, the type is determined from the first array element (CIM arrays must be homogeneous w.r.t. the type of their elements). If the array is empty, that is not possible and
ValueError
is raised.Note that Python numbers are not valid input objects because determining their CIM data type (e.g.
Uint8
,Real32
) would require knowing the value range. Therefore,TypeError
is raised in this case.Parameters: obj (CIM data type) – The object whose CIM data type name is returned.
Returns: The CIM data type name of the object (e.g.
"uint8"
).Return type: Raises: TypeError
– The object does not have a valid CIM data type.ValueError
– Cannot determine CIM data type from an empty array.
-
pywbem.
type_from_name
(type_name)[source]¶ Return the Python type object for a given CIM data type name.
For example, type name
"uint8"
will return type objectUint8
.For CIM data type names
"string"
and"char16"
, the unicode string type is returned (Unicode strings are the preferred representation for these CIM data types).The returned type can be used as a constructor from a differently typed input value in many cases. Notable limitations are:
In Python 3, the
str
type is used to represent CIM string data types. When constructing such an object from a byte string, the resulting string is not a unicode-translated version of the byte string as one would assume (and as is the case in Python 2), but instead that results in a unicode string that is a repr() representation of the byte string:string_type = type_from_name('string') # str s1 = b'abc' s2 = string_type(s1) # results in u"b'abc'", and not in u"abc"
Use decode() and encode() for strings instead of type conversion syntax (in both Python 2 and 3, for consistency).
For CIM type “reference”, type object
CIMInstanceName
is returned, even though for use in CIM method parameters,CIMClassName
is also valid.
Parameters: type_name (string) – The simple (=non-array) CIM data type name (e.g. "uint8"
or"reference"
).Returns: The Python type object for the CIM data type (e.g. Uint8
orCIMInstanceName
).Raises: ValueError
– Unknown CIM data type name.
CIM status codes¶
This section defines constants for two areas:
- CIM status codes (the
CIM_ERR_*
symbols). They are for example stored inCIMError
exceptions. - Other constants.
Note: For tooling reasons, the constants are shown in the namespace
pywbem._cim_constants
. However, they are also available in the pywbem
namespace and should be used from there.
-
pywbem._cim_constants.
CIM_ERR_FAILED
= 1¶ A general error occurred that is not covered by a more specific error code.
-
pywbem._cim_constants.
CIM_ERR_ACCESS_DENIED
= 2¶ Access to a CIM resource is not available to the client.
-
pywbem._cim_constants.
CIM_ERR_INVALID_NAMESPACE
= 3¶ The target namespace does not exist.
-
pywbem._cim_constants.
CIM_ERR_INVALID_PARAMETER
= 4¶ One or more parameter values passed to the method are not valid.
-
pywbem._cim_constants.
CIM_ERR_INVALID_CLASS
= 5¶ The specified class does not exist.
-
pywbem._cim_constants.
CIM_ERR_NOT_FOUND
= 6¶ The requested object cannot be found. The operation can be unsupported on behalf of the WBEM server in general or on behalf of an implementation of a management profile.
-
pywbem._cim_constants.
CIM_ERR_NOT_SUPPORTED
= 7¶ The requested operation is not supported on behalf of the WBEM server, or on behalf of a provided class. If the operation is supported for a provided class but is not supported for particular instances of that class, then CIM_ERR_FAILED shall be used.
-
pywbem._cim_constants.
CIM_ERR_CLASS_HAS_CHILDREN
= 8¶ The operation cannot be invoked on this class because it has subclasses.
-
pywbem._cim_constants.
CIM_ERR_CLASS_HAS_INSTANCES
= 9¶ The operation cannot be invoked on this class because one or more instances of this class exist.
-
pywbem._cim_constants.
CIM_ERR_INVALID_SUPERCLASS
= 10¶ The operation cannot be invoked because the specified superclass does not exist.
-
pywbem._cim_constants.
CIM_ERR_ALREADY_EXISTS
= 11¶ The operation cannot be invoked because an object already exists.
-
pywbem._cim_constants.
CIM_ERR_NO_SUCH_PROPERTY
= 12¶ The specified property does not exist.
-
pywbem._cim_constants.
CIM_ERR_TYPE_MISMATCH
= 13¶ The value supplied is not compatible with the type.
-
pywbem._cim_constants.
CIM_ERR_QUERY_LANGUAGE_NOT_SUPPORTED
= 14¶ The query language is not recognized or supported.
-
pywbem._cim_constants.
CIM_ERR_INVALID_QUERY
= 15¶ The query is not valid for the specified query language.
-
pywbem._cim_constants.
CIM_ERR_METHOD_NOT_AVAILABLE
= 16¶ The extrinsic method cannot be invoked.
-
pywbem._cim_constants.
CIM_ERR_METHOD_NOT_FOUND
= 17¶ The specified extrinsic method does not exist.
-
pywbem._cim_constants.
CIM_ERR_NAMESPACE_NOT_EMPTY
= 20¶ The specified namespace is not empty. New in pywbem 0.9.
-
pywbem._cim_constants.
CIM_ERR_INVALID_ENUMERATION_CONTEXT
= 21¶ The enumeration identified by the specified context cannot be found, is in a closed state, does not exist, or is otherwise invalid. New in pywbem 0.9.
-
pywbem._cim_constants.
CIM_ERR_INVALID_OPERATION_TIMEOUT
= 22¶ The specified operation timeout is not supported by the WBEM server. New in pywbem 0.9.
-
pywbem._cim_constants.
CIM_ERR_PULL_HAS_BEEN_ABANDONED
= 23¶ The pull operation has been abandoned due to execution of a concurrent CloseEnumeration operation on the same enumeration. New in pywbem 0.9.
-
pywbem._cim_constants.
CIM_ERR_PULL_CANNOT_BE_ABANDONED
= 24¶ The attempt to abandon a concurrent pull operation on the same enumeration failed. The concurrent pull operation proceeds normally. New in pywbem 0.9.
-
pywbem._cim_constants.
CIM_ERR_SERVER_LIMITS_EXCEEDED
= 27¶ The WBEM server has failed the operation based upon exceeding server limits. New in pywbem 0.9.
-
pywbem._cim_constants.
CIM_ERR_SERVER_IS_SHUTTING_DOWN
= 28¶ The WBEM server is shutting down and cannot process the operation. New in pywbem 0.9.
-
pywbem._cim_constants.
DEFAULT_NAMESPACE
= 'root/cimv2'¶ Default CIM namespace for WBEM connection
-
pywbem._cim_constants.
DEFAULT_URL_SCHEME
= 'http'¶ Default URL scheme for WBEM connection New in pywbem 1.0.
-
pywbem._cim_constants.
DEFAULT_URL_PORT_HTTP
= 5988¶ Default port number for http WBEM connection New in pywbem 1.0.
-
pywbem._cim_constants.
DEFAULT_URL_PORT_HTTPS
= 5989¶ Default port number for https WBEM connection New in pywbem 1.0.
Exceptions¶
The following exceptions are pywbem specific exceptions that can be raised at the WBEM client library API.
-
class
pywbem.
ConnectionError
(message, conn_id=None)[source]¶ This exception indicates a problem with the connection to the WBEM server. A retry may or may not succeed. Derived from
Error
.Parameters: - message (string) – Error message (will be put into args[0]).
- conn_id (connection id) – Connection ID of the connection in whose context the error happened. Omitted or None if the error did not happen in context of any connection, or if the connection context was not known.
Variables: args – A tuple (message, ) set from the corresponding init arguments.
Methods
with_traceback
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self. Attributes
args
conn_id
Connection ID of the connection in whose context the error happened. conn_str
String that identifies the connection in exception messages. Details
-
class
pywbem.
AuthError
(message, conn_id=None)[source]¶ This exception indicates an authentication error with the WBEM server, either during TLS/SSL handshake, or during HTTP-level authentication. Derived from
Error
.Parameters: - message (string) – Error message (will be put into args[0]).
- conn_id (connection id) – Connection ID of the connection in whose context the error happened. Omitted or None if the error did not happen in context of any connection, or if the connection context was not known.
Variables: args – A tuple (message, ) set from the corresponding init arguments.
Methods
with_traceback
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self. Attributes
args
conn_id
Connection ID of the connection in whose context the error happened. conn_str
String that identifies the connection in exception messages. Details
-
class
pywbem.
HTTPError
(status, reason, cimerror=None, cimdetails=None, conn_id=None, request_data=None, response_data=None)[source]¶ This exception indicates that the WBEM server returned an HTTP response with a bad HTTP status code. Derived from
Error
.The args instance variable is a tuple (status, reason, cimerror, cimdetails).
The message instance variable is not set.
Occurrence of this exception nearly always indicates an issue with the WBEM server.
Parameters: - status (integer) – HTTP status code (e.g. 500).
- reason (string) – HTTP reason phrase (e.g. “Internal Server Error”).
- cimerror (string) – Value of the CIMError HTTP header field, if present. None, otherwise.
- cimdetails (dict) –
Dictionary with CIMOM-specific header fields with details about the situation reported in the CIMError header field.
- Key: header field name (e.g. PGErrorDetail)
- Value: header field value (i.e. text message)
Passing None will result in an empty dictionary.
- conn_id (connection id) – Connection ID of the connection in whose context the error happened. None if the error did not happen in context of any connection, or if the connection context was not known.
- request_data (string) – CIM-XML request string. None means the exception does not store a CIM-XML request.
- response_data (string) – CIM-XML response string. None means the exception does not store a CIM-XML response.
Variables: args – A tuple (status, reason, cimerror, cimdetails) set from the corresponding init arguments.
Methods
with_traceback
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self. Attributes
args
cimdetails
CIMOM-specific details on the situation reported in the CIMError header field. cimerror
Value of CIMError HTTP header field in response, if present. conn_id
Connection ID of the connection in whose context the error happened. conn_str
String that identifies the connection in exception messages. reason
HTTP reason phrase. request_data
CIM-XML request string (settable). response_data
CIM-XML response string (settable). status
HTTP status code. Details
-
status
¶ HTTP status code.
Example: 500
See RFC2616 for a list of HTTP status codes and reason phrases.
Type: integer
-
reason
¶ HTTP reason phrase.
Example: “Internal Server Error”
See RFC2616 for a list of HTTP status codes and reason phrases.
Type: string
-
class
pywbem.
TimeoutError
(message, conn_id=None)[source]¶ This exception indicates that the client timed out waiting for the WBEM server. Derived from
Error
.Parameters: - message (string) – Error message (will be put into args[0]).
- conn_id (connection id) – Connection ID of the connection in whose context the error happened. Omitted or None if the error did not happen in context of any connection, or if the connection context was not known.
Variables: args – A tuple (message, ) set from the corresponding init arguments.
Methods
with_traceback
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self. Attributes
args
conn_id
Connection ID of the connection in whose context the error happened. conn_str
String that identifies the connection in exception messages. Details
-
class
pywbem.
ParseError
(message, conn_id=None, request_data=None, response_data=None)[source]¶ This exception indicates a parsing error with the CIM-XML operation response the pywbem client received, or with the CIM-XML indication request the pywbem listener received.
Derived from
Error
.The CIM-XML response data is part of the str() representation of the exception.
This exception is a base class for more specific exceptions:
CIMXMLParseError
- Issue at the CIM-XML level (e.g. NAME attribute missing on CLASS element)XMLParseError
- Issue at the XML level (e.g. ill-formed XML)HeaderParseError
- Issue with HTTP headers (e.g. invalid content-type header)
Occurrence of this exception nearly always indicates an issue with the WBEM server.
Parameters: - message (string) – Error message (will be put into args[0]).
- conn_id (connection id) – Connection ID of the connection in whose context the error happened. None if the error did not happen in context of any connection, or if the connection context was not known.
- request_data (string) – CIM-XML request string. None means the exception does not store a CIM-XML request.
- response_data (string) – CIM-XML response string. None means the exception does not store a CIM-XML response.
Variables: args – A tuple (message, ) set from the corresponding init argument.
Methods
with_traceback
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self. Attributes
args
conn_id
Connection ID of the connection in whose context the error happened. conn_str
String that identifies the connection in exception messages. request_data
CIM-XML request string (settable). response_data
CIM-XML response string (settable). Details
-
class
pywbem.
CIMXMLParseError
(message, conn_id=None, request_data=None, response_data=None)[source]¶ This exception indicates a specific kind of
ParseError
that is an issue at the CIM-XML level.Example: ‘NAME’ attribute missing on ‘CLASS’ element.
Occurrence of this exception nearly always indicates an issue with the WBEM server.
Parameters: - message (string) – Error message (will be put into args[0]).
- conn_id (connection id) – Connection ID of the connection in whose context the error happened. None if the error did not happen in context of any connection, or if the connection context was not known.
- request_data (string) – CIM-XML request string. None means the exception does not store a CIM-XML request.
- response_data (string) – CIM-XML response string. None means the exception does not store a CIM-XML response.
Variables: args – A tuple (message, ) set from the corresponding init argument.
Methods
with_traceback
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self. Attributes
args
conn_id
Connection ID of the connection in whose context the error happened. conn_str
String that identifies the connection in exception messages. request_data
CIM-XML request string (settable). response_data
CIM-XML response string (settable). Details
-
class
pywbem.
XMLParseError
(message, conn_id=None, request_data=None, response_data=None)[source]¶ This exception indicates a specific kind of
ParseError
that is an issue at the XML level.Example: Ill-formed XML.
Occurrence of this exception nearly always indicates an issue with the WBEM server.
Parameters: - message (string) – Error message (will be put into args[0]).
- conn_id (connection id) – Connection ID of the connection in whose context the error happened. None if the error did not happen in context of any connection, or if the connection context was not known.
- request_data (string) – CIM-XML request string. None means the exception does not store a CIM-XML request.
- response_data (string) – CIM-XML response string. None means the exception does not store a CIM-XML response.
Variables: args – A tuple (message, ) set from the corresponding init argument.
Methods
with_traceback
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self. Attributes
args
conn_id
Connection ID of the connection in whose context the error happened. conn_str
String that identifies the connection in exception messages. request_data
CIM-XML request string (settable). response_data
CIM-XML response string (settable). Details
-
class
pywbem.
HeaderParseError
(message, conn_id=None, request_data=None, response_data=None)[source]¶ This exception indicates a specific kind of
ParseError
that is an issue with an HTTP header.Example: Invalid content-type.
Occurrence of this exception nearly always indicates an issue with the WBEM server.
Parameters: - message (string) – Error message (will be put into args[0]).
- conn_id (connection id) – Connection ID of the connection in whose context the error happened. None if the error did not happen in context of any connection, or if the connection context was not known.
- request_data (string) – CIM-XML request string. None means the exception does not store a CIM-XML request.
- response_data (string) – CIM-XML response string. None means the exception does not store a CIM-XML response.
Variables: args – A tuple (message, ) set from the corresponding init argument.
Methods
with_traceback
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self. Attributes
args
conn_id
Connection ID of the connection in whose context the error happened. conn_str
String that identifies the connection in exception messages. request_data
CIM-XML request string (settable). response_data
CIM-XML response string (settable). Details
-
class
pywbem.
CIMError
(status_code, status_description=None, instances=None, conn_id=None, request_data=None)[source]¶ This exception indicates that the WBEM server returned an error response with a CIM status code. Derived from
Error
.Accessing the CIM status code of a
CIMError
object:In Python 2, any
Exception
object can be accessed by index and slice and will delegate such access to itsargs
instance variable. In Python 3, that ability has been removed.In pywbem 0.9, the
status_code
andstatus_description
properties were added.Therefore, the following approach is not recommended, because it does not work on Python 3:
except CIMError as exc: status_code = exc[0]
The following approach works for pywbem 0.7 or newer:
except CIMError as exc: status_code = exc.args[0]
The following approach is recommended when using pywbem 0.9 or newer:
except CIMError as exc: status_code = exc.status_code
Parameters: - status_code (integer) – Numeric CIM status code.
- status_description (string) – CIM status description text returned by the server, representing a human readable message describing the error. None, if the server did not return a description text.
- instances (list of
CIMInstance
) – List of CIM instances returned by the WBEM server in the error response, that provide more details on the error. None if there are no such instances. - conn_id (connection id) – Connection ID of the connection in whose context the error happened. None if the error did not happen in context of any connection, or if the connection context was not known.
- request_data (string) – CIM-XML request string. None means the exception does not store a CIM-XML request.
Variables: args – A tuple (status_code, status_description, instances) set from the corresponding init arguments.
Methods
with_traceback
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self. Attributes
args
conn_id
Connection ID of the connection in whose context the error happened. conn_str
String that identifies the connection in exception messages. instances
CIM instances returned by the WBEM server in the error response, that provide more details on the error. request_data
CIM-XML request string (settable). status_code
Numeric CIM status code. status_code_name
Symbolic name of the CIM status code. status_description
CIM status description text returned by the server, representing a human readable message describing the error. Details
-
status_code
¶ Numeric CIM status code.
New in pywbem 0.9.
Example: 5
See CIM status codes for constants defining the numeric CIM status code values.
Type: integer
-
status_code_name
¶ Symbolic name of the CIM status code.
Example: “CIM_ERR_INVALID_CLASS”
New in pywbem 0.9.
If the CIM status code is invalid, the string “Invalid status code <status_code>” is returned.
Type: string
-
status_description
¶ CIM status description text returned by the server, representing a human readable message describing the error.
New in pywbem 0.9.
Example: “The specified class does not exist.”
If the server did not return a description, a short default text for the CIM status code is returned. If the CIM status code is invalid, the string “Invalid status code <status_code>” is returned.
Type: string
-
instances
¶ CIM instances returned by the WBEM server in the error response, that provide more details on the error.
New in pywbem 0.13.
None if there are no such instances.
Type: List of CIMInstance
-
class
pywbem.
ModelError
(message, conn_id=None)[source]¶ This exception indicates an error with the model implemented by the WBEM server, that was detected by the pywbem client.
Examples are mismatches in data types of CIM elements (properties, methods, parameters) between classes and instances, CIM elements that appear in instances without being declared in classes, or violations of requirements defined in advertised management profiles.
Derived from
Error
.Parameters: - message (string) – Error message (will be put into args[0]).
- conn_id (connection id) – Connection ID of the connection in whose context the error happened. Omitted or None if the error did not happen in context of any connection, or if the connection context was not known.
Variables: args – A tuple (message, ) set from the corresponding init argument.
Methods
with_traceback
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self. Attributes
args
conn_id
Connection ID of the connection in whose context the error happened. conn_str
String that identifies the connection in exception messages. Details
-
class
pywbem.
Error
(*args, **kwargs)[source]¶ Abstract base class for pywbem specific exceptions.
Parameters: - *args – Any other positional arguments are passed to
Exception
. - conn_id (connection id) – Connection ID of the connection in whose context the error happened. Omitted or None if the error did not happen in context of any connection, or if the connection context was not known. Must be specified as a keyword argument.
Methods
with_traceback
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self. Attributes
args
conn_id
Connection ID of the connection in whose context the error happened. conn_str
String that identifies the connection in exception messages. Details
-
conn_id
¶ Connection ID of the connection in whose context the error happened.
None if the error did not happen in context of any connection, or if the connection context was not known.
Type: connection id
-
conn_str
¶ String that identifies the connection in exception messages.
Type: unicode string
- *args – Any other positional arguments are passed to
-
class
pywbem.
_RequestExceptionMixin
(*args, **kwargs)[source]¶ An internal mixin class for pywbem specific exceptions that provides the ability to store the CIM-XML request string in the exception.
New in pywbem 1.0.
Derived classes using this mixin class need to specify it before the base error class.
Parameters: - *args – Any other positional arguments are passed on to the next superclass.
- **kwargs – Any other keyword arguments are passed on to the next superclass.
- request_data (string) – CIM-XML request string. Omitted or None means the exception does not store a CIM-XML request. Must be specified as a keyword argument; if specified it will be removed from the keyword arguments that are passed on.
Methods
Attributes
request_data
CIM-XML request string (settable). Details
-
class
pywbem.
_ResponseExceptionMixin
(*args, **kwargs)[source]¶ Mixin class into pywbem specific exceptions that provides the ability to store the CIM-XML response string in the exception.
New in pywbem 1.0.
Derived classes using this mixin class need to specify it before the base error class.
Parameters: - *args – Any other positional arguments are passed on to the next superclass.
- **kwargs – Any other keyword arguments are passed on to the next superclass.
- response_data (string) – CIM-XML response string. Omitted or None means the exception does not store a CIM-XML response. Must be specified as a keyword argument; if specified it will be removed from the keyword arguments that are passed on.
Methods
Attributes
response_data
CIM-XML response string (settable). Details
Warnings¶
The following warnings are pywbem specific warnings that can be issued by the WBEM client library.
-
class
pywbem.
Warning
(*args, **kwargs)[source]¶ Base class for pywbem specific warnings.
Parameters: - *args – Any other positional arguments are passed to
Exception
. - conn_id (connection id) – Connection ID of the connection in whose context the error happened. Omitted or None if the error did not happen in context of any connection, or if the connection context was not known. Must be specified as a keyword argument.
Methods
with_traceback
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self. Attributes
args
conn_id
Connection ID of the connection in whose context the error happened. conn_str
String that identifies the connection in exception messages. Details
- *args – Any other positional arguments are passed to
-
class
pywbem.
ToleratedServerIssueWarning
(*args, **kwargs)[source]¶ This warning indicates an issue with the WBEM server that has been tolerated by pywbem.
Parameters: - *args – Any other positional arguments are passed to
Exception
. - conn_id (connection id) – Connection ID of the connection in whose context the error happened. Omitted or None if the error did not happen in context of any connection, or if the connection context was not known. Must be specified as a keyword argument.
Methods
with_traceback
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self. Attributes
args
conn_id
Connection ID of the connection in whose context the error happened. conn_str
String that identifies the connection in exception messages. Details
- *args – Any other positional arguments are passed to
WBEM operation statistics¶
New in pywbem 0.11 as experimental and finalized in 0.12.
Pywbem supports measuring the elapsed times of the WBEM operations that were performed in context of a connection, and maintaining a statistics over these times.
This capability is disabled by default and can be enabled in either of these ways:
- When creating a
WBEMConnection
object, via itsstats_enabled
argument. - After the
WBEMConnection
object has been created, by modifying itsstats_enabled
instance attribute.
The Statistics
class maintains statistics over the measured
elapsed times of the WBEM operations and is the interface for accessing the
statistics. The statistics of a WBEMConnection
object are
accessible via its statistics
instance
attribute.
The OperationStatistic
class is a helper class that contains
the actual measurement data for one operation name.
There will be one OperationStatistic
object each operation
name (see the table of WBEMConnection methods in the WBEM operations
section for the operation names).
The OperationStatistic
objects are under control of the
Statistics
class.
The statistics support maintains two kinds of times for each kind of WBEM operation:
Client times: The elapsed times for the WBEMConnection operation methods from call to return. This is measured in pywbem pretty close to the API the pywbem user is calling.
Server times: The elapsed times for processing the WBEM operations in the WBEM server from receiving the CIM-XML request message to sending back the CIM-XML response message. The server times are not measured by pywbem, but are taken from the WBEMServerResponseTime HTTP header field of a CIM-XML response, if present. See DSP0200 for a description of this header field.
The WBEMServerResponseTime HTTP header field is optionally implemented by WBEM servers. The following WBEM servers are known to implement this header field:
- OpenPegasus
The difference between client time and server time is the time spent in the pywbem client, plus the time spent on the network between client and server.
The statistics support also maintains the size of the HTTP body in the CIM-XML request and response messages, in Bytes.
These times and sizes are maintained as average, minimum and maximum values for each kind of operation in a connection.
Finally, the statistics support maintains the total count of operations and the count of operations that failed, for each kind of operation.
All data in the statistics applies to WBEM operations performed during periods of time where the statistics are enabled on a connection. Operations performed during periods of time where the statistics are disabled on a connection, are simply ignored in the statistics.
For the Iter methods of WBEMConnection (e.g.
IterEnumerateInstances()
), the WBEM operations
performed on behalf of them are subject of the statistics, but the Iter methods
themselves do not show up in the statistics.
The following example shows how statistics are enabled, and how statistics
values are accessed individually using the
get_op_statistic()
method:
conn = pywbem.WBEMConnection(..., stats_enabled=True)
# Perform some operations on this connection
insts_1 = conn.EnumerateInstances('CIM_Foo1', 'root/cimv2')
insts_2 = conn.EnumerateInstances('CIM_Foo2', 'root/cimv2')
insts_3 = conn.EnumerateInstances('CIM_Foo3', 'root/cimv2')
inst_paths_1 = conn.EnumerateInstanceNames('CIM_Foo1', 'root/cimv2')
# Access statistics values for EnumerateInstances
ei_stats = conn.statistics.get_op_statistic('EnumerateInstances')
ei_count = ei_stats.count
ei_avg_client_time = ei_stats.avg_time
ei_avg_server_time = ei_stats.avg_server_time
In the previous example, the values in ei_stats
are “live”, i.e. they
continue to be updated as operations are performed. If a snapshot is needed at
a certain point in time that remains unaffected by further operations, this can
be achieved using the snapshot()
method:
# Take snapshot and access statistics values for EnumerateInstances
stats_snapshot = dict(conn.statistics.snapshot())
ei_stats = stats_snapshot['EnumerateInstances']
ei_count = ei_stats.count
ei_avg_client_time = ei_stats.avg_time
ei_avg_server_time = ei_stats.avg_server_time
It is also possible to simply print the current statistics of a connection as a
formatted table, using the formatted()
method:
# Print statistics values for all operations
print(conn.statistics.formatted())
The output could look like this, if the WBEM server returns WBEM server response times:
Statistics (times in seconds, lengths in Bytes):
Count Excep ClientTime ServerTime RequestLen ReplyLen Operation
Cnt Avg Min Max Avg Min Max Avg Min Max Avg Min Max
3 0 0.234 0.100 0.401 0.204 0.080 0.361 1233 1000 1500 26667 20000 35000 EnumerateInstances
1 0 0.100 0.100 0.100 0.080 0.080 0.080 1200 1200 1200 22000 22000 22000 EnumerateInstanceNames
-
class
pywbem.
Statistics
(enable=False)[source]¶ New in pywbem 0.11 as experimental and finalized in 0.12.
The statistics of a connection, that captures and provides statistics data about the WBEM operations performed on the connection.
This class contains an operation statistic object (of class
OperationStatistic
) for each kind of WBEM operation.A
Statistics
object can be in a state of enabled or disabled. If enabled, it accumulates the elapsed times between subsequent calls to thestart_timer()
andstop_timer()
methods of classOperationStatistic
. If disabled, calls to these methods do not accumulate any time. Initially, the statistics container is disabled.The enablement state of the
Statistics
object is controlled by the statistics enablement state of the connection it belongs to (seepywbem.WBEMConnection.stats_enabled()
)This class can also be used as a context manager.
Parameters: enable ( bool
) – Initial enablement status for this statistics container.Methods
disable
Disable the statistics container. enable
Enable the statistics container. formatted
Return a human readable string with the statistics for this container. get_op_statistic
Get the OperationStatistic
object for an operation name or create a new object if an object for that name does not exist.reset
Reset all statistics and clear any statistic names. snapshot
Return a snapshot of the time statistics of this container. start_timer
This method is called by pywbem to start the timer for a particular operation execution. Attributes
enabled
Indicates whether the statistics container is enabled. Details
-
__enter__
()[source]¶ Enter method when the class is used as a context manager.
Starts the operation statistics for the name that was previously set via a call:
stats = Statistics() with stats(name='bla'): # do something
The class supports nesting of context managers:
stats = Statistics() with stats(name='bla1'): # do something for i in ...: with stats(name='bla2'): # do something
-
__exit__
(exc_type, exc_value, traceback)[source]¶ Exit method when the class is used as a context manager.
Stops the operation statistics that was started in the enter method.
-
__call__
(name)[source]¶ This allows the name parameter to be passed when the class is used as a context manager.
-
enabled
¶ Indicates whether the statistics container is enabled.
-
start_timer
(name)[source]¶ This method is called by pywbem to start the timer for a particular operation execution. It returns the corresponding
OperationStatistic
object, creating one if needed.The timer is subsequently stopped by pywbem by calling the
stop_timer()
method on the returnedOperationStatistic
object.Parameters: name (string) – Name of the operation. Returns: The operation statistic for the specified name. If this statistics container is disabled, a dummy operation statistic object is returned. Return type: OperationStatistic
-
get_op_statistic
(name)[source]¶ Get the
OperationStatistic
object for an operation name or create a new object if an object for that name does not exist.Parameters: name (string) – Name of the operation. Returns: The operation statistic for the specified operation name. If this statistics container is disabled, a dummy operation statistic object is returned. Return type: OperationStatistic
-
snapshot
()[source]¶ Return a snapshot of the time statistics of this container.
The snapshot represents the statistics data at the time this method is called, and remains unchanged even if the statistics of this container continues to be updated.
Returns: A list of tuples (name, stats) with: - name (string): Name of the operation
- stats (
OperationStatistic
): Time statistics for the operation
-
formatted
()[source]¶ Return a human readable string with the statistics for this container. The operations are sorted by decreasing average time.
The three columns for ServerTime are included only if the WBEM server has returned WBEM server response times.
The six columns for RequestLen and ReplyLen are included only if they are non-zero (this allows using this class for other purposes).
Example if statistics are enabled:
Statistics: Count ExcCnt Time [s] ServerTime [s] RequestLen [B] ReplyLen [B] Operation Avg Min Max Avg Min Max Avg Min Max Avg Min Max 3 0 0.234 0.100 0.401 0.204 0.080 0.361 1233 1000 1500 26667 20000 35000 EnumerateInstances 1 0 0.100 0.100 0.100 0.080 0.080 0.080 1200 1200 1200 22000 22000 22000 EnumerateInstanceNames . . .
Example if statistics are disabled:
Statistics: Disabled
-
-
class
pywbem.
OperationStatistic
(container, name)[source]¶ New in pywbem 0.11 as experimental and finalized in 0.12.
A statistics data keeper for the executions of all operations with the same operation name.
Objects of this class are created by the
Statistics
class and can be accessed by pywbem users through itsget_op_statistic()
andsnapshot()
methods.Parameters: - container (
Statistics
) – The statistics container that holds this operation statistic object. - name (string) – Name of the operation.
Methods
formatted
Return a formatted one-line string with the statistics values for the operation for which this statistics object maintains data. formatted_header
Return a two-line header. reset
Reset the statistics data for this object. start_timer
This is a low-level method that is called by pywbem at the begin of an operation. stop_timer
This is a low-level method is called by pywbem at the end of an operation. Attributes
avg_reply_len
The average size of the HTTP body in the CIM-XML responses of the measured operations, in Bytes. avg_request_len
The average size of the HTTP body in the CIM-XML requests of the measured operations, in Bytes. avg_server_time
The average elapsed server time for execution of the measured operations, in seconds. avg_time
The average elapsed client time for execution of the measured operations, in seconds. container
The statistics container that holds this statistics object. count
The number of measured operations. exception_count
The number of measured operations that resulted in an exception returned to the pywbem user (for example because a failure was indicated in the operation response of the WBEM server, or because pywbem itself detected a failure before sending the request or after receiving the response). max_reply_len
The maximum size of the HTTP body in the CIM-XML responses of the measured operations, in Bytes. max_request_len
The maximum size of the HTTP body in the CIM-XML requests of the measured operations, in Bytes. max_server_time
The maximum elapsed server time for execution of the measured operations, in seconds. max_time
The maximum elapsed client time for execution of the measured operations, in seconds. min_reply_len
The minimum size of the HTTP body in the CIM-XML responses of the measured operations, in Bytes. min_request_len
The minimum size of the HTTP body in the CIM-XML requests of the measured operations, in Bytes. min_server_time
The minimum elapsed server time for execution of the measured operations, in seconds. min_time
The minimum elapsed client time for execution of the measured operations, in seconds. name
Name of the operation for which this statistics object maintains data. stat_start_time
Point in time when the first statistic was taken since this object was either created or reset, in seconds since the epoch (for details, see time.time()
).Details
-
stat_start_time
¶ Point in time when the first statistic was taken since this object was either created or reset, in seconds since the epoch (for details, see
time.time()
).Type: float
-
container
¶ The statistics container that holds this statistics object.
Type: Statistics
-
exception_count
¶ The number of measured operations that resulted in an exception returned to the pywbem user (for example because a failure was indicated in the operation response of the WBEM server, or because pywbem itself detected a failure before sending the request or after receiving the response).
Type: integer
-
avg_time
¶ The average elapsed client time for execution of the measured operations, in seconds.
Type: float
-
min_time
¶ The minimum elapsed client time for execution of the measured operations, in seconds.
Type: float
-
max_time
¶ The maximum elapsed client time for execution of the measured operations, in seconds.
Type: float
-
avg_server_time
¶ The average elapsed server time for execution of the measured operations, in seconds.
This time is 0 if the WBEM server did not return the WBEM server response time.
Type: float
-
min_server_time
¶ The minimum elapsed server time for execution of the measured operations, in seconds.
This time is 0 if the WBEM server did not return the WBEM server response time.
Type: float
-
max_server_time
¶ The maximum elapsed server time for execution of the measured operations, in seconds.
This time is 0 if the WBEM server did not return the WBEM server response time.
Type: float
-
avg_request_len
¶ The average size of the HTTP body in the CIM-XML requests of the measured operations, in Bytes.
Type: float
-
min_request_len
¶ The minimum size of the HTTP body in the CIM-XML requests of the measured operations, in Bytes.
Type: float
-
max_request_len
¶ The maximum size of the HTTP body in the CIM-XML requests of the measured operations, in Bytes.
Type: float
-
avg_reply_len
¶ The average size of the HTTP body in the CIM-XML responses of the measured operations, in Bytes.
Type: float
-
min_reply_len
¶ The minimum size of the HTTP body in the CIM-XML responses of the measured operations, in Bytes.
Type: float
-
max_reply_len
¶ The maximum size of the HTTP body in the CIM-XML responses of the measured operations, in Bytes.
Type: float
-
start_timer
()[source]¶ This is a low-level method that is called by pywbem at the begin of an operation. It starts the measurement for that operation, if statistics is enabled for the connection.
A subsequent invocation of
stop_timer()
will complete the measurement for that operation and will update the statistics data.
-
stop_timer
(request_len=None, reply_len=None, server_time=None, exception=False)[source]¶ This is a low-level method is called by pywbem at the end of an operation. It completes the measurement for that operation by capturing the needed data, and updates the statistics data, if statistics is enabled for the connection.
Parameters: - request_len (integer) – Size of the HTTP body of the CIM-XML request message, in Bytes.
- reply_len (integer) – Size of the HTTP body of the CIM-XML response message, in Bytes.
- exception (
bool
) – Boolean that specifies whether an exception was raised while processing the operation. - server_time (
bool
) – Time in seconds that the server optionally returns to the client in the HTTP response defining the time from when the server received the request to when it started sending the response. If None, there is no time from the server.
Returns: The elapsed time for the operation that just ended, or None if the statistics container holding this object is not enabled.
Return type:
-
formatted
(include_server_time, include_lengths)[source]¶ Return a formatted one-line string with the statistics values for the operation for which this statistics object maintains data.
This is a low-level method that is called by
pywbem.Statistics.formatted()
.
- container (
WBEM operation logging¶
New in pywbem 0.11 and redesigned in pywbem 0.12. Finalized in pywbem 0.13.
Pywbem logging overview¶
The pywbem package implements selected logging using the Python
logging
facility.
This section describes logging for use of the pywbem package as a WBEM client.
Section Logging in the listener describes logging for use of the pywbem
package as a WBEM listener.
Pywbem logging is used to record information passing between the pywbem client and WBEM servers but not as a general recorder for errors, state, etc. within pywbem. In effect it is a trace tool. Pywbem errors are generally passed to the pywbem API user as Python exceptions rather than being recorded in a log by a pywbem logger.
Pywbem logging uses two Python Logger
objects which are
termed pywbem loggers:
- API logger (Python logger name: ‘pywbem.api’) - Logs API calls and returns,
for the
WBEMConnection
methods that drive WBEM operations (see WBEM operations). This logs the API parameters and results, including CIM objects/exceptions. It also logs the creation ofWBEMConnection
objects to capture connection information in order to determine the connection to which a particular log record belongs. - HTTP logger (Python logger name: ‘pywbem.http’) - Logs HTTP requests and responses between the pywbem client and WBEM server. This logs the HTTP request data and response data including HTTP headers and CIM-XML payload.
Pywbem uses the logging.DEBUG
logging level for both loggers.
Pywbem adds a null handler to the logger named ‘pywbem’, in order to prevent the “No handlers could be found for logger …” warning. This follows best practices recommended in Configuring logging for a library and in several articles, for example in this article. Because this warning is no longer issued on Python 3.4 and higher, pywbem adds a null handler only on Python 2.7.
Because pywbem logs only at the logging.DEBUG
logging level, these
log events will not be printed by the Python root logger by default, and
therefore it is not necessary that pywbem attaches a null handler to any of its
loggers.
There are two steps to setting up pywbem logging:
Configure Python logging parameters
Sets the Python logging parameters for a pywbem logger or its parent loggers, such as log handler, message format, and logging level.
This can be done with Python logging functions or with the functions described in Logging configuration functions.
Activate WBEM connection(s) for logging and set detail level
In order to save the cycles for capturing the possibly large amounts of data needed for creating the log records, pywbem logging is inactive by default. Logging can be activated for an existing WBEM connection, or for all subsequently created WBEM connections.
Because the pywbem loggers can generate large quantities of information, the user can control the quantity of information produced by each pywbem logger by setting a detail level for each logger when activating a WBEM connection for logging.
Activation and setting detail levels are pywbem features so it requires using the functions described in Logging configuration functions.
Logging configuration functions¶
The pywbem loggers may be configured and/or WBEM connections may be activated for logging through the following pywbem functions.
These functions are the only mechanism for setting the detail level of a pywbem logger and for activating WBEM connection(s) for logging.
configure_logger()
- Configure the pywbem loggers and optionally activate WBEM connections for logging and setting a log detail level.configure_loggers_from_string()
- Configure the pywbem loggers and optionally activate WBEM connections for logging and setting a log detail level, from a log configuration string.This is most useful in defining the pywbem logging from a command line tool such as pywbemcli so the complete logger configuration can be compressed into a single command line string.
Logging configuration examples¶
Examples for using configure_logger()
for configuring pywbem loggers and
for activating WBEM connections for logging:
Example: Configure the ‘pywbem.api’ logger with detail level ‘summary’ and output to stderr, and activate all subsequently created WBEM connections for logging:
configure_logger('api', log_dest='stderr', detail_level='summary', connection=True) # All of the following connections will log to stderr with summary output: conn1 = WBEMConnection(...) conn2 = WBEMConnection(...)
Example: Configure all pywbem loggers with the default detail level (‘all’) and output to a file, and activate a single existing WBEM connection for logging:
conn = WBEMConnection(...) configure_logger('all', log_dest='file', log_filname='my_logfile.log', connection=conn)
Examples for configuring the pywbem loggers using Python logging methods, and using the pywbem logging configuration functions only for setting the detail level and for activating WBEM connections for logging:
Example: Configure the pywbem parent logger (named ‘pywbem’) for logging to a rotating file, configure both pywbem loggers for detail level ‘summary’, and activate all subsequent WBEM connections for logging:
import logging from logging.handlers import RotatingFileHandler logger = logging.getLogger('pywbem') handler = RotatingFileHandler("my_log.log", maxBytes=2000, backupCount=10) handler.setLevel(logging.DEBUG) formatter = logging.Formatter('%(asctime)s - %(name)s - %(message)s') handler.setFormatter(formatter) logger.addHandler(handler) # configure without setting log_dest configure_logger('api', detail_level='summary', connection=True) # All of the following connections will log using the rotating file handler: conn1 = WBEMConnection(...) conn2 = WBEMConnection(...)
Examples for using configure_loggers_from_string()
for configuring the
pywbem loggers and for activating WBEM connections for logging:
Example: Configure the ‘pywbem.api’ logger with detail level ‘summary’, output to stderr, and activate all subsequently created WBEM connections for logging:
configure_loggers_from_string('api=stderr:summary', connection=True) # All of the following connections will log: conn1 = WBEMConnection(...) conn2 = WBEMConnection(...)
Example: Configure both pywbem loggers with the default detail level (‘all’) and output to the file ‘my_log.log’, and activate a single existing WBEM connection object (conn) for logging:
conn = WBEMConnection(...) configure_loggers_from_string('all=file', log_filname='my_log.log', connection=conn)
Log records¶
The following is an example of log output with detail level ‘summary’, where ‘1-32073’ is the connection identifier:
2018-03-17 11:39:09,877-pywbem.api.1-32073-Connection:1-32073 WBEMConnection(url='http://localhost', creds=None, default_namespace='root/cimv2')
2018-03-17 11:41:13,176-pywbem.api.1-32073-Request:1-32073 EnumerateClasses(ClassName=None, DeepInheritance=None, IncludeClassOrigin=None, IncludeQualifiers=None, LocalOnly=None, namespace=None)
2018-03-17 11:41:13,635-pywbem.api.1-32073-Return:1-32073 EnumerateClasses(list of CIMClass; count=103)
The keywords in each log record (‘Connection’, ‘Request’, ‘Return’ or ‘Exception’) identify whether the log record is connection data, API/HTTP request data, API/HTTP response data, or API exception data.
The loggers that actually create the log records are children of the configured
pywbem loggers and are unique for each WBEMConnection
object.
Their logger names are created from the configured logger names by appending
the connection identifier (conn_id
).
Thus the names of the loggers that actually create the log records are of the
form: ‘pywbem.<api/http>.<conn_id>’.
Logging related constants and functions¶
Note: Due to limitations of the documentation tooling, the following constants
and functions are shown in the pywbem._logging
namespace. However, they
should be accessed via the pywbem
namespace.
-
pywbem._logging.
LOGGER_API_CALLS_NAME
= 'pywbem.api'¶ Name of the pywbem API logger, which logs user-issued calls to and returns from
WBEMConnection
methods that drive WBEM operations.
-
pywbem._logging.
LOGGER_HTTP_NAME
= 'pywbem.http'¶ Name of the pywbem HTTP logger, which logs HTTP requests and responses between the pywbem client and WBEM servers.
-
pywbem._logging.
LOGGER_SIMPLE_NAMES
= ['api', 'http', 'all']¶ List of the simple pywbem logger names that the logging configuration functions (see Logging configuration functions) recognize, as follows:
- ‘api’ - Pywbem API logger (Python logger name: ‘pywbem.api’)
- ‘http’ - Pywbem HTTP logger (Python logger name: ‘pywbem.http’)
- ‘all’ - All pywbem loggers
-
pywbem._logging.
LOG_DESTINATIONS
= ['file', 'stderr']¶ List of log destinations that the logging configuration functions recognize, as follows:
- ‘file’ - Log to a file (requires filename to be specified). The file logger appends to the logger file defined by filename.
- ‘stderr’ - Log to the standard error stream of the Python process
-
pywbem._logging.
DEFAULT_LOG_DESTINATION
= 'file'¶ Default log destination if not supplied to the logging configuration functions.
-
pywbem._logging.
LOG_DETAIL_LEVELS
= ['all', 'paths', 'summary']¶ List of the log detail levels that the logging configuration functions recognize, as follows:
- ‘all’ - All of the data available is output. Generally this is
the
repr()
output of the objects in the requests and responses. - ‘paths’ - For the API logger, for operations that return CIM classes or CIM instances, only their path component is output as a WBEM URI string. Otherwise, all of the data available is output.
- ‘summary’ - Only summary information is output. For the API logger this is primarily the count and type of objects returned. For the HTTP logger the HTTP header information is output.
- ‘all’ - All of the data available is output. Generally this is
the
-
pywbem._logging.
DEFAULT_LOG_DETAIL_LEVEL
= 'all'¶ Default log detail level if not supplied to the logging configuration functions.
-
pywbem._logging.
configure_logger
(simple_name, log_dest=None, detail_level='all', log_filename='pywbem.log', connection=None, propagate=False)[source]¶ Configure the pywbem loggers and optionally activate WBEM connections for logging and setting a log detail level.
Parameters: - simple_name (string) –
Simple name (ex. ‘api’) of the single pywbem logger this method should affect, or ‘all’ to affect all pywbem loggers.
Must be one of the strings in
LOGGER_SIMPLE_NAMES
. - log_dest (string) –
Log destination for the affected pywbem loggers, controlling the configuration of its Python logging parameters (log handler, message format, and log level).
If it is a string, it must be one of the strings in
LOG_DESTINATIONS
and the Python logging parameters of the loggers will be configured accordingly for their log handler, message format, and with a logging level oflogging.DEBUG
.If None, the Python logging parameters of the loggers will not be changed.
- detail_level (string or
int
or None) –Detail level for the data in each log record that is generated by the affected pywbem loggers.
If it is a string, it must be one of the strings in
LOG_DETAIL_LEVELS
and the loggers will be configured for the corresponding detail level.If it is an
int
, it defines the maximum size of the log records created and the loggers will be configured to output all available information up to that size.If None, the detail level configuration will not be changed.
- log_filename (string) – Path name of the log file (required if the log destination is ‘file’; otherwise ignored).
- connection (
WBEMConnection
orbool
or None) –WBEM connection(s) that should be affected for activation and for setting the detail level.
If it is a
bool
, the information for activating logging and for the detail level of the affected loggers will be stored for use by subsequently createdWBEMConnection
objects. A value of True will store the information to activate the connections for logging, and will add the detail level for the logger(s). A value of False will reset the stored information for future connections to be deactivated with no detail levels specified.If it is a
WBEMConnection
object, logging will be activated for that WBEM connection only and the specified detail level will be set for the affected pywbem loggers on the connection.If None, no WBEM connection will be activated for logging.
- propagate (
bool
) – Flag controlling whether the affected pywbem logger should propagate log events to its parent loggers.
Raises: ValueError
– Invalid input parameters (loggers remain unchanged).- simple_name (string) –
-
pywbem._logging.
configure_loggers_from_string
(log_configuration_str, log_filename='pywbem.log', connection=None, propagate=False)[source]¶ Configure the pywbem loggers and optionally activate WBEM connections for logging and setting a log detail level, from a log configuration string.
This is most useful in defining the loggers from a command line tool such as pywbemcli so the complete logger configuration can be compressed into a single command line string.
Parameters: - log_configuration_str (string) –
The log configuration string, in the following format:
log_specs := log_spec [ ',' log_spec ] log_spec := logger_simple_name [ '=' [ log_dest ] [ ":" [ detail_level ]]]]
where:
logger_simple_name
: Simple logger name. Must be one of the strings in theLOGGER_SIMPLE_NAMES
list.log_dest
: Log destination. Must be one of the strings in theLOG_DESTINATIONS
list. Default isDEFAULT_LOG_DESTINATION
.detail_level
: Log detail level. Must be one of the strings in theLOG_DETAIL_LEVELS
list. Default isDEFAULT_LOG_DETAIL_LEVEL
.
- log_filename (string) – Path name of the log file (required if any log destination is ‘file’; otherwise ignored).
- connection (
WBEMConnection
orbool
or None) –WBEM connection(s) that should be affected for activation and for setting the detail level.
If it is a
bool
, the information for activating logging and for the detail level of the affected loggers will be stored for use by subsequently createdWBEMConnection
objects. A value of True will store the information to activate the connections for logging, and will add the detail level for the logger(s). A value of False will reset the stored information for future connections to be deactivated with no detail levels specified.If it is a
WBEMConnection
object, logging will be activated for that WBEM connection only and the specified detail level will be set for the affected pywbem loggers on the connection.If None, no WBEM connection will be activated for logging.
- propagate (
bool
) – Flag controlling whether the affected pywbem logger should propagate log events to its parent loggers.
Raises: ValueError
– Invalid input parameters (loggers remain unchanged).Examples for log_configuration_str:
'api=stderr:summary' # Set 'pywbem.api' logger to stderr output with # summary detail level. 'http=file' # Set 'pywbem.http' logger to file output with # default detail level. 'api=stderr:summary' # Set 'pywbem.api' logger to file output with # summary output level. 'all=file:1000' # Set both pywbem loggers to file output with # a maximum of 1000 characters per log record. 'api=stderr,http=file' # Set 'pywbem.api' logger to stderr output and # 'pywbem.http' logger to file output, both # with default detail level.
- log_configuration_str (string) –
WBEM operation recording¶
The WBEM client library API provides the possibility to record the WBEM operations that are executed on a connection. WBEM Operation recording uses the classes and subclasses defined in WBEM operation recorders.
This is disabled by default and can be enabled by adding recorders to a
WBEMConnection
object with the method
add_operation_recorder()
.
Typical usage scenarios for various operation recorders are the tracing of WBEM operations, tracing of interactions with a WBEM server, or the generation of test cases.
Please note that the method of activating operation recorders changed starting
with pywbem 0.11.0 and the addition of a second recorder. See
add_operation_recorder()
for more information.
This adds the recorder defined in the method call to a list of active recorders
in the WBEMConnection
object. All active recorders are called
for each WBEM operation on a connection.
A recorder can be be disabled with
disable()
method and enabled with
enable()
method.
The following example activates the TestClientRecorder
recorder for a connection:
conn = WBEMConnection(...)
# Add a TestClientRecorder to the connection
yamlfp = TestClientRecorder.open_file(self.yamlfile, 'a')
tc_recorder = TestClientRecorder(yamlfp)
conn.add_operation_recorder(tc_recorder)
# TestClientRecorder is now active and will record WBEM operations
# on that connection.
. . .
# Disable the TestClientRecorder
tc_recorder.disable()
Note that the LogOperationRecorder
is dealt with through
the logging functions described in WBEM operation logging, and should
not be added to a conneciton by pywbem users.
Activated recorders can be computing-wise expensive so it is best not to activate a recorder unless it is to be used for that specific WBEMConnection.
The enable()
and
disable()
methods simply set
flags to bypass creating the final recorder output so activating and disabling
is still more compute-wise expensive than not activating a recorder at all.
WBEM operation recorders¶
The WBEM client library API includes the abstract base class
BaseOperationRecorder
from which operation recorders can be
written that perform specific recording tasks.
Users can write their own operation recorder classes based upon the
abstract base class BaseOperationRecorder
.
The WBEM client library API provides the following operation recorder classes:
Class | Purpose |
---|---|
TestClientRecorder |
Generate test cases for the test_client unit test module. |
LogOperationRecorder |
Generate logs using the Python logging
facility for
WBEMConnection
methods that communicate with a
WBEM server. |
-
class
pywbem.
BaseOperationRecorder
[source]¶ Abstract base class defining the interface to an operation recorder, that records the WBEM operations executed in a connection to a WBEM server.
Experimental: New in pywbem 0.9 as experimental.
An operation recorder can be added to a connection via the
add_operation_recorder()
method. The operation recorders of a connection can be retrieved via theoperation_recorders
property.Each operation that is executed on a connection will cause the
record()
method of those operation recorders of the connection to be called, that are enabled.After being added to a connection, an operation recorder is enabled. It can be disabled and re-enabled using the
disable()
andenable()
methods, respectively. This can be used to temporarily pause the recorder.Methods
disable
Disable the recorder. enable
Enable the recorder. open_file
A static convenience function that performs the open of the recorder file correctly for different versions of Python. record
Function that is called to record a single WBEM operation, i.e. record_staged
Encode staged information on request and result to output reset
Reset all the attributes in the class. stage_http_request
Set request HTTP information including url, headers, etc. stage_http_response1
Set response http info including headers, status, etc. stage_http_response2
Stage second part of http response, the payload stage_pywbem_args
Set requst method and all args. stage_pywbem_result
Set Result return info or exception info stage_wbem_connection
Stage information about the connection. Attributes
enabled
Indicate whether the recorder is enabled. Details
-
enabled
¶ Indicate whether the recorder is enabled.
New in pywbem 0.10.
-
static
open_file
(filename, file_mode='w')[source]¶ A static convenience function that performs the open of the recorder file correctly for different versions of Python.
New in pywbem 0.10.
This covers the issue where the file should be opened in text mode but that is done differently in Python 2 and Python 3.
The returned file-like object must be closed by the caller.
Parameters: Returns: File-like object.
Example:
recorder = TestClientRecorder(...) recorder_file = recorder.open_file('recorder.log') . . . # Perform WBEM operations using the recorder recorder_file.close()
-
reset
(pull_op=None)[source]¶ Reset all the attributes in the class. This also allows setting the pull_op attribute that defines whether the operation is to be a traditional or pull operation. This does NOT reset _conn.id as that exists through the life of the connection.
-
stage_wbem_connection
(wbem_connection)[source]¶ Stage information about the connection. Used only by LogOperationRecorder.
-
stage_pywbem_args
(method, **kwargs)[source]¶ Set requst method and all args. Normally called before the cmd is executed to record request parameters
-
stage_http_request
(conn_id, version, url, target, method, headers, payload)[source]¶ Set request HTTP information including url, headers, etc.
-
stage_http_response1
(conn_id, version, status, reason, headers)[source]¶ Set response http info including headers, status, etc. conn_id unused here. Used in log
-
record
(pywbem_args, pywbem_result, http_request, http_response)[source]¶ Function that is called to record a single WBEM operation, i.e. the invocation of a single
WBEMConnection
method.This function is called only when the recorder is enabled, i.e. it does not need to check for recorder enablement.
Parameters: - pywbem_args (
OpArgs
) – The name and input arguments of theWBEMConnection
method that is recorded. - pywbem_result (
OpResult
) – The result (return value or exception) of theWBEMConnection
method that is recorded. - http_request (
HttpRequest
) –The HTTP request sent by the
WBEMConnection
method that is recorded.None, if no HTTP request had been sent (e.g. because an exception was raised before getting there).
- http_response (
HttpResponse
) –The HTTP response received by the
WBEMConnection
method that is recorded.None, if no HTTP response had been received (e.g. because an exception was raised before getting there).
- pywbem_args (
-
-
class
pywbem.
OpArgs
[source]¶ A named tuple representing the name and input arguments of the invocation of a
WBEMConnection
method.Experimental: New in pywbem 0.9 as experimental.
Variables: - method (unicode string) – Name of the
WBEMConnection
method. - args (
dict
) – Dictionary of input arguments (both positional and keyword-based).
Create new instance of OpArgsTuple(method, args)
- method (unicode string) – Name of the
-
class
pywbem.
OpResult
[source]¶ A named tuple representing the result of the invocation of a
WBEMConnection
method.Experimental: New in pywbem 0.9 as experimental.
Variables: - ret (
object
) –Return value, if the method returned. None, if the method raised an exception.
Note that None may be a legitimate return value, so the test for exceptions should be done based upon the
exc
variable. - exc (
Exception
) – Exception object, if the method raised an exception. None, if the method returned.
Create new instance of OpResultTuple(ret, exc)
- ret (
-
class
pywbem.
HttpRequest
[source]¶ A named tuple representing the HTTP request sent by the WBEM client.
Experimental: New in pywbem 0.9 as experimental.
Variables: - version (number) – HTTP version from the request line (10 for HTTP/1.0, 11 for HTTP/1.1).
- url (unicode string) – URL of the WBEM server (e.g. ‘https://myserver.acme.com:15989’).
- target (unicode string) – Target URL segment as stated in request line (e.g. ‘/cimom’).
- method (unicode string) – HTTP method as stated in the request line (e.g. “POST”).
- headers (
dict
) –A dictionary of all HTTP header fields:
- key (unicode string): Name of the header field
- value (unicode string): Value of the header field
- payload (unicode string) – HTTP payload, i.e. the CIM-XML string.
Create new instance of HttpRequestTuple(version, url, target, method, headers, payload)
-
class
pywbem.
HttpResponse
[source]¶ A named tuple representing the HTTP response received by the WBEM client.
Experimental: New in pywbem 0.9 as experimental.
Variables: - version (number) – HTTP version from the response line (10 for HTTP/1.0, 11 for HTTP/1.1).
- status (number) – HTTP status code from the response line (e.g. 200).
- reason (unicode string) – HTTP reason phrase from the response line (e.g. “OK”).
- headers (
dict
) –A dictionary of all HTTP header fields:
- key (unicode string): Name of the header field
- value (unicode string): Value of the header field
- payload (unicode string) – HTTP payload, i.e. the CIM-XML string.
Create new instance of HttpResponseTuple(version, status, reason, headers, payload)
-
class
pywbem.
TestClientRecorder
(fp)[source]¶ An operation recorder that generates test cases for each recorded operation.
Experimental: New in pywbem 0.9 as experimental.
The test cases are in the YAML format suitable for the test_client unit test module of the pywbem project.
Parameters: fp (file) – An open file that each test case will be written to. This file should have been opened in text mode.
Since there are differences between python 2 and 3 in opening files in text mode, the static method
open_file()
can be used to open the file or python 2/3 compatible open:from io import open f = open('blah.log', encoding='utf-8')
Example:
recorder = TestClientRecorder( BaseOperationRecorder.open_file('recorder.log'))
Methods
disable
Disable the recorder. enable
Enable the recorder. open_file
A static convenience function that performs the open of the recorder file correctly for different versions of Python. record
Function that records the invocation of a single WBEMConnection
method, by appending a corresponding test case to the file.record_staged
Encode staged information on request and result to output reset
Reset all the attributes in the class. stage_http_request
Set request HTTP information including url, headers, etc. stage_http_response1
Set response http info including headers, status, etc. stage_http_response2
Stage second part of http response, the payload stage_pywbem_args
Set requst method and all args. stage_pywbem_result
Set Result return info or exception info stage_wbem_connection
Stage information about the connection. toyaml
Convert any allowable input argument to or return value from an operation method to an object that is ready for serialization into test_client yaml format. Attributes
EXCLUDE_REQUEST_HEADERS
EXCLUDE_RESPONSE_HEADERS
TESTCASE_PASSWORD
TESTCASE_URL
TESTCASE_USER
enabled
Indicate whether the recorder is enabled. Details
-
record
(pywbem_args, pywbem_result, http_request, http_response)[source]¶ Function that records the invocation of a single
WBEMConnection
method, by appending a corresponding test case to the file.Parameters: See
pywbem.BaseOperationRecorder.record()
.
-
-
class
pywbem.
LogOperationRecorder
(conn_id, detail_levels=None)[source]¶ A recorder that logs certain aspects of the WBEM operations driven by pywbem users to Python loggers.
Experimental: New in pywbem 0.11 and redesigned in pywbem 0.12 as experimental.
This recorder supports two Python loggers:
- API logger (Python logger name: ‘pywbem.api’) - Logs API calls and
returns, for the
WBEMConnection
methods that drive WBEM operations (see WBEM operations). This logs the API parameters and results, including CIM objects/exceptions. It also logs the creation ofWBEMConnection
objects to capture connection information in order to determine the connection to which a particular log record belongs. - HTTP logger (Python logger name: ‘pywbem.http’) - Logs HTTP requests and responses between the pywbem client and WBEM server. This logs the HTTP request data and response data including HTTP headers and CIM-XML payload.
All logging calls are at the
logging.DEBUG
logging level.Parameters: - conn_id (connection id) – String that represents an id for a particular connection that is used to build the name of each logger. The logger names are uniqueqly idenfified by the conn_id suffix to the logger name (ex.pywbem.ops.1-2343) so that each WBEMConnection could be logged with a separate logger.
- detail_levels (
dict
) – Dictionary identifying the detail level for one or both of the loggers. Key: Simple logger name (e.g. ‘api’). Value: Detail level, either a string fromLOG_DETAIL_LEVELS
, or an integer that specifies the maximum size of each log record.
Methods
disable
Disable the recorder. enable
Enable the recorder. open_file
A static convenience function that performs the open of the recorder file correctly for different versions of Python. record
Not used for logging record_staged
Not used for logging. reset
Reset all the attributes in the class. set_detail_level
Sets the detail levels from the input dictionary in detail_levels. stage_http_request
Log request HTTP information including url, headers, etc. stage_http_response1
Set response http info including headers, status, etc. stage_http_response2
Log complete http response, including response1 and payload stage_pywbem_args
Log request method and all args. stage_pywbem_result
Log result return or exception parameter. stage_wbem_connection
Log connection information. Attributes
enabled
Indicate whether the recorder is enabled. Details
-
set_detail_level
(detail_levels)[source]¶ Sets the detail levels from the input dictionary in detail_levels.
-
stage_wbem_connection
(wbem_connection)[source]¶ Log connection information. This includes the connection id (conn_id) that is output with the log entry. This entry is logged if either http or api loggers are enable. It honors both the logger and detail level of either api logger if defined or http logger if defined. If the api logger does not exist, the output shows this as an http loggger output since we do not want to create an api logger for this specific output
-
stage_pywbem_args
(method, **kwargs)[source]¶ Log request method and all args. Normally called before the cmd is executed to record request parameters. This method does not support the summary detail_level because that seems to add little info to the log that is not also in the response.
-
stage_pywbem_result
(ret, exc)[source]¶ Log result return or exception parameter. This method provides varied type of formatting based on the detail_level parameter and the data in ret.
-
stage_http_request
(conn_id, version, url, target, method, headers, payload)[source]¶ Log request HTTP information including url, headers, etc.
-
stage_http_response1
(conn_id, version, status, reason, headers)[source]¶ Set response http info including headers, status, etc.
- API logger (Python logger name: ‘pywbem.api’) - Logs API calls and
returns, for the
Mapping between ValueMap and Values qualifiers¶
The ValueMapping
class supports translating between the values
of an integer-typed CIM element (e.g. property, method, or parameter) that is
qualified with the ValueMap and Values qualifiers, and the corresponding
values of the Values qualifier, in both directions.
This class supports value ranges (e.g. "4..6"
) and the unclaimed marker
(".."
).
-
class
pywbem.
ValueMapping
[source]¶ New in pywbem 0.9 as experimental and finalized in 0.10.
A utility class that supports translating between the values of an integer-typed CIM element (property, method, parameter) that is qualified with the ValueMap and Values qualifiers, and the corresponding values of the Values qualifier, in both directions.
The CIM element may be a scalar or an array.
This is done by retrieving the CIM class definition defining the CIM element in question, and by inspecting its ValueMap and Values qualifiers.
The translation is performed by the
tovalues()
andtobinary()
methods.Instances of this class must be created through one of the factory class methods:
for_property()
,for_method()
, orfor_parameter()
.Value ranges (
"2..4"
) and the indicator for unclaimed values (".."
) in the ValueMap qualifier are supported.All representations of the integer values in the ValueMap qualifier are supported (decimal, binary, octal, hexadecimal), consistent with the definition of the ValueMap qualifier in DSP0004.
Example
Given the following definition of a property in MOF:
class CIM_Foo { [ValueMap{ "0", "2..4", "..6", "7..", "9", ".." }, Values{ "zero", "two-four", "five-six", "seven-eight", "nine", "unclaimed"}] uint16 MyProp; };
Assuming this class exists in a WBEM server, the following code will get the class from the server, create a value mapping for this property, and look up the Values strings that correspond to binary property values. This is useful when preparing binary property values for human consumption:
namespace = 'root/cimv2' conn = pywbem.WBEMConnection(...) # WBEM server myprop_vm = pywbem.ValueMapping.for_property( conn, namespace, 'CIM_Foo', 'MyProp') print("Binary value: Values string") for bin_value in range(0, 12): values_str = myprop_vm.tovalues(bin_value) print("{0:12}: {1!r}".format(bin_value, values_str))
Resulting output:
Binary value: Values string 0: 'zero' 1: 'unclaimed' 2: 'two-four' 3: 'two-four' 4: 'two-four' 5: 'five-six' 6: 'five-six' 7: 'seven-eight' 8: 'seven-eight' 9: 'nine' 10: 'unclaimed' 11: 'unclaimed'
Translating in the other direction is also of interest, for example when processing values that are provided by humans in terms of the Values strings, or when using the pywbem mock support and the test cases specify property values for CIM instances in terms of the more human-readable Values strings.
Again, assuming the class shown above exists in a WBEM server, the following code will get the class from the server, create a value mapping for this property, and look up the binary property values from the Values strings:
namespace = 'root/cimv2' conn = pywbem.WBEMConnection(...) # WBEM server myprop_vm = pywbem.ValueMapping.for_property( conn, namespace, 'CIM_Foo', 'MyProp') values_strs = ["zero", "two-four", "five-six", "seven-eight", "nine", "unclaimed"] print("Values string: Binary value") for values_str in values_strs: bin_value = myprop_vm.tobinary(values_str) print("{0:12}: {1!r}".format(values_str, bin_value))
Resulting output:
Values string: Binary value 'zero': 0 'two-four': (2, 4) 'five-six': (5, 6) 'seven-eight': (7, 8) 'nine': 9 'unclaimed': None
Iterating through the pairs of ValueMap and Values entries is also possible. Assuming the class shown above exists in a WBEM server, the following code will get the class from the server, and iterate through the value mapping:
namespace = 'root/cimv2' conn = pywbem.WBEMConnection(...) # WBEM server myprop_vm = pywbem.ValueMapping.for_property( conn, namespace, 'CIM_Foo', 'MyProp') print("Values string: Binary value") for bin_value, values_str in myprop_vm.items(): print("{0:12}: {1!r}".format(values_str, bin_value))
Resulting output:
Values string: Binary value 'zero': 0 'two-four': (2, 4) 'five-six': (5, 6) 'seven-eight': (7, 8) 'nine': 9 'unclaimed': None
Methods
for_method
Factory method that returns a new ValueMapping
instance that maps CIM method return values to the Values qualifier of that method.for_parameter
Factory method that returns a new ValueMapping
instance that maps CIM parameter values to the Values qualifier defined on that parameter.for_property
Factory method that returns a new ValueMapping
instance that maps CIM property values to the Values qualifier defined on that property.items
Generator that iterates through the items of the value mapping. tobinary
Return the integer value or values for a Values string, based upon this value mapping. tovalues
Return the Values string(s) for an element value, based upon this value mapping. Attributes
classname
Name of the CIM class defining the mapped CIM element. conn
Connection to the WBEM server containing the CIM namespace (that contains the mapped CIM element). element
The mapped CIM element. methodname
Name of the CIM method, that either is mapped itself, or that has the parameter that is mapped. namespace
Name of the CIM namespace containing the class that defines the mapped CIM element. parametername
Name of the CIM parameter that is mapped. propname
Name of the CIM property that is mapped. Details
-
classmethod
for_property
(server, namespace, classname, propname)[source]¶ Factory method that returns a new
ValueMapping
instance that maps CIM property values to the Values qualifier defined on that property.The CIM property may be a scalar or an array.
If a Values qualifier is defined but no ValueMap qualifier, a default of 0-based consecutive numbers is applied (that is the default defined in DSP0004).
Parameters: - server (
WBEMConnection
orWBEMServer
) – The connection to the WBEM server containing the namespace. - namespace (string) – Name of the CIM namespace containing the class. If None, the default namespace of the connection will be used.
- classname (string) – Name of the CIM class exposing the property. The property can be defined in that class or inherited into that class.
- propname (string) – Name of the CIM property that defines the Values / ValueMap qualifiers.
Returns: The new
ValueMapping
instance.Raises: - Exceptions raised by
WBEMConnection
. KeyError
– The CIM property does not exist in the CIM class.ModelError
– The CIM property is not integer-typed.ValueError
– No Values qualifier defined on the CIM property.ModelError
– Invalid integer representation in ValueMap qualifier defined on the CIM property.
- server (
-
classmethod
for_method
(server, namespace, classname, methodname)[source]¶ Factory method that returns a new
ValueMapping
instance that maps CIM method return values to the Values qualifier of that method.If a Values qualifier is defined but no ValueMap qualifier, a default of 0-based consecutive numbers is applied (that is the default defined in DSP0004).
Parameters: - server (
WBEMConnection
orWBEMServer
) – The connection to the WBEM server containing the namespace. - namespace (string) – Name of the CIM namespace containing the class.
- classname (string) – Name of the CIM class exposing the method. The method can be defined in that class or inherited into that class.
- methodname (string) – Name of the CIM method that defines the Values / ValueMap qualifiers.
Returns: The new
ValueMapping
instance.Raises: - Exceptions raised by
WBEMConnection
. KeyError
– The CIM method does not exist in the CIM class.ModelError
– The CIM method is not integer-typed.ValueError
– No Values qualifier defined on the CIM method.ModelError
– Invalid integer representation in ValueMap qualifier defined on the CIM method.
- server (
-
classmethod
for_parameter
(server, namespace, classname, methodname, parametername)[source]¶ Factory method that returns a new
ValueMapping
instance that maps CIM parameter values to the Values qualifier defined on that parameter.The CIM parameter may be a scalar or an array.
If a Values qualifier is defined but no ValueMap qualifier, a default of 0-based consecutive numbers is applied (that is the default defined in DSP0004).
Parameters: - server (
WBEMConnection
orWBEMServer
) – The connection to the WBEM server containing the namespace. - namespace (string) – Name of the CIM namespace containing the class.
- classname (string) – Name of the CIM class exposing the method. The method can be defined in that class or inherited into that class.
- methodname (string) – Name of the CIM method that has the parameter.
- parametername (string) – Name of the CIM parameter that defines the Values / ValueMap qualifiers.
Returns: The new
ValueMapping
instance.Raises: - Exceptions raised by
WBEMConnection
. KeyError
– The CIM method does not exist in the CIM class.KeyError
– The CIM parameter does not exist in the CIM method.ModelError
– The CIM parameter is not integer-typed.ValueError
– No Values qualifier defined on the CIM parameter.ModelError
– Invalid integer representation in ValueMap qualifier defined on the CIM parameter.
- server (
-
__repr__
()[source]¶ Return a representation of the
ValueMapping
object with all attributes, that is suitable for debugging.
-
conn
¶ Connection to the WBEM server containing the CIM namespace (that contains the mapped CIM element).
Type: WBEMConnection
-
namespace
¶ Name of the CIM namespace containing the class that defines the mapped CIM element.
Type: string
-
methodname
¶ Name of the CIM method, that either is mapped itself, or that has the parameter that is mapped. None, if no method or parameter is mapped.
Type: string
-
parametername
¶ Name of the CIM parameter that is mapped. None, if no parameter is mapped.
Type: string
-
element
¶ The mapped CIM element.
Type: CIMProperty
,CIMMethod
, orCIMParameter
-
tovalues
(element_value)[source]¶ Return the Values string(s) for an element value, based upon this value mapping.
The element value may be a single value or list/tuple of values and the return value will be a single string or list of strings, respectively. An element value of None causes None to be returned.
The passing of array values or scalar values does not need to match whether the element is array-typed or scalar-typed. For example, there may be a need to have the loop through a list of values of an array-typed element on the caller’s side, invoking this method in the loop with a single value. As another example, the method may be used to translate a list of possible values for a scalar-typed element in one call to this method by passing them as a list.
Parameters: element_value (integer or
CIMInt
or list/tuple thereof) – The value(s) of the CIM element. May be None.Returns: The Values string(s) for the element value. This is: * a single string, if the element value was a single value * a list of strings, if the element value was a list/tuple of values * None, if the element value was None
Return type: Raises: ValueError
– Element value outside of the set defined by ValueMap.TypeError
– Element value is not an integer type.
-
tobinary
(values_str)[source]¶ Return the integer value or values for a Values string, based upon this value mapping.
Due to the complexity of its return value, this method only supports a single Values string at a time. It does support array-typed elements, though. Thus, if multiple Values strings need to be translated, this method must be invoked once for each value to be translated.
Any returned integer value is represented as the CIM type of the element (e.g.
Uint16
).If the Values string corresponds to a single value, that single value is returned as an integer.
If the Values string corresponds to a value range (e.g. “1..” or “..2” or “3..4”), that value range is returned as a tuple with two items that are the lowest and the highest value of the range. That is the case also when the value range is open on the left side or right side.
If the Values string corresponds to the unclaimed indicator “..”, None is returned.
Parameters: values_str (string) – The Values string for the (single) element value. Must not be None.
Returns: The element value or value range corresponding to the Values string, or None for unclaimed.
Return type: Raises: ValueError
– Values string outside of the set defined by Values.TypeError
– Values string is not a string type.
-
items
()[source]¶ Generator that iterates through the items of the value mapping. The items are the array entries of the Values and ValueMap qualifiers, and they are iterated in the order specified in the arrays. If the ValueMap qualifier is not specified, the default of consecutive integers starting at 0 is used as a default, consistent with DSP0004.
Each iterated item is a tuple of integer value(s) representing the ValueMap array entry, and the corresponding Values string. Any integer value in the iterated items is represented as the CIM type of the element (e.g.
Uint16
).If the Values string corresponds to a single element value, the first tuple item is that single integer value.
If the Values string corresponds to a value range (e.g. “1..” or “..2” or “3..4”), that value range is returned as a tuple with two items that are the lowest and the highest value of the range. That is the case also when the value range is open on the left side or right side.
If the Values string corresponds to the unclaimed indicator “..”, the first tuple item is None.
Returns: iterator for tuple of integer value(s) and Values string.
-
classmethod
Support for PUnit and Units qualifiers¶
The pywbem.siunit_obj()
and pywbem.siunit()
functions translate
the PUnit
and Units
qualifier values into human readable SI conformant
unit strings.
Experimental: New in 1.1.0 as experimental
Note: These functions do not perform any class operations; they take the qualifiers as input.
The reason the Units
qualifier is still supported is that the DMTF CIM
Schema (as of its version 2.49) still contains a number of schema elements that
have the Units
qualifier but not the PUnit
qualifier set.
The format and valid base units for the PUnit
qualifier and the
valid values for the Units
qualifier are defined in Annex C of
DSP0004. Pywbem supports the definitions from DSP0004
version 2.8, and the following additional Units
qualifier values that are
used in DMTF CIM Schema version 2.49:
Additional Units values |
---|
-dBm |
Blocks |
Percentage |
Proportion |
Tenths of Revolutions per Minute |
By default, the string value returned from these functions may contain the
following Unicode characters outside of the 7-bit ASCII range. If the
use_ascii
parameter is True, these Unicode characters are replaced with
7-bit ASCII text as follows:
Unicode character code | Unicode | 7-bit ASCII |
---|---|---|
U+00B0: DEGREE SIGN | ° |
deg |
U+00B5: MICRO SIGN | µ |
u |
U+2030: PER MILLE SIGN | ‰ |
1/1000 |
U+2126: OHM SIGN | Ω |
Ohm |
U+00B2: SUPERSCRIPT TWO | ² |
^2 |
U+00B3: SUPERSCRIPT THREE | ³ |
^3 |
Examples:
PUnit("byte / second * 10^3")
->kB/s
PUnit("byte * 2^10")
->KiB
PUnit("hertz * 10^6")
->MHz
PUnit("ampere * 10^-3")
->mA
Units("KiloBits per Second")
->kbit/s
Units("Tenths of Degrees C")
->1/10 °C
Limitations:
- For PUnit qualifiers, vendor-defined base units are not supported
(e.g.
vendor:myunit
). - For PUnit qualifiers, space characters within the parenthesis of
decibel
(e.g.decibel ( A )
) are not supported. - For Units qualifiers, arbitrary numeric values that are part of the Units
value (e.g.
<numeric-value> NanoSeconds
orAmps at <numeric-value> Volts
) are not generally supported, but only for those cases that are used in the DMTF CIM Schema (as of its version 2.49):250 NanoSeconds
Amps at 120 Volts
-
pywbem.
siunit_obj
(cim_obj, use_ascii=False)[source]¶ Returns a human readable SI conformant unit string from the
PUnit
orUnits
qualifiers of the specified CIM object.Experimental: New in 1.1.0 as experimental
If the CIM object has both the
PUnit
andUnits
qualifiers set, thenPUnit
is used andUnits
is ignored.Parameters: - cim_obj (
CIMProperty
orCIMMethod
orCIMParameter
) – CIM object with qualifiers. - use_ascii (
bool
) – Replace any Unicode characters in the returned string with 7-bit ASCII replacements, as describedabove
.
Returns: Human readable SI conformant unit string, or None if the CIM object has neither the
PUnit
nor theUnits
qualifiers set.Return type: Raises: TypeError
– Invalid type for cim_objValueError
– Invalid format in PUnit qualifierValueError
– Unknown base unit in PUnit qualifierValueError
– Unknown unit in Units qualifier
- cim_obj (
-
pywbem.
siunit
(punit=None, units=None, use_ascii=False)[source]¶ Returns a human readable SI conformant unit string from the specified
PUnit
orUnits
qualifier values.Experimental: New in 1.1.0 as experimental
If both
punit
andunits
are specified, thenpunit
is used andunits
is ignored.Parameters: Returns: Human readable SI conformant unit string, or None if both qualifier value input parameters were None.
Return type: Raises: TypeError
– Invalid type for punit or unitValueError
– Invalid format in PUnit qualifierValueError
– Unknown base unit in PUnit qualifierValueError
– Unknown unit in Units qualifier
Security considerations¶
Authentication types¶
Authentication is the act of establishing the identity of a user on the client side to the server, and possibly also of establishing the identity of a server to the client.
There are two levels of authentication in CIM-XML:
TLS/SSL level authentication (only when HTTPS is used):
This kind of authentication is also known as transport level authentication. It is used during the TLS/SSL handshake protocol, before any HTTP requests flow.
In almost all cases (unless an anonymous cipher is used), this involves an X.509 certificate that is presented by the server (therefore called server certificate) and that allows the client to establish the identity of the server.
It optionally involves an X.509 certificate that is presented by the client (therefore called client certificate) and that allows the server to establish the identity of the client or even of the client user, and thus can avoid the use of credentials in the HTTP level authentication.
If a client certificate is used, the authentication scheme at the TLS/SSL level is called 2-way authentication (also known as client authentication or mutual SSL authentication). If a client certificate is not used, the authentication scheme is called 1-way authentication (also known as SSL authentication).
Userid/password credentials do not play any role in TLS/SSL level authentication.
HTTP level authentication:
This kind of authentication is used in HTTP/HTTPS requests and responses (in case of HTTPS, after the TLS/SSL handshake protocol has completed).
In case of Basic Authentication and Digest Authentication (see RFC2617), it involves passing credentials (userid and password) via the
Authenticate
andWWW-Authenticate
HTTP headers. In case of no authentication, credentials are not passed.A client can either provide the
Authenticate
header along with a request, hoping that the server supports the authentication scheme that was used.A client can also omit that header in the request, causing the server to send an error response with a
WWW-Authenticate
header that tells the client which authentication types are supported by the server (also known as a challenge). The client then repeats the first request with one of the supported authentication types.HTTP is extensible w.r.t. authentication schemes, and so is CIM-XML. However, pywbem only supports Basic Authentication and no authentication.
X.509 certificates do not play any role in HTTP level authentication.
HTTP/HTTPS knows a third level of authentication by the use of session cookies. CIM-XML does not define how cookies would be used, and pywbem does not deal with cookies in any way (i.e. it does not pass cookies provided in a response into the next request).
The following table shows the possible combinations of protocol, TLS/SSL level and HTTP level authentication schemes, which information items need to be provided to the WBEM client library, and whether the combination is supported by pywbem:
Protocol | SSL auth. | HTTP auth. | Credentials | Client cert. | CA cert. | Supported |
---|---|---|---|---|---|---|
HTTP | N/A | None | No | No | No | Yes (1) |
HTTP | N/A | Basic | Yes | No | No | Yes (2) |
HTTP | N/A | Digest | Yes | No | No | No |
HTTPS | 1-way | None | No | No | Yes (3) | Yes (1) |
HTTPS | 1-way | Basic | Yes | No | Yes (3) | Yes |
HTTPS | 1-way | Digest | Yes | No | Yes (3) | No |
HTTPS | 2-way | None | No | Yes | Yes (3) | Yes (4) |
HTTPS | 2-way | Basic | Yes | Yes | Yes (3) | Yes |
HTTPS | 2-way | Digest | Yes | Yes | Yes (3) | No |
Notes:
- This option does not allow a server to establish the identity of the user. Its use should be limited to environments where network access is secured.
- The use of HTTP Basic Authentication is strongly discouraged, because the password is sent unencrypted over the network.
- A CA certificate is needed, unless server certificate verification is disabled via the no_verification parameter (not recommended), or unless an anonymous cipher is used for the server certificate (not recommended).
- This is the most desirable option from a security perspective, if the WBEM server is able to establish the user identity based on the client certificate.
The protocol and authentication types that can be used on a connection to a
WBEM server are set by the user when creating the
WBEMConnection
object:
- The scheme of the URL in the url parameter controls whether the HTTP or HTTPS protocol is used.
- The cred parameter may specify credentials (userid/password). If specified,
pywbem uses them for Basic Authentication at the HTTP level. Pywbem provides
an
Authenticate
HTTP header on each request, and also handles server challenges transparently to the user of the WBEM client library, by retrying the original request. - The x509 parameter may specify an X.509 client certificate and key. If specified, pywbem uses 2-way authentication; otherwise it uses 1-way authentication at the TLS/SSL level.
- The ca_certs parameter controls which X.509 CA certificates are used to validate the X.509 server certificate returned by the WBEM server.
It is important to understand which side actually makes decisions about security-related parameters: The client only decides whether HTTP or HTTPS is used, and whether the server certificate is verified. The server decides everything else: Which HTTP authentication scheme is used (None, Basic, Digest), whether an X.509 client certificate is requested from the client and if so, whether it tolerates a client not providing one. In addition, when HTTPS is used, the client proposes cipher suites it supports, and the server picks one of them.
Therefore, the cred and x509 parameters do not control the authentication scheme that is actually used, but merely prepare pywbem to deal with whatever authentication scheme the WBEM server elects to use.
WBEM servers typically support corresponding configuration parameters.
Verification of the X.509 server certificate¶
When using HTTPS, the TLS/SSL handshake protocol requires that the server always returns an X.509 server certificate to the client (unless anonymous ciphers are used, which is not recommended).
Pywbem uses the requests Python package for communicating with the WBEM server, and thus delegates the validation of the server certificate to OpenSSL.
If the validation of the server certificate fails, the WBEM operation methods
of the WBEMConnection
object raise
pywbem.ConnectionError
with an according error message.
Validation of the server certificate can be disabled via the no_verification
parameter of WBEMConnection
. Disabling certificate
validation makes the communication of pywbem with the WBEM server vulnerable
to man-in-the-middle attacks, because the identity of the server cannot be
verified.
Use of X.509 client certificates¶
When using HTTPS, the TLS/SSL handshake protocol provides the option for the client to present an X.509 certificate to the server (therefore called client certificate).
This procedure is initiated by the server, by requesting that the client present a client certificate. If the client does not have one (for example, because the x509 parameter was not specified in pywbem), it must send an empty list of certificates to the server. Depending on the server configuration, the server may or may not accept an empty list. If a client certificate is presented, the server must validate it.
The server can support to accept the user identity specified in the client certificate as the user’s identity, and refrain from sending HTTP challenges that request credentials.
Authentication errors¶
The operation methods of WBEMConnection
raise
pywbem.AuthError
when the WBEM server returns HTTP status 401
“Unauthorized” and the retries in the client are exhausted. The server
typically returns that status in any of these situations:
- invalid credentials provided by client
- no credentials provided by client but server requires them
- user is not authorized to access a resource
- server does not support the HTTP authentication scheme used by the client. Pywbem uses the “Basic” authentication scheme, which is recommended in DSP0200.
Proxy support¶
Starting with version 1.0, pywbem supports HTTP and SOCKS 5 proxies for connecting to the WBEM server. This is done by utilizing the proxy support in the underlying requests Python package.
The proxies to be used can be specified using the proxies
init argument
of WBEMConnection
, or via the environment variables HTTP_PROXY
and HTTPS_PROXY.
If the proxies
init argument is not None, it takes precedence over the
environment variables and must be a dictionary with item keys ‘http’ and
‘https’. Each item value specifies the URL of the proxy that is to be used for
the WBEM server protocol specified by the key.
In case of the environment variables, the value of HTTP_PROXY and HTTPS_PROXY specify the URL of the proxy that is to be used for the http and https WBEM server protocol, respectively.
If the proxy support is used, the url
init argument of
WBEMConnection
specifies the connection properties the proxy
uses for connecting to the WBEM server. The no_verification
, ca_certs
,
and x509
init arguments are also applied to the connection between the proxy
and the WBEM server. The URL of the proxy specified via the proxies
init
argument or via the HTTP_PROXY and HTTPS_PROXY environment variables is what the
pywbem client uses to connect to the proxy.
The following examples show some typical cases and are not exhaustive. For the
full description of what is possible, refer to the Proxies section in the
documentation of the requests package. In these examples, the proxy URLs are
specified using the proxies
init argument, but they can also be specified
using the HTTP_PROXY and HTTPS_PROXY environment variables.
Use of an HTTP proxy requiring authentication:
proxies = {
'http': 'http://user:pass@10.10.1.10:3128',
'https': 'http://user:pass@10.10.1.10:1080',
}
conn = pywbem.WBEMConnection(..., proxies=proxies)
Use of SOCKS proxies requires installing the socks option of the requests Python package:
$ pip install requests[socks]
Use of a SOCKS 5 proxy requiring authentication where the DNS resolution for the WBEM server hostname is done on the client (where pywbem runs):
proxies = {
'http': 'socks5://user:pass@10.10.1.10:3128',
'https': 'socks5://user:pass@10.10.1.10:1080',
}
conn = pywbem.WBEMConnection(..., proxies=proxies)
Use of a SOCKS 5 proxy requiring authentication where the DNS resolution for the WBEM server hostname is done on the proxy:
proxies = {
'http': 'socks5h://user:pass@10.10.1.10:3128',
'https': 'socks5h://user:pass@10.10.1.10:1080',
}
conn = pywbem.WBEMConnection(..., proxies=proxies)
WBEM server library¶
New in pywbem 0.9 as experimental and finalized in 0.10.
The WBEM server library API of pywbem encapsulates selected functionality of a WBEM server for use by a WBEM client application, such as determining the Interop namespace and other basic information about the server, or the management profiles advertised by the server.
This chapter has the following sections:
- Example - An example on how to use the WBEM server library API.
- WBEMServer - The
WBEMServer
class serves as a general access point for clients to WBEM servers. It allows determining the Interop namespace of the server and other basic information about the server, or the advertised management profiles.
Example¶
The following example code displays some information about a WBEM server:
from pywbem import WBEMConnection, WBEMServer, ValueMapping
def explore_server(server_url, username, password):
print("WBEM server URL:\n {0}".format(server_url))
conn = WBEMConnection(server_url, (username, password))
server = WBEMServer(conn)
print("Brand:\n {0}".format(server.brand))
print("Version:\n {0}".format(server.version))
print("Interop namespace:\n {0}".format(server.interop_ns))
print("All namespaces:")
for ns in server.namespaces:
print(" {0}".format(ns))
print("Advertised management profiles:")
org_vm = ValueMapping.for_property(server, server.interop_ns,
'CIM_RegisteredProfile', 'RegisteredOrganization')
for inst in server.profiles:
org = org_vm.tovalues(inst['RegisteredOrganization'])
name = inst['RegisteredName']
vers = inst['RegisteredVersion']
print(" {0} {1} Profile {2}".format(org, name, vers))
Example output:
WBEM server URL:
http://0.0.0.0
Brand:
OpenPegasus
Version:
2.12.0
Interop namespace:
root/PG_Interop
All namespaces:
root/PG_InterOp
root/PG_Internal
root/cimv2
root
Advertised management profiles:
SNIA Indication Profile 1.1.0
SNIA Indication Profile 1.2.0
SNIA Software Profile 1.1.0
SNIA Software Profile 1.2.0
SNIA Profile Registration Profile 1.0.0
SNIA SMI-S Profile 1.2.0
SNIA Server Profile 1.1.0
SNIA Server Profile 1.2.0
DMTF Profile Registration Profile 1.0.0
DMTF Indications Profile 1.1.0
WBEMServer¶
-
class
pywbem.
WBEMServer
(conn)[source]¶ New in pywbem 0.9 as experimental and finalized in 0.10.
A representation of a WBEM server that serves as a general access point to a client.
It supports determining the Interop namespace of the server, all namespaces, its brand and version, the advertised management profiles and finally allows retrieving the central instances of an implementation of a management profile with one method invocation regardless of whether the profile implementation chose to implement the central or scoping class profile advertisement methodology (see section Profile advertisement methodologies).
It also provides functions to subscribe for indications.
Parameters: conn ( WBEMConnection
) – Connection to the WBEM server.Methods
create_namespace
Create the specified CIM namespace in the WBEM server and update this WBEMServer object to reflect the new namespace there. delete_namespace
Delete the specified CIM namespace in the WBEM server and update this WBEMServer object to reflect the removed namespace there. get_central_instances
Return the instance paths of the central instances of a management profile. get_selected_profiles
Return the CIM_RegisteredProfile instances representing a filtered subset of the management profiles advertised by the WBEM server, that can be filtered by registered organization, registered name, and/or registered version. Attributes
INTEROP_NAMESPACES
A class variable with the possible names of Interop namespaces that should be tried when determining the Interop namespace on the WBEM server. NAMESPACE_CLASSNAMES
A class variable with the possible names of CIM classes for representing CIM namespaces, that should be tried when determining the namespaces on the WBEM server. brand
Brand of the WBEM server. cimom_inst
CIM instance of class CIM_ObjectManager that represents the WBEM server. conn
Connection to the WBEM server. interop_ns
Name of the Interop namespace of the WBEM server. namespace_classname
Name of the CIM class that was found to represent the CIM namespaces of the WBEM server. namespace_paths
Instance paths of the CIM instances in the Interop namespace that represent the namespaces of the WBEM server. namespaces
Names of all namespaces of the WBEM server. profiles
The CIM_RegisteredProfile instances representing all management profiles advertised by the WBEM server. url
URL of the WBEM server. version
Version of the WBEM server. Details
-
INTEROP_NAMESPACES
= ['interop', 'root/interop', 'root/PG_Interop']¶ A class variable with the possible names of Interop namespaces that should be tried when determining the Interop namespace on the WBEM server.
-
NAMESPACE_CLASSNAMES
= ['CIM_Namespace', '__Namespace']¶ A class variable with the possible names of CIM classes for representing CIM namespaces, that should be tried when determining the namespaces on the WBEM server.
-
__str__
()[source]¶ Return a representation of the
WBEMServer
object with a subset of its attributes.
-
__repr__
()[source]¶ Return a representation of the
WBEMServer
object with all attributes, that is suitable for debugging.
-
conn
¶ Connection to the WBEM server.
Type: WBEMConnection
-
interop_ns
¶ Name of the Interop namespace of the WBEM server.
Raises: - Exceptions raised by
WBEMConnection
. CIMError
– CIM_ERR_NOT_FOUND, Interop namespace could not be determined.
Type: - Exceptions raised by
-
namespace_classname
¶ Name of the CIM class that was found to represent the CIM namespaces of the WBEM server.
Raises: - Exceptions raised by
WBEMConnection
. ModelError
– An error with the model implemented by the WBEM server.
Type: - Exceptions raised by
-
namespaces
¶ Names of all namespaces of the WBEM server.
Raises: - Exceptions raised by
WBEMConnection
. ModelError
– An error with the model implemented by the WBEM server.
Type: list
of string- Exceptions raised by
-
namespace_paths
¶ Instance paths of the CIM instances in the Interop namespace that represent the namespaces of the WBEM server.
Note: One WBEM server has been found to support an Interop namespace without representing it as a CIM instance. In that case, this property will not have an instance path for the Interop namespace, but the
namespaces
property will have the name of the Interop namespace.Raises: - Exceptions raised by
WBEMConnection
. ModelError
– An error with the model implemented by the WBEM server.
Type: list
ofCIMInstanceName
- Exceptions raised by
-
brand
¶ Brand of the WBEM server.
The brand is determined from the CIM_ObjectManager instance in the Interop namespace, by looking at its ElementName property.
For known WBEM servers, the brand is then normalized in order to make it identifiable:
"OpenPegasus"
"SFCB"
(Small Footprint CIM Broker)"WBEM Solutions J WBEM Server"
"EMC CIM Server"
"FUJITSU CIM Object Manager"
For all other WBEM servers, the brand is the value of the ElementName property, or the string
"unknown"
, if that property is not set or the empty string.Raises: - Exceptions raised by
WBEMConnection
. CIMError
– CIM_ERR_NOT_FOUND, Interop namespace could not be determined.CIMError
– CIM_ERR_NOT_FOUND, Unexpected number of CIM_ObjectManager instances.
Type:
-
version
¶ Version of the WBEM server.
None, if the version cannot be determined.
The version is determined from the CIM_ObjectManager instance in the Interop namespace, by looking at its ElementName property, or if that is not set, at its Description property, and by taking the string after
"version"
or"release"
(case insensitively).Raises: - Exceptions raised by
WBEMConnection
. CIMError
– CIM_ERR_NOT_FOUND, Interop namespace could not be determined.CIMError
– CIM_ERR_NOT_FOUND, Unexpected number of CIM_ObjectManager instances.
Type: - Exceptions raised by
-
cimom_inst
¶ CIM instance of class CIM_ObjectManager that represents the WBEM server.
Raises: - Exceptions raised by
WBEMConnection
. CIMError
– CIM_ERR_NOT_FOUND, Interop namespace could not be determined.CIMError
– CIM_ERR_NOT_FOUND, Unexpected number of CIM_ObjectManager instances.
Type: - Exceptions raised by
-
profiles
¶ The CIM_RegisteredProfile instances representing all management profiles advertised by the WBEM server.
Raises: - Exceptions raised by
WBEMConnection
. CIMError
– CIM_ERR_NOT_FOUND, Interop namespace could not be determined.
Type: list
ofCIMInstance
- Exceptions raised by
-
create_namespace
(namespace)[source]¶ Create the specified CIM namespace in the WBEM server and update this WBEMServer object to reflect the new namespace there.
This method attempts the following approaches for creating the namespace, in order, until an approach succeeds:
Namespace creation as described in the WBEM Server profile (DSP1092) via CIM method CIM_WBEMServer.CreateWBEMServerNamespace().
This is a new standard approach that is not likely to be widely implemented yet.
Issuing the CreateInstance operation using the CIM class representing namespaces (‘PG_Namespace’ for OpenPegasus, and ‘CIM_Namespace’ otherwise), against the Interop namespace.
This approach is typically supported in WBEM servers that support the creation of CIM namespaces. This approach is similar to the approach described in DSP0200.
Creating namespaces using the __Namespace pseudo-class has been deprecated already in DSP0200 1.1.0 (released in 01/2003), and pywbem does not implement that approach.
Parameters: namespace (string) – CIM namespace name. Must not be None. The namespace may contain leading and a trailing slash, both of which will be ignored.
Returns: The specified CIM namespace name in its standard format (i.e. without leading or trailing slash characters).
Return type: Raises: - Exceptions raised by
WBEMConnection
. ModelError
– An error with the model implemented by the WBEM server.
-
delete_namespace
(namespace)[source]¶ Delete the specified CIM namespace in the WBEM server and update this WBEMServer object to reflect the removed namespace there.
The specified namespace must be empty (i.e. must not contain any classes, instances, or qualifier types.
This method attempts the following approaches for deleting the namespace, in order, until an approach succeeds:
Issuing the DeleteInstance operation using the CIM class representing namespaces (‘PG_Namespace’ for OpenPegasus, and ‘CIM_Namespace’ otherwise), against the Interop namespace.
This approach is typically supported in WBEM servers that support the creation of CIM namespaces. This approach is similar to the approach described in DSP0200.
The approach described in the WBEM Server profile (DSP1092) via deleting the CIM_WBEMServerNamespace instance is not implemented because that would also delete any classes, instances, and qualifier types in the namespace.
Deleting namespaces using the __Namespace pseudo-class has been deprecated already in DSP0200 1.1.0 (released in 01/2003), and pywbem does not implement that approach.
Parameters: namespace (string) – CIM namespace name. Must not be None. The namespace may contain leading and a trailing slash, both of which will be ignored.
Returns: The specified CIM namespace name in its standard format (i.e. without leading or trailing slash characters).
Return type: Raises: - Exceptions raised by
WBEMConnection
. ModelError
– An error with the model implemented by the WBEM server.CIMError
– CIM_ERR_NOT_FOUND, Specified namespace does not exist.CIMError
– CIM_ERR_NAMESPACE_NOT_EMPTY, Specified namespace is not empty.
-
get_selected_profiles
(registered_org=None, registered_name=None, registered_version=None)[source]¶ Return the CIM_RegisteredProfile instances representing a filtered subset of the management profiles advertised by the WBEM server, that can be filtered by registered organization, registered name, and/or registered version.
Parameters: - registered_org (string) – A filter for the registered organization of the profile, matching (case insensitively) the RegisteredOrganization property of the CIM_RegisteredProfile instance, via its Values qualifier. If None, this parameter is ignored for filtering.
- registered_name (string) – A filter for the registered name of the profile, matching (case insensitively) the RegisteredName property of the CIM_RegisteredProfile instance. If None, this parameter is ignored for filtering.
- registered_version (string) – A filter for the registered version of the profile, matching (case insensitively) the RegisteredVersion property of the CIM_RegisteredProfile instance. Note that version strings may contain aplhabetic characters to indicate the draft level. If None, this parameter is ignored for filtering.
Returns: The CIM_RegisteredProfile instances representing the filtered subset of the management profiles advertised by the WBEM server.
Return type: list
ofCIMInstance
Raises: - Exceptions raised by
WBEMConnection
. CIMError
– CIM_ERR_NOT_FOUND, Interop namespace could not be determined.KeyError
– If an instance in the list of profiles is incomplete and does not include the required properties.
-
get_central_instances
(profile_path, central_class=None, scoping_class=None, scoping_path=None, reference_direction='dmtf', try_gci_method=False)[source]¶ Return the instance paths of the central instances of a management profile.
DMTF defines the following profile advertisement methodologies in DSP1033:
- GetCentralInstances methodology (new in DSP1033 1.1, only when explicitly requested by the caller)
- Central class methodology
- Scoping class methodology
A brief explanation of these methodologies can be found in section Profile advertisement methodologies.
Pywbem attempts all three profile advertisement methodologies in the order listed above.
All three methodologies start from the CIM_RegisteredProfile instance referenced by the profile_path parameter. That instance represents a management profile. In case of multiple uses of a component profile in a WBEM server, one such instance is supposed to represent one such profile use.
If the profile is a component profile and its implementation does not support the GetCentralInstances or central class methodologies, the central_class, scoping_class, and scoping_path parameters are required in order for the method to attempt the scoping class methodology. The method will not fail if these parameters are not provided, as long as the profile implementation supports the GetCentralInstances or central class methodology.
Example parameters for a 1-hop scoping path:
central_class = "CIM_Fan"
scoping_path = ["CIM_SystemDevice"]
scoping_class = "CIM_ComputerSystem"
Example parameters for a 2-hop scoping path:
central_class = "CIM_Sensor"
scoping_path = ["CIM_AssociatedSensor", "CIM_Fan", "CIM_SystemDevice"]
scoping_class = "CIM_ComputerSystem"
Parameters: - profile_path (
CIMInstanceName
) – Instance path of the CIM_RegisteredProfile instance representing the management profile (or its use, if there are multiple uses in a WBEM server). - central_class (string) –
Class name of central class defined by the management profile.
Will be ignored, unless the profile is a component profile and its implementation supports only the scoping class methodology. None will cause the scoping class methodology not to be attempted.
- scoping_class (string) –
Class name of scoping class defined by the management profile.
Will be ignored, unless the profile is a component profile and its implementation supports only the scoping class methodology. None will cause the scoping class methodology not to be attempted.
- scoping_path (list of string) –
Scoping path defined by the management profile.
Will be ignored, unless the profile is a component profile and its implementation supports only the scoping class methodology. None will cause the scoping class methodology not to be attempted.
- reference_direction (string) –
Defines the navigation direction across the CIM_ReferencedProfile association when navigating from the current profile to its scoping (= referencing, autonomous) profile when using the scoping class methodology, as follows:
- ’dmtf’ (default): Assume DMTF conformance, i.e. the ‘Dependent’ end is followed.
- ’snia’: Assume SNIA SMI-S conformance, i.e. the ‘Antecedent’ end is followed.
This parameter supports the different definitions between DMTF and SNIA SMI-S standards regarding the use of the two ends of the CIM_ReferencedProfile association:
- The DMTF standards define in DSP1033 and DSP1001:
- Antecedent = referenced profile = component profile
- Dependent = referencing profile = autonomous profile
- The SNIA SMI-S standard defines in the “Profile Registration
Profile” (in the SMI-S “Common Profiles” book):
- Antecedent = autonomous profile
- Dependent = component (= sub) profile
It should be assumed that all profiles that are directly or indirectly scoped by a particular top-level (= wrapper) specification implement the reference direction that matches the registered organisation of the top-level specification.
Examples:
- All profiles scoped by the SNIA SMI-S top-level specification should be assumed to implement the ‘snia’ reference direction.
- All profiles scoped by the DMTF SMASH wrapper specification should be assumed to implement the ‘dmtf’ reference direction.
- try_gci_method (
bool
) – Flag indicating that the GetCentralInstances methodology should be attempted. This methodology is not expected to be implemented by WBEM servers at this point, and causes undesirable behavior with some WBEM servers, so it is not attempted by default. Note that WBEM servers are required to support the scoping class methodology.
Returns: The instance paths of the central instances of the implementation of the management profile.
Return type: list
ofCIMInstanceName
Raises: - Exceptions raised by
WBEMConnection
. ModelError
– An error with the model implemented by the WBEM server.ValueError
– User errors regarding input parameter values.TypeError
– User errors regarding input parameter types.
-
WBEM indication listener¶
New in pywbem 0.9 as experimental and finalized in 0.10.
The WBEM indication listener API supports creating and managing a thread-based WBEM listener that waits for indications (i.e. events) emitted by a WBEM server using the CIM-XML protocol. The API supports registering callback functions that get called when indications are received by the listener.
See WBEM subscription manager for the API for viewing and managing subscriptions for indications on a WBEM server.
WBEMListener¶
New in pywbem 0.9 as experimental and finalized in 0.10.
The WBEMListener
class provides a thread-based WBEM listener
service that can receive CIM indications from multiple WBEM servers and that
calls registered callback functions to deliver the received indications.
Examples¶
The following example creates and runs a listener:
import logging
from socket import getfqdn
from pywbem import WBEMListener
def process_indication(indication, host):
'''This function gets called when an indication is received.'''
print("Received CIM indication from {host}: {ind!r}".
format(host=host, ind=indication))
def main():
# Configure logging of the listener via the Python root logger
logging.basicConfig(
filename='listener.log', level=logging.WARNING,
format='%(asctime)s - %(levelname)s - %(message)s')
certkeyfile = 'listener.pem'
listener = WBEMListener(host=getfqdn(),
http_port=5990,
https_port=5991,
certfile=certkeyfile,
keyfile=certkeyfile)
listener.add_callback(process_indication)
try:
listener.start()
# process_indication() will be called for each received indication
. . . # wait for some condition to end listening
finally:
listener.stop()
Alternative code using the class as a context manager:
with WBEMListener(...) as listener:
listener.add_callback(process_indication)
listener.start()
# process_indication() will be called for each received indication
... # wait for some condition to end listening
# listener.stop() has been called automatically
See the example in section WBEMSubscriptionManager for an example of using a listener in combination with a subscription manager.
Another listener example is in the script examples/listen.py
(when you
clone the GitHub pywbem/pywbem project). It is an interactive Python shell that
creates a listener and displays any indications it receives, in MOF format.
Logging in the listener¶
Each WBEMListener
object has its own separate Python logger
object with the name:
‘pywbem.listener.{id}’
where {id} is a string that is unique for each WBEMListener
object within the Python process.
The logger
property of a
WBEMListener
object provides access to that Python logger
object, if needed.
The listener will log any indications it receives and any responses it sends
back to the indication sender, at the logging.INFO
logging level.
In addition, it will log errors at the logging.ERROR
logging level.
Starting with Python 2.7, the Python root logger will by default (i.e. when not
being configured) print log records of logging level logging.WARNING
or greater to sys.stderr. So the indication and response interactions will not
be printed by default, but any errors logged at the logging.ERROR
logging level will be printed by default.
Pywbem adds a null handler to the logger named ‘pywbem’, in order to prevent the “No handlers could be found for logger …” warning. This follows best practices recommended in Configuring logging for a library and in several articles, for example in this article. Because this warning is no longer issued on Python 3.4 and higher, pywbem adds a null handler only on Python 2.7.
WBEMListener class¶
-
class
pywbem.
WBEMListener
(host, http_port=None, https_port=None, certfile=None, keyfile=None)[source]¶ New in pywbem 0.9 as experimental and finalized in 0.10.
A WBEM listener.
The listener supports starting and stopping threads that listen for CIM-XML ExportIndication messages using HTTP and/or HTTPS, and that pass any received indications on to registered callback functions.
The listener must be stopped in order to free the TCP/IP port it listens on. Using this class as a context manager ensures that the listener is stopped when leaving the context manager scope.
Parameters: - host (string) – IP address or host name at which this listener can be reached.
- http_port (string or integer) –
HTTP port at which this listener can be reached. Note that at least one port (HTTP or HTTPS) must be set.
None means not to set up a port for HTTP.
- https_port (string or integer) –
HTTPS port at which this listener can be reached.
None means not to set up a port for HTTPS.
- certfile (string) –
File path of certificate file to be used as server certificate during SSL/TLS handshake when creating the secure HTTPS connection.
It is valid for the certificate file to contain a private key; the server certificate sent during SSL/TLS handshake is sent without the private key.
None means not to use a server certificate file. Setting up a port for HTTPS requires specifying a certificate file.
- keyfile (string) –
File path of private key file to be used by the server during SSL/TLS handshake when creating the secure HTTPS connection.
It is valid to specify a certificate file that contains a private key.
None means not to use a private key file. Setting up a port for HTTPS requires specifying a private key file.
Methods
add_callback
Add a callback function to the listener. deliver_indication
This function is called by the listener threads for each received indication. start
Start the WBEM listener threads, if they are not yet running. stop
Stop the WBEM listener threads, if they are running. Attributes
certfile
File path of the certificate file used as server certificate during SSL/TLS handshake when creating the secure HTTPS connection. host
IP address or host name at which this listener can be reached. http_port
HTTP port at which this listener can be reached. http_started
Boolean indicating whether the listener is started for the HTTP port. https_port
HTTPS port at which this listener can be reached. https_started
Boolean indicating whether the listener is started for the HTTPS port. keyfile
File path of the private key file used by the server during SSL/TLS handshake when creating the secure HTTPS connection. logger
Logger object for this listener. Details
-
__str__
()[source]¶ Return a representation of the
WBEMListener
object with a subset of its attributes.
-
__repr__
()[source]¶ Return a representation of the
WBEMListener
object with all attributes, that is suitable for debugging.
-
__enter__
()[source]¶ New in pywbem 0.12.
Enter method when the class is used as a context manager.
Returns the listener object.
-
__exit__
(exc_type, exc_value, traceback)[source]¶ New in pywbem 0.12.
Exit method when the class is used as a context manager.
Stops the listener by calling
stop()
.
-
http_port
¶ HTTP port at which this listener can be reached.
None means there is no port set up for HTTP.
Type: integer
-
https_port
¶ HTTPS port at which this listener can be reached.
None means there is no port set up for HTTPS.
Type: integer
-
http_started
¶ Boolean indicating whether the listener is started for the HTTP port.
If no port is set up for HTTP, False is returned.
New in pywbem 0.12.
Type: bool
-
https_started
¶ Boolean indicating whether the listener is started for the HTTPS port.
If no port is set up for HTTPS, False is returned.
New in pywbem 0.12.
Type: bool
-
certfile
¶ File path of the certificate file used as server certificate during SSL/TLS handshake when creating the secure HTTPS connection.
None means there is no certificate file being used (that is, no port is set up for HTTPS).
Type: string
-
keyfile
¶ File path of the private key file used by the server during SSL/TLS handshake when creating the secure HTTPS connection.
None means there is no certificate file being used (that is, no port is set up for HTTPS).
Type: string
-
logger
¶ Logger object for this listener.
Each listener object has its own separate logger object with the name:
‘pywbem.listener.{id}’where {id} is a unique string for each listener object.
Users of the listener should not look up the logger object by name, but should use this property to get to it.
Type: logging.Logger
-
start
()[source]¶ Start the WBEM listener threads, if they are not yet running.
A thread serving CIM-XML over HTTP is started if an HTTP port was specified for the listener. A thread serving CIM-XML over HTTPS is started if an HTTPS port was specified for the listener.
These server threads will handle the ExportIndication export message described in DSP0200 and they will invoke the registered callback functions for any received CIM indications.
The listener must be stopped again in order to free the TCP/IP port it listens on. The listener can be stopped explicitly using the
stop()
method. The listener will be automatically stopped when the main thread terminates (i.e. when the Python process terminates), or whenWBEMListener
is used as a context manager when leaving its scope.Raises: OSError
– witherrno
=errno.EADDRINUSE
when the WBEM listener port is already in use.
-
deliver_indication
(indication, host)[source]¶ This function is called by the listener threads for each received indication. It is not supposed to be called by the user.
It delivers the indication to all callback functions that have been added to the listener.
If a callback function raises any exception this is logged as an error using the listener logger and the next registered callback function is called.
Parameters: - indication (
CIMInstance
) – Representation of the CIM indication to be delivered. - host (string) – Host name or IP address of WBEM server sending the indication.
- indication (
-
add_callback
(callback)[source]¶ Add a callback function to the listener.
The callback function will be called for each indication this listener receives from any WBEM server.
If the callback function is already known to the listener, it will not be added.
Parameters: callback ( callback_interface()
) – Callable that is being called for each CIM indication that is received while the listener threads are running.
-
pywbem.
callback_interface
(indication, host)[source]¶ New in pywbem 0.9 as experimental and finalized in 0.10.
Interface of a callback function that is provided by the user of the API and that will be called by the listener for each received CIM indication.
Parameters: - indication (
CIMInstance
) – Representation of the CIM indication that has been received. Its path attribute is None. - host (string) – Host name or IP address of WBEM server sending the indication.
Raises: Exception
– If a callback function raises any exception this is logged as an error using the listener logger and the next registered callback function is called.- indication (
WBEM subscription manager¶
New in pywbem 0.9 as experimental and finalized in 0.10.
The WBEM subscription manager API supports viewing and managing subscriptions for indications on a WBEM server.
See WBEM indication listener for the API for creating and managing a WBEM listener.
WBEMSubscriptionManager¶
New in pywbem 0.9 as experimental and finalized in 0.10.
The WBEMSubscriptionManager
class is a subscription manager
that provides for creating and removing indication subscriptions (including
indication filters and listener destinations) for multiple WBEM servers and
multiple WBEM listeners and for getting information about existing indication
subscriptions.
The WBEM listener is identified through its URL, so it may be the pywbem
listener (that is, a WBEMListener
object) or any other WBEM
listener.
This subscription manager supports three types of ownership of the CIM instances in WBEM servers that represent subscriptions, filters and listener destinations:
Owned
Owned CIM instances are created via the subscription manager and their life cycle is bound to the life cycle of the registration of that WBEM server with the subscription manager via
add_server()
.Owned CIM instances are deleted automatically when their WBEM server is deregistered from the subscription manager via
remove_server()
orremove_all_servers()
. In addition, they can be deleted by the user via the removal methods of theWBEMSubscriptionManager
class.Permanent
Permanent CIM instances are created via the subscription manager and their life cycle is independent of the life cycle of the registration of that WBEM server with the subscription manager.
Permanent CIM instances are not deleted automatically when their WBEM server is deregistered from the subscription manager. The user is responsible for their lifetime management: They can be deleted via the removal methods of the
WBEMSubscriptionManager
class.Static
Static CIM instances pre-exist in the WBEM server and cannot be deleted (or created) by a WBEM client.
If a client creates a subscription between a filter and a listener destination, the types of ownership of these three CIM instances may be arbitrarily mixed, with one exception:
- A permanent subscription cannot be created on an owned filter or an owned
listener destination. Allowing that would prevent the automatic life cycle
management of the owned filter or listener destination by the subscription
manager. This restriction is enforced by the
WBEMSubscriptionManager
class.
The WBEMSubscriptionManager
object remembers owned
subscriptions, filters, and listener destinations. If for some reason that
object gets deleted before all servers could be removed (e.g. because the
Python program aborts), the corresponding CIM instances in the WBEM server
still exist, but the knowledge is lost that these instances were owned by that
subscription manager. Therefore, the subscription manager discovers owned
subscriptions, filters, and listener destinations when a server is added.
For filters, this discovery is based upon the Name property. Therefore, if
the Name property is set by the user (e.g. because a management profile
requires a particular name), the filter must be permanent and cannot be owned.
Examples¶
The following example code demonstrates the use of a subscription manager to subscribe for a CIM alert indication on a WBEM server. The WBEM listener is assumed to exist somewhere and is identified by its URL:
from pywbem import WBEMConnection, WBEMServer, WBEMSubscriptionManager
server_url = 'http://myserver'
server_credentials = ('myuser', 'mypassword')
listener_url = 'http://mylistener'
conn = WBEMConnection(server_url, server_credentials)
server = WBEMServer(conn)
sub_mgr = WBEMSubscriptionManager(subscription_manager_id='fred')
# Register the server in the subscription manager:
server_id = sub_mgr.add_server(server)
# Add a listener destination in the server:
dest_inst = sub_mgr.add_listener_destinations(server_id, listener_url)
# Subscribe to a static filter of a given name:
filter1_name = "DMTF:Indications:GlobalAlertIndicationFilter"
filter1_insts = sub_mgr.get_all_filters(server_id)
for inst in filter1_insts:
if inst['Name'] == filter1_name:
sub_mgr.add_subscriptions(server_id, inst.path, dest_inst.path)
break
# Create a dynamic alert filter and subscribe to it:
filter2_source_ns = "root/cimv2"
filter2_query = "SELECT * FROM CIM_AlertIndication " \
"WHERE OwningEntity = 'DMTF' " \
"AND MessageID LIKE 'SVPC0123|SVPC0124|SVPC0125'"
filter2_language = "DMTF:CQL"
filter2_inst = sub_mgr.add_filter(
server_id, filter2_source_ns, filter2_query, filter2_language,
owned=True, filter_id="myalert")
sub_mgr.add_subscriptions(server_id, filter2_inst.path, dest_inst.path)
The following example code briefly shows how to use a subscription manager as a context manager, in order to get automatic cleanup of owned instances:
with WBEMSubscriptionManager('fred') as sub_mgr:
server_id = sub_mgr.add_server(server)
. . .
# The exit method automatically calls remove_all_servers(), which deletes
# all owned subscription, filter and destination instances in the servers
# that were registered.
The Tutorial section contains a tutorial about the subscription manager.
-
class
pywbem.
WBEMSubscriptionManager
(subscription_manager_id)[source]¶ New in pywbem 0.9 as experimental and finalized in 0.10.
A class for managing subscriptions for CIM indications in a WBEM server.
The class may be used as a Python context manager, in order to get automatic clean up (see
__exit__()
).Parameters: subscription_manager_id (string) –
A subscription manager ID string that is used as a component in the value of the Name property of indication filter and listener destination instances to help the user identify these instances in a WBEM server.
Must not be None.
The string must consist of printable characters, and must not contain the character ‘:’ because that is the separator between components within the value of the Name property.
The subscription manager ID must be unique on the current host.
For example, the form of the Name property of a filter instance is (for details, see
add_filter()
):"pywbemfilter:" {ownership} ":" {subscription_manager_id} ":" {filter_id} ":" {guid}
Raises: ValueError
– Incorrect input parameter values.TypeError
– Incorrect input parameter types.
Methods
add_filter
Add a dynamic indication filter to a WBEM server, by creating an indication filter instance (of CIM class “CIM_IndicationFilter”) in the Interop namespace of the server. add_listener_destinations
Register WBEM listeners to be the target of indications sent by a WBEM server. add_server
Register a WBEM server with the subscription manager. add_subscriptions
Add subscriptions to a WBEM server for a particular set of indications defined by an indication filter and for a particular set of WBEM listeners defined by the instance paths of their listener destinations, by creating indication subscription instances (of CIM class “CIM_IndicationSubscription”) in the Interop namespace of that server. get_all_destinations
Return all listener destinations in a WBEM server. get_all_filters
Return all indication filters in a WBEM server. get_all_subscriptions
Return all indication subscriptions in a WBEM server. get_owned_destinations
Return the listener destinations in a WBEM server owned by this subscription manager. get_owned_filters
Return the indication filters in a WBEM server owned by this subscription manager. get_owned_subscriptions
Return the indication subscriptions in a WBEM server owned by this subscription manager. remove_all_servers
Remove all registered WBEM servers from the subscription manager. remove_destinations
Remove listener destinations from a WBEM server, by deleting the listener destination instances in the server. remove_filter
Remove an indication filter from a WBEM server, by deleting the indication filter instance in the WBEM server. remove_server
Remove a registered WBEM server from the subscription manager. remove_subscriptions
Remove indication subscription(s) from a WBEM server, by deleting the indication subscription instances in the server. Attributes
Details
-
__str__
()[source]¶ Return a representation of the
WBEMSubscriptionManager
object with a subset of its attributes.
-
__repr__
()[source]¶ Return a representation of the
WBEMSubscriptionManager
object with all attributes, that is suitable for debugging.
-
__enter__
()[source]¶ New in pywbem 0.10.
Enter method when the class is used as a context manager. Returns the subscription manager object
-
__exit__
(exc_type, exc_value, traceback)[source]¶ New in pywbem 0.10.
Exit method when the class is used as a context manager.
It cleans up by calling
remove_all_servers()
.
-
add_server
(server)[source]¶ Register a WBEM server with the subscription manager. This is a prerequisite for adding listener destinations, indication filters and indication subscriptions to the server.
This method discovers listener destination, indication filter, and subscription instances in the WBEM server owned by this subscription manager, and registers them in the subscription manager as if they had been created through it.
In this discovery process, listener destination and indication filter instances are matched based upon the value of their Name property. Subscription instances are matched based upon the ownership of the referenced destination and filter instances: If a subscription references a filter or a destination that is owned by this subscription manager, it is considered owned by this subscription manager as well.
Parameters: server (
WBEMServer
) – The WBEM server.Returns: An ID for the WBEM server, for use by other methods of this class.
Return type: Raises: - Exceptions raised by
WBEMConnection
. ValueError
– Incorrect input parameter values.TypeError
– Incorrect input parameter types.
- Exceptions raised by
-
remove_server
(server_id)[source]¶ Remove a registered WBEM server from the subscription manager. This also unregisters listeners from that server and removes all owned indication subscriptions, owned indication filters and owned listener destinations.
Parameters: server_id (string) – The server ID of the WBEM server, returned by add_server()
.Raises: Exceptions raised by WBEMConnection
.
-
remove_all_servers
()[source]¶ Remove all registered WBEM servers from the subscription manager. This also unregisters listeners from these servers and removes all owned indication subscriptions, owned indication filters, and owned listener destinations.
Raises: Exceptions raised by WBEMConnection
.
-
add_listener_destinations
(server_id, listener_urls, owned=True)[source]¶ Register WBEM listeners to be the target of indications sent by a WBEM server.
This function automatically creates a listener destination instance (of CIM class “CIM_ListenerDestinationCIMXML”) for each specified listener URL in the Interop namespace of the specified WBEM server.
The form of the Name property of the created destination instance is:
"pywbemdestination:" {ownership} ":" {subscription_manager_id} ":" {guid}
where
{ownership}
is"owned"
or"permanent"
dependent on the owned argument;{subscription_manager_id}
is the subscription manager ID; and{guid}
is a globally unique identifier.Owned listener destinations are added or updated conditionally: If the listener destination instance to be added is already registered with this subscription manager and has the same property values, it is not created or modified. If it has the same path but different property values, it is modified to get the desired property values. If an instance with this path does not exist yet (the normal case), it is created.
Permanent listener destinations are created unconditionally, and it is up to the user to ensure that such an instance does not exist yet.
Parameters: - server_id (string) – The server ID of the WBEM server, returned by
add_server()
. - listener_urls (string or list of string) –
The URL or URLs of the WBEM listeners to be registered.
The WBEM listener may be a
WBEMListener
object or any external WBEM listener.Each listener URL string must have the format:
[{scheme}://]{host}:{port}
The following URL schemes are supported:
https
: Causes HTTPS to be used.http
: Causes HTTP to be used. This is the default
The host can be specified in any of the usual formats:
- a short or fully qualified DNS hostname
- a literal (= dotted) IPv4 address
- a literal IPv6 address, formatted as defined in RFC3986
with the extensions for zone identifiers as defined in
RFC6874, supporting
-
(minus) for the delimiter before the zone ID string, as an additional choice to%25
.
Note that the port is required in listener URLs.
See
WBEMConnection
for examples of valid URLs, with the caveat that the port in server URLs is optional. - owned (
bool
) – Defines the ownership type of the created listener destination instances: If True, they will be owned. Otherwise, they will be permanent. See WBEMSubscriptionManager for details about these ownership types.
Returns: The created listener destination instances for the defined listener URLs.
Return type: list
ofCIMInstance
Raises: Exceptions raised by
WBEMConnection
.- server_id (string) – The server ID of the WBEM server, returned by
-
get_owned_destinations
(server_id)[source]¶ Return the listener destinations in a WBEM server owned by this subscription manager.
This function accesses only the local list of owned destinations; it does not contact the WBEM server. The local list of owned destinations is discovered from the WBEM server when the server is registered with the subscription manager, and is maintained from then on as changes happen through this subscription manager.
Parameters: server_id (string) – The server ID of the WBEM server, returned by add_server()
.Returns: The listener destination instances. Return type: list
ofCIMInstance
-
get_all_destinations
(server_id)[source]¶ Return all listener destinations in a WBEM server.
This function contacts the WBEM server and retrieves the listener destinations by enumerating the instances of CIM class “CIM_ListenerDestinationCIMXML” in the Interop namespace of the WBEM server.
Parameters: server_id (string) – The server ID of the WBEM server, returned by add_server()
.Returns: The listener destination instances. Return type: list
ofCIMInstance
Raises: Exceptions raised by WBEMConnection
.
-
remove_destinations
(server_id, destination_paths)[source]¶ Remove listener destinations from a WBEM server, by deleting the listener destination instances in the server.
The listener destinations must be owned or permanent (i.e. not static).
This method verifies that there are not currently any subscriptions on the listener destinations to be removed, in order to handle server implementations that do not ensure that on the server side as required by DSP1054.
Parameters: - server_id (string) – The server ID of the WBEM server, returned by
add_server()
. - destination_paths (
CIMInstanceName
or list ofCIMInstanceName
) – Instance path(s) of the listener destination instance(s) in the WBEM server.
Raises: - Exceptions raised by
WBEMConnection
. CIMError
– CIM_ERR_FAILED, if there are referencing subscriptions.
- server_id (string) – The server ID of the WBEM server, returned by
-
add_filter
(server_id, source_namespace, query, query_language='WQL', owned=True, filter_id=None, name=None)[source]¶ Add a dynamic indication filter to a WBEM server, by creating an indication filter instance (of CIM class “CIM_IndicationFilter”) in the Interop namespace of the server.
The Name property of the created filter instance can be set in one of two ways:
directly by specifying the name parameter.
In this case, the Name property is set directly to the name parameter.
This should be used in cases where the user needs to have control over the filter name (e.g. because a DMTF management profile requires a particular name), but it cannot be used for owned filters.
indirectly by specifying the filter_id parameter.
In this case, the value of the Name property will be:
"pywbemfilter:" {ownership} ":" {subscription_manager_id} ":" {filter_id} ":" {guid}
where
{ownership}
is"owned"
or"permanent"
dependent on whether the filter is owned or permmanent;{subscription_manager_id}
is the subscription manager ID;{filter_id}
is the filter ID; and{guid}
is a globally unique identifier.This can be used for both owned and permanent filters.
Owned indication filters are added or updated conditionally: If the indication filter instance to be added is already registered with this subscription manager and has the same property values, it is not created or modified. If it has the same path but different property values, it is modified to get the desired property values. If an instance with this path does not exist yet (the normal case), it is created.
Permanent indication filters are created unconditionally, and it is up to the user to ensure that such an instance does not exist yet.
Parameters: - server_id (string) – The server ID of the WBEM server, returned by
add_server()
. - source_namespace (string) – Source namespace of the indication filter.
- query (string) – Filter query in the specified query language.
- query_language (string) –
Query language for the specified filter query.
Examples: ‘WQL’, ‘DMTF:CQL’.
- owned (
bool
) – Defines the ownership type of the created indication filter instance: If True, it will be owned. Otherwise, it will be permanent. See WBEMSubscriptionManager for details about these ownership types. - filter_id (string) –
A filter ID string that is used as a component in the value of the Name property of filter instances to help the user identify these instances in a WBEM server, or None if the name parameter is specified.
The string must consist of printable characters, and must not contain the character ‘:’ because that is the separator between components within the value of the Name property.
There is no requirement that the filter ID be unique. This can be used to identify groups of filters by using the same value for multiple filters.
- name (string) –
New in pywbem 0.10.
The filter name to be used directly for the Name property of the filter instance, or None if the filter_id parameter is specified.
Returns: The created indication filter instance.
Return type: Raises: - Exceptions raised by
WBEMConnection
. ValueError
– Incorrect input parameter values.TypeError
– Incorrect input parameter types.
-
get_owned_filters
(server_id)[source]¶ Return the indication filters in a WBEM server owned by this subscription manager.
This function accesses only the local list of owned filters; it does not contact the WBEM server. The local list of owned filters is discovered from the WBEM server when the server is registered with the the subscription manager, and is maintained from then on as changes happen through this subscription manager.
Parameters: server_id (string) – The server ID of the WBEM server, returned by add_server()
.Returns: The indication filter instances. Return type: list
ofCIMInstance
-
get_all_filters
(server_id)[source]¶ Return all indication filters in a WBEM server.
This function contacts the WBEM server and retrieves the indication filters by enumerating the instances of CIM class “CIM_IndicationFilter” in the Interop namespace of the WBEM server.
Parameters: server_id (string) – The server ID of the WBEM server, returned by add_server()
.Returns: The indication filter instances. Return type: list
ofCIMInstance
Raises: Exceptions raised by WBEMConnection
.
-
remove_filter
(server_id, filter_path)[source]¶ Remove an indication filter from a WBEM server, by deleting the indication filter instance in the WBEM server.
The indication filter must be owned or permanent (i.e. not static).
This method verifies that there are not currently any subscriptions on the specified indication filter, in order to handle server implementations that do not ensure that on the server side as required by DSP1054.
Parameters: - server_id (string) – The server ID of the WBEM server, returned by
add_server()
. - filter_path (
CIMInstanceName
) – Instance path of the indication filter instance in the WBEM server.
Raises: - Exceptions raised by
WBEMConnection
. CIMError
– CIM_ERR_FAILED, if there are referencing subscriptions.
- server_id (string) – The server ID of the WBEM server, returned by
-
add_subscriptions
(server_id, filter_path, destination_paths=None, owned=True)[source]¶ Add subscriptions to a WBEM server for a particular set of indications defined by an indication filter and for a particular set of WBEM listeners defined by the instance paths of their listener destinations, by creating indication subscription instances (of CIM class “CIM_IndicationSubscription”) in the Interop namespace of that server.
The specified indication filter may be owned, permanent or static.
The specified listener destinations may be owned, permanent or static.
When creating permanent subscriptions, the indication filter and the listener destinations must not be owned.
Owned subscriptions are added or updated conditionally: If the subscription instance to be added is already registered with this subscription manager and has the same property values, it is not created or modified. If it has the same path but different property values, it is modified to get the desired property values. If an instance with this path does not exist yet (the normal case), it is created.
Permanent subscriptions are created unconditionally, and it is up to the user to ensure that such an instance does not exist yet.
Upon successful return of this method, the added subscriptions are active, so that the specified WBEM listeners may immediately receive indications.
Parameters: - server_id (string) – The server ID of the WBEM server, returned by
add_server()
. - filter_path (
CIMInstanceName
) – Instance path of the indication filter instance in the WBEM server that specifies the indications to be sent. - destination_paths (
CIMInstanceName
or list ofCIMInstanceName
) –Instance paths of the listener destination instances in the WBEM server that specify the target WBEM listener.
If None, subscriptions will be created for all owned listener destinations registered to this subscription manager.
- owned (
bool
) – Defines the ownership type of the created subscription instances: If True, they will be owned. Otherwise, they will be permanent. See WBEMSubscriptionManager for details about these ownership types.
Returns: The indication subscription instances created in the WBEM server.
Return type: list
ofCIMInstance
Raises: - Exceptions raised by
WBEMConnection
. ValueError
– Incorrect input parameter values.
- server_id (string) – The server ID of the WBEM server, returned by
-
get_owned_subscriptions
(server_id)[source]¶ Return the indication subscriptions in a WBEM server owned by this subscription manager.
This function accesses only the local list of owned subscriptions; it does not contact the WBEM server. The local list of owned subscriptions is discovered from the WBEM server when the server is registered with the subscription manager, and is maintained from then on as changes happen through this subscription manager.
Parameters: server_id (string) – The server ID of the WBEM server, returned by add_server()
.Returns: The indication subscription instances. Return type: list
ofCIMInstance
-
get_all_subscriptions
(server_id)[source]¶ Return all indication subscriptions in a WBEM server.
This function contacts the WBEM server and retrieves the indication subscriptions by enumerating the instances of CIM class “CIM_IndicationSubscription” in the Interop namespace of the WBEM server.
Parameters: server_id (string) – The server ID of the WBEM server, returned by add_server()
.Returns: The indication subscription instances. Return type: list
ofCIMInstance
Raises: Exceptions raised by WBEMConnection
.
-
remove_subscriptions
(server_id, sub_paths)[source]¶ Remove indication subscription(s) from a WBEM server, by deleting the indication subscription instances in the server.
The indication subscriptions must be owned or permanent (i.e. not static).
Parameters: - server_id (string) – The server ID of the WBEM server, returned by
add_server()
. - sub_paths (
CIMInstanceName
or list ofCIMInstanceName
) – Instance path(s) of the indication subscription instance(s) in the WBEM server.
Raises: Exceptions raised by
WBEMConnection
.- server_id (string) – The server ID of the WBEM server, returned by
MOF compiler¶
The language in which CIM classes, CIM Instances, etc. are specified, is called MOF (for Managed Object Format). It is defined in DSP0004.
MOF compilers take MOF files as input, compile them and use the result (CIM classes, instances, and/or qualifier declarations) to update a target CIM repository. The repository may initially be empty, or may contain CIM classes, instances, and/or qualifier declarations that are used to resolve dependencies the new MOF compilation may have.
The pywbem package includes a MOF compiler that is provided in two forms:
- as an API (described in this chapter)
- as a command (described in section mof_compiler)
The pywbem MOF compiler will compile MOF files whose syntax complies with DSP0004, with some limitations:
- Although there is no formal keyword list of illegal words for property/parameter.etc. names , there is a list of mof syntax tokens in DSP0004 section A.3. Generally these should not be used as property names. The pywbem MOF compiler largely enforces this so that words like ‘indication’ are not allowed as property/parameter/etc. names.
- The key properties of instances with aliases must be initialized in the instance specification, or their default values must be non-NULL. (See pywbem issue #1079).
- An alias must be defined before it is used. In DSP0004, no such requirement is documented. (See pywbem issue #1079).
The MOF compiler API provides for invoking the MOF compiler programmatically. It consists of the following parts, which are described in the remaining sections of this chapter:
- MOFCompiler Class - Describes the
MOFCompiler
class, which allows invoking the MOF compiler programmatically. - Repository connections - Describes the
BaseRepositoryConnection
class that defines the interface for connecting to a CIM repository. This is an extension point where users can implement a CIM repository for use by the MOF compiler. - Exceptions - Describes the exceptions that can be raised by the MOF compiler API.
MOFCompiler Class¶
-
class
pywbem.
MOFCompiler
(handle, search_paths=None, verbose=False, log_func=<function _print_logger>)[source]¶ A MOF compiler. See MOF compiler for an explanation of MOF compilers in general.
A MOF compiler may be associated with one CIM repository. The repository is used for looking up dependent CIM elements (e.g. the superclass specified in a class whose MOF definition is being compiled), and it is also updated with the result of the compilation. A repository contains CIM namespaces, and the namespaces contain CIM classes, instances and qualifier types.
The association of a MOF compiler with a CIM repository is established when creating an object of this class. The interactions with the CIM repository are defined in the abstract base class
BaseRepositoryConnection
.Parameters: - handle (BaseRepositoryConnection or
WBEMConnection
) –A handle identifying the CIM repository that will be associated with the MOF compiler.
If the provided object is a repository connection (i.e. derived from
BaseRepositoryConnection
, typically that would be aMOFWBEMConnection
object), it is directly used by the MOF compiler to interface with the repository.If the provided object is a WBEM connection (i.e.
WBEMConnection
orFakedWBEMConnection
), the MOF compiler connects directly to interface defined by handle.None means that no CIM repository will be associated. In this case, the MOF compiler can only process standalone MOF that does not depend on existing CIM elements in the repository.
- search_paths (iterable of string or string) –
Directory path name(s) where the MOF compiler will search for MOF dependent files if the MOF element they define is not in the target namespace of the CIM repository. The compiler searches the specified directories and their subdirectories.
MOF dependent files are:
- The MOF file defining the superclass of a class that is compiled. The MOF file searched for is ‘<classname>.mof’.
- The MOF file defining the qualifier type of a qualifier that is specified on a MOF element that is compiled. The MOF files searched for are ‘qualifiers.mof’ and ‘qualifiers_optional.mof’.
- The MOF file of a class specified in a reference property or in the EmbeddedInstance qualifier that is compiled. The MOF file searched for is ‘<classname>.mof’. This is only partly implemented, see issue #1138.
Note that MOF include files are not searched for; they are specified in the
pragma include
directive as a file path relative to the including file. - verbose (
bool
) – Indicates whether to issue more detailed compiler messages. - log_func (callable) – A logger function that is invoked for each compiler message. The logger function must take one parameter of string type. The default logger function prints to stdout. If None, compiler messages are not logged.
Methods
compile_embedded_value
Compile a string of MOF statements that must represent one or CIMInstance objects and save the resulting CIMInstance(s) in a known variable. compile_file
Compile a MOF file into a namespace of the associated CIM repository. compile_string
Compile a string of MOF statements into a namespace of the associated CIM repository. find_mof
Find the MOF file that defines a particular CIM class, in the search path of the MOF compiler. rollback
Rollback any changes to the CIM repository that were performed by compilations using this MOF compiler object, since the object was created. Attributes
Details
-
compile_embedded_value
(mof, ns, filename=None)[source]¶ Compile a string of MOF statements that must represent one or CIMInstance objects and save the resulting CIMInstance(s) in a known variable. Thiis method in conjunction with the compiler does not put the compiled instances into the repository but returns them to the user.
Parameters: - mof (string or list of string) – The string or list of strings MOF statements to be compiled.
- ns (string) – The name of the CIM namespace in the associated CIM repository that is used for lookup of any dependent CIM elements, and that is also the target of the compilation.
- filename (string) – The path name of the file that the MOF statements were read from. This information is used only in compiler messages.
Raises: MOFCompileError
– Error compiling the MOF.
-
compile_string
(mof, ns, filename=None)[source]¶ Compile a string of MOF statements into a namespace of the associated CIM repository.
Parameters: - mof (string) – The string of MOF statements to be compiled.
- ns (string) – The name of the CIM namespace in the associated CIM repository that is used for lookup of any dependent CIM elements, and that is also the target of the compilation.
- filename (string) – The path name of the file that the MOF statements were read from. This information is used only in compiler messages.
Raises: MOFCompileError
– Error compiling the MOF.
-
compile_file
(filename, ns)[source]¶ Compile a MOF file into a namespace of the associated CIM repository.
Parameters: Raises: IOError
– MOF file not found.MOFCompileError
– Error compiling the MOF.
-
find_mof
(classname)[source]¶ Find the MOF file that defines a particular CIM class, in the search path of the MOF compiler.
The MOF file is found based on its file name: It is assumed that the base part of the file name is the CIM class name.
Example: The class “CIM_ComputerSystem” is expected to be in a file “CIM_ComputerSystem.mof”.
Parameters: classame (string) – The name of the CIM class to look up. Returns: Path name of the MOF file defining the CIM class, if it was found. None, if it was not found. Return type: string
- handle (BaseRepositoryConnection or
Repository connections¶
-
class
pywbem.
BaseRepositoryConnection
[source]¶ An abstract base class for implementing CIM repository connections (or an entire CIM repository) for use by the MOF compiler. This class defines the interface that is used by the
MOFCompiler
class when it interacts with its associated CIM repository.Class
MOFCompiler
invokes only the WBEM operations that are defined as methods on this class:EnumerateInstanceNames()
- Enumerate the paths of CIM instances in the repository.CreateInstance()
- Create a CIM instance in the repository.ModifyInstance()
- Modify a CIM instance in the repository.DeleteInstance()
- Delete a CIM instance in the repository.GetClass()
- Retrieve a CIM class from the repository.ModifyClass()
- Modify a CIM class in the repository.CreateClass()
- Create a CIM class in the repository.DeleteClass()
- Delete a CIM class in the repository.EnumerateQualifiers()
- Enumerate CIM qualifier types in the repository.GetQualifier()
- Retrieve a CIM qualifier type from the repository.SetQualifier()
- Create or modify a CIM qualifier type in the repository.DeleteQualifier()
- Delete a qualifier type from the repository.
Raises: Implementation classes should raise only exceptions derived from Error
or use assert for methods that are not implemented. Other exceptions are considered programming errors.Methods
CreateClass
Create a CIM class in a namespace of the CIM repository. CreateInstance
Create a CIM instance in a namespace of the CIM repository. DeleteClass
Delete a CIM class in a namespace of the CIM repository. DeleteInstance
Delete a CIM instance in a namespace of the CIM repository. DeleteQualifier
Delete a CIM qualifier type in a namespace of the CIM repository. EnumerateInstanceNames
Enumerate the instance paths of CIM instances in a namespace of the CIM repository. EnumerateQualifiers
Enumerate the CIM qualifier types in a namespace of the CIM repository. GetClass
Retrieve a CIM class in a namespace of the CIM repository. GetQualifier
Retrieve a CIM qualifier type in a namespace of the CIM repository. ModifyClass
Modify a CIM class in a namespace of the CIM repository. ModifyInstance
Modify a CIM instance in a namespace of the CIM repository. SetQualifier
Create or modify a CIM qualifier type in a namespace of the CIM repository. Attributes
default_namespace
The default repository namespace. Details
-
EnumerateInstanceNames
(*args, **kwargs)[source]¶ Enumerate the instance paths of CIM instances in a namespace of the CIM repository.
For a description of the parameters, see
pywbem.WBEMConnection.EnumerateInstanceNames()
.
-
CreateInstance
(*args, **kwargs)[source]¶ Create a CIM instance in a namespace of the CIM repository.
For a description of the parameters, see
pywbem.WBEMConnection.CreateInstance()
.
-
ModifyInstance
(*args, **kwargs)[source]¶ Modify a CIM instance in a namespace of the CIM repository.
For a description of the parameters, see
pywbem.WBEMConnection.ModifyInstance()
.
-
DeleteInstance
(*args, **kwargs)[source]¶ Delete a CIM instance in a namespace of the CIM repository.
For a description of the parameters, see
pywbem.WBEMConnection.DeleteInstance()
.
-
GetClass
(*args, **kwargs)[source]¶ Retrieve a CIM class in a namespace of the CIM repository.
For a description of the parameters, see
pywbem.WBEMConnection.GetClass()
.
-
ModifyClass
(*args, **kwargs)[source]¶ Modify a CIM class in a namespace of the CIM repository.
For a description of the parameters, see
pywbem.WBEMConnection.ModifyClass()
.
-
CreateClass
(*args, **kwargs)[source]¶ Create a CIM class in a namespace of the CIM repository.
For a description of the parameters, see
pywbem.WBEMConnection.CreateClass()
.
-
DeleteClass
(*args, **kwargs)[source]¶ Delete a CIM class in a namespace of the CIM repository.
For a description of the parameters, see
pywbem.WBEMConnection.DeleteClass()
.
-
EnumerateQualifiers
(*args, **kwargs)[source]¶ Enumerate the CIM qualifier types in a namespace of the CIM repository.
For a description of the parameters, see
pywbem.WBEMConnection.EnumerateQualifiers()
.
-
GetQualifier
(*args, **kwargs)[source]¶ Retrieve a CIM qualifier type in a namespace of the CIM repository.
For a description of the parameters, see
pywbem.WBEMConnection.GetQualifier()
.
-
SetQualifier
(*args, **kwargs)[source]¶ Create or modify a CIM qualifier type in a namespace of the CIM repository.
For a description of the parameters, see
pywbem.WBEMConnection.SetQualifier()
.
-
DeleteQualifier
(*args, **kwargs)[source]¶ Delete a CIM qualifier type in a namespace of the CIM repository.
For a description of the parameters, see
pywbem.WBEMConnection.DeleteQualifier()
.
Exceptions¶
The MOF compiler API raises exceptions that are derived from the common base
class MOFCompileError
.
-
class
pywbem.
MOFCompileError
(msg, parser_token=None)[source]¶ Base class for exceptions indicating issues with compiling MOF.
Derived from
Error
.Parameters: - msg (string) – Message text describing the error.
- parser_token (lex.LexToken or yacc.YaccProduction) –
PLY lex or yacc parser token (that is, the
p
argument of a yacc parser function or thet
argument of a lex parser function). This token is used to obtain the MOF source text and location information.None will result in no MOF source text and location information to be obtained.
Methods
get_err_msg
Return a multi-line error message for being printed, in the following format. with_traceback
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self. Attributes
args
column
Position within the line in the MOF file or MOF string where the error occurred (1-based). conn_id
Connection ID of the connection in whose context the error happened. conn_str
String that identifies the connection in exception messages. context
MOF context, consisting of a first line that is the MOF line in error, and a second line that uses the ‘^’ character to indicate the position of the token in error in the MOF line. error_kind
file
File name of the MOF file where the error occurred. lineno
Line number in the MOF file or MOF string where the error occurred (1-based). msg
Message text describing the error. Details
-
column
¶ Position within the line in the MOF file or MOF string where the error occurred (1-based).
Type: integer
-
file
¶ File name of the MOF file where the error occurred.
None if the error occurred in a MOF string that was compiled.
Type: string
-
context
¶ MOF context, consisting of a first line that is the MOF line in error, and a second line that uses the ‘^’ character to indicate the position of the token in error in the MOF line.
Type: string
-
get_err_msg
()[source]¶ Return a multi-line error message for being printed, in the following format. The text in angle brackets refers to the same-named properties of the exception instance:
<error kind>:<file>:<lineno>:<colno>: <msg> <context - MOF line> <context - position indicator line>
Returns: Multi-line error message. Return type: string
-
class
pywbem.
MOFParseError
(msg, parser_token=None)[source]¶ Exception indicating that MOF cannot be parsed correctly, e.g. for syntax errors.
Derived from
MOFCompileError
.Parameters: - msg (string) – Message text describing the error.
- parser_token (lex.LexToken or yacc.YaccProduction) –
PLY lex or yacc parser token (that is, the
p
argument of a yacc parser function or thet
argument of a lex parser function). This token is used to obtain the MOF source text and location information.None will result in no MOF source text and location information to be obtained.
Methods
get_err_msg
Return a multi-line error message for being printed, in the following format. with_traceback
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self. Attributes
args
column
Position within the line in the MOF file or MOF string where the error occurred (1-based). conn_id
Connection ID of the connection in whose context the error happened. conn_str
String that identifies the connection in exception messages. context
MOF context, consisting of a first line that is the MOF line in error, and a second line that uses the ‘^’ character to indicate the position of the token in error in the MOF line. error_kind
file
File name of the MOF file where the error occurred. lineno
Line number in the MOF file or MOF string where the error occurred (1-based). msg
Message text describing the error. Details
-
class
pywbem.
MOFDependencyError
(msg, parser_token=None)[source]¶ Exception indicating that MOF cannot be compiled because of a missing dependency. For example, the MOF to be compiled specifies a class but the superclass of the class cannot be found.
Derived from
MOFCompileError
.Parameters: - msg (string) – Message text describing the error.
- parser_token (lex.LexToken or yacc.YaccProduction) –
PLY lex or yacc parser token (that is, the
p
argument of a yacc parser function or thet
argument of a lex parser function). This token is used to obtain the MOF source text and location information.None will result in no MOF source text and location information to be obtained.
Methods
get_err_msg
Return a multi-line error message for being printed, in the following format. with_traceback
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self. Attributes
args
column
Position within the line in the MOF file or MOF string where the error occurred (1-based). conn_id
Connection ID of the connection in whose context the error happened. conn_str
String that identifies the connection in exception messages. context
MOF context, consisting of a first line that is the MOF line in error, and a second line that uses the ‘^’ character to indicate the position of the token in error in the MOF line. error_kind
file
File name of the MOF file where the error occurred. lineno
Line number in the MOF file or MOF string where the error occurred (1-based). msg
Message text describing the error. Details
-
class
pywbem.
MOFRepositoryError
(msg, parser_token=None, cim_error=None)[source]¶ Exception indicating that MOF cannot be compiled because of a CIM error returned by the target CIM repository. The CIM error is attached to this exception and is part of the exception message.
Derived from
MOFCompileError
.Parameters: - msg (string) – Message text describing the error.
- parser_token (lex.LexToken or yacc.YaccProduction) –
PLY lex or yacc parser token (that is, the
p
argument of a yacc parser function or thet
argument of a lex parser function). This token is used to obtain the MOF source text and location information.None will result in no MOF source text and location information to be obtained.
- cim_error (
CIMError
) – CIM error returned by the CIM repository.
Methods
get_err_msg
Return a multi-line error message for being printed, in the following format. with_traceback
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self. Attributes
args
cim_error
CIM error returned by the CIM repository. column
Position within the line in the MOF file or MOF string where the error occurred (1-based). conn_id
Connection ID of the connection in whose context the error happened. conn_str
String that identifies the connection in exception messages. context
MOF context, consisting of a first line that is the MOF line in error, and a second line that uses the ‘^’ character to indicate the position of the token in error in the MOF line. error_kind
file
File name of the MOF file where the error occurred. lineno
Line number in the MOF file or MOF string where the error occurred (1-based). msg
Message text describing the error. Details
-
get_err_msg
()[source]¶ Return a multi-line error message for being printed, in the following format. The text in angle brackets refers to the same-named properties of the exception instance:
<error kind>:<file>:<lineno>:<colno>: <msg> <context - MOF line> <context - position indicator line> <CIM error>
Returns: Multi-line error message. Return type: string
Mock WBEM server¶
Experimental: New in pywbem 0.12.0 as experimental.
Overview¶
The ‘pywbem_mock’ module of pywbem provides a mock WBEM server that enables using the pywbem client library without a real WBEM server. This is useful for testing the pywbem client library itself as well as for the development and testing of Python programs that use the pywbem client library.
The pywbem_mock.FakedWBEMConnection
class establishes an in-process
mock WBEM server and represents a faked connection to that mock WBEM server.
That class acts as both the client API and as an API for managing the mocked
WBEM server.
The pywbem_mock.FakedWBEMConnection
class is a subclass of
pywbem.WBEMConnection
and replaces its internal methods that use
HTTP/HTTPS to communicate with a WBEM server with methods that communicate with
the mock WBEM server. As a result, the operation methods of
FakedWBEMConnection
are those inherited from
WBEMConnection
, so they have exactly the same input parameters,
output parameters, return values, and even most of the raised exceptions, as
when invoked on a WBEMConnection
object against a real
WBEM server.
The mock WBEM server has an in-memory repository of CIM objects
(the CIM repository). Each FakedWBEMConnection
object
creates its own CIM repository that contains the same kinds of CIM objects a
WBEM server repository contains: CIM classes, CIM instances, and CIM qualifier
declarations types, contained in CIM namespaces. Because
FakedWBEMConnection
operates only on the CIM repository,
the class does not have any connection- or security-related constructor
parameters.
Like WBEMConnection
, FakedWBEMConnection
has a default CIM namespace that is created in the CIM repository upon
FakedWBEMConnection
object creation.
Additional namespaces in the CIM repository can be created with
add_namespace()
.
The CIM repository must contain the CIM classes, CIM instances and CIM qualifier
declaration types that are needed for the operations that are invoked. This
results in a behavior of the mock WBEM server that is close to the behavior of
the operations of a real WBEM server.
FakedWBEMConnection
has methods that provide for adding
CIM classes, instances and qualifier types to its CIM repository by providing
them as CIM objects, or by compiling MOF.
See Building a mocked CIM repository for details.
The following example demonstrates setting up a mock WBEM server, adding several CIM objects defined in a MOF string to its CIM repository, and executing WBEM operations on the faked connection:
import pywbem
import pywbem_mock
# MOF string defining qualifiers, class, and instance
mof = '''
Qualifier Key : boolean = false,
Scope(property, reference),
Flavor(DisableOverride, ToSubclass);
Qualifier Description : string = null,
Scope(any),
Flavor(EnableOverride, ToSubclass, Translatable);
Qualifier In : boolean = true,
Scope(parameter),
Flavor(DisableOverride, ToSubclass);
[Description ("This is a dumb test class")]
class CIM_Foo {
[Key, Description ("This is key prop")]
string InstanceID;
[Description ("This is some simplistic data")]
Uint32 SomeData;
[Description ("This is a method without parameters")]
string Fuzzy();
[Description ("This is a second method with parameter")]
uint32 Delete([IN, Description('blahblah']
boolean Immediate);
};
instance of CIM_Foo as $I1 { InstanceID = "I1"; SomeData=3 };
'''
# Create a faked connection including a mock WBEM server with a CIM repo
conn = pywbem_mock.FakedWBEMConnection(default_namespace='root/cimv2')
# Compile the MOF string and add its CIM objects to the default namespace
# of the CIM repository
conn.compile_mof_string(mof)
# Perform a few operations on the faked connection:
# Enumerate top-level classes in the default namespace (without subclasses)
classes = conn.EnumerateClasses();
for cls in classes:
print(cls.tomof())
# Get the 'Description' qualifier type in the default namespace
qd = conn.GetQualifier('Description')
# Enumerate subclasses of 'CIM_Foo' in the default namespace (without subclasses)
classes2 = conn.EnumerateClasses(classname='CIM_Foo')
# Get 'CIM_Foo' class in the default namespace
my_class = conn.GetClass('CIM_Foo')
# Get a specific instance of 'CIM_Foo' in the default namespace
inst = conn.GetInstance(CIMInstanceName('CIM_Foo', {'InstanceID': "I1"})
The mock WBEM server supports:
- All of the
WBEMConnection
operation methods that communicate with the WBEM server (see below for the operations supported and their limitations). - Multiple CIM namespaces and a default namespace on the faked connection.
- Gathering time statistics and delaying responses for a predetermined time.
WBEMConnection
logging except that there are no HTTP entries in the log.- User-defined providers that replace the the default providers specific request methods, CIM classes, and namespaces. See User-defined providers.
The mock WBEM server does NOT support:
- CIM-XML protocol security and security constructor parameters of
WBEMConnection
. - Processing of queries defined for
ExecQuery()
in languages like CQL and WQL. The mocked operation parses only the very general portions of the query for class/instance name and properties. - Filter processing of FQL (see DSP0212) the Filter Query Language
parameter
QueryFilter
used by the Open… operations because it does not implement the parser/processor for the FQL language. It returns the same data as if the filter did not exist. - Providing data in the trace variables for last request and last reply in
WBEMConnection
:last_request
,last_raw_request
,last_reply
,last_raw_reply
,last_request_len
, orlast_reply_len
. - Log entries for HTTP request and response in the logging support of
WBEMConnection
, because it does not actually build the HTTP requests or responses. - Generating CIM indications.
- Some of the functionality that may be implemented in real WBEM servers such as the __Namespace__ class/provider. Note that such capabilities can be at least partly built on top of the existing capabilities by implementing user-defined providers. Thus the CIM_Namespace class is supported with the user defined provider in the pywbem_mock directory but only registered if the user wants to use the provider.
+----------------------------------+
| |
| +------------------------------+ | +-------------+
| | | | | |
| | WBEM Server Mock Methods | | | Main |
| | | | | Provider |
| | All other Requests+------------>+ |
| | CreateInstance, ModifyInst +------+ | Class ,assoc|
| | DeleteInstance, InvokeMeth | | | | some inst |
| +------------^-----------------+ | | | requests +--+
| | | | +-------------+ |
| +------------+-----------------+ | | |
| | WBEM Server Mock Interface | | | +-------------+ | +-----------+
| | | | | | | | | Instance |
| +------------^-----------------+ | | | Provider | | | Write |
| | | | | Dispatcher | | | Provider |
| | | | | +------->+ (Default) |
| | | | | Dispatches | | +-|---|-----+ +----------+
| +------------+-----------------+ | | | methods to | | +-----| |-------------+ User |
| | | | +----->+ default or +----------------------------> Instance |
| | Client API request methods | | | registered | | | | Providers|
| | from WBEM Connection | | | user | | | +------------+ | +-----+
| | | | | providers | | | | | +----------+ |
| | *CreateClass, etc. | | | +------->+ Method | |
---> | | | | | | | Provider | |
| | | | | | | | | (Default) | |
| | | | +-----------+-+ | | +-----|------+ |
| +------------------------------+ | | | | |------------------------+ |
| +------------------------------+ | +-------------------------------> User | |
| | Mock Environment management | | | | | Method | |
| | methods | | | | | Providers |
| | * Mof Compiler, add objects | | | | | | |
| | * Manage namespaces | | | | +---------+ |
| | * Register user providers +---------+ +---------------v-V----------------------------------+ |
| +------------------------------+ | | | | |
| FakedWBEMConnection | +----> CIM Repository <-----+
+----------------------------------+ | |
+----------------------------------------------------+
Diagram of flow of requests operations through mocker
WBEM operations of a mock WBEM server¶
The pywbem_mock.FakedWBEMConnection
class supports the same WBEM
operations that are supported by the pywbem.WBEMConnection
class and
in addition a set of methods for setting up its mocked CIM repository, and
for registering user-defined providers for selected WBEM operations.
These faked WBEM operations generally adhere to the behavior requirements defined in DSP0200 for handling input parameters and returning a result.
The faked WBEM operations get the data to be returned from the CIM repository of the mock WBEM server, and put the data provided in operation parameters that modify objects (create, modify, and delete operations) into the CIM repository.
However, because the pywbem mock support is only a simulation of a WBEM server and intended to be used primarily for testing, there are limitations and differences between the behavior of the faked WBEM operations and a real WBEM server.
The descriptions below describe differences between the faked WBEM operations of the pywbem mock support and the operations of a real WBEM server, and the effects of the operation modes of the CIM repository.
Faked instance operations¶
The operations that retrieve instances require instances in the repository for the instances to be recovered and that the classes for these instances exist in the repository.
GetInstance: Behaves like
GetInstance()
. Returns an instance defined by the instance name input parameter if that instance exists in the repository.EnumerateInstances: Behaves like
EnumerateInstances()
, returning all instances of the CIM class defined on input and subclasses of this class filtered by the optional attributes for property names, etc.EnumerateInstanceNames: Behaves like
EnumerateInstances()
, Returns the instance name of all instances of thepywbem.CIMClass
defined on input and subclasses of this class.CreateInstance: Behaves like
CreateInstance()
.Creates the defined instance in the CIM repository.
If there is no user-defined provider (see User-defined providers)for the class defined in the
NewInstance
parameter operation requires that all key properties be specified in the new instance since the CIM repository has no support for dynamically setting key properties and all key properties are required to get the newly defined instance with other requests. If a user-defined provider exists for the class, the behavior depends on that provider.ModifyInstance: Behaves like
ModifyInstance()
. Modifies the instance defined by the instance name provided on input if that instance exists in the repository. It modifies only the properties defined by the instance provided and will not modify any key properties. If there is a user-defined provider defined for this operation, that provider may modify the default behavior.DeleteInstance: Behaves like
DeleteInstance()
. Deletes the instance defined by the instance name provided on input if that instance exists. If there is a user-defined provider defined for this operation, that provider may modify the default behavior.ExecQuery: This operation is not currently implemented.
See User-defined providers for more information on writing a user-defined provider.
Faked association operations¶
The faked association operations support both instance-level use and class-level requests. Class-level use requires the CIM repository to be in full mode, while instance-level use works in both operation modes of the CIM repository.
- AssociatorNames: Behaves like
AssociatorNames()
, with the following requirements: The source, target, and association classes and their subclasses must exist in the CIM repository for both class-level use and instance-level use. - Associators: Behaves like
Associators()
, with the requirements described for AssociatorNames, above. - ReferenceNames: Behaves like
ReferenceNames()
, with the requirements described for AssociatorNames, above. - References: Behaves like
References()
, with the requirements described for AssociatorNames, above.
Faked method invocation operation¶
The faked method invocation operation (InvokeMethod) behaves like
InvokeMethod()
, but because of the nature of
InvokeMethod, the user must provide an implementation of InvokeMethod
based on the API defined in InvokeMethod()
.
NOTE: InvokeMethod is the method name pywbem and other clients and WBEM servers use for what the DMTF defines as extrinsic methods.
See User-defined providers for more information on writing a user-defined provider.
Faked pull operations¶
The faked pull operations behave like the pull operations of
WBEMConnection
, with the following exceptions:
- The filter query related parameters FilterQuery and FilterQueryLanguage are ignored and no such filtering takes place.
- The ContinueOnError parameter is ignored because injecting an error into the processing of the pull operations is not supported by the pywbem mock support, so no failures can happen during the processing of the pull operations.
- The OperationTimeout parameter is currently ignored. As a result, there
will be no timeout if the
response_delay
property is set to a time larger than the OperationTimeout parameter.
The faked pull operations are:
- OpenEnumerateInstances: Behaves like
OpenEnumerateInstances()
, with the stated exceptions. - OpenEnumerateInstancePaths: Behaves like
OpenEnumerateInstancePaths()
, with the stated exceptions. - OpenAssociatorInstances: Behaves like
OpenAssociatorInstances()
, with the stated exceptions. - OpenAssociatorInstancePaths: Behaves like
OpenAssociatorInstancePaths()
, with the stated exceptions. - OpenReferenceInstances: Behaves like
OpenReferenceInstances()
, with the stated exceptions. - OpenReferenceInstancePaths: Behaves like
OpenReferenceInstancePaths()
, with the stated exceptions. - OpenQueryInstances: Behaves like
OpenQueryInstances()
, with the stated exceptions. - PullInstancesWithPath: Behaves like
PullInstancesWithPath()
, with the stated exceptions. - PullInstancePaths: Behaves like
PullInstancePaths()
, with the stated exceptions. - PullInstances: Behaves like
PullInstances()
, with the stated exceptions. - CloseEnumeration: Behaves like
CloseEnumeration()
, with the stated exceptions.
Faked iter operations¶
The iter operations on a faked connection are in fact the iter operations
on WBEMConnection
, because they do not directly issue requests
and responses on the connection, but instead are a layer on top of
underlying operations. For example, IterEnumerateInstances
invokes either pull operations (i.e. OpenEnumerateInstances followed by
PullInstancesWithPath) or traditional operations (i.e. EnumerateInstances).
The use of pull vs. traditional operations is controlled via the
use_pull_operations init parameter of
FakedWBEMConnection
.
The iter operations are:
Faked class operations¶
Class operations only work if the CIM repository is in full operation mode.
- GetClass: Behaves like
GetClass()
. Requires that the class to be returned is in the CIM repository. - EnumerateClasses: Behaves like
EnumerateClasses()
. Requires that the class specified in the ClassName parameter be in the CIM repository. - EnumerateClassNames: Behaves like
EnumerateClassNames()
. Requires that the class specified in the ClassName parameter be in the CIM repository. - CreateClass: Behaves like
CreateClass()
. Requires that the superclass of the new class (if it specifies one) is in the CIM repository. - DeleteClass: Behaves like
DeleteClass()
, with the following difference: This operation additionally deletes all direct and indirect subclasses of the class to be deleted, and all instances of the classes that are being deleted. Requires that the class to be deleted is in the CIM repository. - ModifyClass: Not currently implemented.
Faked qualifier declaration operations¶
Qualifier operations declaration include the following.
- SetQualifier: Behaves like
SetQualifier()
. Requires that the specified qualifier type is in the CIM repository. - GetQualifier: Behaves like
GetQualifier()
. Requires that the specified qualifier type is in the CIM repository. - EnumerateQualifiers: Behaves like
EnumerateQualifiers()
. Requires that the qualifier types to be returned are in the CIM repository. - DeleteQualifier: - Not implemented.
FakedWBEMConnection class¶
-
class
pywbem_mock.
FakedWBEMConnection
(default_namespace='root/cimv2', use_pull_operations=False, stats_enabled=False, timeout=None, response_delay=None, disable_pull_operations=None)[source]¶ A subclass of
pywbem.WBEMConnection
that mocks the communication with a WBEM server by utilizing a local in-memory CIM repository to generate responses in the same way the WBEM server would.Experimental: New in pywbem 0.12 as experimental.
Each
FakedWBEMConnection
object has its own CIM repository which contains multiple CIM namespaces, and each namespace may contain CIM qualifier types (declarations), CIM classes and CIM instances.This class provides only a subset of the init parameters of
WBEMConnection
because it does not have a connection to a WBEM server. It uses a faked and fixed URL for the WBEM server (http://FakedUrl
) as a means of identifying the connection by users.Logging of the faked operations is supported via the pywbem logging facility and can be controlled in the same way as for
WBEMConnection
. For details, see WBEM operation logging.Some of the longer running methods of this class add time statistics to the
WBEMConnection.statistics
. For details on how to get the statistics, see WBEM operation statistics.Parameters: - default_namespace (string) – Default namespace.
This parameter has the same characteristics as the same-named init
parameter of
WBEMConnection
. - use_pull_operations (
bool
) – Flag to control whether pull or traditional operations are used in the iter… operations. This parameter has the same characteristics as the same-named init parameter ofWBEMConnection
. - timeout (number) – This parameter has the same characteristics as the same-named init
parameter of
WBEMConnection
. - stats_enabled (
bool
) – Flag to enable operation statistics. This parameter has the same characteristics as the same-named init parameter ofWBEMConnection
. - response_delay (number) –
Artifically created delay for each operation, in seconds. This must be a positive number. Delays less than a second or other fractional delays may be achieved with float numbers. None disables the delay.
Note that the
response_delay
property can be used to set this delay subsequent to object creation. - disable_pull_operations (
bool
) –Flag to allow user to disable the pull operations ( Open… and Pull.. requests). The default is None which enables pull operations to execute. Setting the flag to True causes pull operations to raise CIMError(CIM_ERR_NOT_SUPPORTED).
The
disable_pull_operations
property can be used to set this variable.
Methods
AssociatorNames
Retrieve the instance paths of the instances associated to a source instance, or the class paths of the classes associated to a source class. Associators
Retrieve the instances associated to a source instance, or the classes associated to a source class. CloseEnumeration
Close an open enumeration session, causing an early termination of an incomplete enumeration session. CreateClass
Create a class in a namespace. CreateInstance
Create an instance in a namespace. DeleteClass
Delete a class. DeleteInstance
Delete an instance. DeleteQualifier
Delete a qualifier type (= qualifier declaration). EnumerateClassNames
Enumerate the names of subclasses of a class, or of the top-level classes in a namespace. EnumerateClasses
Enumerate the subclasses of a class, or the top-level classes in a namespace. EnumerateInstanceNames
Enumerate the instance paths of instances of a class (including instances of its subclasses) in a namespace. EnumerateInstances
Enumerate the instances of a class (including instances of its subclasses) in a namespace. EnumerateQualifiers
Enumerate the qualifier types (= qualifier declarations) in a namespace. ExecQuery
Execute a query in a namespace. GetClass
Retrieve a class. GetInstance
Retrieve an instance. GetQualifier
Retrieve a qualifier type (= qualifier declaration). InvokeMethod
Invoke a method on a target instance or on a target class. IterAssociatorInstancePaths
Retrieve the instance paths of the instances associated to a source instance, using the Python generator idiom to return the result. IterAssociatorInstances
Retrieve the instances associated to a source instance, using the Python generator idiom to return the result. IterEnumerateInstancePaths
Enumerate the instance paths of instances of a class (including instances of its subclasses) in a namespace, using the Python generator idiom to return the result. IterEnumerateInstances
Enumerate the instances of a class (including instances of its subclasses) in a namespace, using the Python generator idiom to return the result. IterQueryInstances
Execute a query in a namespace, using the Python generator idiom to return the result. IterReferenceInstancePaths
Retrieve the instance paths of the association instances that reference a source instance, using the Python generator idiom to return the result. IterReferenceInstances
Retrieve the association instances that reference a source instance, using the Python generator idiom to return the result. ModifyClass
Modify a class. ModifyInstance
Modify the property values of an instance. OpenAssociatorInstancePaths
Open an enumeration session to retrieve the instance paths of the instances associated to a source instance. OpenAssociatorInstances
Open an enumeration session to retrieve the instances associated to a source instance. OpenEnumerateInstancePaths
Open an enumeration session to enumerate the instance paths of instances of a class (including instances of its subclasses) in a namespace. OpenEnumerateInstances
Open an enumeration session to enumerate the instances of a class (including instances of its subclasses) in a namespace. OpenQueryInstances
Open an enumeration session to execute a query in a namespace and to retrieve the instances representing the query result. OpenReferenceInstancePaths
Open an enumeration session to retrieve the instance paths of the association instances that reference a source instance. OpenReferenceInstances
Open an enumeration session to retrieve the association instances that reference a source instance. PullInstancePaths
Retrieve the next set of instance paths from an open enumeration session. PullInstances
Retrieve the next set of instances (without instance paths) from an open enumeration session. PullInstancesWithPath
Retrieve the next set of instances (with instance paths) from an open enumeration session. ReferenceNames
Retrieve the instance paths of the association instances that reference a source instance, or the class paths of the association classes that reference a source class. References
Retrieve the association instances that reference a source instance, or the association classes that reference a source class. SetQualifier
Create or modify a qualifier type (= qualifier declaration) in a namespace. add_cimobjects
Add CIM classes, instances and/or CIM qualifier types (declarations) to the specified CIM namespace of the CIM repository. add_namespace
Add a CIM namespace to the CIM repository of the faked connection. add_operation_recorder
Experimental: Add an operation recorder to this connection. compile_mof_file
Compile the MOF definitions in the specified file (and its included files) and add the resulting CIM objects to the specified CIM namespace of the CIM repository. compile_mof_string
Compile the MOF definitions in the specified string and add the resulting CIM objects to the specified CIM namespace of the CIM repository. compile_schema_classes
Compile the classes defined by class_names and all of their dependences. display_registered_providers
Display information on the currently registered providers. display_repository
Display the namespaces and objects in the CIM repository in one of multiple formats to a destination. find_interop_namespace
Find the Interop namespace in the CIM repository, or return None. install_namespace_provider
FakedWBEMConnection user method to install the namespace provider in the Interop namespace where the proposed interop_namespace is defined by the parameter interop_namespace is_interop_namespace
Tests if a namespace name is a valid Interop namespace name. is_subclass
Return boolean indicating whether a class is a (direct or indirect) subclass of a superclass, or the same class, in the specified namespace. operation_recorder_reset
Experimental: Low-level method used by the operation-specific methods of this class. operation_recorder_stage_pywbem_args
Experimental: Low-level method used by the operation-specific methods of this class. operation_recorder_stage_result
Experimental: Low-level method used by the operation-specific methods of this class. register_provider
Register the provider object for specific namespaces and CIM classes. remove_namespace
Remove a CIM namespace from the CIM repository of the faked connection. Attributes
ca_certs
Selects the CA certificates (trusted certificates) for verifying the X.509 server certificate returned by the WBEM server. cimrepository
The mocked in-memory CIM repository. conn_id
Connection ID (a unique ID) of this connection. creds
Credentials for HTTP authentication with the WBEM server. debug
Boolean indicating that debug is enabled for this connection. default_namespace
Name of the CIM namespace to be used by default (if no namespace is specified for an operation). disable_pull_operations
Boolean flag to set option to disable the execution of the open and pull operation request handlers in the CIM repository. host
Normalized host and port number of the WBEM server, in the format host:port
.interop_namespace_names
The valid Interop namespace names. last_operation_time
Elapsed time of the last operation that was executed via this connection in seconds or None. last_raw_reply
CIM-XML data of the last response received from the WBEM server on this connection, formatted as it was received (=raw). last_raw_request
CIM-XML data of the last request sent to the WBEM server on this connection, formatted as it was sent (=raw). last_reply
CIM-XML data of the last response received from the WBEM server on this connection, formatted as prettified XML. last_reply_len
The size of the HTTP body in the CIM-XML response of the last operation, in Bytes. last_request
CIM-XML data of the last request sent to the WBEM server on this connection, formatted as prettified XML. last_request_len
The size of the HTTP body in the CIM-XML request of the last operation, in Bytes. last_server_response_time
Server-measured response time of the last request, or None. namespaces
The names of the namespaces that exist in the CIM repository. no_verification
Boolean indicating that verifications are disabled for this connection. operation_recorder_enabled
Experimental: Enablement status for all operation recorders of the connection. operation_recorders
Experimental: The operation recorders of this connection. provider_dependent_registry
The registry for provider dependent files, in context of a mock script. proxies
Dictionary with the URLs of HTTP or SOCKS proxies to use for the connection to the WBEM server. response_delay
Artifically created delay for each operation, in seconds. scheme
Normalized scheme of the URL of the WBEM server, for example ‘http’ or ‘https’. statistics
Statistics for this connection. stats_enabled
Statistics enablement status for this connection. timeout
Timeout in seconds, for requests sent to the server. url
Normalized URL of the WBEM server. use_pull_operations
Boolean indicating that the client should attempt the use of pull operations in any Iter…() methods. x509
X.509 client certificate and key file to be presented to the WBEM server during the TLS/SSL handshake. Details
-
namespaces
¶ The names of the namespaces that exist in the CIM repository.
Type: NocaseList of string
-
interop_namespace_names
¶ The valid Interop namespace names.
Only these names may be the Interop namespace and only one Interop namespace may exist in a WBEM server environment. This list is defined in
pywbem.WBEMServer.INTEROP_NAMESPACES
.Type: NocaseList of string
-
cimrepository
¶ The mocked in-memory CIM repository.
The CIM repository is the data store for CIM classes, CIM instances, and CIM qualifier declarations, all partitioned by CIM namespaces.
Type: InMemoryRepository
-
provider_dependent_registry
¶ The registry for provider dependent files, in context of a mock script.
Type: ProviderDependentRegistry
-
response_delay
¶ Artifically created delay for each operation, in seconds. If None, there is no delay.
This attribute is settable. For details, see the description of the same-named init parameter of
this class
.Type: number
-
disable_pull_operations
¶ Boolean flag to set option to disable the execution of the open and pull operation request handlers in the CIM repository. This emulates the characteristic in some CIM servers that did not implement pull operations. The default is to allow pull operations. All pull operations requests may be forbidden from executing by setting disable_pull_operations to True.
This attribute is settable. For details, see the description of the same-named init parameter of
this class
.Type: bool
-
add_namespace
(namespace)[source]¶ Add a CIM namespace to the CIM repository of the faked connection.
The namespace must not yet exist in the CIM repository.
Parameters: namespace (string) – The name of the CIM namespace to be added to the CIM repository. Must not be None. Any leading or trailing slash characters are removed before the string is used to define the namespace name.
Raises: ValueError
– Namespace argument must not be None.CIMError
– CIM_ERR_ALREADY_EXISTS if the namespace already exists in the CIM repository.
-
remove_namespace
(namespace)[source]¶ Remove a CIM namespace from the CIM repository of the faked connection.
The namespace must exist in the CIM repository and must be empty.
Parameters: namespace (string) – The name of the CIM namespace in the CIM repository (case insensitive). Must not be None. Leading or trailing slash characters are ignored.
Raises: ValueError
– Namespace argument must not be NoneCIMError
– (CIM_ERR_NOT_FOUND) if the namespace does not exist in the CIM repository.CIMError
– (CIM_ERR_NAMESPACE_NOT_EMPTY) if the namespace is not empty.CIMError
– (CIM_ERR_NAMESPACE_NOT_EMPTY) if attempting to delete the default connection namespace. This namespace cannot be deleted from the CIM repository
-
is_interop_namespace
(namespace)[source]¶ Tests if a namespace name is a valid Interop namespace name.
This method does not access the CIM repository for this test; it merely compares the specified namespace name against the list of valid Interop namespace names returned by
interop_namespace_names()
.Parameters: namespace (string) – The namespace name that is to be tested. Returns: Indicates whether the namespace name is a valid Interop namespace name. Return type: bool
-
find_interop_namespace
()[source]¶ Find the Interop namespace in the CIM repository, or return None.
The Interop namespace is identified by comparing all namespace names in the CIM repository against the list of valid Interop namespace names returned by
interop_namespace_names()
.Returns: The name of the Interop namespace if one exists in the CIM repository or otherwise None. Return type: string
-
install_namespace_provider
(interop_namespace, schema_pragma_file=None, verbose=None)[source]¶ FakedWBEMConnection user method to install the namespace provider in the Interop namespace where the proposed interop_namespace is defined by the parameter interop_namespace
Because this provider requires a set of classes from the DMTF schema, the schema_pragma_file install the schema is required.
This method should only be called once at the creation of the mock environment.
Parameters: - interop_namespace (string) – The Interop namespace defined for this environment
- schema_pragma_file (string) –
File path defining a CIM schema pragma file for the set of CIM classes that make up a schema such as the DMTF schema. This file must contain a pragma statement for each of the classes defined in the schema.
If None, no attempt is made to any CIM classes required for the provider and it is assumed that the CIM classes are already installed
- verbose (
bool
) – If True, displays progress information as providers are installed.
Raises: CIMError
– with status code appropriate for any- error encountered in the installation of the provider.
-
compile_mof_file
(mof_file, namespace=None, search_paths=None, verbose=None)[source]¶ Compile the MOF definitions in the specified file (and its included files) and add the resulting CIM objects to the specified CIM namespace of the CIM repository.
If the namespace does not exist,
CIMError
with status CIM_ERR_INVALID_NAMESPACE is raised.This method supports all MOF pragmas, and specifically the include pragma.
If a CIM class or CIM qualifier type to be added already exists in the target namespace with the same name (comparing case insensitively), this method raises
CIMError
.If a CIM instance to be added already exists in the target namespace with the same keybinding values, this method raises
CIMError
.In all cases where this method raises an exception, the CIM repository remains unchanged.
Parameters: - mof_file (string) – Path name of the file containing the MOF definitions to be compiled.
- namespace (string) – The name of the target CIM namespace in the CIM repository. This namespace is also used for lookup of any existing or dependent CIM objects. If None, the default namespace of the connection is used.
- search_paths (iterable of string) – An iterable of directory path names where MOF dependent files will
be looked up.
See the description of the search_path init parameter of the
MOFCompiler
class for more information on MOF dependent files. - verbose (
bool
) – Controls whether to issue more detailed compiler messages.
Raises: IOError
– MOF file not found.MOFCompileError
– Compile error in the MOF.
-
compile_mof_string
(mof_str, namespace=None, search_paths=None, verbose=None)[source]¶ Compile the MOF definitions in the specified string and add the resulting CIM objects to the specified CIM namespace of the CIM repository.
If the namespace does not exist,
CIMError
with status CIM_ERR_INVALID_NAMESPACE is raised.This method supports all MOF pragmas, and specifically the include pragma.
If a CIM class or CIM qualifier type to be added already exists in the target namespace with the same name (comparing case insensitively), this method raises
CIMError
.If a CIM instance to be added already exists in the target namespace with the same keybinding values, this method raises
CIMError
.In all cases where this method raises an exception, the CIM repository remains unchanged.
Parameters: - mof_str (string) – A string with the MOF definitions to be compiled.
- namespace (string) – The name of the target CIM namespace in the CIM repository. This namespace is also used for lookup of any existing or dependent CIM objects. If None, the default namespace of the connection is used.
- search_paths (iterable of string) – An iterable of directory path names where MOF dependent files will
be looked up.
See the description of the search_path init parameter of the
MOFCompiler
class for more information on MOF dependent files. - verbose (
bool
) – Controls whether to issue more detailed compiler messages.
Raises: IOError
– MOF file not found.MOFCompileError
– Compile error in the MOF.
-
compile_schema_classes
(class_names, schema_pragma_files, namespace=None, verbose=False)[source]¶ Compile the classes defined by class_names and all of their dependences. The class names must be classes in the defined schema and with pragma statements in a schema pragma file. Each schema pragma file in the schema_pragma_files parameter must be in a directory that also encompasses the MOF files for all of the classes defined in the schema pragma file and the dependencies of those classes. While the relative paths of all of the CIM class files is defined in the schema_pragma_file the pywbem MOF compiler may also search for dependencies (ex. superclasses, references, etc.) that are not specifically listed in the class_names and the path of the schema_pragma_file is the top level directory for that search. The mof schema directory must include:
- Qualifier declarations defined in a single file with the name qualifiers.mof defined within the directory defined by the schema_mof_dir parameter
- The file schema_pragma_file that defines the location of all of the CIM class files within the a schema mof directory hierarchy. This is the schema_pragma_file attribute of the DMTFCIMSchema class.
- The MOF files, one for each class, for the classes that could be compiled within the directory hierarchy defined by schema_mof_dir.
Only the leaf class names need be included in the class_names list since the compiler will find all dependencies as part of the dependency resolution for the compile of each class in class_names.
Parameters: - class_names (string or
list
of string) – Class names of the classes to be compiled. These class names must be a subset of the classes defined in schema_pragma_file. - schema_pragma_files (string or
list
of string) – Relative or absolute file path(s) of schema pragma files that include a MOF pragma include statement for each CIM class to be compiled. This file path is available frompywbem_mock.DMTFCIMSchema.schema_pragma_file
. - namespace (string) – Namespace into which the classes and qualifier declarations will be installed.
- verbose (
bool
) – If True, progress messages are output to stdout as the schema is downloaded and expanded. Default is False.
Raises: MOFCompileError
– For errors in MOF parsing, finding MOF dependencies or issues with the CIM repository.CIMError
– Other errors relating to the target server environment.
-
add_cimobjects
(objects, namespace=None)[source]¶ Add CIM classes, instances and/or CIM qualifier types (declarations) to the specified CIM namespace of the CIM repository.
This method adds a copy of the objects presented so that the user may modify the objects without impacting the repository.
If the namespace does not exist,
CIMError
with status CIM_ERR_INVALID_NAMESPACE is raised.The method imposes very few limits on the objects added. It does require that the superclass exist for any class added and that instances added include a path component. If the qualifier flavor attributes are not set, it sets them to those defined in the Qualifier Declarations if those exist.
If a CIM class or CIM qualifier type to be added already exists in the target namespace with the same name (comparing case insensitively), this method fails, and the CIM repository remains unchanged.
If a CIM instance to be added already exists in the target namespace with the same keybinding values, this method fails, and the CIM repository remains unchanged.
Parameters: - objects (
CIMClass
orCIMInstance
orCIMQualifierDeclaration
, or list of them) – CIM object or objects to be added to the CIM repository. The list may contain different kinds of CIM objects. - namespace (string) – The name of the target CIM namespace in the CIM repository. This namespace is also used for lookup of any existing or dependent CIM objects. If None, the default namespace of the connection is used.
Raises: ValueError
– Invalid input CIM object in objects parameter.TypeError
– Invalid type in objects parameter.CIMError
– CIM_ERR_INVALID_NAMESPACE: Namespace does not exist.CIMError
– Failure related to the CIM objects in the CIM repository.
- objects (
-
display_repository
(namespaces=None, dest=None, summary=False, output_format='mof')[source]¶ Display the namespaces and objects in the CIM repository in one of multiple formats to a destination.
Parameters: - namespaces (string or list of string) – Limits display output to the specified CIM namespace or namespaces. If None, all namespaces of the CIM repository are displayed.
- dest (string) – File path of an output file. If None, the output is written to stdout.
- summary (
bool
) – Flag for summary mode. If True, only a summary count of CIM objects in the specified namespaces of the CIM repository is produced. If False, both the summary count and the details of the CIM objects are produced. - output_format (string) – Output format, one of: ‘mof’, ‘xml’, or ‘repr’.
-
register_provider
(provider, namespaces=None, schema_pragma_files=None, verbose=None)[source]¶ Register the provider object for specific namespaces and CIM classes. Registering a provider tells the FakedWBEMConnection that the provider implementation provided with this method as the provider parameter is to be executed as the request response method for the namespaces defined in the namespaces parameter, the provider type defined in the ‘provider_type` attribute of the provider and the class(es) defined in the provider provider_classnames attribute of the provider.
The provider registration process includes:
- Validation that the namespaces defined for the provider exist.
- Validation that the superclass of the provider is consistent with the provider_type attribute defined in the provider.
- Installation of any CIM classes defined by the provider provider_classnames attribute including dependencies for these classes using the schema_pragma_files parameter to define the MOF compiler search directories for dependencies.
- Adding the provider to the registry of user_providers so that any of the request methods defined for the provider_type are passed to this provider in place of the default request processors.
- Execute post_register_setup() call to the provider to allow the provider to perform any special setup functionality.
Providers can only be registered for the following request response methods:
- provider_type = ‘instance’: defines methods for CreateInstance, ModifyInstance, and DeleteInstance requests within a subclass of the InstanceWriteProvider class.
- provider_type = ‘method’: defines a InvokeMethod method within a subclass of the MethodProvider class.
Each classname in a particular namespace may have at most one provider registered
Parameters: - provider (instance of subclass of
pywbem_mock.InstanceWriteProvider
orpywbem_mock.MethodProvider
) – An instance of the user provider class which is a subclass ofpywbem_mock.InstanceWriteProvider
. The methods in this subclass override the corresponding methods in InstanceWriteProvider. The method call parameters must be the same as the defult method in InstanceWriteProvider and it must return data in the same format if the default method returns data. - namespaces (string or
list
of string) –Namespace or namespaces for which the provider is to be registered.
If None, the default namespace of the connection will be used.
- schema_pragma_files (string or
list
of string) –File paths defining a schema pragma file MOF for the set of CIM classes that make up a schema such as the DMTF schema. These files must contain include pragma statements defining the file location of the classes to be compiled for the defined provider and for any dependencies required to compile those classes. The directory containing each schema pragma file is passed to the MOF compiler as the search path for compile dependencies.
See
pywbem.MOFCompiler
for more information on the search_paths parameter. - verbose (
bool
) – Flag to enable detailed display of actions
Raises: TypeError
– Invalid provider_type retrieved from provider or provider_type does not match superlclass or the namespace parameter is invalid.ValueError
– Provider_type retrieved from provider is not a valid string.ValueError
– Classnames parameter retrieved from provider not a valid string or iterable or namespace does not exist in repository.
- default_namespace (string) – Default namespace.
This parameter has the same characteristics as the same-named init
parameter of
Building a mocked CIM repository¶
The CIM repository of a mock WBEM server needs to contain the CIM namespaces, and within them, the CIM qualifier declarations, CIM classes, and CIM instances required by the user. These are created as part of the setup of any particular pywbem mock environment. Thus, if the user only requires CIM_ComputerSystem in a particular namespace, only that class and its dependent classes and qualifier declarations need be in that namespace in the CIM repository, along with instances of the classes that will satisfy the client methods executed.
The classes FakedWBEMConnection
and
DMTFCIMSchema
provide the tools to build the
CIM repository.
CIM namespaces are created in the CIM repository by defining a default
namespace for the FakedWBEMConnection
object, and by using
the add_namespace()
method to create
additional namespaces.
There are multiple ways to add CIM objects to a target namespace of the CIM repository:
From CIM objects, using the
add_cimobjects()
method.The specified CIM objects are added to or updated in a target namespace of the CIM repository. Dependent classes and qualifier types of these objects must already exist in the target namespace.
From definitions of the CIM objects in a MOF string or a MOF file, using the
compile_mof_string()
orcompile_mof_file()
methods.The CIM objects defined in the MOF are added to or updated in a target namespace of the CIM repository. Dependent classes and qualifier types of these objects must already exist in the target namespace.
From CIM class names and a schema search path containing the MOF files of one or more schemas, using the
compile_schema_classes()
method.The schema MOF files can either be provided by the user, or the DMTF CIM schema can be automatically downloaded from the DMTF using the
DMTFCIMSchema()
class.The specified CIM classes are added to or updated in a target namespace of the CIM repository, and their dependent classes and qualifier types are added to the target namespace from the schemas in the search path as needed.
The dependent classes and qualifier types are determined automatically and recursively. This includes superclasses, reference classes (used in reference properties and reference parameters), and embedded classes (i.e. classes referenced through the EmbeddedInstance qualifier). Thus, a user building a CIM repository does not have to track down those dependent classes and qualifier types, and instead only needs to know the schema(s) to be used and the creation classes for any CIM instances. This also means that there is normally no reason to compile the complete schema which is much larger than the classes that are minimally needed.
It may take a combination of all of the above methods to build a CIM repository that satisfies a particular usage requirement. A typical approach for building a CIM repository is:
- Establish the MOF subtrees for the schema(s) needed. That can be a downloaded version of the DMTF CIM schema, local modifications to a version of the DMTF CIM schema, user-defined schemas including schemas derived from the DMTF CIM schema, or a combination thereof.
- Create the CIM namespaces needed, either as the default namespace or by adding namespaces, including the interop namespace.
- For each CIM namespace needed, create the set of needed CIM classes and
qualifier types by using the
compile_schema_classes()
method and specifying the set of creation classes of the CIM instances that are intended to be added, and specifying the pragma MOF files of the schema(s) added in step 1 as a schema search path. - For each CIM namespace needed, create the set of needed CIM instances
by defining and compiling instance MOF, or by creating and adding
CIMInstance
objects, or both. Often defining MOF is easier for this because it simplifies the definition of association instances with the instance alias. - Register user-defined providers such as the
CIMNamespaceProvider
or user-written providers for the creation classes of the CIM instances that have non-default instance write behavior or that need CIM methods to be supported. See User-defined providers for details.
Example: Set up qualifier types and classes in DMTF CIM schema¶
This example creates a mock WBEM server using root/interop
as the default
namespace and compiles the classes defined in the list ‘classes’ from DMTF
schema version 2.49.0 into the CIM repository along with all of the qualifier
types defined by the DMTF CIM schema and any dependent classes
(superclasses, etc.).
import pywbem
import pywbem_mock
conn = pywbem_mock.FakedWBEMConnection(default_namespace='root/interop')
# Leaf classes that are to be compiled along with their dependent classes
leaf_classes = ['CIM_RegisteredProfile',
'CIM_Namespace',
'CIM_ObjectManager',
'CIM_ElementConformsToProfile',
'CIM_ReferencedProfile']
# Download DMTF CIM schema version 2.49.0 into directory my_schema_dir.
schema = DMTFCIMSchema((2, 49, 0), "my_schema_dir", leaf_classes,
verbose=True)
# Compile the leaf classes, looking up dependent classes and qualifier
# types from the downloaded DMTF CIM schema.
conn.compile_schema_classes(leaf_classes, schema.schema_pragma_file
verbose=True)
# Display the resulting repository
conn.display_repository()
Example: Set up qualifier types and classes from MOF¶
This example creates a mock WBEM server and sets up its CIM repository with qualifier types and classes that are defined in a MOF string.
import pywbem
import pywbem_mock
tst_namespace = 'root/blah'
conn = pywbem_mock.FakedWBEMConnection()
# Add some qualifier types and classes to the CIM repo by compiling MOF
mof = '''
Qualifier Key : boolean = false,
Scope(property, reference),
Flavor(DisableOverride, ToSubclass);
Qualifier Association : boolean,
Scope(class),
Flavor(DisableOverride, ToSubclass);
class TST_Class1 {
[Key]
string InstanceID;
string Prop1;
};
class TST_Class2 {
[Key]
string InstanceID;
string Prop2;
};
[Association]
class TST_Association12 {
[Key]
TST_Class1 REF Ref1;
[Key]
TST_Class2 REF Ref2;
};
'''
conn.compile_mof_string(mof, tst_namespace)
conn.display_repository()
Here is the output from displaying the CIM repository in the example above:
# ========Mock Repo Display fmt=mof namespaces=all =========
# NAMESPACE root/blah
# Namespace root/blah: contains 2 Qualifier Declarations
Qualifier Association : boolean,
Scope(class),
Flavor(DisableOverride, ToSubclass);
Qualifier Key : boolean = false,
Scope(property, reference),
Flavor(DisableOverride, ToSubclass);
# Namespace root/blah: contains 3 Classes
[Association ( true )]
class TST_Association12 {
[Key ( true )]
TST_Class1 REF Ref1;
[Key ( true )]
TST_Class2 REF Ref2;
};
class TST_Class1 {
[Key ( true )]
string InstanceID;
string Prop1;
};
class TST_Class2 {
[Key ( true )]
string InstanceID;
string Prop2;
};
============End Repository=================
Example: Set up instances from single CIM objects¶
Based on the CIM repository content of the previous example, this example
adds two class instances and one association instance from their CIM objects
using the add_cimobjects()
method.
c1_key = pywbem.CIMProperty('InstanceID', type='string', value='111')
c1_path = pywbem.CIMInstanceName(
'TST_Class1',
keybindings={c1_key.name: c1_key.value},
)
c1 = pywbem.CIMInstance(
'TST_Class1',
properties=[
c1_key,
pywbem.CIMProperty('Prop1', type='string', value='1'),
],
path=c1_path,
)
c2_key = pywbem.CIMProperty('InstanceID', type='string', value='222')
c2_path = pywbem.CIMInstanceName(
'TST_Class2',
keybindings={c2_key.name: c2_key.value},
)
c2 = pywbem.CIMInstance(
'TST_Class2',
properties=[
c2_key,
pywbem.CIMProperty('Prop2', type='string', value='2'),
],
path=c2_path,
)
a12_key1 = pywbem.CIMProperty('Ref1', type='reference', value=c1_path)
a12_key2 = pywbem.CIMProperty('Ref2', type='reference', value=c2_path)
a12_path = pywbem.CIMInstanceName(
'TST_Association12',
keybindings={
a12_key1.name: a12_key1.value,
a12_key2.name: a12_key2.value,
},
)
a12 = pywbem.CIMInstance(
'TST_Association12',
properties=[
a12_key1,
a12_key2,
],
path=a12_path,
)
conn.add_cimobjects([c1, c2, a12], tst_namespace)
conn.display_repository()
This adds the instances to the repository display of the previous example:
# Namespace root/blah: contains 3 Instances
# Path=/root/blah:TST_Class1.InstanceID="111"
instance of TST_Class1 {
InstanceID = "111";
Prop1 = "1";
};
# Path=/root/blah:TST_Class2.InstanceID="222"
instance of TST_Class2 {
InstanceID = "222";
Prop2 = "2";
};
# Path=/root/blah:TST_Association12.Ref1="/:TST_Class1.InstanceID=\"111\"",Ref2="/:TST_Class2.InstanceID=\"222\""
instance of TST_Association12 {
Ref1 = "/:TST_Class1.InstanceID=\"111\"";
Ref2 = "/:TST_Class2.InstanceID=\"222\"";
};
DMTF CIM schema download support¶
A CIM schema is the collection of CIM qualifier declarations and CIM classes and available a single tested, coherent package with a defined major, minor, update version number. The DMTF regularly releases updates to the DMTF CIM schema that represent all of the classes approved by the DMTF. The MOF representation of a DMTF schema release is packaged as a single zip file and is available on the DMTF web site ( https://www.dmtf.org/standards/cim ).
Because CIM schemas are the source of most of the classes that a WBEM server
normally implements it was important to create a simple mechanism to include
the DMTF CIM classes and qualifier declarations from a CIM schema in the
CIM repository of FakedWBEMConnection
.
The DMTFCIMSchema
class downloads the DMTF CIM schema
zip file defined by version from the DMTF web site into a defined directory,
unzips the MOF files into a subdirectory and makes this subdirectory
available as a property of the DMTFCIMSchema
object.
The implementation of this class depends on all of the qualiifiers and classes in the CIM schema having unique class names; this is always true for DMTF CIM schema releases to assure that they can be installed in the same namespace in a WBEM server repository.
Once aCIM schema is extracted into the individual MOF files it consumes
considerable space since it expands to almost 3000 files. Therefore it is
logical to remove all of the individual MOF files when not being used and also
if the schema information is to be committed to be used in testing in an
environment like github. Therefore, a method
clean()
removes all of the MOF files from
local storage. They are restored the next time the
DMTFCIMSchema
object for the same version is constructed.
The DMTF maintains two versions of each released schema:
- Final - This schema does not contain any of the schema classes that are marked experimental. It is considered the stable release.
- Experimental - Contains the classes in the final schema plus other classes that are considered experimental. It is considered less stable and the experimental classes with the Experimental qualifier are subject to incompatible changes .
DMTFCIMSchema
will install either the final or
experimental schema depending on the value of the use_experimental
parameter.
Because it is usually necessary to compile only a subset of the DMTF CIM
classes into a CIM repository for any test, the
DMTFCIMSchema
class provides a
build_schema_mof()
method to create a
list of MOF pragmans that includes only a subset of the classes in the
downloaded CIM Schema. The task of listing classes to be compiled is futher
simplified because the pywbem MOF compiler searches the DMTF schema for
prerequisite classes (superclasses, reference classes, and EmbeddedInstance
classes) so that generally only the leaf CIM classes required for the
repository need to be in the class list. This speeds up the process of
compiling DMTF CIM classes for any test significantly.
-
class
pywbem_mock.
DMTFCIMSchema
(schema_version, schema_root_dir, use_experimental=False, verbose=False)[source]¶ DMTFCIMSchema
represents a DMTF CIM Schema downloaded from the DMTF web site.This class manages the download of the DMTF schema zip file and extraction of MOF files of DMTF CIM schema releases into a directory that can be used by
compile_schema_classes()
to compile into a CIM repository with class and qualifier declarations from the schema.The init method downloads the schema if the schema_root_dir or the schema zip file do not exist into the directory defined by the schema_root_dir parameter and extracts the MOF files into schema_mof_dir.
If the schema zip file is already downloaded it simply sets the
DMTFCIMSchema
property values.If the schema zip file was previously downloaded but schema_mof_dir does not exist the directory is created and the MOF files are extracted into this directory.
Parameters: - schema_version (tuple of 3 integers (m, n, u) –
Represents the DMTF CIM schema version m.n.u where:
- m is the DMTF CIM schema major version
- n is the DMTF CIM schema minor version
- u is the DMTF CIM schema update version
This must represent a DMTF CIM schema that is available from the DMTF web site.
- schema_root_dir (string) –
Path name of the schema root directory into which the DMTF CIM schema zip file is downloaded and in which a subdirectory for the extracted MOF files for the schema version defined is created
Multiple DMTF CIM schemas may be maintained in the same schema_root_dir simultaneously because the MOF for each schema is extracted into a subdirectory identified by the schema version information See
schema_mof_dir
. - use_experimental (
bool
) –If True, the experimental version of the defined DMTF schema is installed.
If False, (default) the final version of the defined DMTF schema is installed.
- verbose (
bool
) – If True, progress messages are output to stdout as the schema is downloaded and expanded. Default is False.
Raises: ValueError
– if the schema cannot be retrieved from the DMTF web site.TypeError
– if the schema_version is not a valid tuple with 3 integer components
Methods
build_schema_mof
Build a string that includes the #include pragma
statement for the CIM schema classes defined in class_names using the DMTF CIM schema defined by this instance of the class.clean
Remove all of the MOF files and the schema_mof_dir for the defined schema. remove
The schema_mof_dir directory is removed if it esists and the schema_zip_file is removed if it exists. Attributes
schema_mof_dir
Path name of the directory in which the DMTF CIM Schema MOF files are extracted from the downloaded zip file. schema_pragma_file
Path name of the schema pragma file for the DMTF CIM schema. schema_root_dir
Path name of the directory in which the DMTF CIM schema zip file is downloaded. schema_version
The DMTF CIM schema version as a tuple of 3 integers with major version, minor version, and update version. schema_version_str
The DMTF CIM schema version as a string in the form major version>.<minor version>.<update version>
.schema_zip_file
Path name of the DMTF CIM schema zip file after being downloaded from the DMTF web site. schema_zip_url
URL of the DMTF CIM schema zip file that is downloaded from the DMTF web site. Details
-
schema_version
¶ The DMTF CIM schema version as a tuple of 3 integers with major version, minor version, and update version.
Example: (2, 49, 0) defines DMTF CIM schema version 2.49.0.
Type: tuple()
-
schema_version_str
¶ The DMTF CIM schema version as a string in the form
major version>.<minor version>.<update version>
.Example: “2.49.0” defines DMTF CIM schema version 2.49.0.
Type: string
-
schema_root_dir
¶ Path name of the directory in which the DMTF CIM schema zip file is downloaded. The MOF files are extracted into the subdirectory indicated by
schema_mof_dir
.Type: string
-
schema_mof_dir
¶ Path name of the directory in which the DMTF CIM Schema MOF files are extracted from the downloaded zip file. This property can be used as the MOF compiler search path for compiling classes in the DMTF CIM schema. This directory will also contain the schema pragma file.
Type: string
-
schema_pragma_file
¶ Path name of the schema pragma file for the DMTF CIM schema. This file contains #pragama include statements for all of the classes and qualifier declarations of the schema.
The classes are represented with one file per class, and the qualifier declarations are in the files qualifiers.mof and qualifiers_optional.mof.
The path name of the schema pragma file is of the general form:
<schema_mof_dir>/cim_schema_<schema_version_str>.mof
Example:
schemas/dmtf/moffinal2490/cim_schema_2.49.0.mof
Type: string
-
schema_zip_file
¶ Path name of the DMTF CIM schema zip file after being downloaded from the DMTF web site.
Type: string
-
schema_zip_url
¶ URL of the DMTF CIM schema zip file that is downloaded from the DMTF web site.
Type: string
-
__str__
()[source]¶ Return a short string representation of the
DMTFCIMSchema
object for human consumption. This displays the major properties of the object.
-
__repr__
()[source]¶ Return a string representation of the
DMTFCIMSchema
object that is suitable for debugging.
-
build_schema_mof
(class_names)[source]¶ Build a string that includes the
#include pragma
statement for the CIM schema classes defined in class_names using the DMTF CIM schema defined by this instance of the class.The class names in class_names can be just leaf classes within the schema . The pywbem MOF compiler will search for dependent classes including superclasses, and other classes referenced as the classes are compiled.
It builds a compilable MOF string in the form:
#pragma locale ("en_US") #pragma include ("System/CIM_ComputerSystem.mof") ...
with a
#pragma include
for each class name in the class_names list.The resulting set of #pragma statements is in the same order as the original pragmas. In some cases that could be important because the cim schema pragma file is ordered to missing dependencies and conflicts between class mof compiles
Parameters: class_names (list of string or string) – These must be class names of classes in the DMTF CIM schema represented by this
DMTFCIMSchema
object. This parameter can be a string if there is only a single class name to be included.If the returned string is compiled, the MOF compiler will search the directory defined by schema_mof_dir for classes referenced by each class in this list including super classes, classed defined by reference properties, and classes defined by an embedded-object.
Returns: Valid MOF containing pragma statements for all of the classes in schema_classes. Return type: string Raises: ValueError
– If any of the classnames in schema_classes are not in the DMTF CIM schema installed
-
clean
()[source]¶ Remove all of the MOF files and the schema_mof_dir for the defined schema. This is useful because while the downloaded schema is a single compressed zip file, it creates several thousand MOF files that take up considerable space.
The next time the
DMTFCIMSchema
object for this schema_version and schema_root_dir is created, the MOF file are extracted again.
- schema_version (tuple of 3 integers (m, n, u) –
In-memory CIM repository classes¶
The class InMemoryRepository
implements a CIM repository
that stores the CIM objects in memory. It contains an object store
(InMemoryObjectStore
) for each type of CIM object
(classes, instances, qualifier declarations) and for each CIM namespace in the
repository. Each object store for a CIM object type contains the CIM objects
of that type in a single CIM namespace.
The CIM repository of a mock WBEM server represented by a
FakedWBEMConnection
object is a
InMemoryRepository
object that is created and destroyed
automatically when the
FakedWBEMConnection
object is created and destroyed.
The CIM repository of a mock WBEM server is accessible through its
pywbem_mock.FakedWBEMConnection.cimrepository
property.
-
class
pywbem_mock.
InMemoryRepository
(initial_namespace=None)[source]¶ A CIM repository that maintains the data in memory using the methods defined in its superclass (~pywbem_mock:BaseObjectStore). This implementation creates the repository as multi-level dictionary elements to define the namespaces and within each namespace the CIM classes, CIM instances, and CIM qualifiers in the repository.
Initialize an empty in-memory CIM repository and optionally add a namespace in the repository..
Parameters: initial_namespace – (string or None): Optional initial namespace that will be added to the CIM repository. Methods
add_namespace
Add a CIM namespace to the repository. get_class_store
Return the CIM class object store for the namespace provided. get_instance_store
Return the CIM instance object store for the namespace provided. get_qualifier_store
Return the CIM qualifier declaration object store for the namespace provided. load
Replace the data in this object with the data from the other object. print_repository
Print the CIM repository to a destination. remove_namespace
Remove a CIM namespace from the repository. validate_namespace
Validate if the namespace exists in the repository. Attributes
namespaces
The names of the namespaces that exist in this CIM repository. Details
-
print_repository
(dest=None)[source]¶ Print the CIM repository to a destination. This displays information on the items in the data base and is only a diagnostic tool.
Parameters: dest (string) – File path of an output file. If None, the output is written to stdout.
-
validate_namespace
(namespace)[source]¶ Validate if the namespace exists in the repository. If the namespace does not exist a KeyError is raised.
Parameters: namespace (string) – The name of the CIM namespace in the CIM repository. The name is treated case insensitively and it must not be None. Any leading and trailing slash characters in the namespace string are ignored when accessing the repository.
Raises: KeyError
– If the namespace is not defined in the repository.ValueError
– if the namespace is None.
-
add_namespace
(namespace)[source]¶ Add a CIM namespace to the repository.
The namespace must not yet exist in the CIM repository.
Parameters: namespace (string) – The name of the CIM namespace in the CIM repository. The name is treated case insensitively and it must not be None. Any leading and trailing slash characters in the namespace string are ignored when accessing the repository. Raises: ValueError
– If the namespace argument is None or the namespace already exists.
-
remove_namespace
(namespace)[source]¶ Remove a CIM namespace from the repository.
The namespace must exist in the repository and must be empty.
Parameters: namespace (string) – The name of the CIM namespace in the CIM repository. The name is treated case insensitively and it must not be None. Any leading and trailing slash characters in the namespace string are ignored when accessing the repository.
Raises: ValueError
– Namespace argument is None or the repository namespace is not empty.KeyError
– Namespace does not exist in the CIM repository.
-
namespaces
¶ The names of the namespaces that exist in this CIM repository.
Note that if there were any leading or trailing slash (“/”) characters in namespace parameters used to add the namespaces to the repository, they will be removed from the namespaces returned with this property.
Type: NocaseList of string
-
get_class_store
(namespace)[source]¶ Return the CIM class object store for the namespace provided.
Parameters: namespace (string) – The name of the CIM namespace in the CIM repository. The name is treated case insensitively and it must not be None. Any leading and trailing slash characters in the namespace string are ignored when accessing the repository.
Returns: CIM class object store for the namespace provided.
Return type: Raises: ValueError
– Namespace argument is None.KeyError
– Namespace does not exist in the repository
-
get_instance_store
(namespace)[source]¶ Return the CIM instance object store for the namespace provided.
Parameters: namespace (string) – The name of the CIM namespace in the CIM repository. The name is treated case insensitively and it must not be None. Any leading and trailing slash characters in the namespace string are ignored when accessing the repository.
Returns: CIM instance object store for the namespace provided.
Return type: Raises: ValueError
– Namespace argument is None.KeyError
– Namespace argument does exist in the repository.
-
get_qualifier_store
(namespace)[source]¶ Return the CIM qualifier declaration object store for the namespace provided.
Parameters: namespace (string) – The name of the CIM namespace in the CIM repository. The name is treated case insensitively and it must not be None. Any leading and trailing slash characters in the namespace string are ignored when accessing the repository.
Returns: CIM qualifier declaration object store for the namespace provided.
Return type: Raises: ValueError
– namespace parameter is NoneKeyError
– namespace argument does exist in therepository.
-
-
class
pywbem_mock.
InMemoryObjectStore
(cim_object_type)[source]¶ A store for CIM objects of a single type (CIM classes, CIM instances, or CIM qualifier declarations) that maintains its data in memory.
Methods
create
Add the CIM object to the object store. delete
Delete the CIM object identified by name from the object store. get
Get with deepcopy because the pywbem .copy is only middle level and we need to completely isolate the repository. iter_names
Only copies the names for those objects that use CIMNamespaceName as the name. iter_values
Return an iterator to the CIM objects in the object store. len
Return the count of objects in this object store. object_exists
Test if the CIM object identified by name exists in the object store. update
Replace the CIM object in the object store idenfified by the name argument with the CIM object defined by the cim_object argument. Attributes
Details
-
object_exists
(name)[source]¶ Test if the CIM object identified by name exists in the object store.
Parameters: name (string or CIMInstanceName
) – Name by which the object is identified in the object store.Returns: Indicates whether the CIM object exists in the object store. Return type: bool
-
get
(name, copy=True)[source]¶ Get with deepcopy because the pywbem .copy is only middle level and we need to completely isolate the repository.
-
create
(name, cim_object)[source]¶ Add the CIM object to the object store.
Parameters: - name (string or
CIMInstanceName
) – Name by which the CIM object will be identified in the object store. - cim_object (CIM object) – The CIM object to be added to the object store. The object is copied into the object store so the user can safely modify the original object without affecting the store.
Raises: ValueError
– If CIM object already exists in the object store.- name (string or
-
update
(name, cim_object)[source]¶ Replace the CIM object in the object store idenfified by the name argument with the CIM object defined by the cim_object argument.
Parameters: - name (string or
CIMInstanceName
) – Name by which the object is identified in the object store. - cim_object (CIM object) – The CIM object to replace the original CIM object in the data store. The object is copied into the object store so the user can safely modify the original object without affecting the store.
Raises: KeyError
– If no CIM object with name exists in the object store.- name (string or
-
delete
(name)[source]¶ Delete the CIM object identified by name from the object store.
Parameters: name (string or CIMInstanceName
) – Name by which the object to be deleted is identified in the object store.Raises: KeyError
– If there is no object with name in this object store
-
iter_names
()[source]¶ Only copies the names for those objects that use CIMNamespaceName as the name. The others are immutable ex. classname.
-
iter_values
(copy=True)[source]¶ Return an iterator to the CIM objects in the object store. This allows iteration through all the objects in this object store using iterator methods.
The order of returned CIM objects is undetermined.
Parameters: copy ( bool
) – Copy the objects before returning them. This is the default behavior and also the mode that should be used unless the user is certain the object will NOT be modified after it is returned.Returns: An iterator for the objects in the object store. If copy == True, each object is copied before it is returned. Return type: iterator
-
Mocking multiple CIM namespaces¶
The mock WBEM server allows creating multiple CIM namespaces in its CIM repository and adding CIM objects in some or all of those namespaces.
There is a default namespace created when the
FakedWBEMConnection
object is created from either the
value of the default_namespace init parameter or its default value
root/cimv2
.
However, a working WBEM environment normally includes at least two namespaces:
- An interop namespace which contains the parts of the model that deal with the WBEM server itself and with the implemented model (ex. CIM_Namespace, CIM_ObjectManager, CIM_RegisteredProfile, etc.) and which must be publically discoverable without the user knowing what CIM namespaces exist in the WBEM server.
- A user namespace containing the CIM objects for the user model.
Pywbem_mock includes a user-defined provider for the CIM_Namespace class that can be enabled by adding code similar to the following to the setup of a mock environment.
# Register the provider for the CIM_Namespace class, assuming that
# dependent classes and qualifier types have already been created in
# the interop namespace.
ns_provider = pywbem_mock.CIMNamespaceProvider(conn.cimrepository)
interop_namespace = "interop" # or "root/interop"
conn.add_namespace(interop_namespace)
conn.register_provider(ns_provider, namespaces=interop_namespace)
User-defined providers¶
Within the mock WBEM server, the response to client requests is normally
determined by provider methods that use data in the CIM
repository to generate responses (ex. GetInstance
gets the instances from
the repository, possibly filters properties and returns the instance).
However, it is expected that the user may want WBEM operations on specific
CIM classes to have side effects, or manage the returns differently
than the normal responses.
Thus, for example, the DMTF-defined CIM_Namespace class represents the
namespaces in the CIM repository. That means that its provider method for
CreateInstance
must create a namespace as a side effect, and that its
provider methods for GetInstance
or EnumerateInstances
must inspect
the set of namespaces in the CIM repository to generate responses, etc.
Another example of user-defined providers are classes that create their key
property values automatically, for example classes that have a single
InstanceID
key. The provider method for CreateInstance
of such classes
would ignore the values for the key properties provided in the NewInstance
parameter, and determine the key values on its own.
Also, the InvokeMethod
operation depends on a specific provider method for
the invoked CIM method in the mock WBEM server.
To meet these needs, the capability is provided to users to write user-defined providers that replace the default providers for defined classes and operations.
User-defined providers are written by implementing subclasses of
specific provider classes and registering these subclasses as providers using
register_provider()
.
The WBEM operations supported by user-defined providers can be implemented one by one. If a user-defined provider does not implement all WBEM operations, the default implementation will be used.
The following table shows the WBEM operations for which user-defined providers are supported, and the corresponding provider types:
WBEM operation | Provider type | Superclass | Provider description |
---|---|---|---|
CreateInstance | instance write | InstanceWriteProvider |
User-defined instance write providers |
ModifyInstance | instance write | InstanceWriteProvider |
User-defined instance write providers |
DeleteInstance | instance write | InstanceWriteProvider |
User-defined instance write providers |
InvokeMethod | method | MethodProvider |
User-defined method providers |
Creating user-defined providers¶
A user-defined provider can be created as follows:
Define a subclass of the superclass listed in the table above, with the methods and attributes listed below.
Example for an instance write provider:
from pywbem_mock import InstanceWriteProvider class MyInstanceProvider(InstanceWriteProvider): . . .
Optional: It may have an
__init__()
method.The
__init__()
method takes as input parameters at least thecimrepository
parameter and passes it to the superclass, and may have additional init parameters the user-defined provider requires (that are not passed on to the superclass). Additional init parameters are possible because the user creates the provider object when registering it withregister_provider()
. Having an__init__()
method is optional if no additional init parameters are defined.Example for an
__init__()
method that does not define additional init parameters (and that could therefore be omitted):def __init__(self, cimrepository): super(MyInstanceWriteProvider, self).__init__(cimrepository)
It must have a declaration of the CIM class(es) served by the provider.
The CIM class or classes served by the provider are declared with a class attribute named
provider_classnames
. Its value must be a single string or a list/tuple of strings with the CIM class names (in any lexical case).provider_classnames = 'CIM_Foo'
or
provider_classnames = ['CIM_Foo', 'CIM_Foo_blah']
It must have an implementation of the Python methods for the WBEM operations that are overwritten by the provider.
This must be all or a subset of the WBEM operations defined for the provider type. WBEM operations not implemented in the user-defined provider class default to implementations in the superclass. See Python operation methods in user-defined providers for details.
Example for an
CreateInstance
method of an instance write provider that just calls superclass method to perform the work (and that could therefore be omitted):def CreateInstance(self, namespace, NewInstance): return super(MyInstanceWriteProvider, self).CreateInstance( namespace, NewInstance)
Optional: It may define a post register setup method.
The provider may override the
post_register_setup()
method of the provider superclass to do any special setup it needs. That method includes the current connection as a parameter so that WBEM operations on the same or on different classes can be executed. That method will be called during invocation ofregister_provider()
, after the provider registration is successful.Example:
def post_register_setup(self, conn): # code that performs post registration setup for the provider
Register the user-defined provider using
pywbem_mock.FakedWBEMConnection.register_provider()
.This specifies the CIM namespaces for which the user-defined provider will be active. These namespaces must already exist in the CIM repository if the mock WBEM server.
provider = MyInstanceProvider(self.cimrepository) conn.register_provider(provider, namespaces=['root/interop', 'root/cimv2'])
Python operation methods in user-defined providers¶
The Python operation methods (i.e. the Python methods implementing WBEM operations) in user-defined providers may:
- provide parameter or CIM repository validation in addition to the normal request validation,
- modify parameters of the request,
- abort the request with a
pywbem.CIMError
exception, - make modifications to the CIM repository.
The Python operation methods may call the corresponding superclass method to complete the CIM repository modification, or may implement the code to complete the modification. In any case, once a Python operation method returns, the CIM repository needs to reflect any changes on CIM objects the WBEM operation is normally expected to perform.
The Python operation methods have access to:
- methods defined in the superclass of the provider, including :class:~pywbem_mock.BaseProvider`
- methods to access the CIM repository using the methods defined in
InMemoryRepository
The input parameters for the Python operation methods will have been already validated, including:
- The input parameters have the correct Python type as per the descriptions in the superclasses.
- The CIM namespace exists in the CIM repository.
- The CIM class of a CIM instance or instance path specified as an input parameter exists in that namespace of the CIM repository.
- The CIM properties of a CIM instance specified as an input parameter are defined in the CIM class of the instance and have the correct CIM types.
- The CIM instance does not yet exist for CreateInstance and does exist for ModifyInstance.
The Python operation methods should raise any exceptions using
pywbem.CIMError
using the CIM status codes defined in DSP0200.
User-defined instance write providers¶
The InstanceWriteProvider
class provides the default
implementations of the CreateInstance
, ModifyInstance
and
DeleteInstance
provider methods by means of
CreateInstance()
,
ModifyInstance()
, and
DeleteInstance()
.
A user-defined instance write provider may implement some or all of these provider methods. The method descriptions linked above provide a detailed definition of the input parameters, return values, and required behavior.
The following is a simple example of a user-defined instance write provider
that serves the ‘CIM_Foo’ and ‘CIM_FooFoo’ classes and implements
CreateInstance
for the purpose of setting a value for the ‘InstanceID’ key
property:
import uuid
from pywbem_mock import InstanceWriteProvider
class MyInstanceProvider(InstanceWriteProvider):
# CIM classes served by this provider
provider_classnames = ['CIM_Foo', 'CIM_FooFoo']
def CreateInstance(self, namespace, new_instance):
new_instance.properties["InstanceID"] = \
"{}.{}".format(new_instance.classname, uuid.uuid4())
return super(MyInstanceProvider, self).CreateInstance(
namespace, new_instance)
Because the provider in this example does not implement the
ModifyInstance
and DeleteInstance
methods, these operations will
use their default implementations from
InstanceWriteProvider
.
The provider in this example does not need to implement an __init__()
method, because no additional init parameters are needed.
-
class
pywbem_mock.
InstanceWriteProvider
(cimrepository=None)[source]¶ This class defines those instance provider methods that may have user- defined providers that override the default provider implementation in this class.
User providers are defined by creating a subclass of this class and defining a new provider method for one of the methods in this class with the same signature.
Note that user-defined providers may, in turn, call the default providers in this class.
Parameters: cimrepository ( BaseRepository
or subclass) – The CIM repository to be used by the provider.Methods
CreateInstance
Default provider method for pywbem.WBEMConnection.CreateInstance()
.DeleteInstance
Default provider method for pywbem.WBEMConnection.DeleteInstance()
.ModifyInstance
Default provider method for pywbem.WBEMConnection.CreateInstance()
.add_namespace
Add a CIM namespace to the CIM repository. class_exists
Test if class defined by classname parameter exists in CIM repository defined by namespace parameter. filter_properties
Remove properties from an instance or class that aren’t in the property_list parameter. find_interop_namespace
Find the Interop namespace name in the CIM repository, or return None. get_class
Get class from CIM repository. is_interop_namespace
Tests if a namespace name is a valid Interop namespace name. is_subclass
Return boolean indicating whether a class is a (direct or indirect) subclass of a superclass, or the same class, in the specified class store of the CIM repository (i.e. post_register_setup
Method called by provider registration after registation of provider is successful. remove_namespace
Remove a CIM namespace from the CIM repository. validate_namespace
Validates that a namespace is defined in the CIM repository. Attributes
cimrepository
Instance of class that represents the CIM repository. interop_namespace_names
The valid Interop namespace names. namespaces
The names of the namespaces that exist in the CIM repository. provider_type
Keyword defining the type of request the provider will service. Details
-
provider_type
= 'instance-write'¶ Keyword defining the type of request the provider will service. The type for this provider class is predefined as ‘instance’.
Type: string
-
CreateInstance
(namespace, new_instance)[source]¶ Default provider method for
pywbem.WBEMConnection.CreateInstance()
.Create a new CIM instance in the CIM repository of the mock WBEM server.
Validation already performed by the provider dispatcher that calls this provider method:
- The provider method is called only for the registered class and namespace (only applies to user-defined providers).
- The Python types of all input parameters to this provider method are as specified below.
- The namespace exists in the CIM repository.
- The creation class of the new instance exists in the namespace in the CIM repository.
- All properties specified in the new instance are exposed (i.e. defined and inherited with any overrides resolved) by the creation class in the CIM repository, and have the same type-related attributes (i.e. type, is_array, embedded_object).
Validation that should be performed by this provider method:
- new_instance does not specify any properties that are not allowed to be initialized by the client, depending on the model implemented by the provider.
- new_instance specifies all key properties needed by the provider, depending on the model implemented by the provider. The CIM repository will reject any new instance that does not have all key properties specified.
- The new instance (i.e. an instance with the new instance path) does not exist in the CIM repository. This validation needs to be done by the provider because the determination of the key properties for the new instance path may depend on the model implemented by the provider. The CIM repository will reject the creation of instances that already exist, so this check can be delegated to the repository once the new instance path has been determined.
Parameters: - namespace (string) – The name of the CIM namespace in which the CIM instance is to be created, in any lexical case, and with leading and trailing slash characters removed.
- new_instance (
CIMInstance
) –A representation of the CIM instance to be created.
This object is a deep copy of the original client parameter, and may be modified by the provider as needed, before storing it in the CIM repository.
The property names in this object have been adjusted to match the lexical case of the property definitions in the creation class of the instance in the CIM repository.
The classname attribute of this object will specify the creation class for the new instance, in any lexical case.
The properties attribute of this object will specify the initial property values for the new CIM instance, with property names in any lexical case. Key properties may or may not be included.
The path attribute of this object will be None.
The qualifiers attribute of this object, if non-empty, should be ignored by the provider, because instance-level qualifiers have been deprecated in CIM.
Returns: Instance path of the new CIM instance.
Return type: Raises: CIMError
– The provider may raise CIMError with any status code, and typically raises: - CIM_ERR_INVALID_PARAMETER - CIM_ERR_ALREADY_EXISTS
-
ModifyInstance
(modified_instance, IncludeQualifiers=None)[source]¶ Default provider method for
pywbem.WBEMConnection.CreateInstance()
.Modify an existing CIM instance in the CIM repository of the mock WBEM server.
NOTE: This method specifies the namespace in modified_instance.path rather than as a separate input parameter.
The modification of the instance in the CIM repository that is performed by the provider should be limited to property value changes (including addition of properties if not yet set on the instance), because instance-level qualifiers have been deprecated in CIM.
The set of properties that are to be modified in the CIM instance has already been determined by the caller so that the modified_instance parameter specifies exactly the set of properties to be modified. Therefore, this provider method does not have a property list parameter.
Validation already performed by the provider dispatcher that calls this provider method:
- The provider method is called only for the registered class and namespace (only applies to user-defined providers).
- The Python types of all input parameters to this provider method are as specified below.
- The classnames in modified_instance are consistent between instance and instance path.
- The namespace exists in the CIM repository.
- The creation class of the instance to be modified exists in the namespace of the CIM repository.
- The instance to be modified exists in the namespace of the CIM repository.
- All properties in modified_instance that are to be modified are exposed (i.e. defined and inherited with any overrides resolved) by the creation class in the CIM repository, and have the same type-related attributes (i.e. type, is_array, embedded_object).
- No key properties are requested to change their values.
Validation that should be performed by this provider method:
- modified_instance does not specify any changed values for properties that are not allowed to be changed by the client, depending on the model implemented by the provider.
Parameters: - modified_instance (
CIMInstance
) –A representation of the modified CIM instance, also indicating its instance path, with exactly the set of properties to be modified.
This object is a deep copy of the original client parameter, and may be modified by the provider as needed, before storing it in the CIM repository.
The path attribute of this object will be set and is the instance path of the instance to be modified in the CIM repository. Its namespace, classname and keybindings attributes will be set. The names will be in any lexical case.
The classname attribute of this object will specify the creation class of the instance to be modified, in any lexical case.
The properties attribute of this object will specify exactly the set of properties that are to be updated, taking into account the original ModifiedInstance and PropertyList input parameters of the ModifyInstance() client call. The lexical case of the property names has been adjusted to match the lexical cae of the property definitions in the creation class in the CIM repository.
The qualifiers attribute of this object, if non-empty, should be ignored by the provider, because instance-level qualifiers have been deprecated in CIM.
- IncludeQualifiers (
bool
) – This parameter should be ignored by the provider, because instance-level qualifiers have been deprecated in CIM.
Raises: CIMError
– The provider may raise CIMError with any status code, and typically raises: - CIM_ERR_INVALID_PARAMETER
-
DeleteInstance
(InstanceName)[source]¶ Default provider method for
pywbem.WBEMConnection.DeleteInstance()
.Delete an existing instance in the CIM repository of the mock WBEM server.
NOTE: This method specifies the namespace in InstanceName rather than as a separate input parameter.
The provider is not responsible for determining other instances that depend on the instance to be deleted (e.g. association instances referencing the instance to be deleted); such dependency detection and handling is done elsewhere.
Validation already performed by the provider dispatcher that calls this provider method:
- The provider method is called only for the registered class and namespace (only applies to user-defined providers).
- The Python types of all input parameters to this provider method are as specified below.
- The namespace exists in the CIM repository.
- The creation class of the instance to be deleted exists in the namespace of the CIM repository.
- The instance to be deleted exists in the namespace of the CIM repository.
Parameters: InstanceName ( CIMInstanceName
) –The instance path of the instance to be deleted with the following attributes:
- classname: Name of the creation class of the instance.
- keybindings: Keybindings of the instance.
- namespace: Name of the CIM namespace containing the instance. Will not be None.
- host: Will be None.
Raises: None
-
post_register_setup
(conn)[source]¶ Method called by provider registration after registation of provider is successful. Using this method is optional for registration cases where the provider must execute some activity (ex. modify the CIM repository after successful provider registration).
Override this method in the user-defined provider subclass to execute this method.
Parameters: conn ( WBEMConnection
) – Current connection which allows client methods to be executed from within this method.
-
User-defined method providers¶
The MethodProvider
class provides the default
implementation of the InvokeMethod
provider method by means of
InvokeMethod()
.
The default implementation raises CIMError with CIM_ERR_METHOD_NOT_AVAILABLE, because there is no meaningful default implementation of CIM methods. A user-defined method provider implements this provider method. The method description linked above provides a detailed definition of the input parameters, return values, and required behavior.
The following example implements method Method1
defined in class
CIM_Foo_sub_sub
that is defined as follows:
[Description ("Subclass of CIM_Foo_sub")]
class CIM_Foo_sub_sub : CIM_Foo_sub {
string cimfoo_sub_sub;
[Description("Sample method with input and output parameters")]
uint32 Method1(
[IN ( false), OUT, Description("Response param 2")]
string OutputParam2);
};
The example implementation of method Method1
in the user-defined method
provider modifies the value of property cimfoo_sub_sub
of the instance,
and returns it as its output parameter OutputParam2
:
from pywbem import CIMInstanceName, CIMError, \
CIM_ERR_INVALID_PARAMETER, CIM_ERR_METHOD_NOT_AVAILABLE
from pywbem_mock import MethodProvider
class MyMethodProvider(MethodProvider):
provider_classnames = 'CIM_Foo_sub_sub'
def InvokeMethod(self, methodname, localobject, params):
if methodname.lower() == 'method1':
if isinstance(localobject, CIMClassName):
raise CIMError(
CIM_ERR_INVALID_PARAMETER,
"CIM method {0} must be invoked on a CIM instance".
format(methodname))
return self.Method1(localobject, params)
else:
raise CIMError(CIM_ERR_METHOD_NOT_AVAILABLE)
def Method1(self, localobject, params):
'''
Implementation of CIM method 'Method1'.
'''
namespace = localobject.namespace
instance_store = self.cimrepository.get_instance_store(namespace)
# Get the instance the method was invoked on, from the CIM
# repository (as a copy)
instance = instance_store.get(localobject.path) # a copy
# Modify a property value in the local copy of the instance
if 'cimfoo_sub_sub' not in instance.properties:
instance.properties['cimfoo_sub_sub'] = 'new'
instance.properties['cimfoo_sub_sub'] += '+'
# Update the instance in the CIM repository from the changed
# local instance
instance_store.update(localobject.path, instance)
# Return the property value in the output parameter
outputparam2 = instance.properties['cimfoo_sub_sub']
out_params = [
CIMParameter('OutputParam2', type='string', value=outputparam2),
]
# Set the return value of the CIM method
return_value = 0
return (return_value, out_params)
-
class
pywbem_mock.
MethodProvider
(cimrepository=None)[source]¶ This class defines the provider class that handles the default InvokeMethod.
User method providers are defined by creating a subclass of this class and defining an InvokeMethod based on the method in this class.
Parameters: cimrepository ( BaseRepository
or subclass) – Defines the repository to be used by the provider.Methods
InvokeMethod
Default provider method for pywbem.WBEMConnection.InvokeMethod()
.add_namespace
Add a CIM namespace to the CIM repository. class_exists
Test if class defined by classname parameter exists in CIM repository defined by namespace parameter. filter_properties
Remove properties from an instance or class that aren’t in the property_list parameter. find_interop_namespace
Find the Interop namespace name in the CIM repository, or return None. get_class
Get class from CIM repository. is_interop_namespace
Tests if a namespace name is a valid Interop namespace name. is_subclass
Return boolean indicating whether a class is a (direct or indirect) subclass of a superclass, or the same class, in the specified class store of the CIM repository (i.e. post_register_setup
Method called by provider registration after registation of provider is successful. remove_namespace
Remove a CIM namespace from the CIM repository. validate_namespace
Validates that a namespace is defined in the CIM repository. Attributes
cimrepository
Instance of class that represents the CIM repository. interop_namespace_names
The valid Interop namespace names. namespaces
The names of the namespaces that exist in the CIM repository. provider_type
Keyword defining the type of request the provider will service. Details
-
provider_type
= 'method'¶ Keyword defining the type of request the provider will service. The type for this class is predefined as ‘method’
Type: provider_type (string)
-
InvokeMethod
(methodname, localobject, params)[source]¶ Default provider method for
pywbem.WBEMConnection.InvokeMethod()
.Invoke a CIM method (static or dynamic) on a target CIM object (class or instance) in the CIM repository of the mock WBEM server.
This default provider always raises CIMError(CIM_ERR_METHOD_NOT_FOUND) because there is no concept of a default method invocation behavior in in CIM (other than raising this error). A user-defined method provider is necessary to have a meaningful implementation of a method invocation.
Validation already performed by the provider dispatcher that calls this provider method:
- The provider method is called only for the registered class and namespace (only applies to user-defined providers).
- The Python types of all input parameters to this provider method are as specified below.
- The namespace exists in the CIM repository.
- For instance-level use:
- The creation class of the target instance exists in the namespace of the CIM repository.
- The target instance exists in the namespace of the CIM repository.
- The creation class of the target instance exposes the method to be invoked.
- For class-level use:
- The target class exists in the namespace of the CIM repository.
- The target class exposes the method to be invoked.
- The method exposed by the creation class is a static method as per its ‘Static’ qualifier.
- The set of specified CIM method input parameters matches exactly the set of input parameters defined by the method in the CIM repository (as detected by their ‘In’ qualifier in the creation class), w.r.t. parameter name and type-related attributes (type, is_array, embedded_object).
Validation that should be performed by this provider method:
- MethodName is the name of a method the provider implements.
- Constraints on the values of input parameters.
Parameters: - methodname (string) – Name of the CIM method to be invoked, in any lexical case.
- objectname –
(
CIMInstanceName
orCIMClassName
): A reference to the target CIM object, as follows:- For instance-level use: The instance path of the target
instance, as a
CIMInstanceName
object, with the following attributes:- classname: Will be set, in any lexical case.
- keybindings: Will be set, with key names in any lexical case.
- namespace: Will be set, in any lexical case, and with leading and trailing slash characters removed.
- host: Will be None.
- For class-level use: The class path of the target class, as a
CIMClassName
object, with the following attributes:- classname: Will be set, in any lexical case.
- namespace: Will be set, in any lexical case, and with leading and trailing slash characters removed.
- host: Will be None.
- For instance-level use: The instance path of the target
instance, as a
- params (
NocaseDict
) –The input parameters for the method invocation, with items as follows:
- key (string): The parameter name, in any lexical case.
- value (
CIMParameter
): The parameter value.
Returns: The return value and output parameters of the method invocation:
return_value (CIM data type): Return value of the method invocation.
out_params (
colletions.abc.Sequence
orcolletions.abc.Mapping
): Output parameters of the method invocation.If
Sequence
, the items must beCIMParameter
in any order, with these attributes set:- name (string): Parameter name
- value (CIM data type): Parameter value
If
Mapping
, the items must be as follows:- key (string): Parameter name
- value (CIM data type or
CIMParameter
): Parameter value
Return type: tuple()
(return_value, out_params)Raises: CIMError
– (CIM_ERR_METHOD_NOT_FOUND) because the default method is only a placeholder for the API and documentation and not a real InvokeMethod action implementation.
-
post_register_setup
(conn)[source]¶ Method called by provider registration after registation of provider is successful. Using this method is optional for registration cases where the provider must execute some activity (ex. modify the CIM repository after successful provider registration).
Override this method in the user-defined provider subclass to execute this method.
Parameters: conn ( WBEMConnection
) – Current connection which allows client methods to be executed from within this method.
-
Registry for provider dependent files¶
A faked WBEM connection provides a registry for provider dependent files
in its provider_dependent_registry
property of type pywbem_mock.ProviderDependentRegistry
.
This registry can be used by callers to register and look up the path names of additional dependent files of a mock script, in context of that mock script.
The pywbemtools project makes use of this registry for validating whether its mock cache is up to date w.r.t. additional dependent files a mock script has used.
-
class
pywbem_mock.
ProviderDependentRegistry
[source]¶ A registry for provider dependent files in context of a mock script.
This registry allows registering additional dependent files in context of a mock script, and to look them up again.
The registry works with the path names of the mock script and dependent files and normalizes these path names as follows:
- The path is relative to the user’s home directory, if possible. If not possible (i.e. on Windows when on a different drive than the home directory), the path is absolute.
- The path does not contain redundant path separators or same-level or up-level directories.
- On case insensitive file systems, the lexical case is normalized to lower case.
- The native path seprarators of the operating system are used.
Methods
add_dependents
Add dependent files to the registry, in context of a mock script. iter_dependents
Iterate through the path names of the dependent files that are registered for a mock script. load
Replace the data in this object with the data from the other object. Attributes
Details
-
add_dependents
(mock_script_path, dependent_paths)[source]¶ Add dependent files to the registry, in context of a mock script.
Parameters: - mock_script_path (string) – Path name of the mock script. May be relative or absolute, and will be normalized to look up the registered dependents.
- dependent_paths (string or
list
of string) – Path name(s) of provider dependent files to be registered. May be relative or absolute, and will be normalized when registering them.
-
iter_dependents
(mock_script_path)[source]¶ Iterate through the path names of the dependent files that are registered for a mock script.
If the mock script is not registered, the iteration is empty.
The iterated path names are the normalized path names, but with a path that makes them accessible from within the current directory.
Parameters: mock_script_path (string) – Path name of the mock script. May be relative or absolute, and will be normalized to look up the registered dependents. Returns: A generator iterator for the path names of the dependent files. Return type: iterator
Configuration of mocked behavior¶
Pywbem_mock supports several variables that provide configuration and behavior control of the mock environment.
These configuration variables can be modified by the user directly after importing pywbem. For example:
import pywbem_mock
pywbem_mock.config.SYSTEMNAME = 'MyTestSystemName'
Note that the pywbem source file defining these variables should not be changed by the user. Instead, the technique shown in the example above should be used to modify the configuration variables.
-
pywbem_mock.config.
OBJECTMANAGERNAME
= 'FakeObjectManager'¶ Name for the object manager It is used in defining user-defined provider properties for CIM_Namespace provider and CIM_ObjectManager provider if if they are defined.
-
pywbem_mock.config.
OBJECTMANAGERCREATIONCLASSNAME
= 'CIM_ObjectManager'¶ Value for the CIM_ObjectManagerCreationClassName defined in the CIM_ObjectManager class.
-
pywbem_mock.config.
SYSTEMNAME
= 'MockSystem_WBEMServerTest'¶ The name of the mock object. This string value becomes part of the CIM_ObjectNamager instance and CIM_Namespace instances
-
pywbem_mock.config.
SYSTEMCREATIONCLASSNAME
= 'CIM_ComputerSystem'¶ Name for the property SystemCreationClassname defined a number of CIM classes that are used by the pywbem_mock including CIM_Namespace
-
pywbem_mock.config.
DEFAULT_MAX_OBJECT_COUNT
= 100¶ Default value for the MaxObjectCount parameter of the Open…() methods of the mock WBEM server, if the value was not provided by the user.
-
pywbem_mock.config.
OPEN_MAX_TIMEOUT
= 40¶ Maximum value for the OperationTimeout parameter of the Open…() methods of the mock WBEM server.
-
pywbem_mock.config.
IGNORE_INSTANCE_IQ_PARAM
= True¶ Use of the IncludeQualifiers parameter on instance requests is DEPRECATED in DMTF DSP0200. The definition of IncludeQualifiers is ambiguous and when this parameter is set to true, WBEM clients cannot be assured that any qualifiers will be returned. A WBEM client should always set this parameter to false. To minimize the impact of this recommendation on WBEM clients, a WBEM server may choose to treat the value of IncludeQualifiers as false for all requests.
The following variable forces pywbem_mock to ignore the client supplied variable and not return qualifiers on EnumerateInstances and GetInstance responses.
- True (default): pywbem_mock always removes qualifiers from instances in responses
- False: pywbem_mock uses value of input parameter or its default to determine if qualifiers are to be removed
-
pywbem_mock.config.
IGNORE_INSTANCE_ICO_PARAM
= True¶ Use of the IncludeClassOrigin parameter on instance requests is DEPRECATED. A WBEM server may choose to treat the value of IncludeClassOrigin parameter as false for all requests, otherwise the implementation shall support the original behavior as defined in the rest of this paragraph. If the IncludeClassOrigin input parameter is true, the CLASSORIGIN attribute shall be present on all appropriate elements in each returned Instance. If it is false, no CLASSORIGIN attributes are present.
The following variable forces pywbem_mock to ignore the client supplied variable and not return qualifiers on EnumerateInstances and GetInstance responses.
- True (default): pywbem_mock always removes class origin attributes from instances in responses
- False: pywbem_mock uses value of input parameter or its default to determine if class origin attributes are to be removed
Mocker base classes¶
Some bases classes are included in this documentation in order to provide the descriptions for inherited methods and properties in the previous class descriptions of the mock WBEM server.
-
class
pywbem_mock.
BaseRepository
[source]¶ An abstract base class defining the required APIs to provide access to a a CIM repository. The API provides functions to:
- Manage CIM namespaces in the data repository including creation, deletion and getting a list of the existing namespaces.
- Access the object store for each CIM object type in the repository for
the objects of the following CIM types: (
CIMClass
,CIMInstance
, andCIMQualifierDeclaration
) so that methods of the BaseObjectStore are used to access and manipulate CIM objects of a single CIM type by namespace in the repository.
Methods
add_namespace
Add a CIM namespace to the repository. get_class_store
Return the CIM class object store for the namespace provided. get_instance_store
Return the CIM instance object store for the namespace provided. get_qualifier_store
Return the CIM qualifier declaration object store for the namespace provided. remove_namespace
Remove a CIM namespace from the repository. validate_namespace
Validate if the namespace exists in the repository. Attributes
namespaces
The names of the namespaces that exist in this CIM repository. Details
-
namespaces
¶ The names of the namespaces that exist in this CIM repository.
Note that if there were any leading or trailing slash (“/”) characters in namespace parameters used to add the namespaces to the repository, they will be removed from the namespaces returned with this property.
Type: NocaseList of string
-
validate_namespace
(namespace)[source]¶ Validate if the namespace exists in the repository. If the namespace does not exist a KeyError is raised.
Parameters: namespace (string) – The name of the CIM namespace in the CIM repository. The name is treated case insensitively and it must not be None. Any leading and trailing slash characters in the namespace string are ignored when accessing the repository.
Raises: KeyError
– If the namespace is not defined in the repository.ValueError
– if the namespace is None.
-
add_namespace
(namespace)[source]¶ Add a CIM namespace to the repository.
The namespace must not yet exist in the CIM repository.
Parameters: namespace (string) – The name of the CIM namespace in the CIM repository. The name is treated case insensitively and it must not be None. Any leading and trailing slash characters in the namespace string are ignored when accessing the repository. Raises: ValueError
– If the namespace argument is None or the namespace already exists.
-
remove_namespace
(namespace)[source]¶ Remove a CIM namespace from the repository.
The namespace must exist in the repository and must be empty.
Parameters: namespace (string) – The name of the CIM namespace in the CIM repository. The name is treated case insensitively and it must not be None. Any leading and trailing slash characters in the namespace string are ignored when accessing the repository.
Raises: ValueError
– Namespace argument is None or the repository namespace is not empty.KeyError
– Namespace does not exist in the CIM repository.
-
get_class_store
(namespace)[source]¶ Return the CIM class object store for the namespace provided.
Parameters: namespace (string) – The name of the CIM namespace in the CIM repository. The name is treated case insensitively and it must not be None. Any leading and trailing slash characters in the namespace string are ignored when accessing the repository.
Returns: CIM class object store for the namespace provided.
Return type: Raises: ValueError
– Namespace argument is None.KeyError
– Namespace does not exist in the repository
-
get_instance_store
(namespace)[source]¶ Return the CIM instance object store for the namespace provided.
Parameters: namespace (string) – The name of the CIM namespace in the CIM repository. The name is treated case insensitively and it must not be None. Any leading and trailing slash characters in the namespace string are ignored when accessing the repository.
Returns: CIM instance object store for the namespace provided.
Return type: Raises: ValueError
– Namespace argument is None.KeyError
– Namespace argument does exist in the repository.
-
get_qualifier_store
(namespace)[source]¶ Return the CIM qualifier declaration object store for the namespace provided.
Parameters: namespace (string) – The name of the CIM namespace in the CIM repository. The name is treated case insensitively and it must not be None. Any leading and trailing slash characters in the namespace string are ignored when accessing the repository.
Returns: CIM qualifier declaration object store for the namespace provided.
Return type: Raises: ValueError
– namespace parameter is NoneKeyError
– namespace argument does exist in therepository.
-
class
pywbem_mock.
BaseObjectStore
(cim_object_type)[source]¶ An abstract class that defines the APIs for the methods of an object store for CIM objects including CIMClass, CIMInstance, and CIMQualifierDeclaration objects that constitute a WBEM server repository. This class provides the abstract methods for creating, accessing, and deleting, CIM objects of a single CIM object type in the repository.
CIM objects in the object store are identified by a name which is part of the methods that access the CIM objects and must be unique within a single object store.
Each object store conatins only a single CIM object type.
Instantiate the self.cim_object_type variable.
Parameters: cim_object_type (CIM object) – The Pywbem CIM object type as defined in cim_types.py for the objects in the data store. Used to verify values on create. Methods
create
Add the CIM object to the object store. delete
Delete the CIM object identified by name from the object store. get
Return the CIM object identified by name if it exists in the object store. iter_names
Return an iterator to the names of the CIM objects in the object store. iter_values
Return an iterator to the CIM objects in the object store. len
Return the count of objects in this object store. object_exists
Test if the CIM object identified by name exists in the object store. update
Replace the CIM object in the object store idenfified by the name argument with the CIM object defined by the cim_object argument. Attributes
Details
-
object_exists
(name)[source]¶ Test if the CIM object identified by name exists in the object store.
Parameters: name (string or CIMInstanceName
) – Name by which the object is identified in the object store.Returns: Indicates whether the CIM object exists in the object store. Return type: bool
-
get
(name, copy=True)[source]¶ Return the CIM object identified by name if it exists in the object store.
Parameters: - name (string or
CIMInstanceName
) – Name by which the object is identified in the object store - copy (
bool
) – If True, returns a copy of the object to insure that modifying the returned object does not change the data store. The default behavior is True . If copy is False, the object in the object store is returned but if it is modified by the user, the object in the store may be modified also.
Returns: Returns the CIM object identified by the name parameter.
Return type: Raises: KeyError
– CIM object identified with name not in the object store- name (string or
-
create
(name, cim_object)[source]¶ Add the CIM object to the object store.
Parameters: - name (string or
CIMInstanceName
) – Name by which the CIM object will be identified in the object store. - cim_object (CIM object) – The CIM object to be added to the object store. The object is copied into the object store so the user can safely modify the original object without affecting the store.
Raises: ValueError
– If CIM object already exists in the object store.- name (string or
-
update
(name, cim_object)[source]¶ Replace the CIM object in the object store idenfified by the name argument with the CIM object defined by the cim_object argument.
Parameters: - name (string or
CIMInstanceName
) – Name by which the object is identified in the object store. - cim_object (CIM object) – The CIM object to replace the original CIM object in the data store. The object is copied into the object store so the user can safely modify the original object without affecting the store.
Raises: KeyError
– If no CIM object with name exists in the object store.- name (string or
-
delete
(name)[source]¶ Delete the CIM object identified by name from the object store.
Parameters: name (string or CIMInstanceName
) – Name by which the object to be deleted is identified in the object store.Raises: KeyError
– If there is no object with name in this object store
-
iter_names
()[source]¶ Return an iterator to the names of the CIM objects in the object store. Objects may be accessed using iterator methods.
The order of returned names is undetermined.
Returns: An iterator for the names of CIM objects in the object store. Return type: iterator
-
iter_values
(copy=True)[source]¶ Return an iterator to the CIM objects in the object store. This allows iteration through all the objects in this object store using iterator methods.
The order of returned CIM objects is undetermined.
Parameters: copy ( bool
) – Copy the objects before returning them. This is the default behavior and also the mode that should be used unless the user is certain the object will NOT be modified after it is returned.Returns: An iterator for the objects in the object store. If copy == True, each object is copied before it is returned. Return type: iterator
-
-
class
pywbem_mock.
BaseProvider
(cimrepository)[source]¶ BaseProvider is the top level class in the provider hiearchy and includes methods required by both builtin providers and user-defined providers. This class is not intended to be executed directly.
Parameters: cimrepository ( BaseRepository
or subclass) – Defines the repository to be used by providers. The repository is fully initialized but contains only objects defined by theFakedWbemConnection
methods that create objects in the repository (ex.compile_file()
)Methods
add_namespace
Add a CIM namespace to the CIM repository. class_exists
Test if class defined by classname parameter exists in CIM repository defined by namespace parameter. filter_properties
Remove properties from an instance or class that aren’t in the property_list parameter. find_interop_namespace
Find the Interop namespace name in the CIM repository, or return None. get_class
Get class from CIM repository. is_interop_namespace
Tests if a namespace name is a valid Interop namespace name. is_subclass
Return boolean indicating whether a class is a (direct or indirect) subclass of a superclass, or the same class, in the specified class store of the CIM repository (i.e. remove_namespace
Remove a CIM namespace from the CIM repository. validate_namespace
Validates that a namespace is defined in the CIM repository. Attributes
cimrepository
Instance of class that represents the CIM repository. interop_namespace_names
The valid Interop namespace names. namespaces
The names of the namespaces that exist in the CIM repository. Details
-
cimrepository
¶ Instance of class that represents the CIM repository.
The CIM repository is the data store for CIM classes, CIM instances, and CIM qualifier declarations. All access to the mocker CIM data must pass through this variable to the CIM repository. See
BaseRepository
for a description of the repository interface.The mocker may use subclasses of
BaseRepository
for specific functionality. Thus,InMemoryRepository
implements an InMemory CIM repository that must be initialized for eachFakedWbemConnection
construction.Type: BaseRepository
or subclass
-
namespaces
¶ The names of the namespaces that exist in the CIM repository.
Type: NocaseList of string
-
interop_namespace_names
¶ The valid Interop namespace names.
Only these names may be the Interop namespace and only one Interop namespace may exist in a WBEM server environment. This list is defined in
pywbem.WBEMServer.INTEROP_NAMESPACES
.Type: NocaseList of string
-
validate_namespace
(namespace)[source]¶ Validates that a namespace is defined in the CIM repository. Returns only if namespace is valid. Otherwise it generates an exception.
Parameters: namespace (string) – The name of the CIM namespace in the CIM repository (case insensitive). Must not be None. Any leading or trailing slash characters are ignored. Raises: CIMError
– (CIM_ERR_INVALID_NAMESPACE) Namespace does not exist.
-
add_namespace
(namespace)[source]¶ Add a CIM namespace to the CIM repository.
The namespace must not yet exist in the CIM repository and the repository can contain only one Interop namespace.
Parameters: namespace (string) – The name of the CIM namespace in the CIM repository. Must not be None. Any leading or trailing slash characters are removed before the string is used to define the namespace name.
Raises: ValueError
– Namespace argument must not be None.CIMError
– CIM_ERR_ALREADY_EXISTS if the namespace already exists in the CIM repository.CIMError
– CIM_ERR_ALREADY_EXISTS if the namespace is one of the possible Interop namespace names and an interop namespace already exists in the CIM repository.
-
remove_namespace
(namespace)[source]¶ Remove a CIM namespace from the CIM repository.
The namespace must exist in the CIM repository and must be empty.
Parameters: namespace (string) – The name of the CIM namespace in the CIM repository (case insensitive). Must not be None. Leading or trailing slash characters are ignored.
Raises: ValueError
– Namespace argument must not be None.CIMError
– CIM_ERR_NOT_FOUND if the namespace does not exist in the CIM repository.CIMError
– CIM_ERR_NAMESPACE_NOT_EMPTY if the namespace icontains objects.CIMError
– CIM_ERR_NAMESPACE_NOT_EMPTY if attempting to delete the default connection namespace. This namespace cannot be deleted from the CIM repository
-
is_interop_namespace
(namespace)[source]¶ Tests if a namespace name is a valid Interop namespace name.
This method does not access the CIM repository for this test; it merely compares the specified namespace name against the list of valid Interop namespace names returned by
interop_namespace_names
.Parameters: namespace (string) – The namespace name that is to be tested. Returns: Indicates whether the namespace name is a valid Interop namespace name. Return type: bool
-
find_interop_namespace
()[source]¶ Find the Interop namespace name in the CIM repository, or return None.
The Interop namespace is identified by comparing all namespace names in the CIM repository against the list of valid Interop namespace names returned by
interop_namespace_names
.Returns: The name of the Interop namespace if one exists in the CIM repository or None. Return type: string
-
get_class
(namespace, classname, local_only=None, include_qualifiers=None, include_classorigin=None, property_list=None)[source]¶ Get class from CIM repository. Gets the class defined by classname from the CIM repository, creates a copy, expands the copied class to include superclass properties if not localonly, and filters the class based on propertylist and includeClassOrigin.
This method executes all of the filter actions on the class that are defined for the GetClass operation and so returns a class that satisfies the behavior requirements of the GetClass client request operation defined in DSP0200 . (see:
pywbem.WBEMConnection.GetClass()
)It also sets the propagated attribute.
Parameters: - classname (string) – Name of class to retrieve
- namespace (string) – The name of the CIM namespace in the CIM repository (case insensitive). Must not be None. Leading or trailing slash characters are ignored.
- local_only (
bool
) – If True or None, only properties and methods in this specific class are returned. None means not supplied by client and the normal server default is True. If False, properties and methods from the superclasses are included. - include_qualifiers (
bool
) – If True or None, include qualifiers. None is the server default if the parameter is not provided by the client. If False, do not include qualifiers. - include_classorigin (
bool
) – If True, return the class_origin attributes of properties and methods. If False or None (use server default), class_origin attributes of properties and methods are not returned - property_list (list of string) – Properties to be included in returned class. If None, all properties are returned. If empty list, no properties are returned
Returns: Copy of the CIM class in the CIM repository if found. Includes superclass properties installed and filtered in accord with the local_only, etc. arguments.
Return type: Raises:
-
class_exists
(namespace, classname)[source]¶ Test if class defined by classname parameter exists in CIM repository defined by namespace parameter.
Returns: True if class exists and False if it does not exist. Return type: bool Raises: Exception if the namespace does not exist
-
static
filter_properties
(obj, property_list)[source]¶ Remove properties from an instance or class that aren’t in the property_list parameter.
Parameters: - obj (
CIMClass
orCIMInstance
) – The class or instance from which properties are to be filtered - property_list (list of string) – List of properties which are to be included in the result. If None, remove nothing. If empty list, remove everything. else remove properties that are not in property_list. Duplicated names are allowed in the list and ignored.
- obj (
-
is_subclass
(klass, superclass, class_store)[source]¶ Return boolean indicating whether a class is a (direct or indirect) subclass of a superclass, or the same class, in the specified class store of the CIM repository (i.e. in the namespace of that class store).
This test is done by starting at the class and walking its superclasses up to the root, so it is not as expensive as determining all subclasses of a given class.
Parameters: - klass (string) – Class name of the class.
- superclass (string) – Class name of the superclass.
- class_store (
BaseObjectStore
) – Class store of the CIM repository to search for the classes.
Returns: Boolean indicating whether the class is a (direct or indirect) subclass of the superclass, or the same class.
Return type: Raises: KeyError
– Class or superclass does not exist in the class store.
-
WBEM utility commands¶
The pywbem package provides a number of WBEM utility commands. They are all implemented as pure-Python scripts.
These commands are installed into the Python script directory and should therefore automatically be available in the command search path.
The following commands are provided:
-
A MOF compiler that takes MOF files as input and updates the CIM repository of a WBEM server with the result.
Versions of pywbem before 1.0.0 provided a command wbemcli
as an
interactive command line environment. It is recommended to use the
pywbemcli
command from the
pywbemtools package on Pypi
as a replacement.
mof_compiler¶
The mof_compiler
command compiles MOF files and updates the CIM repository
of a WBEM server with the result.
If the compiler fails, any changes made to the CIM repository in the WBEM server as part of the current compilation are rolled back. A limitation is that changes to qualifier declarations are not yet rolled back (see issue #990).
The compiler provides a dry-run mode that simulates the compilation but does not change the CIM repository in the WBEM server.
Here is the help text of the command:
usage: mof_compiler [options] moffile ...
Compile MOF files, and update a namespace in a WBEM server with the result.
Positional arguments:
moffile Path name of the MOF file to be compiled.
Can be specified multiple times.
Server related options:
Specify the WBEM server and namespace the MOF compiler works against, for
looking up existing elements, and for applying the MOF compilation results
to.
-s url, --server url Host name or URL of the WBEM server (required),
in this format:
[scheme://]host[:port]
- scheme: Defines the protocol to use:
- "https" for HTTPS protocol
- "http" for HTTP protocol
Default: "https".
- host: Defines host name as follows:
- short or fully qualified DNS hostname
- literal IPV4 address(dotted)
- literal IPV6 address (RFC 3986) with zone
identifier extensions(RFC 6874)
supporting "-" or %25 for the delimiter
- port: Defines the WBEM server port to be used.
Defaults:
- 5988, when using HTTP
- 5989, whenusing HTTPS
-n namespace, --namespace namespace
Namespace in the WBEM server.
Default: root/cimv2
Connection security related options:
Specify user name and password or certificates and keys
-u user, --user user User name for authenticating with the WBEM server.
Default: No user name.
-p password, --password password
Password for authenticating with the WBEM server.
Default: Will be prompted for, if user name
specified.
-nvc, --no-verify-cert
Client will not verify certificate returned by the
WBEM server (see cacerts). This bypasses the client-
side verification of the server identity, but allows
encrypted communication with a server for which the
client does not have certificates.
--cacerts cacerts CA certificates to be used for verifying the server
certificate presented by the WBEM server during TLS/SSL
handshake:
FILE: Use the certs in the specified cert file;
DIR: Use the certs in the specified cert directory.
Default: Use certs from the certifi Python package.
--certfile certfile Client certificate file for authenticating with the
WBEM server. If option specified the client attempts
to execute mutual authentication.
Default: Simple authentication.
--keyfile keyfile Client private key file for authenticating with the
WBEM server. Not required if private key is part of the
certfile option. Not allowed if no certfile option.
Default: No client key file. Client private key should
then be part of the certfile
Action related options:
Specify actions against the WBEM server's namespace. Default:
Create/update elements.
-r, --remove Removal mode: Remove elements (found in the MOF files)
from the WBEM server's namespace, instead of creating
or updating them
-d, --dry-run Dry-run mode: Don't actually modify the WBEM server's
namespace, just check MOF syntax. Connection to WBEM
server is still required to check qualifiers.
General options:
-I dir, --include dir
Path name of a MOF include directory. Can be specified
multiple times.
-v, --verbose Print more messages while processing
-V, --version Display pywbem version and exit.
-h, --help Show this help message and exit
--log log_spec[,logspec]
Log_spec defines characteristics of the various named
loggers. It is the form:
COMP=[DEST[:DETAIL]] where:
COMP: Logger component name:[api|http|all].
(Default=all)
DEST: Destination for component:[file|stderr].
(Default=file)
DETAIL: Detail Level to log: [all|paths|summary] or
an integer that defines the maximum length of
of each log record.
(Default=all)
Example: mof_compiler CIM_Schema_2.45.mof -s https://localhost -n root/cimv2
-u sheldon -p p42
Development¶
This section only needs to be read by developers of the pywbem package. People that want to make a fix or develop some extension, and people that want to test the project are also considered developers for the purpose of this section.
Setting up the development environment¶
You may use any supported OS platform as the development environment for pywbem. On native Windows, you need to use a Windows command prompt in administrator mode.
It is recommended that you set up a virtual Python environment. Have the virtual Python environment active for all remaining steps.
Make sure the following commands are available:
git
make
(GNU make)choco
on native Windows (Chocolatey package manager)
Clone the Git repo of this project and switch to its working directory:
$ git clone git@github.com:pywbem/pywbem.git $ cd pywbem
Install the prerequsites for pywbem development. This will install Python packages into the active Python environment, and OS-level packages:
$ make develop
On Python 3.4 on native Windows, this may fail during installation of the
lxml
Python package. If so, see Troubleshooting for details.This project uses Make to do things in the currently active Python environment. The command:
$ make
displays a list of valid Make targets and a short description of what each target does. See the next sections for details.
Building the documentation¶
The ReadTheDocs (RTD) site is used to publish the documentation for the pywbem package at https://pywbem.readthedocs.io/
This page is automatically updated whenever the Git repo for this package changes the branch from which this documentation is built.
In order to build the documentation locally from the Git work directory, execute:
$ make builddoc
The top-level document to open with a web browser will be
build_doc/html/docs/index.html
.
Testing¶
All of the following make commands run the tests in the currently active Python environment, and need to be invoked in the Git repo work directory.
By default, the tests use the pywbem and pywbem_mock modules from the respective directories in the Git repo work directory. Pywbem 0.14.5 introduced a way to test installed versions of the pywbem package. For details, see Testing installed versions of pywbem.
The tests directory has the following subdirectory structure:
tests
+-- unittest Unit tests
| +-- utils Utility functions used by unit tests
| +-- pywbem Unit tests for the pywbem package
| +-- pywbem_mock Unit tests for the pywbem_mock package
| +-- unittest_utils Unit tests for tests/unittest/utils
| +-- functiontest Unit tests for tests/functiontest
| +-- end2endtest_utils Unit tests for tests/end2endtest/utils
| +-- servers Unit tests for tests/servers
+-- functiontest Function tests
+-- end2endtest End2end tests
| +-- utils Utility functions used by end2end tests
+-- manualtest Manual tests
+-- server_definitions WBEM server definition file used by some tests and module
| for accessing it
+-- profiles Simple definitions of management profiles used by some tests
+-- schema The CIM schema MOF files used by some MOF tests
+-- dtd The CIM DTD file used by some CIM-XML validation tests
There are multiple types of tests in pywbem:
Unit tests and function tests
These tests do not require any WBEM server to be available, and the tests validate their results automatically.
The distinction between unit tests and function tests as used in pywbem is that function tests exercise the entire pywbem client component or entire pywbem scripts, while unit tests exercise single modules.
They are run by executing:
$ make test
Test execution can be modified by a number of environment variables, as documented in the make help (execute make help).
An alternative that does not depend on the makefile and thus can be executed from the source distribution archive, is:
$ ./setup.py test
Options for pytest can be passed using the
--pytest-options
option.End2end tests
These tests are run against one or more WBEM servers, and the tests validate their results automatically.
They are run by preparing a server definition file:
tests/server_definitions/server_definition_file.yml
from the provided example, and by executing:
$ make end2endtest
Again, test execution can be modified by a number of environment variables, as documented in the make help (execute make help).
An alternative that does not depend on the makefile, is:
$ ./setup.py end2endtest
Options for pytest can be passed using the
--pytest-options
option.Manual tests
There are several Python scripts and shell scripts that can be run manually. The results need to be validated manually.
These scripts are in the directory:
tests/manualtest/
and are executed by simply invoking them from within the main directory of the repository, e.g.:
tests/manualtest/run_cim_operations.py
Some of the scripts support a –help option that informs about their usage.
The run_cim_operations.py script needs a particular MOF file loaded in the repository of the WBEM server that is used for the test. This can be done using the MOF compiler of pywbem:
$ mof_compiler -s <target_url> tests/unittest/pywbem/test.mof
To run the unit and function tests in all supported Python environments, the Tox tool can be used. It creates the necessary virtual Python environments and executes make test (i.e. the unit and function tests) in each of them.
For running Tox, it does not matter which Python environment is currently active, as long as the Python tox package is installed in it:
$ tox # Run tests on all supported Python versions
$ tox -e py27 # Run tests on Python 2.7
Testing from the source archives on Pypi or GitHub¶
The wheel distribution archives on Pypi
(e.g. pywbem-1.0.0-py2.py3-none-any.whl
)
contain only the files needed to run pywbem, but not the files needed to test
it.
The source distribution archives on Pypi and GitHub
(e.g. pywbem-1.0.0.tar.gz
)
contain all files that are needed to run and to test pywbem.
This allows testing pywbem without having to check out the entire repository, and is convenient for testing e.g. when packaging pywbem into OS-level packages.
When installing these source distribution archives, the files needed for running pywbem are installed into the active Python environment, but not the test files.
The following commands download the source distribution archive on Pypi for a particular version of pywbem into the current directory and unpack it:
$ pip download --no-deps --no-binary :all: pywbem==1.0.0
$ tar -xf pywbem-1.0.0.tar.gz
$ cd pywbem-1.0.0
$ ls -1
-rw-r--r-- 1 maiera staff 468 Jun 29 22:31 INSTALL.md
-rw-r--r-- 1 maiera staff 26436 May 26 06:45 LICENSE.txt
-rw-r--r-- 1 maiera staff 367 Jul 3 07:54 MANIFEST.in
-rw-r--r-- 1 maiera staff 3451 Jul 3 07:55 PKG-INFO
-rw-r--r-- 1 maiera staff 7665 Jul 2 23:20 README.rst
-rw-r--r-- 1 maiera staff 1624 Jul 2 23:20 README_PYPI.rst
-rwxr-xr-x 1 maiera staff 2881 Jun 29 22:31 build_moftab.py
-rwxr-xr-x 1 maiera staff 13850 Jun 29 22:31 mof_compiler
-rw-r--r-- 1 maiera staff 105 May 26 06:45 mof_compiler.bat
drwxr-xr-x 29 maiera staff 928 Jul 3 07:55 pywbem
drwxr-xr-x 8 maiera staff 256 Jul 3 07:55 pywbem.egg-info
drwxr-xr-x 18 maiera staff 576 Jul 3 07:55 pywbem_mock
-rw-r--r-- 1 maiera staff 1067 Jun 29 22:31 requirements.txt
-rw-r--r-- 1 maiera staff 38 Jul 3 07:55 setup.cfg
-rwxr-xr-x 1 maiera staff 7555 Jul 3 07:24 setup.py
-rw-r--r-- 1 maiera staff 2337 Jul 2 23:20 test-requirements.txt
drwxr-xr-x 15 maiera staff 480 Jul 3 07:55 tests
Pywbem, its dependent packages, and packages needed for testing pywbem can be installed with the package extra named “test”:
$ pip install .[test]
When testing pywbem installations in Linux distributions that include pywbem as
an OS-level package, the corresponding OS-level packages would instead be
installed for these dependent Python packages. The test-requirements.txt
file shows which dependent Python packages are needed for testing pywbem.
Finally, the tests can be run using the setup.py
script:
$ ./setup.py test
$ ./setup.py leaktest
$ ./setup.py end2endtest
These commands are listed in the help of the setup.py
script:
$ ./setup.py --help-commands
. . .
Extra commands:
. . .
test pywbem: Run unit and function tests using pytest
leaktest pywbem: Run leak tests using pytest
end2endtest pywbem: Run end2end tests using pytest
. . .
The additional options supported by these commands are shown in their help:
$ ./setup.py test --help
. . .
Options for 'test' command:
--pytest-options additional options for pytest, as one argument
. . .
Note: The test
command of setup.py
is not the deprecated built-in
command (see https://github.com/pypa/setuptools/issues/1684), but has been
implemented in setup.py
in such a way that it only runs the tests but
does not install anything upfront. The leaktest
and
end2endtest
commands have been implemented in the same way. Therefore, this
approach can be used for testing pywbem installations from OS-level packages
in Linux distributions that include pywbem.
Testing installed versions of pywbem¶
By default, the tests use the pywbem and pywbem_mock modules from the respective directories in the Git repo work directory.
Pywbem 0.14.5 introduced a way to test installed versions of the pywbem package. This is useful for example for testing a version of pywbem that has been packaged as an OS-level package. Typically, such a version would be installed into the system Python.
Some words of caution:
- Testing an installed version of pywbem with test cases from a pywbem repo
of a different version can result in failing test cases for several reasons:
- If a new version of pywbem has added functionality, its test cases are also extended accordingly. Running such newer test cases against an older installed version of pywbem may fail simply because the installed version does not yet have the added functionality.
- Fixes in pywbem or in the test cases may change behavior in a subtle way that causes test cases to fail.
- Unit test cases are particularly vulnerable to version mismatches because they test at the module level, including module interfaces that are internal to pywbem and thus can legally change incompatibly between versions.
- If the version of the installed pywbem is before 0.14.5, some test cases that compile MOF will be skipped to avoid permission denied errors when ply attempts to re-generate its parsing table files in the pywbem installation directory in case of ply version mismatches. Starting with pywbem 0.14.5, it has tolerance against ply version mismatches.
In order to not clutter up the system Python with Python packages needed for running the pywbem tests, the following steps use a virtual Python environment that uses the packages of the system Python. That way, the installed version of pywbem becomes available to the virtual Python environment from the system Python, while any additional packages that are needed but not yet available that way, will be installed into the virtual Python environment.
Follow these steps to run pywbem tests against a version of pywbem that is installed into the system Python:
Verify that the following commands are available when the system Python is active:
$ virtualenv --version # Python virtualenv package $ pip --version
Create and activate a virtual Python environment of the intended Python version, that is based on the system Python:
$ virtualenv --system-site-packages --no-setuptools --no-pip --no-wheel .virtualenv/test $ source .virtualenv/test/bin/activate
The pywbem project is set up so that Git ignores the
.virtualenv
directory, so use that directory name for ease of Git handling.Verify that in that virtual Python environment, pywbem comes from the intended installation:
$ pip show pywbem
Ensure a fresh start of the make process. This should be done whenever switching between the installed version of pywbem and the local directories:
$ make clobber
Run the pywbem tests with environment variable
TEST_INSTALLED
being set:$ TEST_INSTALLED=1 make test
This will assume that the pywbem package and any prerequisite Python packages and OS-level packages are already installed.
This will also move the current directory (i.e. the repo working directory) to the end of the module search path, so that the installed version of pywbem is used when importing it into the test scripts.
Setting
TEST_INSTALLED=DEBUG
causes some debug messages to be printed that allow verifying from where the pywbem and pywbem_mock modules are loaded.This also works for the pywbem end2end tests:
$ TEST_INSTALLED=1 make end2end
Note that tox does not support creating its virtual Python environments based on the system Python, so at this point, tox cannot be used for this approach.
Updating the DMTF MOF Test Schema¶
Pywbem uses DMTF CIM Schemas in its CI testing. The schema used is stored in
the form received from the DMTF in the directory tests/schema
and is
expanded and compiled as part of the unit tests.
Since the DMTF regularly updates the schema, the pywbem project tries to stay up-to-date with the current schema. At the same time, earlier schemas can be used for testing also by changing the definitions for the dmtf schema to be tested.
The schema used for testing can be modified by modifying the test file:
tests/unittest/utils/dmtf_mof_schema_def.py
Developing PyWBEM Ipython Documentation Notebooks¶
The pywbem developers are using ipython notebooks to demonstrate the use of pywbem. Today we generally have one notebook per operation or group of operations including definition of the operation, references back to the pywbem documentation, and one or more examples (hopefully examples that will actually execute against a wbem server)
These can easily be extended or supplemented using a local ipython or jupyter server by:
1. Install ipython or Jupyter software using pip or pip3. The notebook server may be installed as root or within a python virtual environment. For example:
$ sudo pip install ipython
or
$ sudo pip3 install ipython
or
$ sudo pip install jupyter
The notebook server may be installed as root or within a python virtual environment.
2. Start the local ipython/jupyter notebook server in the notebook directory (pywbem/docs/notebooks) referencing that directory in the command line call:
$ ipython notebook docs/notebooks
or
$ jupyter notebook docs/notebooks
This will start the local ipython/juypter notebook server and on the first page displayed in your web browser all existing pywbem ipython notebooks will be available for editing. New ones can be created using the commands on that ipython server web page.
New and changed notebooks must go through the same contribution process as other components of pywbem to be integrated into the github repository.
Contributing¶
Third party contributions to this project are welcome!
In order to contribute, create a Git pull request, considering this:
- Test is required.
- Each commit should only contain one “logical” change.
- A “logical” change should be put into one commit, and not split over multiple commits.
- Large new features should be split into stages.
- The commit message should not only summarize what you have done, but explain why the change is useful.
- The commit message must follow the format explained below.
What comprises a “logical” change is subject to sound judgement. Sometimes, it makes sense to produce a set of commits for a feature (even if not large). For example, a first commit may introduce a (presumably) compatible API change without exploitation of that feature. With only this commit applied, it should be demonstrable that everything is still working as before. The next commit may be the exploitation of the feature in other components.
For further discussion of good and bad practices regarding commits, see:
Core Development Team¶
Anyone can contribute to pywbem via pull requests as described in the previous section.
The pywbem project has a core development team that holds regular web conferences and that is using Slack for offline communication, on the Slack workspace: https://pywbem.slack.com.
The web conference and the Slack workspace are by invitation, and if you want to participate in the core team, please open an issue to let us know.
Appendix¶
This section contains information that is referenced from other sections, and that does not really need to be read in sequence.
Special type names¶
This documentation uses a few special terms to refer to Python types:
- string
- a unicode string or a byte string
- unicode string
- a Unicode string type (
unicode
in Python 2, andstr
in Python 3) - byte string
- a byte string type (
str
in Python 2, andbytes
in Python 3). Unless otherwise indicated, byte strings in pywbem are always UTF-8 encoded. - connection id
- a string (string) that uniquely identifies each
pywbem.WBEMConnection
object created. The connection id is immutable and is accessible frompywbem.WBEMConnection.conn_id
. It is included in of each log record created for pywbem log output and may be used to correlate pywbem log records for a single connection. - number
- one of the number types
int
,long
(Python 2 only), orfloat
. - integer
- one of the integer types
int
orlong
(Python 2 only). - callable
- a callable object; for example a function, a class (calling it returns a
new object of the class), or an object with a
__call__()
method. - hashable
- a hashable object. Hashability requires an object not only to be able to
produce a hash value with the
hash()
function, but in addition that objects that are equal (as per the==
operator) produce equal hash values, and that the produced hash value remains unchanged across the lifetime of the object. See term “hashable” in the Python glossary, although the definition there is not very crisp. A more exhaustive discussion of these requirements is in “What happens when you mess with hashing in Python” by Aaron Meurer. - unchanged-hashable
- an object that is hashable with the exception that its hash value may change over the lifetime of the object. Therefore, it is hashable only for periods in which its hash value remains unchanged. CIM objects are examples of unchanged-hashable objects in pywbem.
- DeprecationWarning
- a standard Python warning that indicates a deprecated functionality.
See section Deprecation and compatibility policy and the standard
Python module
warnings
for details. - Element
- class
xml.dom.minidom.Element
. Its methods are described in section Element Objects of modulexml.dom
, with minidom specifics described in section DOM Objects of modulexml.dom.minidom
. - CIM data type
- one of the types listed in CIM data types.
- CIM object
- one of the types listed in CIM objects.
- CIM namespace
- an object that is accessible through a WBEM server and is a naming space for CIM classes, CIM instances and CIM qualifier declarations. The namespace is a component of other elements like namespace path used to access objects in the WBEM server.
- NocaseList
- A case-insensitive list class provided by the nocaselist package.
- interop namespace
- A CIM namespace is the interop namespace if it has one of the following names: DMTF definition; (‘interop’, ‘root/interop’) pywbem implementation; (‘interop’, ‘root/interop’, ‘root/PG_Interop’), Only one interop namespace is allowed in a WBEM Server. The interop namespace contains CIM classes that the client needs to discover characteristics of the WBEM server (namespaces, coniguration of server components like indications) and the registered profiles implemented by that server.
- keybindings input object
a Python object used as input for initializing an ordered list of keybindings in a parent object (i.e. a
CIMInstanceName
object).None will result in an an empty list of keybindings.
Otherwise, the type of the input object must be one of:
- iterable of
CIMProperty
- iterable of tuple(key, value)
OrderedDict
with key and valuedict
with key and value (will not preserve order)
with the following definitions for key and value:
key (string): Keybinding name.
Must not be None.
The lexical case of the string is preserved. Object comparison and hash value calculation are performed case-insensitively.
value (CIM data type or number or
CIMProperty
): Keybinding value.If specified as CIM data type or number, the provided object will be stored unchanged as the keybinding value.
If specified as a
CIMProperty
object, its name attribute must match the key (case insensitively), and a copy of its value (a CIM data type) will be stored as the keybinding value.None for the keybinding value will be stored unchanged.
If the WBEM server requires the TYPE attribute on KEYVALUE elements to be set in operation requests, this can be achieved by specifying the keybinding value as CIM data type (either directly, or via a
CIMProperty
object).
The order of keybindings in the parent object is preserved if the input object is an iterable or a
OrderedDict
object, but not when it is adict
object.The resulting set of keybindings in the parent object is independent of the input object (except for unmutable objects), so that subsequent modifications of the input object by the caller do not affect the parent object.
- iterable of
- methods input object
a Python object used as input for initializing an ordered list of methods represented as
CIMMethod
objects in a parent object that is aCIMClass
.None will result in an an empty list of methods.
Otherwise, the type of the input object must be one of:
- iterable of
CIMMethod
- iterable of tuple(key, value)
OrderedDict
with key and valuedict
with key and value (will not preserve order)
with the following definitions for key and value:
key (string): Method name.
Must not be None.
The lexical case of the string is preserved. Object comparison and hash value calculation are performed case-insensitively.
value (
CIMMethod
): Method declaration.Must not be None.
The name attribute of the
CIMMethod
object must match the key (case insensitively).The provided object is stored in the parent object without making a copy of it.
The order of methods in the parent object is preserved if the input object is an iterable or a
OrderedDict
object, but not when it is adict
object.The resulting set of methods in the parent object is independent of the input collection object, but consists of the same
CIMMethod
objects that were provided in the input collection. Therefore, a caller must be careful to not accidentally modify the providedCIMMethod
objects.- iterable of
- parameters input object
a Python object used as input for initializing an ordered list of parameters represented as
CIMParameter
objects in a parent object that is aCIMMethod
.None will result in an an empty list of parameters.
Otherwise, the type of the input object must be one of:
- iterable of
CIMParameter
- iterable of tuple(key, value)
OrderedDict
with key and valuedict
with key and value (will not preserve order)
with the following definitions for key and value:
key (string): Parameter name.
Must not be None.
The lexical case of the string is preserved. Object comparison and hash value calculation are performed case-insensitively.
value (
CIMParameter
): Parameter (declaration).Must not be None.
The name attribute of the
CIMParameter
object must match the key (case insensitively).The provided object is stored in the parent object without making a copy of it.
The order of parameters in the parent object is preserved if the input object is an iterable or a
OrderedDict
object, but not when it is adict
object.The resulting set of parameters in the parent object is independent of the input collection object, but consists of the same
CIMParameter
objects that were provided in the input collection. Therefore, a caller must be careful to not accidentally modify the providedCIMParameter
objects.- iterable of
- properties input object
a Python object used as input for initializing an ordered list of properties represented as
CIMProperty
objects, in a parent object.The
CIMProperty
objects represent property values when the parent object is aCIMInstance
, and property declarations when the parent object is aCIMClass
.None will result in an an empty list of properties.
Otherwise, the type of the input object must be one of:
- iterable of
CIMProperty
- iterable of tuple(key, value)
OrderedDict
with key and valuedict
with key and value (will not preserve order)
with the following definitions for key and value:
key (string): Property name.
Must not be None.
The lexical case of the string is preserved. Object comparison and hash value calculation are performed case-insensitively.
value (CIM data type or
CIMProperty
): Property (value or declaration).Must not be None.
CIMProperty
objects can be used as input for both property values and property declarations. CIM data type objects can only be used for property values.If specified as a CIM data type, a new
CIMProperty
object will be created from the provided value, inferring its CIM data type from the provided value.If specified as a
CIMProperty
object, its name attribute must match the key (case insensitively), and the provided object is stored in the parent object without making a copy of it.
The order of properties in the parent object is preserved if the input object is an iterable or a
OrderedDict
object, but not when it is adict
object.The resulting set of properties in the parent object is independent of the input collection object, but consists of the same
CIMProperty
objects that were provided in the input collection. Therefore, a caller must be careful to not accidentally modify the providedCIMProperty
objects.- iterable of
- provider
An element of a WBEM server that responds to requests for selected classes. A WBEM server normally contains a main provider that may interface with a CIM respository and provides responses to client requests for which no specific provider is defined and providers which providers that allow specialized responses for selected classes and request types (communicate with managed components) or manipulate the objects being managed.
NOTE: In the SNIA terminology, a provider may also be a complete WBEM server implementation.
- user-defined provider
- A :term:provider that can be defined independently of the WBEM server and attached dynamically to the WBEM server. In pywbem, user-defined providers can be defined as subclasses of specific default provider types and attached to the server by registering them with the connection.
- qualifiers input object
a Python object used as input for initializing an ordered list of qualifiers represented as
CIMQualifier
objects in a parent object (e.g. in aCIMClass
object).None will result in an an empty list of qualifiers.
Otherwise, the type of the input object must be one of:
- iterable of
CIMQualifier
- iterable of tuple(key, value)
OrderedDict
with key and valuedict
with key and value (will not preserve order)
with the following definitions for key and value:
key (string): Qualifier name.
Must not be None.
The lexical case of the string is preserved. Object comparison and hash value calculation are performed case-insensitively.
value (CIM data type or
CIMQualifier
): Qualifier (value).Must not be None.
If specified as a CIM data type, a new
CIMQualifier
object will be created from the provided value, inferring its CIM data type from the provided value.If specified as a
CIMQualifier
object, its name attribute must match the key (case insensitively), and the provided object is stored in the parent object without making a copy of it.
The order of qualifiers in the parent object is preserved if the input object is an iterable or a
OrderedDict
object, but not when it is adict
object.The resulting set of qualifiers in the parent object is independent of the input collection object, but consists of the same
CIMQualifier
objects that were provided in the input collection. Therefore, a caller must be careful to not accidentally modify the providedCIMQualifier
objects.- iterable of
Profile advertisement methodologies¶
This section briefly explains the profile advertisement methodologies defined by DMTF. A full description can be found in DSP1033.
These methodologies describe how a client can discover the central instances of a management profile. Discovering the central instances through a management profile is the recommended approach for clients, over simply enumerating a CIM class of choice. The reason is that this approach enables clients to work seamlessly with different server implementations, even when they have implemented a different set of management profiles.
DMTF defines three profile advertisement methodologies in DSP1033:
- GetCentralInstances methodology (new in DSP1033 1.1)
- Central class methodology
- Scoping class methodology
At this point, the GetCentralInstances methodology has not widely been implemented, but pywbem supports it nevertheless.
All three profile advertisement methodologies start from the CIM_RegisteredProfile instance that identifies the management profile, by means of registered organisation, registered name, and registered version.
It is important to understand that the CIM_RegisteredProfile instance not only identifies the management profile, but represents a particular use of the management profile within its scoping profiles. For an autonomous profile, there are no scoping profiles, so in that case, there is only one use of the autonomous profile in a server. However, component profiles do have scoping profiles, and it is well possible that a component profile is used multiple times in a server, in different scoping contexts. If that is the case, and if discovery of central instances using any of the profile advertisement methodologies is supposed to work, then each such use of the profile needs to have its own separate CIM_RegisteredProfile instance, because each such use of the profile will also have its own separate set of central instances.
Unfortunately, neither the DMTF standards nor the SMI-S standards are clear about that requirement, and so there are plenty of implementations that share a single CIM_RegisteredProfile instance identifying a particular component profile, for multiple distinct uses of the profile by its scoping profiles. In such a case, the profile advertisement methodologies will not be able to distinguish the distinct sets of central instances alone, and other means need to be used to distinguish them.
It is also important to understand that the choice which profile advertisement methodology to implement, is done by the WBEM server side. Therefore, a WBEM client such as pywbem needs to support all methodologies and needs to try them one by one until one succeeds. Pywbem tries the three methodologies in the order listed above.
In the GetCentralInstances methodology, the CIM_RegisteredProfile instance has a CIM method named GetCentralInstances that returns the instance paths of the central instances of the use of the profile.
In the central class methodology, the CIM_RegisteredProfile instance is associated directly with the set of central instances of the use of the profile, via a CIM_ElementConformsToProfile association.
In the scoping class methodology, the CIM_RegisteredProfile instance is not associated directly with the set of central instances of the use of the profile, but delegates that to its scoping profile. The client navigates up to the CIM_RegisteredProfile instance representing the (use of the) scoping profile, looks up its central instances, and from each of those, navigates down along the reversed scoping path to the central instances of the profile in question. The scoping path of a component profile describes the traversal across associations and ordinary classes from the central class to the scoping class of the profile. This profile advertisement methodology is obviously the most complex one of the three.
Pywbem encapsulates the complexity and choice of these methodologies into
a single invocation of an easy-to use method
get_central_instances()
.
Profile implementations in a WBEM server are not entirely free when making a choice of which methodology to implement:
Autonomous profiles in a WBEM server must implement the central class methodology, and may in addition implement the new GetCentralInstances methodology.
Note that the scoping class methodology falls together with the central class methodology for autonomous profiles, because their scoping class is also their central class.
Component profiles in a WBEM server may implement the central class methodology and the new GetCentralInstances methodology, and must support the scoping class methodology.
Note that implementing the scoping class methodology in a WBEM server requires implementing the classes and associations of the scoping path, which are usually mandatory anyway. So while the scoping class methodology is more complex to use for clients than the central class methodology, it is easier to implement for servers.
Use of the scoping class methodology by a client requires knowing the central class, scoping class and scoping path defined by the component profile.
DSP1001 requires that conformant autonomous profiles specify a central class, and that conformant component profiles specify a central class, scoping class and a scoping path.
Older DMTF component profiles and older SNIA subprofiles do not always specify scoping class and scoping path. In such cases, the scoping class and scoping path can often be determined from the class diagram in the specification for the profile. Many times, CIM_System or CIM_ComputerSystem is the scoping class.
Troubleshooting¶
Here are some trouble shooting hints for the installation of pywbem.
Installation fails with “invalid command ‘bdist_wheel’”¶
The installation of some Python packages requires the Python “wheel” package. If that package is not installed in the current Python environment, the installation will fail with the following (or similar) symptom:
python setup.py bdist_wheel
usage: setup.py [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...]
or: setup.py --help [cmd1 cmd2 ...]
or: setup.py --help-commands
or: setup.py cmd --help
error: invalid command 'bdist_wheel'
To fix this, install the Python “wheel” package:
pip install wheel
Installation of lxml misses include files on Python 3.4 on native Windows¶
On Python 3.4 on native Windows, the installation of the lxml
Python
package may fail during installation of the development prerequisites
(i.e. during make develop
), reporting missing include files such as
libxml/xmlversion.h
.
It has not been investigated what causes this on Python 3.4 (it works on other Python versions). If this issue shows up, try installing the Binary lxml package for Windows manually, with the lxml version >=4.2.4 and <4.4.0.
ConnectionError raised with [SSL: UNSUPPORTED_PROTOCOL]¶
On newer versions of the operating system running the pywbem client, communication with the WBEM server may fail with:
pywbem.exceptions.ConnectionError: SSL error <class 'ssl.SSLError'>:
[SSL: UNSUPPORTED_PROTOCOL] unsupported protocol (_ssl.c:1056)
For example, this happened after an upgrade of the client OS to Debian buster using Python 3.7, with OpenSSL 1.1.1d.
This is an error that is created by the OpenSSL library and handed back up to the SSL module of Python which hands it up to pywbem. The error indicates that OpenSSL and the WBEM server do not agree about which SSL/TLS protocol level to use.
Pywbem specifies SSL parameters such that the highest SSL/TLS protocol version is used that both the client and server support. Thus, pywbem does not put any additional restrictions on top of OpenSSL.
Debian buster includes OpenSSL 1.1.1d and increased its security settings to require at least TLS 1.2 (see https://stackoverflow.com/a/53065682/1424462).
This error means most likely that the WBEM server side does not yet support TLS 1.2 or higher.
This can be fixed for example by adding TLS 1.2 support to the server side
(preferred) or by lowering the minimum TLS level OpenSSL requires on the client
side (which lowers security). The latter can be done by changing the
MinProtocol
parameter in the OpenSSL config file on the client OS
(typically /etc/ssl/openssl.cnf
on Linux and OS-X,
and C:\OpenSSL-Win64\openssl.cnf
on Windows).
At the end of the file there is:
[system_default_sect]
MinProtocol = TLSv1.2
CipherString = DEFAULT@SECLEVEL=2
ConnectionError raised with [SSL] EC lib¶
Using pywbem on Python 3.5 with OpenSSL 1.0.1e-fips against an IBM DS8000 raised the following exception:
pywbem.exceptions.ConnectionError: SSL error <class 'ssl.SSLError'>:
[SSL] EC lib (_ssl.c:728)
This is an error that is created by the OpenSSL library and handed back up to the SSL module of Python which hands it up to pywbem. The error indicates that OpenSSL on the client side cannot deal with the cipher used by the server side. This was fixed by upgrading OpenSSL on the client OS to version 1.1.1.
Glossary¶
- dynamic indication filter
- dynamic filter
- An indication filter in a WBEM server whose life cycle is managed by a client. See DSP1054 for an authoritative definition and for details.
- static indication filter
- static filter
- An indication filter in a WBEM server that pre-exists and whose life cycle cannot be managed by a client. See DSP1054 for an authoritative definition and for details.
References¶
- DSP0004
- DMTF DSP0004, CIM Infrastructure, Version 2.8
- DSP0200
- DMTF DSP0200, CIM Operations over HTTP, Version 1.4
- DSP0201
- DMTF DSP0201, Representation of CIM in XML, Version 2.4
- DSP0207
- DMTF DSP0207, WBEM URI Mapping, Version 1.0
- DSP0212
- DMTF DSP0212, Filter Query Language, Version 1.0.1
- DSP1001
- DMTF DSP1001, Management Profile Specification Usage Guide, Version 1.1
- DSP1033
- DMTF DSP1033, Profile Registration Profile, Version 1.1
- DSP1054
- DMTF DSP1054, Indications Profile, Version 1.2
- DSP1092
- DMTF DSP1092, WBEM Server Profile, Version 1.0
- X.509
- ITU-T X.509, Information technology - Open Systems Interconnection - The Directory: Public-key and attribute certificate frameworks
- RFC2616
- IETF RFC2616, Hypertext Transfer Protocol – HTTP/1.1, June 1999
- RFC2617
- IETF RFC2617, HTTP Authentication: Basic and Digest Access Authentication, June 1999
- RFC3986
- IETF RFC3986, Uniform Resource Identifier (URI): Generic Syntax, January 2005
- RFC6874
- IETF RFC6874, Representing IPv6 Zone Identifiers in Address Literals and Uniform Resource Identifiers, February 2013
- WBEM Standards
- DMTF WBEM Standards
- Python Glossary
Change log¶
This version of the documentation is development version 1.1.4.dev1 and contains the master branch up to this commit:
Mitigated the coveralls HTTP status 422 by Andreas Maier at 2021-01-14 07:22:44
Details: * coveralls-python 3.0.0 has an issue whereby the coveralls.io site responds with HTTP status 422. Mitigated this by pinning coveralls-python to <3.0.0. See also https://github.com/TheKevJames/coveralls-python/issues/252. Signed-off-by: Andreas Maier <andreas.r.maier@gmx.de>
Version 1.1.4.dev1¶
Released: not yet
Incompatible changes:
Deprecations:
Bug fixes:
Enhancements:
Cleanup:
Known issues:
- See list of open issues.
pywbem 1.1.3¶
Released: 2021-01-01
Bug fixes:
- MOF compiler: Fixed bug where MOF compiler did not correctly install a CIM schema in a non-default namespace because it tried to get the qualifiers from the default namespace. (see issue #2502)
- Test: Changed dependency to ‘typed-ast’ to match the needs of ‘astroid’ and to install it only on CPython. This allows re-enabling PyPy3 on Travis.
- Test: Pinned psutil to <=5.6.3 on PyPy2+3 to avoid an installation error.
- Test: Increased the minimum version of ‘pyzmq’ on Python 3.9 to 19.0.0 to avoid an installation error.
- Test: Circumvented unicode issue with lxml.etree.fromstring()/XML() on Python 3.9 by passing in binary strings.
- Test: Adjusted _format()/_ascii2() testcases to PyPy3 behavior with binary vs unicode results.
- Test: Disabled leaktest in travis also on PyPy3 (in addition to PyPy2).
- Fixed a DeprecationWarning issued by urllib3 about using the whitelist_methods parameter of Retry.
- Fixed issue on GitHub Actions with macos by no longer running “brew update” in pywbem_os_setup.sh. (issue #2544)
- Docs: Fixed incorrect attribute name ‘provider_classnames’ in method provider example. (issue #2564)
- Mitigated the coveralls HTTP status 422 by pinning coveralls-python to <3.0.0.
Enhancements:
- Migrated from Travis and Appveyor to GitHub Actions. This required several changes in package dependencies for development.
pywbem 1.1.2¶
Released: 2020-10-31
Enhancements:
- Improved exception handling during the parsing of CIM-XML responses received from a WBEM server. Exceptions that were raised as TypeError or ValueError during the creation of CIM objects that are part of the operation result, are now raised as pywbem.CIMXMLParseError. Note that this is not an incompatible change because users were already potentially getting pywbem.CIMXMLParseError exceptions in other cases. (see issue #2512)
- Test: Added CIM-XML testcases in the area of instance paths. (see issue #2514)
- Docs: Clarified that pywbem.type_from_name() returns CIMInstanceName for type name “reference”, even though for use in CIM method parameters, CIMClassName is also valid.
- Issued a new pywbem.MissingKeybindingsWarning warning if a CIMInstanceName object that does not have any keybindings gets converted to CIM-XML by calling its tocimxml() method, or gets converted to a WBEM URI by calling its to_wbem_uri() method, or gets parsed from CIM-XML via an INSTANCENAME element without keybindings. This is motivated by the fact that DSP0004 does not allow instance paths without keys (section 8.2.5). (See issue #2514)
pywbem 1.1.1¶
Released: 2020-10-12
Bug fixes:
- MOF compiler: Fixed bug where MOF compiler did not correctly install a CIM schema in a non-default namespace because it tried to get the qualifiers from the default namespace. (see issue #2502)
pywbem 1.1.0¶
This version contains all fixes up to pywbem 1.0.3.
Released: 2020-10-05
Deprecations:
Deprecated the propagation of key property value changes to corresponding path keybindings in CIMInstance objects. A DeprecationWarning is now issued in that case. A future release of pywbem will remove the propagation. If you change key property values of a CIMInstance object that has a path set and depend on the corresponding keybinding values in the path to also change, then you should now change these keybindings values in your code instead of relying on the automatic propagation.
Reasons for this deprecation are:
- There are valid scenarios to have the keybindings different from the key properties, for example when passing an instance to the ModifyInstance operation that attempts to modify the key property values of an instance.
- A propagation in the opposite direction was missing, so the approach did not ensure consistency of the CIMInstance object anyway.
- Propagating the update of a key property value to the path is a hidden side effect and complicates an otherwise simple operation.
Bug fixes:
- Fixed erronously raised HeaderParseError when WBEM server returns Content-type: text/xml. This content-type is valid according to DSP0200. Added testcases. (See issue #2420)
- Fixed handling of ReturnQueryResultClass=True in WBEMConnection.OpenQueryInstances(). (See issue #2412)
- Mock: In the mock support, fixed multiple errors in the mocked OpenQueryInstances(), and added testcases for it. (See issue #2412)
- Test: Fixed dependency issues with ‘pyrsistent’ package on Python 2.7 and Python 3.4.
- Increased minimum versions of nocasedict to 1.0.0 and nocaselist to 1.0.2 to pick up fixes needed for pywbem.
- Windows install: Upgraded WinOpenSSL to 1.1.1h.
- Upgraded the minimum versions of nocasedict to 1.0.3 and of nocaselist to 1.0.1, to pick up fixes in these packages.
- Test: Fixed ResourceWarning that was issued due to not closing a MOF compiler log file used during tests. (see issue #2487)
Enhancements:
- Mock: Added load() methods to the ProviderRegistry and InMemoryRepository classes, in support of caching mock environments. They replace the data of the target object with the data from a second object. That is needed for restoring these objects from a serialization, because multiple other objects have references to these objects which requires that the object state can be set without having to create a new object.
- Mock: Added an iteritems() method to the ProviderRegistry class that iterates through the flattened list of providers, represented as tuples.
- Mock: Added support for more ways the output parameters can be returned in method providers: The container for the output parameters can now also be a Mapping (including pywbem’s internal NocaseDict or nocasedict.NocaseDict), in addition to just the built-in dict. The values in such a Mapping container can now also be CIMParameter objects, in addition to just the CIM data values. This provides consistency with the way the input parameters of the method provider are represented. (See issue #2415)
- Added time statistics support to pywbem_mock, that allows measuring which parts of the setup and execution of a mock environment takes how much time. (Part of issue #2365)
- Added a new method
is_subclass()
toWBEMConnection
that checks whether a class is a subclass of a class. Both classes can be specified as classnames or asCIMClass
objects. - Added support for translating the values of
PUnit
andUnits
qualifiers into human readable SI conformant unit strings, via new functionspywbem.siunit_obj()
andpywbem.siunit()
. These new functions are marked as experimental. (See issue #2423) - Mock: Added a new property
provider_dependent_registry
toFakedWBEMConnection
which is a registry of provider dependent files. This registry can be used by callers to register and look up the path names of additional files in context of a mock script. This ability is used by the pywbemtools project to validate whether its mock cache is up to date w.r.t. these files. - Test: The testcases using the
simplified_test_function
decorator now verify that no warnings are issued. Previously, not expecting warnings in a testcase caused warnings that occurred to be tolerated. Adjusted some code in pywbem and in testcases to accomodate that. Fixed the ResourceWarning in validate.py. - Test: When testing with latest package levels, the package versions of indirect dependencies are now also upgraded to the latest compatible version from Pypi. (see issue #2485)
Cleanup:
- Mock: Cleaned up the output of repr(BaseProvider) to no longer show the CIM repository, and to include the other attributes that were not shown so far. (See issue #2432)
- Complete pywbem_mock tests that were documented as missing in issue. (see issue # 2327)
- Removed dependency on package custom-inherit and removed package from pywbem. (see issue # 2436)
- Test: Changed collection of .yaml files in function tests to address DeprecationWarning issued by pytest (see issue #2430).
- Fix issue where pywbem_mock would accept a CreateClass where the qualifier scopes did not match the corresponding QualifierDeclarations (See issue #2451)
- Fixed issue where pywbem_mock CreateClass was not testing for class dependencies (reference classes and EmbeddedObject classes). (see issue #2455)
- Fixed issue where compiler would fail of a EmbeddedObject qualifier defined Null (None) as the embedded object class.
- Fixed issue where mof compiler asserts if the creation of new class fails because of reference or embedded object depency failures. Changed to a MOFDependencyError exception (see issue # 2458)
- Added test with mocker to demonstrate that a ModifiedInstance with key property modified results in PARAMETER_ERROR. (see issue #2449)
- Complete test of embedded instances. (see issue #464)
pywbem 1.0.0¶
Released: 2020-08-08
Enhancements:
- Improved logging in WBEM listener and its test module.
pywbem 1.0.0b4¶
Released: 2020-08-02
Incompatible changes:
Removed the following classes that were providing support for UNIX Domain Socket based connections:
- PegasusUDSConnection
- SFCBUDSConnection
- OpenWBEMUDSConnection
They are no longer supported since moving to the ‘requests’ package.
Updated the change history of 1.0.0b1 to mention one more incompatible change where support was removed for specifying multiple directory paths or file paths from the ca_certs parameter of WBEMConnection. Now, only a single directory path or file path can be specified, or None.
The use of NocaseDict from the nocasedict package caused the CIM objects that have a dictionary interface (i.e. CIMInstance and CIMInstanceName), and all CIM object attributes that are dictionaries (e.g. CIMInstance.properties) to now behave consistent with the built-in dict class. This causes the following incompatibilities:
- The update() method now supports only a single (optional) positional argument. Previously, multiple positional arguments were supported.
- The iterkeys(), itervalues(), and iteritems() methods are no longer available on Python 3. Use the keys(), values(), or items() methods instead.
- The keys(), values(), and items() methods now return a dictionary view instead of a list. That no longer allows modifying the dictionary while iterating over it. Create a list from the result of these methods and iterate over the list, if you have to delete dictionary items while iterating.
- CIM object attributes that are dictionaries can no longer be set to None (which previously caused the dictionary to be empty). Set such attributes to an empty iterable instead, to get an empty dictionary.
- Changed the exception that is raised when CIM object attributes are set with an unnamed key (None) from TypeError to ValueError.
The dictionary view objects that are now returned on Python 3 by CIMInstance.values() and CIMInstance.items() can no longer be used to iterate over when the underlying properties dictionary is modified in the loop. The returned dictionary view raises RuntimeError if the dictionary is modified while iterating, so that case is properly detected. Put list() around the calls to these methods if you need to modify the underlying properties dictionary in the loop. (See issue #2391)
Deprecations:
- Deprecated the iterkeys(), itervalues() and iteritems() methods of CIMInstance and CIMInstanceName on Python 3, to be more consistent with the built-in dict class that does not support these methods on Python 3. Use the keys(), values() or items() methods instead. (See issue #2372)
Bug fixes:
- Test: Fixed issue with Swig when installing M2Crypto on native Windows in the Appveyor CI, reporting mssing files swig.swg and python.swg. This was fixed by pinning the swig version to 4.0.1 in pywbem_os_setup.bat. This fix only applies to pywbem versions before 1.0.0, but is needed in 1.0.0 as well, because e.g. pywbemtools pulls the fixed pywbem_os_setup.bat file from the master branch of pywbem (one of the recommended approaches, and the only one with a stable URL) (See issue #2359).
- Docs: Fixed the description of return values of the keys(), values() and items() methods of CIMInstanceName to state that they return lists on Python 2, but dictionary views on Python 3. (See issue #2373)
- Install: Increased the minimum version of six to 1.14.0 (it was 1.12.0 on Python 3.8 and 1.10.0 below Python 3.8). (See issue #2379)
- Test: Added libffi-devel as an OS-level package on CygWin, it is needed by the Python cffi package which recently started to be needed. (See issue #2394)
Enhancements:
- Test: Enabled coveralls to run on all Python versions in the Travis CI, resulting in a combined coverage for all Python versions.
Cleanup:
- Changed the order of inheriting from mixin classes to put them after the main base class, following Python standards for inheritance (issue #2363).
- Docs: Switched to using the sphinx_rtd_scheme for the HTML docs (See issue #2367).
- Replaced pywbem’s own NocaseDict with NocaseDict from the nocasedict package and adjusted code and testcases where needed. See also the ‘Incompatible changes’ section. (See issue #2356)
- Improved the values() and items() methods of CIMInstance on Python 3 to return a dictionary view object instead of a list, to improve performance and for consistency with Python 3 behavior of the built-in dictionary. The keys() method already returned a dictionary view object on Python 3. The value item in each iteration is the same as before this change, i.e. the CIMProperty.value attribute. (See issue #2391)
pywbem 1.0.0b3¶
Released: 2020-07-15
Incompatible changes:
Removed the deprecated compile_dmtf_schema() method in FakedWBEMConnection in favor of a new method compile_schema_classes() that does not automatically download the DMTF schema classes as a search path, but leaves the control over where the search path schema comes from, to the user. (See issue #2284)
To migrate your existing use of compile_dmtf_schema() to the new approach, the code would be something like:
schema = DMTFCIMSchema(...) conn.compile_schema_classes(class_names, schema.schema_pragma_file, namespace)
Removed the deprecated schema_mof_file property in DMTFCIMSchema, in favor of the schema_pragma_file property. (See issue #2284)
Changed the handling of invalid types of input parameters to WBEMConnection operation methods to raise TypeError instead of other exceptions (KeyError, AttributeError, CIMError). This does not change the behavior if valid types are passed. (See issue #2313)
Mock support: Changed the interface of user-defined providers in order to simplify their implementation. (See issue #2326)
Bug fixes:
- Test: On Python 3.8, upgraded the minimum version of lxml from 4.4.1 to 4.4.3, in order to fix an XMLSyntaxError raised when encountering UCS-4 characters. (See issue #2337)
Enhancements:
- Test: Added support for testing from Pypi/GitHub source distribution archives. This allows testing without having to check out the entire repository, and is convenient for testing e.g. when packaging pywbem into OS-level packages. See new section ‘Testing from the source archives on Pypi or GitHub’ for details. (See issue #2260)
- Test: Renamed the ‘end2end’ target in the makefile to ‘end2endtest’. (Part of issue #2260)
- Added type checking for input parameters to WBEMConnection operation methods. Previously, invalid types could cause various exceptions to be raised, including KeyError, AttributeError, or CIMError. Now, all invalid types are properly checked and cause TypeError to be raised. Added testcases for invalid types. (See issue #2313)
- Mock support: Simplified the user-defined providers by checking their input parameters and the related CIM repository objects as much as possible before calling the providers. Updated the provider documentation to be from a perspective of the provider, and clarified what is already verified when the provider is called. This resulted in some incompatible changes at the interface of user-defined providers. (See issue #2326)
- Reworked the documentation about the mock WBEM server, specifically the sections about user-defined providers (See issue #2290).
- Enhance MOF compiler to correctly process MOF that contains instance definitions with properties that have EmbeddedObject or EmbeddedInstance qualifiers. In this case, the property value is defined in the MOF as a string or array of strings that compiles to a CIMInstance. This change does not compile CIMClass definitions. Originally these compiled objects were passed through the compiler as strings. (See issue # 2277).
- Mock support: Added a method BaseProvider.is_subclass() that tests whether two CIM classes in the CIM repository have an inheritance relationship. Used the new method for checking the class of embedded instances against the class specified in the EmbeddedInstance qualifier. (Related to issue #2326)
Cleanup:
- Document the TODOs in pywbem_mock and tests/unittest/pywbem_mock.test_wbemconnection.py and create an issue to document these issues (issue #2327) except for the ones we fixed in place or removed because they are obsolete. (See issue #1240)
- Corrected issue in the Jupyter notebook pywbemmock to reflect the incompatible changes for pywbem mock including 1) the change of the method compile_dmtf_schema to compile_dmtf_classes, and the replacement of the InvokeMethod callback mechanism to define a method provider with the user-defined method provider. (see issue #2310)
pywbem 1.0.0b2¶
Released: 2020-06-29
This version contains all fixes up to 0.17.3.
Bug fixes:
- Change log: Reintegrated the original change log sections for 0.14.1 to 0.17.2 and removed the matching change log entries from the change log section for 1.0.0b1. This reduces the change log entries shown for 1.0.0b1 to just the changes relative to 0.17.2. (See issue #2303)
- Fixed slow performance for EnumerateClasses operation in mock WBEM server. (See issue #2314)
- Updated change history of 1.0.0b1 to add a bug fix for accomodating the newly released flake8 version 3.8.1 by removing the pinning of pyflakes to <2.2.0, and adjusting the source code of pywbem to get around the new flake8 messages E123, E124, E402.
Enhancements:
- Added support for array-typed elements to pywbem.ValueMapping. (See issue #2304)
pywbem 1.0.0b1¶
Released: 2020-06-24
This is a beta version of the upcoming version 1.0.0. Pip will only install this version if explicitly requested, e.g. using any of these commands:
$ pip install pywbem==1.0.0b1
$ pip install --pre pywbem
Incompatible changes:
Because pywbem 1.0.0 is a major change, a number of significant incompatibilites have been incorporated. The following subsections summarize these changes and provide details of the changes themselves and the reasons for the changes.
Summary of incompatible changes:
The details, alternatives, and reasons for these incompatible changes is shown below this list.
- Removed Python 2.6 support.
- Migrated pywbem to use the ‘requests’ Python package for HTTP/HTTPS pywbem client to WBEM server communication. This caused some restrictions, see the detailed decription of incompatible changes, below.
- Removed the following deprecated functionality:
- WBEMConnection verify_callback init parameter.
- WBEMConnection **extra keyword arguments from operation methods.
- Ordering for NocaseDict, CIMInstanceName, CIMInstance and CIMClass objects.
- WBEMConnection properties: url, creds, x509, ca-certs, no_verification, and timeout setter methods. They are now read-only
- WBEMConnection method_call() and imethod_call()` methods.
- WBEMConnection operation_recorder property.
- CIMInstance property property_list and the same-named init parameter.
- pywbem.tocimxml() support for value of None.
- CIMInstance.tomof() indent parameter.
- pywbem.byname() internal function.
- pywbem.tocimobj() function.
- wbemcli command.
- Made the MOFWBEMConnection class (support for the MOF compiler) internal.
- Changed exceptions behavior:
- MOF compilation methods of MOFCompiler and FakedWBEMConnection raises exceptions based on class pywbem.MOFCompileError.
- Some methods of ValueMapping to use pywbem.ModelError.
- Some methods of WBEMServer to raise the new exception pywbem.ModelError.
- WBEMConnection request method responses added a new exception pywbem.HeaderParseError derived from pywbem.ParseError.
- Made all sub-namespaces within the pywbem namespace private, except for ‘pywbem.config’.
- Mock WBEM Server (experimental):
- Replaced the add_method_callback() method in FakedWBEMConnection with user-defined providers.
- Removed the conn_lite init parameter and mode of FakedWBEMConnection.
- Changed the logging behavior of the MOF compilation methods of FakedWBEMConnection so that the default is for the caller to display exceptions rather than the MOF compiler logger.
- Changed the default behavior to ignore IncludeQualifiers and IncludeClassOrigin parameters for GetInstance and EnumerateInstances operations of the mock WBEM server.
Incompatible change details:
Removed Python 2.6 support. The Python Software Foundation stopped supporting Python 2.6 in October 2013. Since then, many Python packages have continued releasing versions for Python 2.6, including pywbem. In 2017 and 2018, a number of Python packages have removed support for Python 2.6 and it has become an increasingly difficult task for pywbem to keep supporting Python 2.6. For this reason, Python 2.6 support has been removed from pywbem in its 1.0.0 version. This allowed eliminating a lot of Python version dependent code, eliminating the dependency to the unittest2 package, and lifting a number of restrictions in test code.
Migrated pywbem to use the ‘requests’ Python package for all HTTP/HTTPS communication between the pywbem client and the WBEM server replacing httplib and different ssl implementations for python 2 and 3. This eliminates several python 2/3 pywbem differences and simplifies the installation and setup of pywbem.
This results in the following changes:
- Changed the behavior of the default value None for the ca_certs parameter of WBEMConnection: Previously, it caused the first existing directory from a predefined set of directories to be used as the certificate directory. Now, it causes the certificates provided by the ‘certifi’ Python package to be used. That package provides the Mozilla Included CA Certificate List.
- Removed support for specifying multiple directory paths or file paths from the ca_certs parameter of WBEMConnection. Now, only a single directory path or file path can be specified, or None (see previous item).
- A non-existing path specified for the ca_certs parameter of WBEMConnection now raises IOError. Previously, the directory or file was simply skipped (and subsequently, verification failed).
- Removed support for the ‘OWLocal’ authentication scheme that was supported for the OpenWBEM server, and the ‘Local’ authentication scheme that was supported for the OpenPegasus server. Pywbem now supports only the ‘Basic’ authentication scheme.
- Removed support for communicating with WBEM servers using UNIX domain sockets by specifying a file-based URL. Use the standard http and https protocols instead.
- The installation of pywbem no longer uses the pywbem_os_setup.sh/.bat scripts because there are no more prerequisite OS-level packages needed for installing pywbem. If you have automated the pywbem installation, this step should be removed from your automation.
- Removal of the WBEMConnection verify_callback method.
Removed the verify_callback parameter of WBEMConnection. It was deprecated in pywbem 0.9.0, and was not supported in Python 3. The ‘requests’ package provides the commonly accepted certificate verification within the package itself. (See issue #1928)
Removed the **extra keyword arguments from WBEMConnection operation methods. Such arguments were passed on to the WBEM server, but they are not needed because all parameters defined by the CIM-XML protocol are supported as named arguments to these methods. This would only be incompatible if a WBEM server supports non-standard parameters or keyword variables were misnamed which would have been ignored and not used but now results in exceptions. (See issue #1415)
Removed the deprecated support for ordering NocaseDict, CIMInstanceName, CIMInstance and CIMClass objects. The ordering of such dictionaries was never supported with pywbem on Python 3, and for Python 2 it had been deprecated since pywbem 0.12.0. The user should do any required ordering. (See issue #1926).
Removed the deprecated ability to set the following properties of class WBEMConnection: url, creds, x509, ca-certs, no_verification, and timeout. These properties should not be set after the connection is defined as the results on the connection are unpreditable.
Removed the deprecated methods method_call() and imethod_call()` and the deprecated property operation_recorder from class WBEMConnection. Users should always use the request methods (ex. GetInstance).
Removed the deprecated property property_list and the same-named init parameter from class CIMInstance. The behavior of this parameter was undefined and incomplete.
Removed the deprecated ability to support a value of None for pywbem.tocimxml().
Removed the deprecated indent parameter of CIMInstance.tomof().
Removed the deprecated internal function pywbem.byname().
Removed the deprecated function pywbem.tocimobj(). The replacement for this method is to use the function cimvalue().
Removed the wbemcli command that was deprecated in pywbem 0.15.0. The recommended replacement is the pywbemcli command from the ‘pywbemtools’ package on Pypi: https://pypi.org/project/pywbemtools/. Some of the reasons for the removal are: (See issue #1932)
- Wbemcli did not have a command line mode (i.e. a non-interactive mode), but pywbemcli does.
- The interactive mode of wbemcli was more of a programming environment than an interactive CLI, and that makes it harder to use than necessary. Pywbemcli has an interactive mode that uses the same commands as in the command line mode. If you need an interactive programming prompt e.g. for demonstrating the pywbem API, use the interactive mode of the python command, or Python’s IDLE.
- Pywbemcli provides more functionality than wbemcli, e.g. server commands, persistent connections, class find, instance count, or multiple output formats.
Made the MOFWBEMConnection class internal and removed it from the pywbem documentation. It has an inconsistent semantics and should not be used by users. (See issue #2001).
Exception changes:
Changed the type of exceptions that are raised by methods of pywbem.ValueMapping for cases where the value-mapped CIM element has issues, as follows:
- From TypeError to pywbem.ModelError, if the value-mapped CIM element is not integer-typed.
- From ValueError to pywbem.ModelError, if an item of the ValueMap qualifier is not an integer.
The exceptions occur only with model definitions that are invalid and do not occur in the CIM Schema published by DMTF.
This change is incompatible only for users that handle these exceptions specifically in their code. (See issue #1429)
Changed the exception behavior of the MOF compilation methods of the MOFCompiler and FakedWBEMConnection classes to no longer raise CIMError, but to raise the following exceptions derived from a new base class MOFCompileError:
- MOFParseError MOF parsing errors. This class already existed and was already used for this purpose.
- MOFDependencyError: New class for MOF dependency errors (e.g. superclass not found).
- MOFRepositoryError: New class for errors returned from the target CIM repository. The CIMError exception raised by the CIM repository is attached to that exception in its attribute cim_error.
If you are using these MOF compilation methods, please change your catch of exceptions accordingly. (See issue #1235)
Changed the CIMError exceptions that were raised by pywbem code in several WBEMServer methods to now raise ModelError, for cases where the model implemented by the server has issues. (See issue #1423)
Added a new exception pywbem.HeaderParseError derived from pywbem.ParseError that is used to report HTTP header issues in the CIM-XML response. Previously, HTTPError had been used for that purpose, misusing its integer-typed status attribute for the message string. This is actually a bug fix, but because it changes the exception type, it is also an incompatible change for users that handle exceptions specifically. (See issue 2110)
Made all sub-namespaces within the pywbem namespace private, except for pywbem.config. Specifically, renamed the following modules by prepending an underscore character: cim_constants.py, cim_http.py, cim_obj.py, cim_operations.py, cim_types.py, cim_xml.py, exceptions.py, mof_compiler.py, moflextab.py, mofparsetab.py, tupleparse.py, tupletree.py. Using these sub-namespaces had been deprecated in pywbem 0.8.0.
This change is compatible for users that followed the recommendation to import only the symbols from the pywbem namespace. Users that imported symbols from these sub-namespace should now import them from the pywbem namespace. If you miss a symbol in the pywbem namespace, it was likely a symbol that is not part of the public pywbem API. (See issue #1925)
Mock WBEM Server (experimental):
Removed the add_method_callback() method and the methods property from the FakedWBEMConnection class. This has been replaced by the user-defined provider concept where the user defines and registers a subclass to the class MethodProvider which implements the InvokeMethod responder in that user-defined provider. The ‘mock WBEM server’ section of the documentation and module documentation for the MethodProvider and InstanceWriteProvider document creation of unser-defined providers (See issue #2062).
Removed the conn_lite init parameter and mode of operation of FakedWBEMConnection. The lite mode turned out too simplistic for mock testing and of no real value, while adding complexity. Users must include classes and qualifier declarations. Most mock environments start with classes and qualifier declarations in any case and the tools to add them are simple. (See issue #1959)
Changed the logging behavior of the MOF compilation methods FakedWBEMConnection.compile_mof_string() and compile_mof_file() (consistent with the new compile_schema_classes() method) to be able to do no logging, by specifying None for the log_func init parameter of MOFCompiler. This is now the default.
MOF compile errors no are longer printed to stdout by default. To continue printing the MOF compile errors to stdout, print the exception in your code. (See issue #1997)
Changed the behavior for the IncludeQualifiers and IncludeClassOrigin parameters on the GetInstance and EnumerateInstances operations of the mock WBEM server. The default is now to ignore the provided parameters and never include either attribute in the returned instances whereas, in previous versions the provided parameters determined whether they were returned. This behavior may be changed back to how it was in previous versions by modifying config variables in the new ‘pywbem_mock.config’ module. Reason for the change was that the behavior of these parameters was inconsistent between versions of DSP0200 and the new behavior implements the recommended default behavior. (See issue #2065)
Deprecations:
- Deprecated Python 2.7 and 3.4 support in pywbem, that are both beyond their End-Of-Life date.
- Deprecated the compile_dmtf_schema() method in FakedWBEMConnection in favor of a new method compile_schema_classes() that does not automatically download the DMTF schema classes as a search path, but leaves the control over where the search path schema comes from, to the user.
- Deprecated the schema_mof_file property in DMTFCIMSchema in favor of a new property schema_pragma_file since this is the file that contains all of the MOF pragmas defining the locations of the class MOF files in a set of directories.
Bug fixes:
- Docs: Fixed issues in Listener and SubscriptionManager examples (See issue #1768)
- Test: Added testcases to the cim_xml module, and migrated from unittest to pytest.
- Fixed a standards compliance issue. DSP0201/203 version 2.4 introduced the requirement to set the TYPE attribute on KEYVALUE elements. In operation requests sent to the WBEM server, pywbem now sets the TYPE attribute of the KEYVALUE element for keybinding values that are specified as CIM data types (e.g. pywbem.Uint8, string, bool). For keybinding values that are specified as Python int/float types or as None, pywbem continues not to set the TYPE attribute on KEYVALUE elements. This is sufficient to be fully standards compliant because it is always possible for a user to cause the TYPE attribute to be set. In operation responses received from the WBEM server, pywbem continues to tolerate an absent TYPE attribute, in order to accomodate WBEM servers that implement DSP0201/203 before version 2.4. (See issue #2052)
- Documented the limitation that the CORRELATOR element introduced in DSP0201/203 version 2.4 is not supported by pywbem. (related to issue #2053)
- Test: Fixed a bug introduced in 0.14.5 where the manualtest scripts failed with invalid relative import. (see issue #2039)
- Test: Fixed incorrect coverage reported at the end of the pytest run, by increasing the minimum version of the coverage package to 4.5.2. (See pywbemtools issue #547)
- Added missing attributes to the test client recorder (class TestClientRecorder) (see issue #2118).
- Fixed issue where DMTFCIMSchema/build_schema_mof creates the new cim_schema pragma list in order different than the DMTF defined file. In some rare cases this could cause an issue because the DMTF carefully ordered the class pragmas to avoid and issues of dependencies, etc. Note that if only leaf classes are use there should never be an issue. (See issue # 2223)
- Fixed issue in MOF compiler where compile_string() modifies the default_namespace of the MOF_Compiler handle parameter which is some subclass of WBEMConnection. This impacts at least the pywbem_mock environment since compiling MOF into a namespace that is not the connection default_namespace changes the default_namespace to that defined for the compile_string. This required extending all subclasses of MOFCompiler.BaseRepository to handle an optional namespace parameter on CreateClass, ModifyClass, GetClass, CreateInstance, etc. methods including the implementation in pywbem_mock. (See issue #2247)
- Removed the incorrect statement about deprecated comparison operators in the NocaseDict class - these operators had already returned errors.
- Accomodated the newly released flake8 version 3.8.1 by removing the pinning of pyflakes to <2.2.0, and adjusting the source code of pywbem to get around the new flake8 messages E123, E124, E402.
Enhancements:
- For the end2end tests, extended the definitions in tests/profiles/profiles.yml by the ability to specify the profile version. (See issue #1554)
- Improved test coverage of function tests by verifying the last_request, last_raw_request, last_reply, and last_raw_reply attributes of a connection.
- Migrated the communication between the pywbem client and WBEM servers to to use the ‘requests’ Python package. This greatly cleaned up the code, made the code common again between Python 2 and Python 3, and removed any prerequisite OS-level packages, thus simplifying the installation of pywbem again to what is expected for a pure Python package.
- Added more unit tests for the cim_http.py module and converted it to pytest. (See issue #1414)
- Added a request_data attribute to the HTTPError and CIMError exceptions and a response_data attribute to the HTTPError exception for storing the CIM-XML request or response, respectively, in order to provide additional context for the error. The ParseError exception and its subclasses already had request_data and response_data attributes. (See issue #1423)
- Added proxy support to the WBEMConnection class, by adding a proxies init parameter and attribute, utilizing the proxy support of the requests package. (see issue #2040)
- Add property to pywbem_mock FakedWBEMConnection to allow the user to modify the mocker behavior to forbid the use of the pull operations. (See issue #2126)
- Refactor pywbem_mock into more consistent components separating the mock repository from the component that represents a CIMOM. (see issue # 2062)
- Refactor pywbem_mock to separate the CIM repository from the class FakedWBEMConnection. This creates a new file _cimrepository.py that implements a CIM server repository. (See issue #2062)
- Enhance FakedWBEMConnection to allow user-defined providers for specific WBEM request operations. This allows user-defined providers for selected instance requests (CreateInstance, ModifyInstance, DeleteInstance) and for the InvokeMethod. Includes the capability to register these providers with a method register_provider in FakedWBEMConnection. This also creates a CIM_Namespace provider to handle the CIM_Namespace class in the interop namespace. See issue #2062)
- Changed format ‘standard’ of CIMInstanceName.to_wbem_uri() to sort the keys in the resulting WBEM URI. (See issue #2264)
- Added a new method FakedWBEMConnection.compile_schema_classes() that does not automatically download the DMTF schema classes as a search path, but leaves the control over where the search path schema comes from, to the user. See the Deprecations section.
Cleanup:
- Improved performance when setting WBEMConnection.debug by prettifying the request and reply XML only when actually accessed. (See issue #1572)
- Removed pywbem_mock conn_lite mode. (See issue # 1959)
- Fixed an error in the CIM-XML creation where the IMETHODRESPONSE element did not support output parameters. The IMETHODRESPONSE element is not used in the pywbem client, though.
- Fixed an error in the CIM-XML creation where the IRETURNVALUE element did not support multiple return objects. The IRETURNVALUE element is not used in the pywbem client, though.
- Fixed issue where the MOF compiler was using an instance path defined when the compiler built the instance as the instance alias instead of the instance path returned by the CreateInstance method. The issue is that the instance path defined in the compiler may not be complete and the only correct instance path is the path returned by the CreateInstance. Mof compiler alias now build with return from CreateInstance and the creation of the path has been moved from the compiler instanceDeclaration to the CreateInstance method defined in the compiler repo. For the tests that means that the path creation is in MOFWBEMConnection.CreateInstance. (See issue # 1911)
- Test: Converted WBEMListener tests from unittest to pytest. (See issue #2179)
pywbem 0.17.2¶
Released: 2020-04-19
Bug fixes:
- Test: Fixed virtualenv related failures during install test. (See issue #2174)
- Dev: Increased the versions of the base packages ‘pip’, ‘setuptools’ and ‘wheel’ to the content of Ubuntu 18.04 as a minimum, and to the lowest versions that support a particular Python versions beyond that. This only affects development of pywbem. (See issue #2174)
- Setup: Added the scripts for installing OS-level dependencies (pywbem_os_setup.sh/.bat) to the source distribution archive. Note that starting with the upcoming pywbem 1.0.0, these scripts are no longer needed, so this change will not be rolled forward into 1.0.0. (See issue #2173)
- Increased the version of ‘PyYAML’ from 5.1 to 5.3 on Python 2.7, to pick up a fix for dealing with Unicode characters above U+FFFF in narrow Python builds. This could not be fixed for Python 2.6 since PyYAML 3.12 dropped support for Python 2.6 (See issue #2182)
- Fixed raise error for invalid reference_direction in WBEMServer.get_central_instances(). (See issue #2187)
- Fixed raise error for missing ports in WBEMListener.__init__(). (See issue #2188)
pywbem 0.17.1¶
Released: 2020-04-13
Bug fixes:
- Fixed version incompatibilities reported by pip for tox/pluggy, ipython/prompt-toolkit, and flake8/pyflakes. (See issue #2153)
- Fixed the issue where formatting the timezone name of a pywbem.MinutesFromUTC object raised NotImplementedError, by adding a tzname() method. (see issue #2160)
- Pinned mock to <4.0.0 on Python <3.6 due to an install issue when installing from the source tarball. (See issue #2150).
- Enabled installation using ‘setup.py install’ from unpacked source distribution archive, and added install tests for various installation methods including this one. (See issue #2150).
- Increased minimum version of ‘six’ from 0.10.0 to 0.12.0 when on Python 3.8 (or higher). (See issue #2150).
- Increased minimum version of ‘setuptools’ on Python 3.7 from 33.1.1 to 38.4.1 to fix a bug with new format of .pyc files. (See issue #2167).
pywbem 0.17.0¶
Released: 2020-04-03
Bug fixes:
- Test: Fixed a bug introduced in 0.14.5 where the manualtest scripts failed with invalid relative import. (see issue #2039)
- Dev: Fixed installation of Jupyter Notebook on Python 3.4 by defining the appropriate minimum versions of the ipython package, per Python version. (See issue #2135)
- Pinned dparse to <0.5.0 on Python 2.7 due to an issue. (See issue #2139)
Enhancements:
- Changed the HTTPS support of pywbem.WBEMListener from using the deprecated ssl.wrap_socket() function to using the ssl.SSLContext class that was introduced in Python 2.7.9. This causes more secure SSL settings to be used. On Python versions before 2.7.9, pywbem will continue to use the deprecated ssl.wrap_socket() function. (See issue #2002)
Cleanup:
- Renamed all sub-modules within the pywbem namespace so they are now private (i.e. with a leading underscore). This has been done for consistency with the upcoming 1.0.0 version of pywbem, for eaier rollback of changes from that version. For compatibility to users of pywbem who use these sub-modules directly, despite the recommendation to import only the symbols from the pywbem namespace, these sub-modules are still available under their previous names. (See issue #1925)
pywbem 0.16.0¶
This version contains all fixes up to pywbem 0.15.0.
Released: 2020-01-09
Bug fixes:
- Silenced the MOFCompiler class for verbose=False. So far, it still printed messages for generating the YACC parser table, causing one test to fail, and others to issue useless prints. (Issue #2004)
- Test: Fixed an error in testing the PLY table version in testcases that caused the LEX/YACC parser table files to be written to the pywbem installation when using TEST_INSTALLED. (Related to issue #2004)
- Fixed that the MOFCompiler could be created with handle=None to work against a local repository. It was documented that way, but failed with AttributeError. (See issue #1998)
- Fixed the error that the MOF compilation of a class could fail but the error was not surfaced. This only happened when the MOF compiler was invoked against a WBEM server, when the class already existed, and when the ModifyClass operation that was attempted in this case, failed.
- Fixed that the CIM-XML payload in log entries was spread over multiple lines. The payload is now escaped as a single-line Python string.
- Test: Fixed an error in test_format_random() for the backslash character. (See issue #2027)
- Fixed handling of Unicode string in ca_certs parm of WBEMConnection on py2 (See issue #2033)
Enhancements:
- Test: Removed the dependency on unittest2 for Python 2.7 and higher. (See issue #2003)
Cleanup:
- For Python 2.7 and higher, replaced the yamlordereddictloader package with yamlloader, as it was deprecated. For Python 2.6, still using yamlordereddictloader. (See issue #2008)
pywbem 0.15.0¶
This version contains all fixes up to pywbem 0.14.6.
Released: 2019-12-01
Deprecations:
- The wbemcli command has been deprecated. Pywbem 1.0.0 will remove the wbemcli
command. The recommended replacement is the pywbemcli command from the
pywbemtools package on Pypi: https://pypi.org/project/pywbemtools/.
Some of the reasons for the intended removal are: (See issue #1932)
- Wbemcli does not have a command line mode (i.e. a non-interactive mode), but pywbemcli does.
- The interactive mode of wbemcli is more of a programming environment than an interactive CLI, and that makes it harder to use than necessary. Pywbemcli has an interactive mode that uses the same commands as in the command line mode. If you need an interactive programming prompt e.g. for demonstrating the pywbem API, use the interactive mode of the python command, or Python’s IDLE.
- Pywbemcli provides more functionality than wbemcli, e.g. server commands, persistent connections, class find, instance count, or multiple output formats.
Bug fixes:
- Fixed that the embedded_object attribute was not copied in CIMProperty.copy().
- Fixed that inconsistent names (between key and object name) were not detected when setting CIMMethod.parameters from an input dictionary.
- Docs: Fixed errors in description of CIMInstance.update_existing().
- Added dependency to pywin32 package for Windows, and pinned it to version 225 to work around an issue in its version 226. (See issue ##1946)
- Modified pywbem_mock to create the instance path of new instances created by the compiler. Previously, the mocker generated an exception if the path for a compiler created new instance was not set by the compiler using the instance alias. That requirement has been removed so the mock repository will attempt to create the path (which is required for the mock repository) from properties provided in the new instance. If any key properties of the class are not in the instance it will generate an exception. This is backward compatible since the mocker will accept paths created by the compiler. The incompatibility is that the mocker tests for the existance of all key properties. (see issue # 1958)
- Circumvented removal of Python 2.7 in Appveyor’s CygWin installation by manually installing the python2 CygWin package. (See issue #1949)
- Fixed issue with MOFCompiler class where mof_compiler script was not writing the new classes and instances to the remote repository defined with the -s parameter. (see issue #1956 )
- Fixed issue with mof_compiler and mof rollback where instances were not removed when rollback was executed. This was caused by MOFWBEMConnection code that did not put correct paths on the instances when they were inserted into the local repository so the rollback delete of the instances could not identify the instances. (see issue #1158)
- Fixed several install issues with the lxml, flake8, pywin32, pip, setuptools, and wheel packages on Python 3.8 on Windows. (See issues #1975, #1980).
Enhancements:
- Removed the use of the ‘pbr’ package because it caused too many undesirable side effects. As part of that, removed PKG-FILE and setup.cfg and went back to a simple setup.py file. (See issues #1875, #1245, #1408, #1410)
- Code: Fixed pywbem_mock issue where CreateInstance was not handling the case sensitivity of property cases if the instance property name case was different than the class property name case. While not legally incorrect the created instance looks bad. See issue #1883
- Code: Fixed pywbem_mock issue where ModifyInstance not handling case sensitivity of property cases if the instance property name case was different than the class property name case. Modify failed if the case of property names did not match. Fixed the case test error and put the class defined proerty name into the modified instance. See issue #1887
- Fix issue in mof compiler where mof instance that duplicates existing instance path can get lost with no warning. NOTE: This does not happen in the standalone compiler because it creates a duplicate instance issue # 1852 but depending on the implementation of ModifyInstance for the compiler, it can simply lose the instance. See issue #1894
- Fix issue in pywbem_mock where instances with duplicate paths defined in mof and put into the mocker repository were originally accepted as separate instances but fixed to cause an exception in issue #1852, conform to the DMTF spec definition that requires that the second instance modify the first. Fix issue in the mof_compiler where the CreateInstance retry logic was first doing a ModifyInstance and if that failed then trying a DeleteInstance and CreateInstance. We removed the DeleteInstance/CreateInstance logic and insured that an exception would occur if the ModifyInstance failed. See issue #1890
- Code: Fix issue with pywbem_mock that allows duplicate instances to be inserted into the mock repository when mof instances are compiled. Duplicate instances (CIMInstanceName) will now cause an exception. See issue #1852
- Added support for byte string values in keybindings of CIMInstanceName method to_wbem_uri(), consistent with other methods.
- Test: Added Python 3.8 to the tested environments. (See issue #1879)
- Clarified that namespace and host will be ignored when the ResultClass and AssocClass parameters of association operations are specified using a CIMClassName object. (See issue #1907)
- Added capability to log calls to WBEM server from mof_compile script. AAdds an option to the cmd line options to enable logging.
- Added SSL related issues to the Troubleshooting section in the Appendix of the docs, and added the OpenSSL version to the pywbem.ConnectionError exceptions raised due to SSL errors for better diagnosis. (See issues #1950 and #1966)
- Added ‘twine check’ when uploading a version to Pypi, in order to get the README file checked before uploading.
Cleanup:
- Removed unnecessary code from cim_obj._scalar_value_tomof() that processed native Python types int, long, float. These types cannot occur in this function, so no tests could be written that test that code.
pywbem 0.14.6¶
Released: 2019-10-10
Bug fixes:
- Fixed case sensitive class name check in mock support of ModifyInstance (See issue #1859)
- Test: Fixed args of WBEMOperation methods in mock unit tests & function tests.
Cleanup:
- Test: Enabled Python warning suppression for PendingDeprecationWarning and ResourceWarning (py3 only), and fixed incorrect make variable for that. (See issue #1720)
- Test: Removed pinning of testfixtures to <6.0.0 for Python 2.7/3.x due to deprecation issue announced for Python 3.8, and increased its minimum version from 4.3.3 to 6.9.0.
- Test: Increased minimum version of pytest from 3.3.0 to 4.3.1 because it fixed an issue that surfaced with pywbem minimum package levels on Python 3.7.
- Increased minimum version of PyYAML from 3.13 to 5.1 due to deprecation issue announced for Python 3.8.
pywbem 0.14.5¶
Released: 2019-09-29
Bug fixes:
- Added test to tests/manual/cim_operations.py specifically to test the iter and pull operations for the IncludeQualifier and LocalOnly parameters based on issue #1780.
- Dev/Test: Pinned lxml to <4.4.0 because that version removed Python 3.4 support.
- Dev/Test: Pinned pytest to <5.0.0 for Python < 3.5 because that version requires Python >= 3.5.
- Test: Fixed errors on Python 2.6 about unnamed format replacements.
- Fixed incorrect format specifiers in exceptions raised in pywbem_mock. (See issue #1817)
- Fixed missing support for the ANY scope in pywbem_mock. (See issue #1820)
- Increased version of WinOpenSSL used on Windows from 1.1.0k to 1.1.0L.
- Fixed that the OpenEnumerateInstances() method of WBEMConnections incorrectly supported a LocalOnly parameter, that was never supported as per DSP0200. Specifying that parameter as True or False on this method caused properly implemented WBEM servers to reject the operation. That parameter now still exist on this operation but is ignored and is not passed on to WBEM servers. The corresponding Iter…() method now also ignores that parameter if the pull operations are used; it is still passed on if the traditional operations are used. (See issue #1780)
- Fixed the issue that EnumerateInstances did not return instances without properties unless DeepInheritance was set (see issue #1802).
- Fixed bad formatting on –mock-server option in wbemcli.py.
- Fixed the issue with ‘dnf makecache fast’ during pywbem_os_setup.sh on Fedora (See issue #1844)
Enhancements:
- Improved handling of missing WinOpenSSL on Windows by recommending manual download of next version.
- Test: Added support for running the pywbem tests against an installed version of pywbem, ignoring the version of pywbem that exists in the respective directories of the repo work directory. This is useful for testing a version of pywbem that has been installed as an OS-level package. (See issue #1803)
- Docs: Improved the section about installing to a native Windows environment (See issue #1804)
- Improved error messages and error handling in wbemcli and in the pywbem mock support.
pywbem 0.14.4¶
Released: 2019-07-20
Bug fixes:
- Test: For Python 2.6 on Travis, pinned the distro version to Ubuntu trusty (14.04) because the default distro version on Travis changed to xenial (16.04) which no longer has Python 2.6.
- Add Jupyter tutorial for pywbem_mock to table of notebooks in documentation.
- Fix issue with Python 3 and WBEMconnection certificate handling. pywbem was getting AttributeError: ‘SSLContext’ object has no attribute ‘load_cert’ because incorrect method called. (See issue # 1769)
- Fixed that the WBEMConnection.Open…() operations incorrectly supported an IncludeQualifiers parameter, that was never supported as per DSP0200. Specifying that parameter as True on these operations caused properly implemented WBEM servers to reject the operation. The parameter is now ignored on these operations. Since this parameter was documented as deprecated in DSP0200 and documented that users could not rely on qualifiers to be returned, this fix should not break user code. The WBEMConnection.Iter…() operations now also ignore that parameter if the pull operations are used, and the documentation has been updated accordingly. (See issue #1780)
- pywbem_mock display_repository() comment defintion that surrounds comments in the output was defined as # but mof comments are // so changed. (see issue #1951)
- Fixed that local tests (i.e. TEST_INSTALLED=False) skipped MOF tests if the mofparsetab or moflextab files did not exist. (See issue #1933)
Enhancements:
- Docs: Clarified how the pywbem_os_setup.sh/bat scripts can be downloaded using a predictable URL, for automated downloads.
- Clarified the ‘x509’ parameter of ‘WBEMConnection’ in that its ‘key_file’ item is optional and if omitted, both the private key and the certificate must be in the file referenced by the ‘cert_file’ item. Added checks for the ‘x509’ parameter.
Cleanup:
- Test: Removed pinning of distro version on Travis to Ubuntu xenial (16.04) for Python 3.7, because that is now the default distro version, in order to pick up a future increase of the default distro version automatically.
pywbem 0.14.3¶
Released: 2019-05-30
Bug fixes:
- Windows install: Upgraded version of Win32/64OpenSSL.exe that is downloaded during installation on native Windows, from 1.1.0j to 1.1.0k. This became necessary because the maintainer of the Win32OpenSSL project at https://slproweb.com/products/Win32OpenSSL.html removes the previous version from the web site whenever a new version is released, causing the pywbem installation to fail during invocation of pywbem_os_setup.bat on Windows. Related to that, fixed the way pywbem_os_setup.bat recognizes that the version does not exist. (see issue #1754)
Enhancements:
Docs: Updated the trouble shooting section with an entry that explains how a user can resolve the installation failure that is caused on Windows when the Win32OpenSSL project at https://slproweb.com/products/Win32OpenSSL.html removes the previous version from their web site when a new version is released.
Increased versions of the following packages to address security vulnerabilities:
- requests from 2.19.1 to 2.20.1 (when on Python 2.7 or higher)
- urllib3 from 1.22 to 1.23
- bleach from 2.1.0 to 2.1.4
These packages are only used for development of pywbem.
Note that requests 2.19.1 has a security issue that is fixed in 2.20.0. However, requests 2.20.0 has dropped support for Python 2.6.
pywbem 0.14.2¶
Released: 2019-05-08
Bug fixes:
- Test: Temporary fix for pytest option –pythonwarnings in end2end tests (issue #1714).
- Test: Fixed AttributeError in end2end assertion functions (Issue #1714)
- Test: Added and fixed profile definitions for end2end tests. (Issue #1714)
- Fix issue in the Jupyter notebook iterablecimoperations where the IterQueryInstance example did not correctly processthe return from the operation. It attempted to itereate the returned object and should have been iterating the generator property in that object. Documentation of that example and the example were corrected. (see issue #1741)
- Fix issue in pywbem_mock/_wbemconnection_mock.py with EnumerateInstances that includes a property list with a property name that differs in case from the property name in the returned instance. Works in the conn_lite=True mode but fails in conn_lite=False mode because the test was case insensitive.
- Test: Fixed Appveyor CI setup for UNIX-like environments under Windows (Issue #1729)
Enhancements:
- Changed GetCentralInstances methodology in WBEMServer.get_central_instances() to be bypassed by default, because (1) WBEM servers do not implement it at this point, and (2) there are WBEM servers that do not behave gracefully when unknown CIM methods are invoked. Because WBEM servers are required to implement one of the other methodologies, this change is not incompatible for pywbem users.
- Improved the performance for receiving large CIM-XML responses in the tupleparser by moving type checks for text content in XML into an error handling path, and by replacing some isinstance() calls with type() comparison.
- Improved the quality of the information in TypeError exceptions that are raised due to invalid types passed in WBEMConnection operation arguments. (Issue #1736)
pywbem 0.14.1¶
Released: 2019-04-05
Bug fixes:
- Change history: Removed incorrect statement about commenting out server-specific functionality from the tuple parser from the change history of pywbem 0.14.0.
pywbem 0.14.0¶
This version contains all fixes up to pywbem 0.13.1.
Released: 2019-04-03
Bug fixes:
- Extend makefile clobber to remove cover files from pywbem_mock package.
- Fixed pip version issue on Appveyor.
- Fixed AttributeError on __offset in CIMDateTime.repr(). See issue #1681.
- Removed the associationDeclaration and IndicationDeclaration mof parser production rules from mof_compiler.py because: a) They were orderd in p_mp_createClass so that the classDeclaration production was always used, b) When reordered, they still created a YACC reduce/reduce conflict where the result was that YACC used the classDeclaration production to resolve the conflict, c) they represent exactly the same syntax as the classDeclaration. In effect, these production rules were never really used executed.
Enhancements:
- Significant performance improvements in the CIM-XML parser, resulting in about 50% elapsed time savings for 10000 returned CIM instances, compared to pywbem 0.13.0. See issue #1630.
- Added the possibility to specify a value of False for the embedded_object attribute/parameter of CIMProperty and CIMParameter. It is stored as None. The only difference to specifying None is that the embedded_object value is not inferred from the property or parameter value in that case, so this saves performance.
- Added the ‘python_requires’ keyword to the package definition, which makes pip aware of the supported Python versions.
- Refactored and extended Jupyter notebook for pywbem_mock.
pywbem 0.13.0¶
Released: 2019-02-23
This version contains all fixes up to pywbem 0.12.6.
Incompatible changes:
- Changed the path argument of CIMInstance to be deep copied, because it may be modified by setting properties. It was previously shallow copied (and incorrectly documented as not being copied). This is only incompatible if user code relies on the init method modifying the keybindings of its path input argument. If user code relies on that, it is highly recommended that you decouple such dependencies (Issue #1251).
- Changed the path argument of CIMClass to be shallow copied, in order to decouple the created object from its input arguments. It was previously not copied but referenced. This is only incompatible if user code relies on the init method modifying the provided path input argument. If user code relies on that, it is highly recommended that you decouple such dependencies (Issue #1251).
- Changed keybinding processing when creating CINInstanceName objects to disallow NULL keybinding values. This is in accord with the CIM standard DSP0004. This is only incompatible if user code relies on the non-standard behavior of creating a keybinding having None as a value. If your code relies on that non-standard behavior, it can be re-established by via the config property IGNORE_NULL_KEY_VALUE in config.py. Note that NULL keybindings may be an issue with some WBEM servers. (Issue #1298)
- The fix for issue #1302 removed the pywbem config variables from the pywbem namespace. They are now only available via the pywbem.config namespace. However, this change should not affect you because the previously documented approach for changing them through the pywbem namespace did not work, so if you changed the config variables successfully, you have done that through the pywbem.config namespace already, and this change does not affect you.
- Removed the ez_setup.py script from the repository. That script is the well-known tool that bootstraps easy_setup which was used for installing Python packages in times before pip became ubiquitous. If anyone still uses easy_setup these days for installing Python packages, it is time to switch to using pip. If you cannot do that for some reason, you will now need to install easy_setup by some other means.
- Changed CIMError exceptions raised to indicate incorrect CIM-XML responses to open/pull operations, to raise ParseError instead, consistent with other response checking (Issue #1320).
Deprecations:
- Added announcement that Python 2.6 support in pywbem will be removed in its future 1.0.0 version.
- Deprecated the tocimobj() function because it has some inconsistencies, in favor of the cimvalue() function introduced in pywbem 0.12.0. Changed all internal uses of tocimobj() to cimvalue(). (Issue #904).
- The deprecated internal methods imethodcall() and methodcall() of the WBEMConnection class will be removed in the next pywbem version after 0.13.
- Removed the deprecation for setting the default_namespace attribute of WBEMConnection that had been introduced in pywbem 0.12; setting it is now fully supported again.
Finalizations:
- Finalized the use_pull_operations property and init argument of the WBEMConnections class that allows controlling whether the Iter…() methods use pull operations or traditional operations.
- Finalized the logging support. The logging support was introduced in pywbem 0.11 and was redesigned in pywbem 0.12. For details, see the “WBEM operation logging” section in the pywbem documentation.
Bug fixes:
- Fixed the issue where wbemcli-help-txt was not being updated when wbemcli.py changed. (Issue #1205)
- Test: Fixed access to incorrect tuple members in run_cim_operations.py. that were used only in long version of the test. Found by Pylint. (Issue #1206).
- Fixed that CIMInstanceName.from_wbem_uri() did not support the representation of integer key values in binary, octal or hex format (part of Issue #904).
- Fixed an issue with running the tests on Travis CI that occurred on Python 2.6 with the latest package level and that was caused by the fact that a new version of the “httpretty” Python package was released that had dropped support for Python 2.6. This was fixed by limiting the version of httpretty to <0.9 when running on Python 2.6. Note that this only affects the development environment.
- Correct issue in pywbem_mock where we return incorrect CIMError (CIM_ERR_NOT_FOUND rather than CIM_ERR_METHOD_NOT_FOUND) when the class for a method is not defined in the methods repository. issue #1256
- Fixed issue in pywbem_mock where we were not creating deepcopy (we were using the pywbem .copy that is part of each object (see issue #1251) of objects returned from the repository so that if the objects were modified some of the changes bled back into the repository. Code modified to do deepcopy of everything inserted into the repository through add_cimobjects and the Create… methods and returned from the repository with any of the get/enumerate/etc. methods. We also modified code so that if there is a class repository there is also an instance repository even if it is empty. See issue #1253
- Fixed issue where pywbem_mock EnumerateClass and EnumerateClassNames parameter losing the ClassName parameter and no test for the ClassName parameter not existing in the repository. (See issue #1271)
- Correct issue in pywbem_mock where we return incorrect CIMError (CIM_ERR_NOT_FOUND rather than CIM_ERR_METHOD_NOT_FOUND) when the class for a method is not defined in the methods repository. issue #1256
- Fix issue causing pywbem_mock/_wbemconnection_mock.py display_repository() to display as bytes in Python 3. See issue # 1276
- Fixed the support for Unicode escape sequences in the MOF compiler. It supported only lower case x1234 but not upper case X1234. Also, it tolerated an invalid x escape sequence, when DSP0004 requires 1..4 hex characters to be present. See issue #1278.
- Fixed issue where Null key values allowed. See issue #1298
- Fixed issue with updating pywbem config variables. So far, the pywbem config variables were defined in the pywbem.config namespace and then imported by pywbem into the pywbem namespace. Pywbem documented that these config variables should be accessed (read and written) through the pywbem namespace. However, pywbem code read them in nearly all cases from the pywbem.config namespace. This caused an update that is done by a pywbem user through the pywbem namespace, not to be visible in the pywbem.config namespace, so pywbem did not react to the user’s change. This was fixed by only using the pywbem.config namespace for config variables. They are no longer imported into the pywbem namespace. See issue #1302.
- Fixed issue where the tomof() methods of CIMProperty, CIMQualifier, and CIMQualifierDeclaration raised IndexError when the value was an empty array. This issue perculated up to higher level CIM objects that are using these objects, i.e. CIMInstance or CIMClass. Added according testcases. See issue #1312.
- Fix issue in IterQueryInstances where the QueryLanguage and Query parameters were reveresed in the fallback call to ExecQuery method. See issue # 1334.
- Fixed the issue that the VALUE.OBJECTWITHLOCALPATH element was not allowed as a child element under IRETURNVALUE. This element is used as one possibility for the result of the ExecQuery operation. See issue #1347.
- Fixed issue in run_cimoperations.py with test for deep inheritance on EnumerateInstances. It was reporting confused result so we created a simpler test. See issue #477.
- Fixed issues in pywbem_mock where classnames on the operation requests were not treated as case insensitive for some operations, in particular the enumerate operations, reference operations, and associator operations. This also adds a number of tests to validate that classnames. See issue #1355.
- Fixed the issue that INSTANCE child elements on a returned ERROR element were not allowed. INSTANCE child elements are now allowed and will appear to the user as a list of CIMInstance objects in a new instances property of the CIMError exception that is raised. See issue #1380.
- Fixed issue in mof_compiler search_paths where doc defined iterable as input but since string is an interable it was allowed but misused. Extended code to specifically allow single string on input. See issue #1227.
- Increased the minimum required versions of the following dependent Python
packages in order to fix security issues with these packages:
- requests from 2.12.4 to 2.19.1
- html5lib from 0.9999999 to 0.999999999
- mistune from 0.7.3 to 0.8.1
- The ValueMapping class only supported decimal representations of integer values in the ValueMap qualifier. However, DSP0004 allows for decimal, binary, octal and hexadecimal representations of integer values. Added support for all these representations to the ValueMapping class. See issue #1547.
- Multiple fixes in WBEMServer.get_central_instances():
- For a profile that implements the central class methodology but has no central instances, the implementation went on to try the scoping class methodology. Now, it accepts that as a valid central instance implementation and returns an empty list of instances, instead. Non-implementation of the central class methodology is not detected from CIM_ERR_NOT_SUPPORTED being returned on the Associators operation that attempts to traverse the CIM_ElementConformsToProfile association.
- For a profile that implements the scoping class methodology, the traversal from the profile side to the resource side incorrectly assumed that for multi-hop scoping paths, the hops above the first hop could be used as the scoping path of the scoping profile. That has been changed to now omit the scoping path when invoking get_central_instances() on the scoping profile. As a result, the scoping profile is now required to implement the central class methodology.
- For a profile that implements the scoping class methodology, the traversal from the central instances of the scoping profile down to the central instances of the original profile incorrectly only traversed the first hop of the reversed scoping path. This has been fixed to traverse the entire reversed scoping path.
- In the recursive invocation of get_central_instances() for the scoping profile, the newly introduced reference direction was not passed on. For now, it is assumed that the scoping profile has the same reference direction as the original profile.
- Because it seems that with these bugs, the get_central_instances() method cannot have been used reasonably, some ValueError exceptions` it returned to indicate server implementation issues, have been changed to use the newly introduced ModelError exception.
- For Python 2.6, pinned version of lxml to <4.3.0, because lxml 4.3.0 has removed support for Python 2.6. See issue #1592.
- Fixed the URL on the DMTF site from which the MOF archive is downloaded. This has changed on the DMTF site and needed to be adjusted.
- Fixed order of parameters in example method_callback_interface defined in pywbem_mock FakedWBEMConnection. (See issue #1614)
- Fixed an error “Python : can’t open file ‘C:Usersfirstname’ : No such file or directory” when invoking wbemcli.bat on native Windows in a directory whose path name contained blanks. (See issue #1622)
- Extend pywbem_mock to correctly handle resolving of classes when they are inserted into the repository. Resolving of classes configures a class inserted with CreateClass or through the mocker add_cimobjects, etc. to reflect the inheritance of properties, methods, etc. from the superclass. The initial release did a very abbreviated resolution which left some characteristics of the new class and did not properly handle things like the override qualifier. (See issue # 1540). This change also simplifies the mocker in that both the compiler and the mock responder methods contribute to the same repository (the original version copied objects from the compiler repository to the mocker repository).
- Test: Fixed a bytes/unicode error in validate.py that occurred on Python 3 when xmllint failed validating the DTD.
- Increased the minimum M2Crypto version to 0.31.0 in order to pick up the fix for pywbem issue #1275 (incorrect timeout value).
- Added the Pyton tox package to the dependencies for development.
Enhancements:
Extend pywbem MOF compiler to search for dependent classes including:
- reference classes (classes defined in reference properties or parameters)
- EmbeddedInstance qualifier classes if they are not compiled before the classes that reference them are compiled. Previously the lack of these dependent classes was ignored. The compiler already searches for superclasses if they are not compiled before their subclasses.
Extends MOFWBEMConnection to generate an exception if the compile of a class with reference parameters or properties reference class is not in the repository or if the class defined for an EmbeddedInstance qualifier is not in the repository.
This uses the capability in the MOF compiler to search the defined search path for the missing classes if they are not in the repository.
This means that the mof_compiler can be used to create a complete class repository builds without having to specifically declare all dependent classes for the classes the user needs in a repository if the mof for the dependent classes in in the search path. (Issue #1160).
Made CIMInstanceName.from_wbem_uri() and CIMClassName.from_wbem_uri() more flexible w.r.t. tolerating non-standard WBEM URIs that omit the leading colon before class names (part of Issue #904).
Added a tobinary() method to the ValueMapping class, which translates the value mapping from a Values string to binary integer values, or a range thereof. This is the opposite direction of the existing tovalues() method. (Issue #1153)
Added an items() generator method to the ValueMapping class for iterating through the items of the value mapping, returning tuples of the binary value (or a range thereof), and the Values string. (Issue #1153)
Docs: Clarified that the copy() methods of NocaseDict and of the CIM object classes produce middle-deep copies, whereby mutable leaf attributes are not copied and thus are shared between original and copy (Issue #1251).
Docs: Added a note to the description of the copy() methods of the CIM objects that states that copy.copy() and copy.deepcopy() can be used to create completely shallow or completely deep copies (Issue #1251).
Extend wbemcli to use pywbem_mock with a new command line parameter (–mock_server <mock_info-filename>). Added a set of new tests for this parameter and a MOF file and test code to test the new option. (Issue #1268)
Installation on Windows is now more automated by means of a new pywbem_os_setup.bat script. As part of that, the latest M2Crypto version 0.30.1 is now used on Windows, and no longer the somewhat aged versions in the M2CryptoWin32/64 packages. For details, see the installation section in the documentation. That script also downloads and installs Win32 OpenSSL from https://slproweb.com/products/Win32OpenSSL.html.
Made exception messages more explicit in the ValueMapping and WBEMServer classes. Issue #1281.
Docs: Added a shell command for determining the version of an installed pywbem package, that covers all released pywbem versions (Issue #1246).
Docs: Added jupyter notebooks to demonstrate use of pywbem_mock.
Make: Eliminated the confusing but unproblematic error message about pbr importing when running certain make targets in a freshly created Python environment. Issue #1288.
In MOFCompiler.__init__(), added a type check for the search_paths parameter to avoid accidential passing of a single string. Issue #1292.
Add new static method to CIMInstance (from_class) that builds an instance from a class and dictionary of property values. Issue #1188
Added support for tolerating a TYPE attribute in the PARAMVALUE element of received CIM-XML responses. The TYPE attribute is not allowed as per DSP0201. However, there are devices that have incorrectly implemented a TYPE attribute instead of the standard PARAMTYPE attribute. The TYPE attribute when present is now used when PARAMTYPE is not present. If both are present, PARAMTYPE is used and TYPE is ignored. Also, test cases were added for tupleparse for the PARAMVALUE element. See issue #1241.
Added support for automatically creating the Pragma: UpdateExpiredPassword HTTP header in the CIM-XML request if pywbem detects that the special SFCB method “UpdateExpiredPassword()” is invoked on class “SFCB_Account”. SFCB requires this HTTP header for that method. See https://sblim.sourceforge.net/wiki/index.php/SfcbExpiredPasswordUpdate for details about this SFCB functionality. The automatic creation of the header field is enabled by default and can be disabled with a new pywbem config variable AUTO_GENERATE_SFCB_UEP_HEADER. See issue #1326.
Add support for ExecQuery (shortcut eqy) to wbemcli. See issue # 1332.
Added support for a new WBEM URI format “canonical” to the to_wbem_uri() methods of CIMInstanceName and CIMClassName. The new format behaves like the existing format “standard”, except that case insensitive components are translated to lower case, and the order of keybindings is the lexical order of the lower-cased key names. The new format guarantees that two instance paths or class paths that are equal according to DSP0004, return equal WBEM URI strings. See issue #1323.
Added support for Python 3.7, which was released 2018-06-27.
Enhanced the output of the string representation of the CIMError exception by adding the status code name (e.g. the string “CIM_ERR_NOT_SUPPORTED” for status code 7). The string representation is used for example when showing the exception in a Python traceback. See issue #1350.
Added checking for the returned instance name to the CreateInstance operation. This changes the exception that is raised from TypeError or IndexError indicating an internal issue, to several pywbem.ParseError exceptions that have reasonable error messages. Note that there is an uncertainty as to whether DSP0200 would allow CreateInstance to not return an instance name. Because this would already have caused an exception to be raised in the current pywbem code, it is assumed that all WBEM server implementations so far always return the instance name, and therefore, pywbem has just improved the quality of the exception that is raised, and continues not to tolerate a missing instance name. Extended the testcases for CreateInstance accordingly. See issue #1319.
Added support for CIM namespace creation via a new WBEMServer.create_namespace() method. See issue #29.
Added support for CIM namespace deletion via a new WBEMServer.delete_namespace() method. See issue #1356.
Added connection information to all pywbem exceptions. This is done via a new optional conn_id keyword argument that was added to all pywbem exception classes. The exception message now has a connection information string at its end. See issue #1155.
Added support for passing a WBEMConnection object for the handle parameter of the MOFCompiler creation. This allows a user to pass the WBEM connection directly as a CIM repository, without first having to create a MOFWBEMConnection object.
Made the namespace handling in the pywbem mock support explicit. It is now required to add any namespaces to the mock registry in a FakedWBEMConnection object. A method add_namespace() has been added for easy setup of the mock repository w.r.t. namespaces. The default namespace of the connection is added automatically when creating a FakedWBEMConnection object.
Extended the support for handling namespace creation in the faked CreateInstance operation to support CIM_Namespace in addition to PG_Namespace, and improved it to properly reflect the created namespace in the mock repository.
Added support for handling namespace deletion in the faked DeleteInstance operation for creation classes CIM_Namespace and PG_Namespace.
Added support for asterisks in CIM datetime values to the pywbem.CIMDateTime class, as defined in DSP0004 for representing insignificant digits. Changed the format returned by its __repr()__ method so that it now shows its internal attributes and no longer the string representation of the value. Added a __repr__() method to the pywbem.MinutesFromUTC class that shows its internal attributes. See issue #1379.
Added an instances property to the CIMError exception class that can be used to represent a list of error instances returned by the WBEM server in error responses. See issue #1380.
Pywbem now ensures that when specifying the default_namespace argument of WBEMConnection() as None, or when setting the default_namespace attribute of an already existing WBEMConnection object to None, that it is set to the built-in default namespace “root/cimv2”, instead. Previously, that was done only when not specifying the default_namespace argument.
All exception and warning messages produced by pywbem now are guaranteed to contain only ASCII characters. Unicode characters in the messages are represented using an escape syntax such as \uXXXX or \U00XXXXXX. That was also done for the result of any __repr__() methods of pywbem. This is important in order to avoid secondary Unicode encoding exceptions while a first exception or warning is processed. See issue #1072.
Docs: Added summary tables for public methods and public attributes exposed by classes defined by the “pywbem” and “pywbem_mock” Python packages, including any methods and attributes inherited from base classes. See issue #1417.
Improved the brand and version attributes of the WBEMServer class so that they produce reasonable results for more types of WBEM servers than just OpenPegasus and SFCB. The WBEM servers that are now recognized, are:
"OpenPegasus"
"SFCB"
(Small Footprint CIM Broker)"WBEM Solutions J WBEM Server"
"EMC CIM Server"
"FUJITSU CIM Object Manager"
See issue #1422.
Added __str__() methods to the WBEMServer, WBEMListener, and WBEMSubscriptionManager classes in order to reduce the amount of information. Previously, this defaulted to the result of __repr__(). See issue #1424.
Improved the quality of any ParseError exception messages when the SAX parser detects errors in CIM-XML responses. See issue #1438.
Added a ToleratedServerIssueWarning class and its base class Warning. The new ToleratedServerIssueWarning is raised in cases when the WBEM server exhibits some incorrect behavior that is tolerated by pywbem.
Added a ModelError exception class that indicates an error with the model implemented by the WBEM server, that was detected by the pywbem client.
Added support for tolerating ill-formed XML in the CIM-XML response returned by the server from the attempt to invoke the CIM method GetCentralInstances() inside of WBEMServer.get_central_instances(). One server was found to return such ill-formed XML. This now causes pywbem to issue a ToleratedServerIssueWarning and to continue with the next approach for determining the central instances. See issue #1438.
The last_raw_request and last_raw_reply properties of WBEMConnection had previously only been set when debug was enabled on the connection. They are now always set. This was needed to support tolerating ill-formed XML, and does not cost any additional conversions. See issues #1438 and #1568.
In the WBEMServer class, the Interop namespace is now added to the set of namespaces in the namespaces property, if missing there. This accomodates the behavior of a particular WBEM server that was found to support the Interop namespace without representing it as a CIM instance. See issue #1430.
Added support for specifying the reference direction in WBEMServer.get_central_instances() by adding an optional parameter reference_direction. This was necessary because the DMTF ‘Profile Registration Profile’ (PRP) and the SNIA PRP use the CIM_ReferencedProfile association class in opposite ways: The DMTF PRP defines that the ‘Dependent’ end of that class goes to the referencing profile which is defined to be the autonomous profile, while the SNIA PRP defines that the ‘Antecedent’ end goes to the autonomous profile. See issue #1411.
In order to be able to distinguish errors at the CIM-XML level (e.g. required attribute missing on an XML element) and at the XML level (e.g. ill-formed XML), two subclasses of the ParseError exception have been added: CIMXMLParseError and XMLParseError, that are now raised instead of ParseError. Because these are subclasses, this change is backwards compatible for users that have caught ParseError. The new subclasses have the CIM-XML request and response data available as properties.
The WBEMServer.get_selected_profiles() method has been changed to match the registered names, organisations and versions of profiles case insensitively, in order to better deal with profile name changes in SMI-S. See issue #1551.
Docs: Clarified in the WBEMServer.get_central_instances() method that all profiles scoped by a top-level specification or autonomous profile implement the same reference direction (‘snia’ or ‘dmtf’).
Docs: The WBEMServer.get_central_instances() method had a description of the profile advertisement methodologies that was hard to understand without knowledge of some of the related DMTF standards. Changed that to make it understandable for pywbem users without requiring knowledge of these documents. Some of the text has been moved to a new section “Profile advertisement methodologies” in the Appendix of the pywbem documentation. As part of that, clarified how to determine the scoping class and scoping path for a component profile that does not specify them in the profile description. See issue #1398.
Corrected the hint how to exit in wbemcli when running on Windows.
Added method to statistics (class Statistics, method reset()) to reset the statistics on a WBEMConnection. This simply resets all of the statistics values gathered on that connection to their initial values.
Cleanup:
- Moved class NocaseDict into its own module (Issue #848).
- Resolved several Pylint issues, including several fixes (Issue #1206).
- Cleanup mof_compiler use of args[0] and args[1] with CIMError. (Issue #1221)
- Removed one level of superflous copies of dictionaries in the copy() methods of the CIM object classes. These dictionaries are already copied in the setter methods for the respective attributes (Issue #1251).
- Added and improved CIM-XML response checks at operation level (Issue #919).
- Changed some warnings classified as UserWarning to be classified as pywbem.ToleratedServerIssueWarning, because that better fits the nature of the warnings. See issue #1595.
- Removed the Connection ID from any exception and warning messages, so that Python warnings about the same thing are now properly folded together into one warning during end2end tests. The exception objects still contain the connection ID as a property conn_id, and the pywbem log also still shows the connection ID for each entry. See issue #1589.
Build, test, quality:
- Add tests for the WBEMSubscriptionManager class using the pywbem mock support. This involved changing the tests for the WBEMServer class using pywbem_mock because the the WBEMSubscriptionManager class depends on the existence of the classes and instances that support the pywbem WbemServer class existing in the WBEM server. A new file (wbemserver_mock.py) was added to the tests that creates the pywbem_mock for any tests that depend on classes like CIM_Namespace, CIM_ObjectManager existing in the mocked server. See issue #1250
- Needed to upgrade PyYAML version from >=3.12 to >=3.13 due to an issue in PyYAML on Python 3.7, that was fixed in PyYAML 3.13. See issue #1337.
- Pinned the version of the pytest-cov package to <2.6 due to the fact that pytest-cov 2.6.0 has increased its version requirement for the coverage package from coverage>=3.7.1 to coverage>=4.4. That is in conflict with the version requirement of python-coveralls for coverage==4.0.3. This is only a workaround; An issue against python-coveralls has been opened: https://github.com/z4r/python-coveralls/issues/66
- Reorganized the testsuite directory to better separate unit tests, function tests, end2end tests, and the tested areas (pywbem, pywbem_mock, and test utility functions). The new top level test directory is now named tests and the new directrory structure is documented in section “Testing” in the development section of the pywbem documentation and in the file tests/README.
- Added the concept of end2end tests for pywbem. The end2end tests execute test files named test_*.py within the tests/end2endtest directory against groups of real WBEM servers defined by a WBEM server definition file in YAML syntax: tests/server_definitions/server_definition_file.yml. There is an example file example_server_definition_file.yml. There are some initial tests, and users can define their own tests.
- For the end2end tests, added a file tests/profiles/profiles.yml that defines the discovery-related characteristics of a number of DMTF and SNIA management profiles, and that is used to drive profile discovery related tests against WBEM servers.
- Added toleration support in the CIM-XML response parsing for WBEM servers that return attribute TYPE with an empty string instead of omitting it. As part of that, improved the checking for valid values of the TYPE attribute. See issue #1564.
- Improved testing of the tocimxml() and tocimxmlstr() methods of the CIM object classes (e.g. CIMinstance) by adding validation against the CIM-XML DTD, and by adding tests for the indent parameter of tocimxmlstr().
- Added support for running pylint also on Python 3.x. See issue #1640.
- Improved the makefile for use on native Windows. See issue #1631. Details:
- Some GNU make versions on native Windows have an issue with double quotes in make $(shell ..) commands; removed the use of double quotes. As a result, most inline python commands have been moved into new small scripts in the tools directory. Also, several make targets that used to produce log files, no longer can do that and the user needs to redirect the make invocation in order to get a log file.
- Removed dependencies on most UNIX-like commands (touch, tee, bash, rm, find, xargs) when using make on native Windows.
- Encapsulated file removal and copy commands to be compatible between native Windows and other platforms.
- Updated the appveyor.yml file to check only the new, smaller, list of commands.
pywbem 0.12.0¶
Released: 2018-04-11
Incompatible changes:
Finalized the Iter support that was experimental so far. This affects the Iter…() methods of class WBEMConnection, the use_pull_operations init parameter and instance attribute of class WBEMConnection, and the iter-related shortcuts in the wbemcli script.
The following initialization parameters of some CIM object classes that are required not to be None (as per the documentation) are now enforced not to be None, and ValueError is now raised when providing them as None:
- CIMInstanceName.classname (already raised ValueError)
- CIMInstance.classname
- CIMClassName.classname (previously raised TypeError)
- CIMClass.classname
- CIMProperty.name (already raised ValueError)
- CIMMethod.name (previously raised TypeError)
- CIMParameter.name
- CIMParameter.type
- CIMQualifier.name
- CIMQualifierDeclaration.name
- CIMQualifierDeclaration.type
Unless otherwise noted, the previous behavior was to tolerate None.
Note that in all cases, the requirement not to be None had previously been documented.
When setting some attributes of CIM object classes that are required not to be None (as per the documentation), ValueError is now raised when attempting to set them to None:
- CIMInstanceName.classname
- CIMInstance.classname
- CIMClassName.classname
- CIMClass.classname
- CIMProperty.name
- CIMMethod.name
- CIMParameter.name
- CIMParameter.type
- CIMQualifier.name
- CIMQualifierDeclaration.name
- CIMQualifierDeclaration.type
The previous behavior was to tolerate None.
Note that in all cases, the requirement not to be None had previously been documented.
When initializing objects of the CIM object classes CIMProperty and CIMQualifier with a type parameter of None, and when initializing the properties of CIMInstance, their CIM type is (and has previously been) inferred from the value.
If inferring the type is not possible (for example because the value is a Python integer, float, long (Python 2 only), or None), the exception that is raised is now ValueError. Previously, TypeError was raised in that case.
When setting the type attribute of the CIM object classes CIMProperty and CIMQualifier, the type is now enforced not to be None, and ValueError is raised when providing it as None.
Previously, setting a type of None was tolerated.
Note that in both cases, the requirement not to be None had previously been documented.
For CIM elements passed as dictionaries into CIM object classes (i.e. the aparameters/attributes properties, keybindings, parameters, qualifiers), the consistency between the dictionary key and the name of the CIM object that is the dictionary value is now checked and ValueError is raised if it does not match (case insensitively).
Initializing a CIMProperty object as an embedded object or embedded instance and with a value of None now requires specifying type=”string”.
Previously (but only starting with pywbem 0.8.1), the type was inferred from the embedded_instance parameter and thus could be omitted. This new requirement for specifying type is not really intentional, but a by-product of simplifying the implementation of CIMProperty. It was considered acceptable because that should not be a common case (and has not been supported before pywbem 0.8.1 anyway).
When converting a CIMInstance object to CIM-XML using its tocimxml() method, instance properties whose values are simple types instead of CIMProperty objects are no longer converted into CIMProperty objects because that has worked only for a very limited set of cases, and because they are required to be CIMProperty objects anyway. A TypeError is now raised if that is detected.
The atomic_to_cim_xml() function now raises TypeError if it cannot convert the input value. Previously, it used str() on the input value as a last resort.
The global tocimxml() function now raises TypeError if it cannot convert the input value. Previously, it raised ValueError.
The CIMQualifierDeclaration.tomof() method now generates the flavor keywords only if the tosubclass and overridable attributes are set to True or False. Previously, default keywords were generated when these attributes were set to None (and these defaults were the opposite of the defaults defined in DSP0004 and DSP0201). The new behavior is consistent with the definition that None for these attributes means the information is not available, and it is also consistent with the tocimxml() method. If you used this method and relied on the defaults being generated, you will now have to set these attributes explicitly.
If a WBEM server specifies contradicting TYPE and VALUETYPE attributes on a KEYVALUE element returned to the client (this element is used in instance paths, e.g. for the result of the EnumerateInstanceNames operation), TYPE now takes precedence. Previously, VALUETYPE took precedence. DSP0201 leaves the handling of such discrepancies open, and it seems more logical to let the more precise value take precedence. Because WBEM servers are required to specify consistent values for these attributes, this change should not affect users of pywbem.
Values of CIM type ‘reference’ in CIM objects (CIMProperty, CIMParameter, CIMQualifier, and CIMQualifierDeclaration) may now be CIMClassName objects (i.e. class paths). This has been changed for consistency with DSP0201 (Issue #1035).
Renamed the enable_stats init argument of class WBEMConnection to stats_enabled, as part of its finalization. It was experimental, before. (Issue #1068).
Renamed the -e, –enable-stats options of the wbemcli utility to –statistics , as part of its finalization. It was experimental, before. (Issue #1068).
Changed the WBEMConnection attributes for the last request and last response to become read-only (last_request, last_raw_request, last_reply, last_raw_reply). They have never been supposed to be writeable by users. (Issue #1068).
In the wbemcli shell, renamed the following function parameters. This is only relevant if you wrote scripts against the shell and named these parameters: (Issue #1110).
- The “op” parameter of iter functions that have it was renamed to “ip”, because it is always an instance path.
- The “qi” parameter of the query functions was renamed to “qs”, for consistency with the filtering functions.
- The “fq” parameter of the filtering functions was renamed to “fs”, for consistency with the query functions.
Revamped the (experimental) logger configuration mechanism completely. It remains experimental. See issue #859. The changes include:
- Created 3 methods in WBEMConnection that allow pywbem logs to be configured and activated. These methods contain parameters for: a. configuring the Python loggers for either/or/both the api and http loggers. b. Setting the level of detail in the log output. c. Activating each logger within WBEMConnection.
- Allow for the standard Python loggers to be used to configure logger names that will be used by the pywbem loggers. This allows the pywbem loggers to be compatible with user code that creates their specific logger configurations.
- Eliminated the PyWBEMLogger class that was the original logging setup tool in pywbem 0.11.0 since its use was incompatible with using standard Python logging configuration methods to define loggers.
- Created a function in the _logging module that allows pywbem logging to be defined by a single string input.
- Addition of a new property conn_id to WBEMConnection which is a unique identifier for each WBEMConnection object and is part of each log record. This allows linking logs for each WBEMConnection in the log.
Deprecations:
- Deprecated modifications of the connection-related attributes of WBEMConnection objects (Issue #1068).
- Deprecated the value None for the value argument of pywbem.tocimxml(), because it generates an empty VALUE element (which represents an empty string) (Issue #1136).
Enhancements:
- Finalized the time statistics support that was experimental so far. This affects classes OperationStatistic, Statistics, the init argument enable_stats of class WBEMConnection, and the properties stats_enabled, statistics, last_operation_time, and last_server_response_time of class WBEMConnection. As part of that, renamed the enable_stats init argument to stats_enabled, consistent with the corresponding property.
- For CIMInstanceName, the values of keybindings can now be specified as CIMProperty objects from which their value will be used (this is in addition to specfying the values of keybindings as CIM data types).
- For CIMInstanceName, values of keybindings specified as binary strings are now converted to Unicode.
- For CIMInstanceName, the type of the input keybindings is now checked and TypeError is raised if the value is not a CIM data type.
- Updating attributes of CIM objects (e.g. updating CIMInstance.properties) now goes through the same conversions (e.g. binary string to unicode string) as for the same-named constructor parameters. As a result, it is ensured that all attributes that are strings (e.g. name) contain unicode strings, all attributes that are booleans (e.g. propagated) contain bool values, and all CIM values (e.g. CIMProperty.value) are of a CIM data type.
- Added static from_wbem_uri() methods to CIMInstanceName and CIMClassName, that create a new object of these classes from a WBEM URI string.
- Added a cimvalue() function that converts input values specified at the interface of CIM object classes, into the internally stored CIM value. It is mainly used internally by the CIM object classes, but has also been made available at the public API of pywbem. Its functionality is very close to the existing tocimobj() function.
- Changed public attributes to Python properties with getter and setter methods in all CIM object classes (e.g. CIMInstance). This allows normalizing and applying checks for new values of these properties. In addition, it solves the Sphinx warnings about duplicate ‘host’ attribute when building the documentation (issue #761).
- Added catching of some exceptions M2Cryptro can raise that were not caught so far: SSL.SSLError, SSL.Checker.SSLVerificationError. These exceptions are now transformed into pywbem.ConnectionError and will therefore be caught by a caller of pywbem who is prepared for pywbem’s own exceptions, but not necessarily aware of these M2Crypto exceptions. (issue #891)
- Added the catching of a httplib base exception to make sure all httplib exceptions are surfaced by WBEMConnection methods as a pywbem.ConnectionError (issue #916).
- In the tomof() methods of the CIM object classes, changed the formatting of the generated MOF to be more consistent with the CIM Schema MOF.
- Added new methods CIMInstanceName.to_wbem_uri() and CIMClassName.to_wbem_uri() that return the path as a WBEM URI string that conforms to untyped WBEM URIs as defined in DSP0207. The CIMInstanceName.__str__() and CIMClassName.__str__() methods still return the same WBEM URI string they previously did, but that is a historical format close to but not conformant to DSP0207 (issues #928, #943).
- Improved the way CIM-XML parsing errors are handled, by providing the original traceback information when re-raising a low-level exception as pywbem.ParseError, and re-established the improved exception message for invalid UTF-8 and XML characters that was broken since the move to using the SAX parser.
- Added support for properly hashing CIM objects (CIMClass, etc.) and CIM data types (particularly CIMDateTime), as long as these (mutable) objects are not changed. Because the objects must not be changed while being in a set, a new term “changed-hashable” has been introduced that describes this. This allows to have CIM objects in sets such that they behave as one would expect from a set. Previously, two CIM objects that were equal could both be in the same set, because their hash value was different. In the documentation, added a new section “Putting CIM objects in sets” that explains the considerations when utilizing the hash value of the mutable CIM objects.
- Added support for retrieving the operation recorders of a connection via a new operation_recorders read-only property (Issue #976).
- Extended CIMParameter to represent CIM parameter values in method invocations. As part of that, removed the deprecation from its value property and added an embedded_object property. Extended the testcases accordingly. Added an as_value argument to CIMParameter.tocimxml() and to tocimxmlstr() to allow control over whether the object is interpreted as a value or as a declaration. (Issue #950).
- Added a new conversion function to the public API: cimtype() takes a CIM data typed value (e.g. Uint8(42)) and returns the CIM data type name for it (e.g. “uint8”). Previously, this was an internal function (Issue #993).
- Added a new conversion function to the public API: type_from_name() takes a CIM data type name (e.g. “uint8”) and returns the Python type representing that CIM data type (e.g. Uint8). Previously, this was an internal function (Issue #993).
- Extended WBEMConnection.InvokeMethod() to accept an iterable of CIMParameter objects as input parameters, in addition to the currently supported forms of input parameters. This allows specifying the embedded_object attribute (instead of inferring it from the value). (Issue #950).
- Docs: Improved the descriptions of CIM objects and their attributes to describe how the attributes are used to determine object equality and the hash value of the object.
- The child elements of CIM objects (e.g. properties of CIMClass) now preserve the order in which they had been added to their parent object. Methods such as tomof(), tocimxml(), and to_wbem_uri() now output the child elements of the target object in the preserved order. If a child element is initialized with an object that does not preserve order of items (e.g. a standard dict), a UserWarning is now issued.
- Added a new kind of input object for initializing CIM objects: An iterable of the desired CIM object type, and documented the already supported iterable of tuple(key, value) as a further input type.
- Improved checking of input objects when initializing a list of child elements in a CIM object(e.g. properties of CIMClass), and raise TypeError if not supported.
- Made the ValueMapping class more generally available and no longer tied to the WBEMServer class. It is now described in the “Client” chapter of the documentation, and it is possible to create new ValueMapping objects by providing a WBEMConnection object (as an alternative to the WBEMServer object that is still supported, for compatibility). Issue #997.
- Extended the ValueMapping class; its objects now remember the context in which the value mapping is defined, in terms of the connection, namespace, class, and of the mapped CIM element (i.e. property, method or parameter).
- Extended the ValueMapping class by adding a __repr__() method that prints all of its attributes, for debug purposes.
- Added capability to mock WBEM Operations so that both pywbem and pywbem users can create unit tests without requiring a working WBEM Server, This feature allows the user to create CIM objects in a mock WBEM Server defined with the class FakedWBEMConnection and substitute that class for WBEMConnection to create a mock WBEM Server that responds to wbem operations. This enhancement is documented in the pywbem documentation section 10, Mock Support. See issue #838.
- Improved the messages in ParseError exceptions raised when parsing CIM-XML received from a WBEM server.
- The type of keybinding names in CIMInstanceName objects is now checked to be a string (or None, for unnamed keys). The requirement for a string has always been documented. This was changed as part of addressing issue #1026.
- Fixed the support for unnamed keys (i.e. instance paths with KEYVALUE or VALUE.REFERENCE elements without a parent KEYBINDINGS element). DSP0201 allows for this as a special case. (Issue #1026).
- Added support for instance qualifiers when parsing received CIM-XML responses (Issue #1030).
- CIM data type names specified for the type or return_type parameter of CIM objects are now checked for validity, and ValueError is raised if not valid (Issue 1043).
- Added a new method CIMInstanceName.from_instance() to create CIMInstanceName objects from class and instance. This was done as part of building the pywbem_mock environment. See issue #1069.
- The url property of WBEMConnection now transforms its input value to unicode. (Issue #1068).
- In the WBEMListener class, added support for using it as a context manager in order to ensure that the listener is stopped automatically upon leaving the context manager scope.
- In the WBEMListener class, added properties http_started and https_started indicating whether the listener is started for the respective port.
- CIMInstance.tocimxml()/tocimxmlstr() were extended to allow controlling whether the path is ignored even if present. This capability is used for ignoring the path in embedded instance parameter values (as part of fixing issue #1136).
- CIMInstanceName/CIMClassName.tocimxml()/tocimxmlstr() were extended to allow controlling whether the host and namespace are ignored even if present. This capability is not currently used but was introduced for consistency with ignoring the path on CIMInstance.tocimxml()/tocimxmlstr() (as part of fixing issue #1136).
- Improved the handling of certain connection errors by retrying and by issuing user warnings instead of printing if debug. (Issue #1118).
Bug fixes:
Added libxml2 operating system package as a dependency. It provides xmllint, which is used for testing.
Fixed issue where MOFCompiler.compile_str() could not compile MOF that was defined through a MOF file containing #pragma include statements. This precluded using a string to define the classes to include in a mof compile in a string and required that the include be a file. See issue #1138.
Fixed issue in IterReferenceNames and IterAssociatiorNames where it was not passing the IncludeQualifiers input parameter to the OpenReferenceNames operation. This should not have been a significant issue since in general qualifiers are not parts of instances. See issue #833.
Also changed code in IterQueryInstances were parameters that are required by the called ExecQuery and OpenQueryInstances were defined as named arguments where since they are required, the name component is not required. This should not change operations except that when we were mocking the methods, it returns sees the parameter as name=value rather than value. See issue #833.
Fixed the bug that CIMInstanceName.tocimxml() produced invalid CIM-XML if a keybinding value was set to an invalid CIM object type (e.g. to CIMParameter). The only allowed CIM object type for a keybinding value is CIMInstanceName, for keys that are references. Now, TypeError is raised in that case.
Fix issues in cim_operations.py where a open or pull that returned with missing enumeration_context and eos would pass one of the internal tests. See issue #844
Fixed an error in the CIM-XML representation of qualifier values where the values were not properly converted to CIM-XML. They are now properly converted using atomic_to_cim_xml().
Fixed local authentication for OpenWBEM and OpenPegasus. Due to one bug introduced in pywbem 0.9.0, it was disabled by accident. A second bug in local authentication has been there at least since pywbem 0.7.0.
Fixed missing exception handling for CIM-XML parsing errors when parsing embedded objects. This could have caused low-level exceptions to be raised at the pywbem API.
Fixed the problem that a for-loop over CIMInstance / CIMInstanceName objects iterated over the lower-case-converted property/key names. They now iterate over the names in their original lexical case, as documented, and consistent with the other iteration mechanisms for CIM objects. The test cases that were supposed to verify that did not perform the correct check and were also fixed.
Fixed the bug that an (unsupported!) reference type could be specified for the return value of CIM methods, by raising ValueError if CIMMethod.return_value is initialized or set to “reference”.
Fixed issue introduced in mof_compiler when atomic_to_cimxml was cleaned up that did not allow using alias with some association classes. Also added test for this issue. See issue #936
Fixed the CIMInstanceName.__str__() and CIMClassName.__str__() methods to now return WBEM URI strings that are compliant to DSP0207. Changes include:
- Local WBEM URIs (i.e. when authority/host is not set) now have a leading slash. That leading slash was previously omitted.
- WBEM URIs with no namespace set now have a colon before the class name. Previously, the colon was produced only when a namespace was set.
Issue #928.
Fixed the comparison of CIMProperty objects to also consider the embedded_object attribute. Previously, this attribute was not considered, probably due to mistake (there is no reason not to consider it, as it is a user-provided input argument). Fixed the yaml testcases for embedded objects that failed as a result of that fix. These testcases did not set the embedded_object attribute to ‘object’, so it got its default value ‘instance’, which caused the testcases to fail. Needed to use the long form for specifying property values inthe yaml now, because the short form does not allow for specifying the embedded_object attribute.
Fixed the comparison of CIMProperty and CIMMethod objects to compare their class_origin attribute case-insensitively. If set, it contains a CIM class name. Previously, that attribute was compared case-sensitively.
Fixed the use of hard coded value limits in the ValueMapping class for open ranges of the ValueMap qualifier, by making them dependent on the data type of the qualified element. This only affected elements with data types other than Uint32 and only if the ValueMap qualifier defined open ranges whose open side reached the min or max limit (i.e. was first or last in the list). Extended the test cases to include this situation (Issue #992).
Fixed the lookup of the Values string for negative values in the ValueMapping class (found when solving #992).
Added support for octal, binary and hex numbers when parsing MOF using the MOFCompiler class, in compliance with DSP0004 (Issue #974). Extended the testcases to cover such numbers.
Fixed the issue that any use of CIMDateTime objects in the TestClientRecorder resulted in a RepresenterError being raised, by adding PyYAML representer and constructor functions that serialize CIMDateTime objects to YAML. Extended the testcases in test_recorder.py accordingly (Issues #702, #588).
Fixed an AttributeError when ValueMapping was used for methods, when an internal method attempted to access the ‘type’ attribute of the CIM object. For methods, that attribute is called ‘return_type’. Testcases for methods and parameters have now been added.
Fixed the issue that leading and trailing slash characters in namespace names were preserved. This was leading to empty NAMESPACE/NAME elements, which can be rejected by WBEM servers. Now, leading and trailing slash characters on namespace names are stripped off in pywbem before sending the request to the server. (Issue #255).
Fixed the issue that the parser for CIM-XML received from the WBEM server required the VALUETYPE attribute of the KEYVALUE element. DSP0201 defines VALUETYPE as optional, with a default of ‘string’. That is now implemented.
Fixed the issue that the parser for CIM-XML received from the WBEM server did not support hexadecimal representations of integers in the KEYVALUE element. They are now supported.
Fixed the issue that the parser for CIM-XML received from the WBEM server accepted characters for char16 typed values outside of the range for UCS-2 characters. Such characters are now rejected by raising ParseError.
Fixed the issue that the parser for CIM-XML received from the WBEM server tolerated invalid child elements under INSTANCE, ERROR and PROPERTY.REFERENCE elements, and invalid attributes on the PROPERTY.ARRAY element. This now results in a ParseError being raised.
Fixed the issue that the parser for CIM-XML received from the WBEM server did not set the propagated attribute to False in CIMProperty objects retrieved from operations (e.g. as part of a class or instance), as required by DSP0201. It does now.
Fixed the issue that VALUE.NULL (for representing array items that are NULL) was not supported in array values returned by the WBEM server. Note that it already had been supported for array values sent to the server, or in CIM-XML created by toximcml() methods (Issue #1022).
Fixed the issue that the size of a fixed-size array property declaration was ignored when retrieving classes from CIM operations. It is now represented in the array_size attribute of the returned CIMProperty objects. (Issue #1031).
Fixed the issue that the xml:lang attributes that are allowed on some CIM-XML elements have been rejected by raising ParseError. They are now tolerated but ignored (Issue #1033).
Fixed the issue that mixed case values (e.g. “True”) for the boolean attributes of the QUALIFIER element in CIM-XML was not supported and resulted in ParseError to be raised (Issue #1042).
Fixed the issue that an empty boolean value in a CIM-XML response returned from a WBEM server was accepted and treated as a NULL value. This treatment does not conform to DSP0201. Empty boolean values now cause a UserWarning to be issued, but otherwise continue to work as before. (Issue #1032).
Fixed the issue that invalid values were accepted for the boolean attributes of the SCOPE element in CIM-XML received from a WBEM server. They now cause ParseError to be raised (Issue #1040).
Fixed the issue that invalid values for the boolean attributes of QUALIFIER.DECLARATION elements in CIM-XML responses from WBEM servers were tolerated and treated as False. They now cause ParseError to be raised (Issue #1041).
Fixed the incorrect default value for the propagated constructor parameter of CIMMethod. Previously, the default value was False and it has been corrected to be None, consistent with its meaning of “information not available”. The only CIM operations that take a CIMMethod object as input are CreateClass() and ModifyClass() (as part of the class that is created or modified). Because WBEM servers must ignore the propagated information on any elements in the provided class, this change is backwards compatible for the CIM operations. (Issue #1039).
Added support for setting the propagated attribute on CIMQualifier objects returned from CIM operations to a default of False when it is not specified in the CIM-XML response, consistent with DSP0201, and consistent with how it was already done for other CIM objects. This change should normally be backwards compatible for pywbem users, because they don’t even know whether the information has been set by the server or defaulted by the client as it is now done. (Issue #1039).
Added support for setting the flavor attributes on CIMQualifier and CIMQUalifierDeclaration objects returned from CIM operations to their default values defined in CIM-XML, when they are not specified in the CIM-XML response, consistent with DSP0201, and consistent with how it was already done for other CIM objects. This change should normally be backwards compatible for pywbem users, because they don’t even know whether the information has been set by the server or defaulted by the client as it is now done. (Issue #1039).
In the wbemcli shell, fixed the “*params” parameter of the im() function, to become “params” (an iterable). (Issue #1110).
For the InvokeMethod operation, fixed that passing Python None as an input parameter valus resulted in TypeError. Extended the testclient testcases for InvokeMethod accordingly. Documented that None is a valid CIM typed value (Issue #1123).
Fixed the error that embedded instances in parameter values were incorrectly represented with the CIM-XML element corresponding to their path (e.g. VALUE.NAMEDINSTANCE). The path is now correctly ignored on embedded instance parameter values, and they are always represented as INSTANCE elements (Issue #1136).
Fixed the error that CIMInstance.tocimxml()/tocimxmlstr() represented its instance path always with a VALUE.NAMEDINSTANCE element and generated incorrect child elements depending which components of the instance path were present. Now, the element for the path depends correctly on the components that are present in the instance path (Issue #1136).
Fixed the missing support for generating a VALUE.INSTANCEWITHPATH element in CIM-XML. This is needed when a CIMInstance with path has namespace and host. This error was previously now showing up because the VALUE.NAMEDINSTANCE element was always created (Issue #1136).
Fixed the error that the tocimxml() and tocimxmlstr() methods of CIMProperty, CIMQualifier and CIMQualifierDeclaration represented NULL entries in array values using an empty VALUE element. They now correctly generate the VALUE.NULL element for NULL entries (Issue #1136). In order to provide for backwards compatibility to WBEM servers that do not support VALUE.NULL, a config option SEND_VALUE_NULL was added that by default sends VALUE.NULL, but allows for disabling that (Issue #1144).
Fixed the error that the special float values INF, -INF and NaN were represented in lower case in CIM-XML. DSP0201 requires the exact case INF, -INF and NaN (Issue #1136).
Fixed the error that float values in CIM-XML were truncated to six significant digits. They now have at least the minimum number of significant digits required by DSP0201: 11 for real32, and 17 for real64. (Issue #1136).
In the WBEMServer.get_central_instances() method, fixed the error that a CIM status code of CIM_ERR_METHOD_NOT_FOUND returned when attempting to invoke the GetCentralInstances() CIM method lead to failing the get_central_instances() method. Now, execution continues with attempting the next approach for determining the central instances (Issue #1145).
In the mof_compiler.bat script file, fixed the issue that it did not return an exit code if the MOF compiler failed (Issue #1156).
Several fixes and display related improvements in the mof_compiler script: MOF file not found is now also handled instead of failing with an exception traceback. Exceptions are now displayed before exiting. Dry-run mode is now displayed, for information. The target MOF repository is now always displayed; previously it was displayed only in verbose mode. (Issue #1157).
Cleanup:
- Removed the unimplemented and unused popitem() method of NocaseDict.
- The atomic_to_cim_xml() function and any generated CIM-XML now generates boolean values in upper case ‘TRUE’ and ‘FALSE’, following the recommendation in DSP0201. Previously, boolean values were produced in lower case. This change is compatible for WBEM servers that meet the requirement of DSP0201 to treat boolean values case-insensitively.
- Cleaned up the implementation of CIMProperty/CIMParameter.tocimxml(), so that it is now easier understandable (as part of fixing issue #1136).
- Removed any logging.NullHandler objects on pywbem loggers, including the pywbem listener loggers, because it turns out that for the use of loggers as a trace tool, the DEBUG level is used by the pywbem client and the INFO level is used by the pywbem listener, which are both not printed by default by the Python root logger, so the use of null handlers is not really needed (Issue #1175).
Build, test, quality:
Added a boolean config variable DEBUG_WARNING_ORIGIN that when enabled causes a stack traceback to be added to the message of most warnings issued by pywbem. This allows identifying which code originated the warning.
Cleaned up a lot of pylint warnings, for things like missing-doc, etc. so that we can actually review the remainder. See issue #808.
Update to current DMTF Schema (2.49.0) for pywbem tests. This also validates that pywbem can compile this DMTF released schema. See issue #816
Add unit tests for the iter… operations. See issue #818
Migrated installation and development setup to use pbr and Pip requirements files. As a consequence, removed files no longer used: os_setup.py, uninstall_pbr_on_py26.py.
Added ability to test with minimum Python package level, according to the package versions defined in minimum-constraints.txt.
Fixed a setup issue on Travis CI with duplicate metadata directories for the setuptools package. This issue prevented downgrading setuptools for the test with minimum package levels. Added script remove_duplicate_setuptools.py for that.
Reorganized the make targets for installing pywbem and its dependencies somewhat. They now need to be used in this order:
- make install - installs pywbem and dependencies for runtime
- make develop - installs dependencies for development
There are two new targets (that are included in the targets above, when first run after a make clobber):
- make install_os - installs OS-level dependencies for runtime
- make develop_os - installs OS-level dependencies for development
Enabled testing on OS-X in the Travis CI.
Added unit test for WBEMServer class using pywbem_mock. See the file testsuite/test_wbemserverclass.py. This test is incomplete today but tests most of the main paths.
Documentation:
Improved the complete pywbem documentation (Issue #1115). Some specific changes are listed in the remainder of this section.
- The installation for Windows on Python 2.7 now requires an additional manual step for installing the M2CryptoWin32/64 Python package. For details, see the Installation section in the documentation.
- Fixed the documentation of the CIMInstanceName.keybindings setter method, by adding ‘number’ as an allowed input type.
- Moved the detail documentation of input to child element lists (e.g. for properties of CIMInstance) as a data type ‘properties input object’, etc., into the glossary. These types are now referenced as the type of the corresponding parameter.
- Clarified that the return type of BaseOperationRecorder.open_file() is a file-like object and that the caller is responsible for closing that file.
- Clarified in the description of the return_type init parameter of CIMMethod that array return types, void return types, and reference return types are all not supported in pywbem. See issue #1038, for void.
- Fixed the type string for the keys of the CIMInstance.qualifiers attribute to be unicode string.
- Many clarifications for CIM objects, e.g. about case preservation of CIM element names, or making copies of input parameters vs. storing the provided object.
- Improved the description of the WBEMConnection.ModifyInstance() method.
- Improved the description of the tocimxml() and tocimxmlstr() methods on CIM objects.
- Clarifications and small fixes in the documentation of the WBEMConnection.Iter…() generator functions.
- Added “New in pywbem M.N …” text to descriptions of anything that was introduced in pywbem 0.8.0 or later.
- Clarified use of ca_certs parameter of WBEMConnection and its defaults in DEFAULT_CA_CERT_PATHS.
- Clarified that the instance path returned by the CreateInstance() operation method has classname, keybindings and namespace set.
- For CIM floating point types (real32, real64), added cautionary text for equality comparison and hash value calculation.
- Clarified that CIM-XML multi-requests are not supported by pywbem and why that is not a functional limitation.
- In the wbemcli shell, improved and fixed the description of operation functions (Issue #1110).
- Improved and fixed the description of WBEMConnection operation methods (Issue #1110).
- Improved and fixed the description of the pywbem statistics support (Issue #1115).
- Clarified the use of logging for the pywbem client (in section 4.8 “WBEM operation logging”) and for the pywbem listener (in section 6.1.2 “Logging in the listener” (Issue #1175).
pywbem 0.11.0¶
Released: 2017-09-27
This version contains all fixes up to pywbem 0.10.1.
Incompatible changes:
None
Enhancements:
Added support for automatically finding out whether for RHEL/CentOS/Fedora, the IUS version of the Python development packages should be used, dependent on whether the Python package is from IUS.
Added the MOF compiler API to the
pywbem
namespace. For compatibility, it is still available in thepywbem.mof_compiler
namespace. See issue #634.Modify the pattern used for cim_operation.py request methods from using except/else to use except/finally to reduce number of places code like the recorder call and future statistics, log, etc. calls have to be included. No other functional changes. See issue #680
Add operation statistics gathering experimental. Adds the class Statistics which serves as a common place to gather execution time and request/reply size information on server requests and replies. The detailed information is available in WBEMConnection for operation execution time and request/reply content size at the end of each operation.
When statistics gathering is enabled, the information is placed into the Statistics class where min/max/avg information is available for each operation type. Statistics gathering is enabled if the WBEMConnection attribute enable_stats is True.
Statistics can be externalized through the snapshot method of the Statistics class.
The functionality is marked experimental for the current release
See issue #761
Extended development.rst to define how to update dmtf mof and move thevariables for this process from test_compiler.py to a separate file to make them easy to find. See issue #54
Changed CIMInstancename.__repr__() to show the key bindings in the iteration order, and no longer in sorted order, to better debug iteration order related issues. See issue #585.
Add new notebooks to the tutorials including notebooks for the WBEMServer class, the pull operations, and the Iter operations. See issue #682
Added unit test for recorder. See issue #676
Ensured that CIMDateTime objects for point in time values are timezone-aware when supplied with a timezone-naive datetime object. This does not change the behavior, but increases code clarity. Clarified that in the documentation of CIMDateTime. See issue #698.
Extend the documentation to list support for specific non-specification features of some WBEM servers. Issue #653.
Extend cim_http.py, cim_operations.py, _statistics.py to handle optional WBEMServerResponseTime header from WBEMServer. This HTTP header reports the server time in microseconds from request to response in the operation response. The extension adds the WBEMConnection property last_server_response_time and places the time from the server into the attribute for this property.
Extend pywbem to handle optional WBEMServerResponseTime header from a WBEM server. This HTTP header reports the server time in microseconds from request to response in the operation response. The extension adds the WBEMConnection property last_server_response_time and places the time from the server into the attribute for this property. It also passes server_response_time to statistics so that max/min/avg are maintained. See issue # 687.
Add test for wbemcli script that will execute the script and test results. issue #569
Experimental: Add logging to record information passing between the pywbem client and WBEM servers both for the WBEMConnection methods that drive information interchange and the http requests and responses. Logging includes a new module (_logging.py) that provides configuration of logging. The logging extends WBEMConnection with methods so that the user can chose to log a)Calls and returns from the WBEMConnection methods that interact with the WBEMServer (ex. getClass), b)http request/responses, c)both. The logging uses the python logging package and the output can be directed to either stderr or a file. The user can chose to log the complete requests and responses or size limited subsets (log_detail level). See issue #691.
Clarify documentation on wbem operation recorder in client.rst. see issue #741
Added an optional class path to the CIMClass class, as a convenience for the user in order so that CIMClass objects are self-contained w.r.t. their path. The class path is set in CIMClass objects returned by the GetClass, EmumerateClasses, and the class-level Associators and References operations. The path is added purely on the client side, based on existing information returned from WBEM server. This change does therefore not affect the interactions with WBEM servers at all. issue #349.
Added a
host
property toWBEMConnection
which contains the host:port component of the WBEM server’s URL. This helps addressing issue #349.Made sure that
repr()
on CIM objects produces a reliable order of items such as properties, qualifiers, methods, parameters, scopes, by ordering them by their names. This makes debugging usingrepr()
easier for pywbem users, and it also helps in some unit test cases of pywbem itself.Made sure that
str()
onCIMInstanceName
produces reliable order of key bindings in the returned WBEM URI, by ordering them by key name.
Bug fixes:
- Fix issue with MaxObjectCount on PullInstances and PullInstancePaths CIM_Operations.py methods. The MaxObjectCount was defined as a keyword parameter where it should have been be positional. This should NOT impact clients unless they did not supply the parameter at all so that the result was None which is illegal(Pull… operations MUST include MaxObjectCount). In that case, server should return error. Also extends these requests to test the Pull.. methods for valid MaxObjectCount and context parameters. See issue #656.
- Add constructor parameter checking to QualifierDeclaration. See issue #645.
- Fixed TypeError “‘str’ does not support the buffer interface” during ‘setup.py develop’ on Python 3.x on Windows (issue #661).
- Fixed ValueError “underlying buffer has been detached” during ‘setup.py develop’ on Python 3.x on Windows (issue #661).
- Fixed names of Python development packages for SLES/OpenSUSE.
- Fixed issue in mof_compiler where instance aliases were incomplete. They only included the class component so that if they were used in the definition of other instances (ex. to define an association where a reference property was the aliased instance, the reference path was incomplete.) This is now a path with keybindings. Note: It is the responsibility of the user to make these instances complete (i.e. with all key properties) see issue #679
- Correct documentation issue in cim_obj (Exceptions definition missing). See issue #677
- Add more mock tests. ModifyInstance was missing and some others were missing an error test. issue#61
- add –version option to mof_compiler and pywbem cli tools. Generates the pywbem version string. See issue # 630
- Fix several issues in recorder including issue #609:indent by 4, # 676: invalid yaml representation for namedtuples that result from open/pull operations, #700 and #663: recorder won’t write utf8 (at least for our tests), #698 : datetime test failures because of timezone, Most of these are tested with the new test_recorder.py unit test.
- Fix error in wbemcli with –enable_stats arg. Since this was added in this release, the bug was never public. See issue #709
- Remove extra print in cim_operations. See issue # 704
- Correct Error in run_cimoperations with use of namespace in iter… function See issue #718. This was a test code issue. No changes to the iter operations.
- Correct issue with Recorder creating non-text files. This issue Documents the requirement for text files and also adds a static method to force creation of the recorder output as a text file. See issue # 700
- Correct issue in wbemcli.bat where it was not returning error level. see issue #727
- Correct issue where dependency pip installs end up with old version of coverage package. This old version generates unwanted deprecation messages that are fixed after version 4.03. This requires a change to the travis.yaml file directly to force a reinstall of coverage. See issue #734
- Fixed the issue that
CIMProperty.__init__()
had an incorrect check for thereference_class
parameter, where it checked the class name specified in that parameter to be the creation class of the referenced instance. According to DSP0201, reference_class is the declared class, which can be a superclass of the creation class of the referenced instance. This is related to issue #598 - Modify mof_compiler documentation to indication issues with property names that are compiler keywords. See issue #62.
- Correct issue where dependency pip installs end up with old version of coverage package. This old version generates unwanted deprecation messages that are fixed after version 4.03. This requires a change to the travis.yaml file directly to force a reinstall of coverage. See issue #734
- Fix minor doc issue in client.rst. See issue #740.
- Fixed that older versions of pip and setuptools failed or were rejected on some older Linux distros during make develop or make install, by upgrading them in these steps. See issues #759 and #760.
- Clean up pylint new messages tied to use of len and if else. See issue #770
Build, test, quality:
- Added Python 3.6 to the environments to be tested in Travis CI and Appveyor CI (issue #661).
- Added Python 2.6, 3.4 and 3.5 to the environments to be tested in Appveyor CI (issue #661).
- Fixed uninstall_pbr_on_py26.py to remove ‘pbr’ only if installed (issue #661).
- Fixed TypeError about dict ordering on Python 3.6 in unit test ‘test_nocasedict.TestOrdering’ (issue #661).
- Added a testcase for CIMInstanceName to compare two objects with different ordering of their key bindings for equality. See issue #686.
- In
parse_property_reference()
intupleparse.py
, a number of attributes of the newCIMProperty
object had been updated after having created it. That bypasses the checks in its__init__()
method. This has been improved to pass these values in when creating the object. - Tolerated incorrect Unicode characters in output of commands invoked by
os_setup.py
(used for installation) that sometimes occurred on Windows (e.g. on the Appveyor CI with Python 3). - Improved the build process to ensure that half-built artefacts are removed before building (issue #754).
- Pinned the version of the wheel package to <0.30.0 for Python 2.6, because wheel removed Python 2.6 support in its 0.30.0 version.
Documentation:
- Documented that pywbem is not supported on Python 2.6 on Windows. and that 64-bit versions of Python are not supported on Windows.
- Added material to README and changed to use restructured text. issue #642
pywbem 0.10.0¶
Released: 2016-12-20
Incompatible changes:
- All methods of the WBEMSubscriptionManager class that returned instance paths (or lists thereof) in pywbem 0.9.x now return the complete instances (or lists thereof) (pr #607).
- In wbemcli, removed the long global function names (e.g. EnumerateInstances), and kept the short names (e.g. ei) (issue #548).
Enhancements:
Experimental: Added new methods to WBEMConnection to provide integrated APIs for the non-pull and pull operations, reducing the amount of code app writers must produce and providing a pythonic (generator based) interface for the methods that enumerate instances and instance paths, enumerator associators and references. These new methods have names in the pattern Iter<name of original function>. Thus, for example the new method IterEnumerateInstances creates a new API to integrate EnumerateInstances and the OpenEnumerateInstancesWithPath / PullInstancesWithPath. (issue #466).
Modified the XML parser to use SAX in place of minidom for operation response processing and indication processing. This is a significant reduction in memory usage (issue #498).
Declared the WBEM indications API and the WBEM server API to be final. These APIs had been introduced in pywbem 0.9.0 as experimental.
Added enter and exit methods to WBEMSubscriptionManager to enable using it as a context manager, whose exit method automatically cleans up by calling remove_all_servers() (issue #407).
Added methods to the operation recorder (class BaseOperationRecorder) for disabling and enabling it (issue #493).
The “Name” property of indication filters created via the WBEMSubscriptionManager class can now be controlled by the user (pr #607).
Indication filter, listener destination and indication subscription instances created via the WBEMSubscriptionManager class, that are “owned”, are now conditionally created, dependent on the owned instances that have been discovered upon restart of the WBEMSubscriptionManager (pr #607).
Modified operations that have a “PropertyList” attribute to allow the “PropertyList” attribute to have a single string in addition to the iterable. Previously this caused an XML error (issue #577).
Added an option -s / –script to wbemcli that supports executing scripts in the wbemcli shell.
Some example scripts are provided in the examples directory:
- wbemcli_server.py - Creates a WBEMServer object named SERVER representing a WBEM server.
- wbemcli_quit.py - Demo of terminating wbemcli from within a script.
- wbemcli_display_args.py - Demo of displaying input arguments.
- wbemcli_count_instances.py - Counts classes and instances in a server.
- wbemcli_clean_subscriptions.py - Removes all subscriptions, filters, and listener destination instances in a server.
- test_wbemcli_script.sh - A shell script that demos scripts.
Improved robustness and diagnostics in os_setup.py (issue #556).
Bug fixes:
- Fixed the use of a variable before it was set in the remove_destinations() method of class WBEMSubscriptionManager.
- Fixed a compatibility issue relative to pywbem 0.7.0, where the pywbem.Error class was no longer available in the pywbem.cim_http namespace. It has been made available in that namespace again, for compatibility reasons. Note that using sub-namespaces of the pywbem namespace such as pywbem.cim_http has been deprecated in pywbem 0.8.0 (issue #511).
- Fixed an AttributeError in the remove_all_servers() method of WBEMSubscriptionManager and dictionary iteration errors in its remove_server() method (pr #583).
- Fixed a TypeError in the TestClientRecorder operation recorder that occurred while handling a ConnectionError (this recorder is used by the –yamlfile option of run_cim_operations.py) (issue #587).
- Fixed several errors in recorder on Python 3 (issue #531).
- In wbemcli, several fixes in the short global functions (issue #548).
- Fixed name of python devel package for Python 3.4 and 3.5.
- Several changes, fixes and improvements on WBEMSubscriptionManager (issues #462, #540, #618, #619).
- Added a check for unset URL target in recorder (issue #612).
- Fixed access to None in recorder (issue #621)
Build, test, quality:
- Added flake8 as an additional lint tool. It is executed with make check. Fixed all flake8 issues (issues #512, #520, #523, #533, #542, #560, #567, #575).
- Changed names of the pylint and flake8 config files to match the default names defined for these utilities (pylintrc and .flak8) (issue #534).
- Added CIM Schema archive to the repository, in order to avoid repeated downloads during testing in the CI systems (issue #49).
- Added git as an OS-level dependency for development (it is used by GitPython when building the documentation) (pr #581).
- Added wheel as a Python dependency for development. This package is not installed by default in some Linux distributions such as CentOS 7, and when installing into the system Python this becomes an issue (pr #622).
- Added retry in setup script to handle xmlrpc failures when installing prerequisites from PyPI.
- Fixed logic errors in pycmp compatibility checking tool.
- Changed makefile to skip documentation build on Python 2.6 due to Sphinx having removed Python 2.6 support (issue #604).
- Fixed UnboundLocalError for exc in setup.py (issue #545).
- Added an executable run_enum_performance.py to the testsuite to test pull performance. It generates a table of the relative performance of EnumerateInstances vs. OpenEnumerateInstances / PullInstancesWithPath performance over a range of MaxObjectCount, response instance sizes, and total number of instances in the response.
- Completed the test_client.py mock tests for all instance operations.
- Improved the tests in run_cim_operations.py.
Documentation:
- Added the global functions available in the wbemcli shell to the documentation (issue #602).
- Improved usage information for the “Tutorial” section, to make usage of Jupyter tutorials more obvious (issue #470).
- Added “Installation” and “Development” sections to the documentation, and moved some content from the “Introduction” section into a new “Appendix” section. Added an installation trouble shooting section to the appendix (pr #509).
- Added a section “Prerequisite operating system packages” to the documentation that describes the prerequisite packages by distribution (pr #549).
- Fixed a documentation build error on Python 2.6, by pinning the GitPython version to <=2.0.8, due to its use of unittest.case which is not available on Python 2.6 (issue #550).
- Clarified the behavior for the default WBEMConnection timeout (None) (issue #628).
- Fixed a documentation issue where the description of CIMError was not clear that the exception object itself can be accessed by index and slice (issue #511).
- Added the wbemcli global functions to the documentation (issue #608).
pywbem 0.9.0¶
Released: 2016-09-06
Deprecations:
- Deprecated the use of the value instance variable and ctor parameter of the CIMParameter class, because that class represents CIM parameter declarations, which do not have a default value. Accessing this instance variable and specifying an initial value other than None now causes a DeprecationWarning to be issued.
- Deprecated ordering comparisons for NocaseDict, CIMInstance, CIMInstanceName, and CIMClass objects. This affects the ordering comparisons between two such objects, not the ordering of the items within such a dictionary. Use of ordering operators on objects of these classes now causes a DeprecationWarning to be issued.
- Deprecated the methodname input argument of CIMMethod(), and renamed it to name. methodname still works but its use causes a DeprecationWarning to be issued.
- Deprecated the use of the verify_callback parameter of WBEMConnection. because it is not used with the Python ssl module and will probably be removed completely in the future. Its use now causes a DeprecationWarning to be issued. (Issue #297)
Known Issues:
- Installing PyWBEM on Python 2.6 has a conflict with the pbr package from PyPI, resulting in a TypeError: “dist must be a Distribution instance”. This issue is specific to Python 2.6 and does not occur in any of the other supported Python versions (2.7, 3.4, 3.5). This issue can be mitigated by uninstalling the pbr package, or if that is not possible, by migrating to Python 2.7. See issue #26 on GitHub.
- MOF using names that are reserved keywords will fail to compile in the MOF compiler. For example, a CIM property named ‘indication’. See issue #62 on GitHub.
Clean Code:
- Moved the following unused modules from the pywbem package directory
into a new attic directory, in order to clean up the pywbem
package:
- cim_provider.py
- cim_provider2.py
- cimxml_parse.py
- test_cimxml_parse.py
- twisted_client.py
- Moved the script-related portions of the pywbem/mof_compiler.py module into the mof_compiler script.
- Moved the complete pywbem/wbemcli.py module into the wbemcli script.
- Removed half-baked code for HTTP proxy/tunneling support.
Enhancements:
Implemented pull operations per DMTF specification DSP0200 and DSP0201. This includes the following new client operations to execute enumeration sequences:
- OpenEnumerateInstances
- OpenEnumerateInstancePaths
- OpenAssociatorInstances
- OpenAssociatorInstancePaths
- OpenReferenceInstances
- OpenReferenceInstancePaths
- OpenQueryInstances
- PullInstances
- PullInstancesWithPath
- PullInstancePaths
- CloseEnumeration
The EnumerationCount operation is NOT implemented, because it is both deprecated and unusable. (Issue #9)
Unit tests of the pull operations are included and mock tests are written for at least some parts of the pull operations.
Implemented support for reading information from WBEM servers according to the DMTF WBEM Server Profile (DSP1071) and DMTF Profile Registration Profile (DSP1033) with a new WBEMServer class. Note that not everyhting in these profiles needs to be implemented in the WBEM server for this to work:
- The WBEMServer class is a client’s view on a WBEM server and provides consistent and convenient access to the common elements of the server, including namespace names, interop namespace name, registered profile information, server branding, and central/scoping class algorithms.
- Added unit tests for this new class in run_cim_operations.py and test_client.py.
- Added a demo of the discovery abilities of the WBEMServer class in the examples/explore.py script.
Experimental - This new class is experimental for pywbem 0.9.0 because this is the initial release of a significant change and subject to changes to the API.
(Issues #9, #346, #468)
Implemented support for WBEM subscription management and a WBEM indication listener:
- Added a WBEMListener class that allows the creation of a listener entity to receive indications.
- Added a WBEMSubscriptionManager class that allows management of indication subscriptions, indication filters, and listener destination instances on the WBEM Server using the new WBEMServer class.
- Added unit tests for these new classes and extended other existing tests accordingly, e.g. run_cim_operations.py.
Experimental - These new classes are experimental for pywbem 0.9.0 because this is the initial release of a significant change and subject to changes to the API.
(Issues #66, #421, #414, #379, #378)
The distribution formats released to PyPI have been extended. There are now:
- Source archive (existed)
- Universal wheel (new)
(Issue #242)
Starting with pywbem 0.9.0, pywbem no longer stores the distribution archives in the repository, because the process for releasing to PyPI creates new distribution archives instead of using the created ones. This makes it difficult to ensure that the archives stored in the repository are the same.
Upgraded M2Crypto to use official 0.24.0 from PyPI.
Added check for minimum Python version 3.4 when running on Python 3. That requirement was already documented, now it is also enforced in the code.
Migrated API documentation to Sphinx.
Improved documentation of many classes of the external API.
Replaced [] and {} default arguments with None.
Changed the return value of repr() for WBEMConnection, CIM type classes (e.g. Sint8, CIMDateTime), and CIM object classes (e.g. CIMInstance) so that they now return all attributes in a reasonable order, and are suitable for debugging.
Clarified in the description of CIMClassName.__str__() and CIMInstanceName.__str__() that they return the WBEM URI representation of the class path and instance path.
Changed the return value of str() for CIM object classes (e.g. CIMProperty) so that they now return a short set of the most important attributes for human consumption. Specifically, this resulted in the following changes:
- For CIMProperty, reduced the complete set of attributes to a short set.
- For CIMQualifierDeclaration, added the attribute value.
Changes in the CIMError exception class:
- Changed the behavior of the __str__() method to return a human readable string containing the symbolic name of the status code, and the status description. The previous behavior was to return a Python representation of the tuple status code, status description.
- Added properties status_code (numeric CIM status code), status_code_name (symbolic name of CIM status code), and status_description (CIM status description).
- Updated the documentation to no longer show the unused third tuple element exception_obj. It was never created, so this is only a doc change.
Added CIM status codes 20 to 28, specifically to support the pull operations.
Changed the ParseError exception to be derived from the Error base exception, so that now all pywbem specific exceptions are derived from Error.
Added tocimxmlstr() as a global function and as methods on all CIM object classes. It returns the CIM-XML representation of the object as a unicode string either in a single-line variant, or in a prettified multi-line variant.
Created tomof() for CIMProperty making common functionality available to both class and instance tomof() (PR #151)
Added an optional namespace parameter to the WBEMConnection.CreateInstance() method, for consistency with other methods, and to have an explicit alternative to the namespace in the path component of the NewInstance parameter.
The ClassName parameter of several operation methods can be specified as both a string and a CIMClassName object. In the latter case, a namespace in that object was ignored so far. Now, it is honored. This affects the following WBEMConnection methods: EnumerateInstanceNames, EnumerateInstances, EnumerateClassNames, EnumerateClasses, GetClass, DeleteClass.
Enhanced the CIM integer data types (e.g. pywbem.Uint8()) to accept all input parameters that are supported by int().
Added the concept of a valid value range for the CIM integer data types, that is enforced at construction time. For compatibility, this strict checking can be turned off via a config variable: pywbem.config.ENFORCE_INTEGER_RANGE = False.
Extended wbemcli arguments to include all possible arguments that would be logical for a ssl or non-ssl client. This included arguments for ca certificates, client keys and certificates, timeout. It also modifies the server argument to use http:// or https:// prefix and suffix with :<port number> and drops the old arguments of –port and –no-ssl
Improved Swig installation code by reinstalling Swig if it was installed but still cannot be found in PATH (e.g. if the installation was tampered with).
Removed dependency on git (this was a leftover from when M2Crypto needed to be obtained from its development repo).
Added debug prints for two probably legitimate situations where socket errors are ignored when the server closes or resets the connection. These debug prints can be enabled via the debug instance variable of the WBEMConnection object; they are targeted at development for investigating these situations.
Extended run_cim_operations.py which is a live test against a server. It has only been tested against OpenPegasus but was extended to cover more details on more of the operation types and to create a test subclass to specifically test against OpenPegasus if OpenPegasus is detected as the server.
Added description of supported authentication types in WBEM client API.
Allowed tuple as input for PropertyList parameter of WBEMConnection operation methods. Documentation indicated that iterable was allowed but was limited to list. (Issue #347)
Added a tutorial section to the generated documentation, using Jupyter Notebooks for each tutorial page. (Issue #324)
Added the concept of operation recording on WBEM connections, that supports user-written operation recorders e.g. for tracing purposes. Added an operation recorder that generates test cases for the test_client unit test module. (Issue #351)
Extended wbemcli for all pull operations. (Issue #341)
Changed command line options of mof_compiler command to be consistent with wbemcli, and added support for specifying certificate related options. use of the old options is checked and causes an according error message to be displayed. Note, this is an incompatible change in the command line options. (Issue #216)
Cleaned up exception handling in WBEMConnection methods: Authentication errors are now always raised as pywbem.AuthError (OpenWBEM raised pywbem.ConnectionError in one case), and any other bad HTTP responses are now raised as a new exception pywbem.HTTPError.
Clarified MofParseError by defining attributes as part of the class init and moving some code from productions to the class itself (Issue #169). This makes the MofParseError exception more suitable for use from the productions themselves. The original definition was really only for use as a call from ply. Add tests for invalid qualifier flavors to unit tests and add test in mof_compiler.py for conflicting flavors ex. tosubclass and restricted in the same definition. This test uses the new MofParseError. (Issue #204)
Extended PropertyList argument in request operations to be either list or tuple. (Issue #347)
Added support for representing control characters in MOF strings using MOF escape sequences, e.g. U+0001 becomes “x0001”.
Modified qualifier MOF output to stay within 80 column limits. (Issue #35)
Bug fixes:
- Fixed KeyError when iterating over CIMInstance and CIMInstanceName objects.
- Fixed bug that MOF escape sequences in strings were passed through unchanged, into generated MOF, by removing needless special-casing code.
- Fixed bug with class MOF generation where output was not including array indicator ([]). (Issue #233)
- Moved class property MOF output processing to CIMProperty and fixed issue where default values were not being generated. (Issues #223 and #231)
- Fixed bug in method MOF output where array flag “[]” was left off array parameters.
- In the WBEMConnection.ModifyInstance() method, the class names in the instance and path component of the ModifiedInstance parameter are required, but that was neither described nor checked. It is now described and checked.
- In the WBEMConnection.ModifyInstance() method, a host that was specified in the path component of the ModifiedInstance parameter incorrectly caused an INSTANCEPATH element to be created in the CIM-XML. This bug was fixed, and a host is now ignored.
- Fixed a bug where the CIM datetime string returned by the str() function on CIMDateTime interval objects contained incorrect values for the minutes and seconds fields on Python 3. (Issue #275).
- Fixed an IndexError in cim_http.wbem_request() that occurred during handling of another exception.
- Fixed issue with Python 3 and https that was causing connect() to fail. This completely separates connect() code for Python 3 ssl module from Python 2 M2Crypto.
- Fixed problem that wbemcli in Python 3 when used without existing history file would fail with “TypeError: ‘FileNotFoundError’ object is not subscriptable”. (Issue #302)
- Fixed issue with tomof() output where datetime values were not quoted. (Issue #289)
- Eliminated automatic setting of toinstance flavor in mof_compiler when tosubclass is set. Also enabled use of toinstance flavor if defined in a class or qualifier declaration. (Issue #193)
- Fixed problem in class-level associator operations that namespace was classname when classname was passed as a string. (Issue #322)
- Fixed hole in checking where class CIMMethod allowed None as a return_type. (Issue #264)
- Fixed a documentation issue with associators/references return types. It was documented as a list of classes for class level return, but it actually is a list of tuples of classname, class. (Issue #339)
- Created a common function for setting SSL defaults and tried to create the same level of defaults for both Python2 (M2Crypto) and Python 3 (SSL module). The minimum level protocol set by the client is TLSV1 now whereas in previous versions of pywbem it was SSLV23. (Issue #295)
- Fixed issue where mof_compiler was setting values for compile of instances into the class object and also setting the values for the last compiled instance in a compile unit into all other compiled instances for the same class. Since the concept of compiling a path into compiled instances is flawed (there is no requirement to include all properties into a instance to compile that code was removed so that the path is NOT build into a compiled instance. Finally the qualifiers from the class were also included in compiled instances which was incorrect and an accident of the code. They are no longer included into the compiled instances.) (Issue #402)
- Fixed description in INSTALL.md to correctly describe how to establish OS-level prerequisites.
- Cleaned up the timeouts on SSL and created specific tests for timeouts against a live server. (Issues #363, #364)
pywbem 0.8.4¶
Released: 2016-05-13
Bug fixes:
- Fixed an IndexError in cim_http.wbem_request() that occurred during handling of another exception.
- Fixed problem that wbemcli in Python 3 when used without existing history file would fail with “TypeError: ‘FileNotFoundError’ object is not subscriptable” (issue #302).
- Fixed issues with Python 3 and HTTPS that were causing the connecttion to fail. This completely separates the connect() code for Python 3 (using the Python SSL module) from the code for Python 2 (using M2Crypto) (issues #150, #273, #274, #288).
Enhancements:
- Improved description in INSTALL.md to better describe how to establish OS-level prerequisites.
- Improved Swig installation code by reinstalling Swig if it was installed but still cannot be found in PATH (e.g. if the installation was tampered with).
- Removed dependency on git (this was a leftover from when M2Crypto needed to be obtained from its development repo).
- Added debug prints for two probably legitimate situations where socket errors are ignored when the server closes or resets the connection. These debug prints can be enabled via the debug instance variable of the WBEMConnection object; they are targeted at development for investigating these situations.
- Added check for minimum Python version 3.4 when running on Python 3. That requirement was already documented, now it is also enforced in the code.
- Enhanced the wbemcli script with options supporting certificates. For details, invoke with –help, or look at the online documentation. NOTE: The –no-ssl and –port options have been removed. Specify the protocol and port number in the server URL.
Clean code:
- Removed half-baked code for HTTP proxy/tunneling support.
pywbem 0.8.3¶
Released: 2016-04-15
Bug fixes:
- To address some M2Crypto issues, upgraded to use M2Crypto >=0.24 from PyPI.
- For Windows, using M2CryptoWin32/64 >=0.21 from PyPI, in order to avoid the Swig-based build in Windows.
- Improved the mechanism to build the LEX/YACC table modules, so that import errors for freshly installed packages (e.g. M2Crypto) no longer occur.
Enhancements:
- Added Windows versions of WBEM utility commands: wbemcli.bat, mof_compiler.bat.
pywbem 0.8.2¶
Released: 2016-03-20
Bug fixes:
- Eliminated dependency on six package during installation of pywbem. (Andreas Maier)
Dependencies:
- Pywbem 0.8.x has the following dependencies on other PyPI packages
(see install_requires argument in setup script):
- M2Crypto
- ply
- six
pywbem 0.8.1¶
Released: 2016-03-18
Known Issues:
- Installing PyWBEM on Python 2.6 has a conflict with the pbr package from PyPI, resulting in a TypeError: “dist must be a Distribution instance”. This issue is specific to Python 2.6 and does not occur in any of the other supported Python versions (2.7, 3.4, 3.5). This issue can be mitigated by uninstalling the pbr package, or if that is not possible, by migrating to Python 2.7. See issue #26 on GitHub.
- MOF using names that are reserved keywords will fail to compile in the MOF compiler. For example, a CIM property named ‘indication’. See issue #62 on GitHub.
- The Pulled Enumeration Operations introduced in DSP0200 1.3 are not supported in this release. See issue #9 on GitHub.
- Note that some components of this PyWBEM Client package are still
considered experimental:
- The twisted client module twisted_client.py.
- The Python provider modules cim_provider.py and cim_provider2.py.
- The CIM indication listener in the irecv directory. See issue #66 on GitHub.
Changes:
- The MOF compiler is now available as the command ‘mof_compiler’ that gets installed into the Python script directory. It is now separate from the ‘mof_compiler’ module within the ‘pywbem’ package. In pywbem 0.7.0, the module was at the same time the script. (Andreas Maier)
- The WBEM client CLI is now available as the command ‘wbemcli’ that gets installed into the Python script directory. It is now separate from the ‘wbemcli’ module within the ‘pywbem’ package. In pywbem 0.7.0, the module was at the same time the script. (Andreas Maier)
- In pywbem 0.7.0, most symbols defined in the sub-modules of the ‘pywbem’ package were folded into the ‘pywbem’ package namespace, cluttering it significantly. The symbols in the ‘pywbem’ package namespace have been reduced to a well-defined set that is now declared the external API of the WBEM client library, and is supposed to be sufficient. If you find that you need something you were used to, please think twice as to whether that makes sense to be part of the external PyWBEM API, and if so, let us know by opening an issue.
- Since pywbem 0.7.0, some exceptions that can be raised at the external API of the WBEM client library have been cleaned up.
Enhancements:
- Verify certificates against platform provided CA trust store in /etc/pki/tls/certs. Linux only. (Peter Hatina)
- Added ‘-d’ option to MOF compiler that causes the compiler to perform a dry-run and just check the MOF file syntax. This allows to more easily detect included MOF files when used together with the ‘-v’ option. (Jan Safranek)
- Added support for non-ASCII (Unicode) characters. (Michal Minar, Andreas Maier)
- Improved information in the message text of some exceptions (TypeError and KeyError in cim_obj.py, ValueError in cim_obj.py, and ParseError in tupleparse.py). (Andreas Maier)
- Moved the definition of the pywbem version from setup.py to __init__.py, in order to make it available to programs using pywbem as pywbem.__version__. (Andreas Maier)
- Added support for direct iteration over NocaseDict objects using for and in by adding __iter__(), e.g. for use with CIMInstance.properties. (Andreas Maier)
- Added more instance attributes to be shown in repr() on CIMProperty and other classes in cim_obj. (Andreas Maier)
- Added and improved docstring-based documentation in the pywbem modules cim_operations, cim_http, cim_obj, cim_types, and the pywbem module. (Andreas Maier)
- Improved the way missing file:// URL support on Windows is handled, by now issuing a proper error message instead of stumbling across the missing socket.AF_UNIX constant. (Andreas Maier)
- Improved the way missing OWLocal authorization with the OpenWBEM server is handled on Windows, by now issuing a proper error message instead of stumbling across the missing os.getuid() function. (Andreas Maier)
- Improved Windows portability by no longer attempting to import pwd in case the userid is not set in the environment variables that are checked when the WBEM server is local. (Andreas Maier)
- Added support for ExecQuery operation to twisted client. (Robert Booth)
- Added get() methods on CIMInstance and CIMInstanceName to step up to the statement that they behave like dictionaries w.r.t. properties and key bindings. (Andreas Maier)
- Improved help text of test_cim_operations.py test program. (Andreas Maier)
- Added an optional Params argument to InvokeMethod(), that is an ordered list of CIM input parameters, that preserves its order in the CIM-XML request message. This is to accomodate deficient WBEM servers that do not tolerate arbitrary order of method input parameters as required by the standard. The new argument is optional, making this a backwards compatible change of InvokeMethod(). (Andreas Maier)
- Cleaned up the public symbols of each module by making symbols private that are used only internally. Specifically, the following symbols have been made private: In cimxml_parse: _get_required_attribute, _get_attribute, _get_end_event, _is_start, _is_end. In cim_xml: _text (was: Text). (Andreas Maier)
- Cleaned up symbols imported by wildcard import by defining __all__ in each module with only the public symbols defined in that module (removing any symbols imported into the module), except for the following modules which define less than the complete set of public symbols in their __all__: mof_compiler, twisted_client, tupleparse, cimxml_parse, cim_http. (Andreas Maier)
- Added support for using CDATA section based escaping in any requests sent to the WBEM server. The default is still XML entity reference based escaping, the CDATA based escaping can be turned on by setting the switch _CDATA_ESCAPING accordingly, which is a global variable in the cim_xml module. (Andreas Maier)
- Simplified the exceptions that can be raised by WBEMConnection methods, and improved the information in the exception messages. See description of WBEMConnection class for details. (Andreas Maier)
- Added support for timeouts to WBEMConnection, via a new timeout argument, that defaults to no timeout. (This finally increased the minimum version of Python to 2.6. (Andreas Maier)
- Improved installation process of PyWBEM, particularly related to M2Crypto. (Andreas Maier)
- Added support for Python 3. Issue #3 on GitHub. (Ross Peoples, Andreas Maier)
Bug fixes:
- Fix syntax error in CIM DTDVERSION error path. Allow KEYVALUE VALUETYPE attribute to be optional as specified in the DTD. (Andreas Linke)
- Added parsing of InvokeMethod return value and output parameters for Twisted Python client. (Tim Potter)
- Fixed cim_provider2.py to properly support shutdown() and can_unload() (called from CMPI cleanup() functions). Support was recently added to cmpi-bindings for this. (Bart Whiteley)
- Fixed XML parsing to accept SFCB-style embedded instance parameters. (Mihai Ibanescu)
- Use getpass module instead of pwd to detect local user to fix Win32. (Tim Potter)
- Re-throw KeyError exceptions with capitalised key string instead of lower cased version in NocaseDict.__getitem__(). (Tim Potter)
- Use base64.b64encode() instead of base64.encodestring() in Twisted client. (Mihai Ibanescu)
- Fix missing CIMDateTime import in Twisted client. (Mihai Ibanescu)
- Fixed CIMInstanceName rendering to string. It is now possible to pass the rendered string value as an instance path argument of a CIM method. (Jan Safranek, Michal Minar)
- For Python providers, fixed the comparsion of the Role parameter in association operations to be case insensitive, and removed an erroneous test that raised an exception when the property specified in the Role parameter was not also in the property list specified by the Properties parameter. (Jan Safranek)
- For Python providers, converted debug ‘print’ statements to trace messages that end up in the system log. (Jan Safranek)
- The CIM-XML parser no longer throws an exception when parsing a qualifier declaration. Note: The CIM-XML supported by this fix does not conform to DSP0201 so far. Further fixes are pending. (Jan Safranek)
- Fixed parsing errors for connection URLs with IPv6 addresses, including zone indexes (aka scope IDs). (Peter Hatina, Andreas Maier)
- Fixed the hard coded socket addressing family used for HTTPS that was incorrect in some IPv6 cases, by determining it dynamically. (Peter Hatina)
- Fixed the list of output parameters of extrinsic method calls to be returned as a case insensitive dictionary (using cim_obj.NocaseDict). (Jan Safranek)
- Fixed the checking of CIMVERSION attributes in CIM-XML to only verify the major version, consistent with DSP0201 (see subclause 5.2.1, in DSP0201 version 2.3.1). (Jan Safranek)
- Fixed error in cim_http.py related to stronger type checking of Python 2.7. (Eduardo de Barros Lima)
- Removed erroneous qualifier scopes SCHEMA and QUALIFIER from the MOF compiler (see DSP0004). (Andreas Maier)
- Fixed debug logging of CIM-XML payload (that is, conn.last_*request/reply attributes) for extrinsic method calls, to now be consistent with intrinsic method calls. (Andreas Maier)
- Fixed TOCTOU (time-of-check-time-of-use) error when validating peer’s certificate. (Michal Minar)
- Added a check in the CIMInstanceName constructor that the classname argument is not None. (Andreas Maier)
- Fixed the issue in the CIMProperty constructor that specifying a tuple for the value argument was incorrectly detected to be a scalar (and not an array). (Andreas Maier)
- Fixed the issue in the CIMProperty constructor that specifying a datetime or timedelta typed value resulted in storing the provided object in the value attribute, instead of converting it to a CIMDateTime object. (Andreas Maier)
- Fixed the issue in the CIMProperty constructor that specifying a datetime formatted string typed value argument along with type=’datetime’ resulted in storing the provided string object in the value attribute, instead of converting it to a CIMDateTime object. (Andreas Maier)
- Fixed several cases in the CIMProperty constructor of unnecessarily requiring the optional arguments type, is_array, embedded_object, or reference_class. These optional arguments are now only necessary to be provided if they cannot be implied from provided arguments (mainly from value). (Andreas Maier)
- Fixed the issue in the CIMProperty constructor that an embedded_object argument value of ‘object’ was changed to ‘instance’ when a CIMInstance typed value argument was also provided. (Andreas Maier)
- Fixed the issue in the CIMProperty constructor that the first array element was used for defaulting the type attribute, without checking that for None, causing an exception to be raised in this case. (Andreas Maier)
- Added a check in the CIMProperty constructor that the name argument is not None. (Andreas Maier)
- Fixed the issue that the CIMProperty constructor raised only TypeError even when the issue was not about types; it now raises in addition ValueError. (Andreas Maier)
- Changed the exception that is raised in NocaseDict.__setitem__() for invalid key types, to be TypeError in instead of KeyError. Updated the testcases accordingly. (Andreas Maier)
- Added checks for more than one argument and for unsupported argument types to the constructor of NocaseDict. (Andreas Maier)
- Fixed incorrectly labeled namespace variables in twisted client. (Robert Booth)
- Fixed that WBEMConnection.last_raw_reply was not set to the current reply in case of parsing errors in the reply. (Andreas Maier)
- Reintroduced Python 2.6 support in cim_http.HTTPSConnection.connect()
that disappeared in early drafts of this version: (Andreas Maier)
- Removed SSLTimeoutError from except list; being a subclass of SSLError, it is catched via SSLError.
- Invoked socket.create_connection() without source_address, if running on Python 2.6.
- Fixed bug where HTTP body was attempted ot be read when CIMError header is set, causing a hang. (Andreas Maier)
- Added CIM-XML declaration support for alternative PyWBEM client based on twisted. (Andreas Maier)
- Added support for Windows to wbemcli.py, by making dependency on HOME environment variable optional, and adding HOMEPATH environment variable. Also, cleaned up the global namespace of wbemcli.py and made it importable as a module. (Andreas Maier)
- Fixed errors in generated MOF (e.g. in any tomof() methods): (Andreas Maier)
- Missing backslash escaping within string literals for n, r, t, “.
- Representation of REF types was incorrect.
- ‘=’ in array-typed qualifier declarations was missing.
- Fixed size indicator was missing in array elements.
- Qualifiers of method parameters were missing.
- Improvements in generated MOF: (Andreas Maier)
- Changed order of qualifiers to be sorted by qualifier name.
- Added empty line before each property and method in the class for better readability.
- Method parameters are now placed on separate lines.
- Moved generation of method qualifiers from class into method. This changes the behavior of CIMMethod.tomof() to now generate the method qualifiers.
- Fixed error where invoking mof_compiler.py with a file based URL that did not start with ‘file:’ failed with an undefined variable url_ in cim_http.py. Issue #1 on GitHub. (Klaus Kaempf, Andreas Maier)
- Fixed build error that raised a YaccError in mof_compiler.py: “Syntax error. Expected ‘:’”. Issue #2 on GitHub. (Andreas Maier)
- Fixed issue where MOF compiler did not find include files with a path specified. Issue #4 on GitHub. (Karl Schopmeyer)
- Added missing LocalOnly parameter to EnumerateInstances() of the wbemcli script. Issue #33 on GitHub. (Karl Schopmeyer)
- Added workaround for Python 2.6 for Python issue 15881.
- Removed the lex.py and yacc.py files from PyWBEM, and used them from the ply package, which is their real home. This fixes a number of issues because the latest version is now used. Issue #8 on GitHub.i (Karl Schopmeyer)
- Fixed the issue that the LEX and YACC table modules were regenerated under certain conditions. Issue #55 on GitHub. (Karl Schopmeyer)
- Fixed bugs in the mof_compiler script. (Karl Schopmeyer)
- Fixed errors in the description of the qualifier operations in WBEMConnection. Issue #91 on GitHub. (Andreas Maier)
Testing:
- Added support for running the unit test cases without having to be in the testsuite directory. This was done by setting up the DTD_FILE path correctly for any XML tests. (Andreas Maier)
- Improved the quality of assertion messages issued when testcases fail, to include context information and types. (Andreas Maier)
- Added docstrings to test cases. (Andreas Maier)
- Added testcases for CIMProperty.__init__() to be comprehensive. (Andreas Maier)
- In XML validation tests, added the expected XML root element. (Andreas Maier)
- Added a header to any error messages issued by xmllint. (Andreas Maier)
- Fix: Merged stderr into stdout for the xmllint invocation, xmllint error messages go to stderr and had been dropped before. (Andreas Maier)
- Fix: The “mkdir -p ..:” command in the comfychair testcase constructor created subdirectories named “-p” when running on Windows; replaced that command with os.makedirs(). (Andreas Maier)
- Fix: Replaced the “rm -fr …” command in the comfychair testcase constructor with shutil.rmtree(), in order to better run on Windows. (Andreas Maier)
- Fix: In comfychair._enter_rundir(), moved registration of cleanup function _restore_directory() to the end, so cleanup happens only if no errors happened. (Andreas Maier)
- Fixed a bug in pywbem/trunk/testsuite/test_tupleparse.py in function ParseCIMProperty.runtest(), where the use of real tab characters caused a few lines to be incorrectly indented, and as a result, ignored for the test. (Andreas Maier)
- Improved Windows portability in testsuite: Moved from using the Unix-only functions posix.WIFSIGNALED() and posix.WEXITSTATUS() for testing the success of subprocess.wait(), to simply testing for 0. (Andreas Maier)
- Added ability to invoke test_cim_operations.py with comfychair arguments, and added printing of exception information if an operation fails. (Andreas Maier)
- Migrated from comfychair to py.test, standard Python unittest, and to tox. (Andreas Maier)
- Added test_client.py with a few initial testcases. This is an end-to-end test concept that allows specifying test cases that cover the entire PyWBEM Client top to bottom. It mocks the socket layer and allows specifying the test cases in YAML, starting with input at the PyWBEM Client API (e.g. an operation and its parameters), the expected CIM-XML request at the socket payload level resulting from this input (the request is verified), the CIM-XML response that is to be generated, and finally an expected result at the PyWBEM Client API that is being verified. (Andreas Maier)
- Added use of Travis CI test environment. Commits to GitHub now trigger test runs on the Travis CI. A badge on the GitHub README page shows the current test result of the master branch, and links to the Travis site for the test results of the branches of any pull requests. (Andreas Maier)
- Added support for reporting test coverage, using the Python ‘coverage’ package. Coverage is reported on stdout as part of testing, e.g. with ‘make test’ for the current Python environment, or with ‘tox’ for all supported Python environments. (Andreas Maier)
- Added multiple tests for client connection timeout. A mock test was added for both HTTP and HTTPs. However, this causes an error in python 2 with HTTPS so two new options were added to test_client.py. First, a new parameter ignore_python_version was added to the yaml to define a major version of python for which a particulare testcase would be ignored. Second a non-documente option was added to test_client.py to execute a single testcase if the name of that testcase is the only parameter on the test_client.py cmd line. Finally a whole new run_operationtimeout.py file was added to testsuite to throughly test for timeouts. This runs ONLY against particular versions of OpenPegasus because it required adding a new method to OpenPegasus. However, it established that the timeouts apparently now really do work in both python 2 and python 3 with both http and https. (see issue #363)
Clean Code:
- Removed dangerous default parameter {} from CIMProperty and CIMInstanceName, and replaced it with None. To support that, added support for initializing an empty NocaseDict object from None. (Andreas Maier)
- In cim_obj, changed the use of the deprecated backticks to using %r in the format string (which produces the same result). (Andreas Maier)
- In the constructor of CIMInstanceName, added assertions to some paths that cannot possibly be taken based on the fact that the keybindings attribute is always a NocaseDict. They should be removed at some point. (Andreas Maier)
- Addressed PyLint issues: (Andreas Maier, Karl Schopmeyer)
- Consolidated imports at the top of the module (after module docstring), consistent with the PEP-8 recommendation.
- Ensured order of imports: standard, non-standard, pywbem, local (on a subset of modules only).
- Replaced wildcard imports with specific imports, as much as possible.
- Removed unused imports.
- Addressed PyLint issues that are related to whitespace, continuation indentation, and line length.
- Replaced all real tab characters with spaces.
- Many more PyLint issues
Packaging / Build:
- Fixed grammatical funkiness in the license text. No change to actual license - still LGPLv2. (Tim Potter)
- Added LICENSE.txt file to release. (Tim Potter)
- Added LICENSE.txt, NEWS, README and INSTALL files to distribution archive. (Andreas Maier)
- Fixed inconsistencies in license text in file headers to consistently say LGPL 2.1 or higher (The LICENSE.txt file has always been LGPL 2.1). (Andreas Maier)
- Removed confusing section about build from INSTALL file, to scope it just to the topic of installation. (Andreas Maier)
- Restructured pywbem/trunk subtree to move pywbem package files into a pywbem subdirectory. (Andreas Maier)
- Added a makefile (invoke ‘make help’ for valid targets). (Andreas Maier)
- Added support for checking the Python source code using PyLint. (Andreas Maier)
- Added support for generating HTML documentation using epydoc, and included the documentation into the distribution archive. The syntax used in Python docstrings is reStructuredText markdown. (Andreas Maier)
- Added support for installing OS-level prerequisites via the new setup.py script commands ‘install_os’ and ‘develop_os’. (Andreas Maier)
- Added support for installing Python-level prerequisites when installing in development mode using the setup.py script command ‘develop’. (Andreas Maier)
pywbem 0.7.0¶
Released: 2008-12-12
Bug fixes:
- Fixed enumInstances and references in cim_provider to do a deep copy of the model before filtering instances so provider writers are less surprised. (Bart Whiteley)
- Added CIMDateTime.__cmp__() so that CIMDateTime instances can be compared. (Bart Whiteley)
- Fixed data types of method return values for python providers. (Bart Whiteley)
- Fixed REF array out parameters in tupleparse.py. (Bart Whiteley)
- Fixed Array parameters with no elements. (Bart Whiteley)
- Fixed precision for real32 and real64 types. (Bart Whiteley)
- Fixed Array properties where is_array isn’t set in __init__. (Bart Whiteley)
- Added NocaseDict.__cmp__(self, other). (Bart Whiteley)
- Fixed WBEMConnection.__repr__ for anonymous connections. (Tim Potter)
- Fixed XML encoding of CIMQualifierDeclarations. (Bart Whiteley)
- Fixed EnumerateQualifiers if there are no qualifiers. (Bart Whiteley)
- Fixed InvokeMethod to only send a LOCALCLASSPATH or LOCALINSTANCEPATH, not a CLASSPATH or INSTANCEPATH. (Bart Whiteley)
- Fix unexpected line break in basic auth header for long credentials. (Daniel Hiltgen)
- Fix Host: HTTP header when connecting to a unix domain socket. (Bart Whiteley)
- Fix deprecation warnings with Python 2.6. (Bart Whiteley)
Enhancements:
- Added support for generating Pegasus provider registration MOF in cim_provider.codegen(). (Bart Whiteley)
- Implemented methods to parse indication export requests. (Bart Whiteley)
- Python provider code generation enhancements. (Bart Whiteley)
- Support for Pegasus Local authentication. (Bart Whiteley)
- Support for Pegasus and OpenWBEM Unix Domain Socket. (Tim and Bart)
- Added support for Pegasus non-compliant EMBEDDEDOBJECT XML attribute. (Bart Whiteley)
- Added CIMQualifierDeclaration.tomof(). (Bart Whiteley)
- Added a powerful MOF compiler. (Bart Whiteley)
- Added property filtering to CIMInstance. (Bart Whiteley)
- Added value attribute to CIMParameter. (Bart Whiteley)
- Rigged CIMInstance to automagically update CIMInstance.path.keybindings as key properties are set. (Bart Whiteley)
- Added cim_provider2.py: A new provider interface. Python providers using this interface can use the cmpi-bindings project within OMC (https://omc-project.org/) to run under any CIMOM supporting the CMPI interface. This is prefered to the old cim_provider.py interface that was used with the Python Provider Managers for OpenWBEM and Pegasus.
- Changed __init__.py to not import anything from cim_provider.py (or cim_provider2.py) into the pywbem namespace. Existing providers based on cim_provider.py can still work with a minor adjustment involving importing CIMProvider from pywbem.cim_provider. The codegen funtion can now be obtained with from pywbem.cim_provider import codegen, or from pywbem.cim_provider2 import codegen or similar.
- Added wbemcli.py command line utility. (Tim Potter)
- Pass keyword args in unix domain socket connection functions down to WBEMConnection(). (Tim Potter)
pywbem 0.6¶
Released: 2007-10-26 (not on Pypi)
Licensing:
- Relicensed from the GNU GPLv2 to the GNU LGPLv2.
API Changes:
- Add a type keyword arg and attribute to CIMQualifier, similar to the CIMProperty object, to allow the creation of null qualifiers. (Tim Potter)
- Remove the toxml() method from CIM object classes. Use tocimxml().toxml() instead which specifies the CIM-XML representation of the object. (Tim Potter)
- CIMDateTime class should now be used instead of datetime.datetime and datetime.timedelta.
- Added a new method, CIMInstance.update_existing(). This behaves like update() on a dict, but only assigns new values to existing properties. It skips values for properties not already present in the instance. This is useful for honoring PropertyList within python providers.
Bug fixes:
- Explicitly specify charset=”utf-8” in HTTP Content-type header as this is required now by the Pegasus cimserver. (Tim Potter)
- Parse VALUETYPE elements that contain a TYPE attribute. This feature was introduced in version 2.2 of the CIM-XML DTD and produced by some CIMOMs such as the Java WBEM Server. (Tim Potter)
- Don’t require CreateInstance to have the path attribute set but if it is, use the namespace from it. (Tim Potter)
- Allow extrinsic methods to return object references. (Tim Potter)
- Fix CIMInstanceName to support more numeric types of keybindings. (Bart Whiteley)
- Fix datetime values to support utc offset. (Bart Whiteley)
- Fix http client to monitor the connection more closely (RFC 2616 section 8.2.2). Previously, a large request could cause a socket exception with no ability to read the response and respond to an authentication challenge.
- Fix NULL qualifiers to have a (required) type. (Martin Mrazik)
- Fix initialising CIMInstanceName keys from a NocaseDict. (Bart Whiteley)
- Return correct namespace in path for return value from GetInstance. (Tim Potter)
- Numerous bugfixes to Twisted Python client. (Tim Potter)
- Fix for x.509 SSL certificate handling. (Bas ten Berge)
- EnumerateClassNames() now returns an empty list instead of None if there are no classes. (Bart Whiteley)
Enhancements:
- Support for OpenWBEM password-less local authentication. (Bart Whiteley)
- Support for embedded objects is described in DSP0201-2.2.0 (Bart Whiteley)
- New CIMDateTime class to deal with CIM-isms of datetimes. Most notably, datetime deals with timezone info poorly. (Bart Whiteley)
- Add InvokeMethod() support in Twisted Python client. (Tim Potter)
pywbem 0.5¶
Released: 2006-11-21 (not on Pypi)
API Changes:
- Many API changes were made to simplify the function and object
interface of PyWBEM. Aspects of just about every CIM operation
call and CIM object have changed. The major changes are:
- The “LocalNamespacePath” keyword argument has been renamed to simply “namespace” for all CIM operations.
- Replaced all object location classes with CIMInstanceName, and all instance classes with CIMInstance. CIMInstanceName now has “host” and “namespace” attributes to fully name a reference to an instance. The CIMInstance class now has a “path” attribute which is of type CIMInstanceName.
- EnumerateInstances() now returns a list of CIMInstance objects (with path attribute set) instead of a list of CIMNamedInstance or tuples of (CIMInstanceName, CIMInstance).
- All representations of properties can now be represented with the CIMProperty class.
- All classes now have a copy() method which return a deep copy of the object. PyWBEM makes extensive use of dictionary objects which are passed by reference in Python. Use the copy() method to create and manipulate objects without modifying them by accident.
Bug fixes:
- Fix parse bug when a CIMInstanceName is passed as the localobject parameter to WBEMConnection.InvokeMethod().
- Fix parsing of INSTANCE elements containing PROPERTY.REFERENCE elements bug found by Bart Whiteley. This turns up when processing associations. (Tim Potter)
- Handle extrinsic method calls that don’t return a value or any output parameters. (Tim Potter)
- Fixed parsing of PARAMETER.ARRAY and PARAMETER.REFARRAY to not require optional attrs. (Bart Whiteley)
- Atomic_to_cim_xml string generation for a datetime - was missing a >> ‘.’ in the string. (Norm Paxton)
- InvokeMethod did not provide for None in output parameters. (Norm Paxton)
Enhancements:
- More parts of the class provider interface have been implemented. (Tim Potter, Bart Whiteley)
- Many case-sensitivity bugs, mostly in __cmp__ methods, were found and fixed. (Tim Potter)
- Implemented a test suite for maintaining backward compatibility and testing new features. (Tim Potter)
- Implemented ExecQuery. (Bart Whiteley)
- Allow a string classname to be passed as the localobject parameter to WBEMConnection.InvokeMethod(). (Tim Potter)
- Add missing qualifiers on array properties. (Bart Whiteley)
- Added code for performing asynchronous WBEM client operations using the Twisted Python framework. (Tim Potter)
- Allow extrinsic method calls that take parameters. (Tim Potter)
- Added cim_http.AuthError exception class. This is raised if the CIMOM returns a 401 (Unauthorized). Now the client can distinguish this condition, and (re)prompt for credentials. (Bart Whiteley)
- Created cim_obj.CIMParameter class. Added return type, class origin, propagated to CIMMethod. CIMParameter object now allows parameter types and qualifiers to be obtained. (Bart Whiteley)
- Implemented case-insensitive keys for property and qualifier dictionaries, as per the CIM specification. (Tim Potter, Bart Whitely)
pywbem 0.4¶
Released: 2005-11-15 (not on Pypi)
Bug fixes:
- Correctly calculate value of Content-Length HTTP header to include opening XML stanza. (Szalai Ferenc)
- Fix syntax error when re-raising socket errors. (Pat Knight)
Enhancements:
- Support for marshaling and unmarshaling CIM dates object into Python datetime objects. (Szalai Ferenc)
- Experimental module for making asynchronous WBEM calls with PyWBEM in Twisted Python. (Tim Potter)
- Add parameter type checking for object location classes. (Tim Potter)
- Allow caller to pass in a dictionary containing the location of the SSL certificate and key files as per the httplib.HTTPSConnection() class constructor. (Pat Knight)
API Changes:
- Change association provider API functions to take a fixed parameter for the named object instead of a keyword argument. This breaks backward compatibility. (Tim Potter)
- Remove the CIMLocalNamespacePath class and replaced by a Python string. (Tim Potter)
Portability:
- Don’t use UserDict.DictMixin base class as it only exists in Python 2.3 and higher. (Tim Potter)
Tests:
- Add tests for parameter type checking for object location classes. (Tim Potter)
- Add tests for string representation of object location classes. (Tim Potter)