pywbem
stable_1.4
  • 1. Introduction
    • 1.1. Functionality
    • 1.2. Supported environments
    • 1.3. Installation
      • 1.3.1. Installing into a different Python environment
      • 1.3.2. Installing a different version of pywbem
      • 1.3.3. Building a compiled archive with Cython
      • 1.3.4. Verifying the installation
      • 1.3.5. Prerequisite operating system packages for install
    • 1.4. Package version
      • __version__
    • 1.5. Version dependent features
      • PYWBEM_USES_REQUESTS
    • 1.6. Standards conformance
    • 1.7. Deprecation and compatibility policy
    • 1.8. Python namespaces
    • 1.9. Configuration variables
      • AUTO_GENERATE_SFCB_UEP_HEADER
      • DEFAULT_ITER_MAXOBJECTCOUNT
      • ENFORCE_INTEGER_RANGE
      • IGNORE_NULL_KEY_VALUE
      • SEND_VALUE_NULL
    • 1.10. WBEM servers
      • 1.10.1. Server-specific features
      • 1.10.2. WBEM server testing
  • 2. Concepts
    • 2.1. The CIM/WBEM architecture
    • 2.2. The CIM model and CIM objects
    • 2.3. WBEM Operations: Communicating with the WBEM Server
      • 2.3.1. WBEM operations overview
      • 2.3.2. Traditional operations
      • 2.3.3. Pull operations
        • 2.3.3.1. Relation to traditional operations
        • 2.3.3.2. Pull operation responses
        • 2.3.3.3. Pull enumeration sequence code pattern
        • 2.3.3.4. Common Pull Operation Request Input Arguments
        • 2.3.3.5. Differences from traditional operations
      • 2.3.4. Iter operations
        • 2.3.4.1. Why the iter operations exist
        • 2.3.4.2. Comparison table
        • 2.3.4.3. Internal processing in the iter operations
      • 2.3.5. Forcing pull vs. traditional operations
      • 2.3.6. Differences between iter operations and pull operations
        • 2.3.6.1. Use of FilterQuery
        • 2.3.6.2. Paths in returned instances
        • 2.3.6.3. Use of MaxObjectCount argument
        • 2.3.6.4. Receiving returned objects before an exception
        • 2.3.6.5. Closing an Iter operation before it is complete
    • 2.4. WBEM indications and subscriptions
    • 2.5. WBEM Management Profiles
  • 3. Tutorial
    • 3.1. Table of Jupyter tutorials
    • 3.2. Executing code in the tutorials
  • 4. WBEM client library
    • 4.1. WBEM operations
      • 4.1.1. WBEMConnection
        • WBEMConnection
        • IterQueryInstancesReturn
    • 4.2. CIM objects
      • 4.2.1. Putting CIM objects in sets
      • 4.2.2. Order of CIM child objects
      • 4.2.3. NocaseDict
        • NocaseDict
      • 4.2.4. CIMInstanceName
        • CIMInstanceName
      • 4.2.5. CIMInstance
        • CIMInstance
      • 4.2.6. CIMClassName
        • CIMClassName
      • 4.2.7. CIMClass
        • CIMClass
      • 4.2.8. CIMProperty
        • CIMProperty
      • 4.2.9. CIMMethod
        • CIMMethod
      • 4.2.10. CIMParameter
        • CIMParameter
      • 4.2.11. CIMQualifier
        • CIMQualifier
      • 4.2.12. CIMQualifierDeclaration
        • CIMQualifierDeclaration
    • 4.3. CIM data types
      • CIMType
        • CIMType.cimtype
      • CIMDateTime
        • CIMDateTime.__eq__()
        • CIMDateTime.__hash__()
        • CIMDateTime.__repr__()
        • CIMDateTime.__str__()
        • CIMDateTime.cimtype
        • CIMDateTime.datetime
        • CIMDateTime.fromtimestamp()
        • CIMDateTime.get_local_utcoffset()
        • CIMDateTime.is_interval
        • CIMDateTime.minutes_from_utc
        • CIMDateTime.now()
        • CIMDateTime.precision
        • CIMDateTime.timedelta
      • MinutesFromUTC
        • MinutesFromUTC.__repr__()
        • MinutesFromUTC.dst()
        • MinutesFromUTC.tzname()
        • MinutesFromUTC.utcoffset()
      • Char16
        • Char16.cimtype
      • CIMInt
        • CIMInt.__repr__()
        • CIMInt.maxvalue
        • CIMInt.minvalue
      • Uint8
        • Uint8.cimtype
        • Uint8.maxvalue
        • Uint8.minvalue
      • Sint8
        • Sint8.cimtype
        • Sint8.maxvalue
        • Sint8.minvalue
      • Uint16
        • Uint16.cimtype
        • Uint16.maxvalue
        • Uint16.minvalue
      • Sint16
        • Sint16.cimtype
        • Sint16.maxvalue
        • Sint16.minvalue
      • Uint32
        • Uint32.cimtype
        • Uint32.maxvalue
        • Uint32.minvalue
      • Sint32
        • Sint32.cimtype
        • Sint32.maxvalue
        • Sint32.minvalue
      • Uint64
        • Uint64.cimtype
        • Uint64.maxvalue
        • Uint64.minvalue
      • Sint64
        • Sint64.cimtype
        • Sint64.maxvalue
        • Sint64.minvalue
      • CIMFloat
        • CIMFloat.__repr__()
      • Real32
        • Real32.cimtype
      • Real64
        • Real64.cimtype
    • 4.4. Conversion functions
      • tocimxml()
      • tocimxmlstr()
      • cimvalue()
      • cimtype()
      • type_from_name()
    • 4.5. CIM status codes
      • CIM_ERR_ACCESS_DENIED
      • CIM_ERR_ALREADY_EXISTS
      • CIM_ERR_CLASS_HAS_CHILDREN
      • CIM_ERR_CLASS_HAS_INSTANCES
      • CIM_ERR_CONTINUATION_ON_ERROR_NOT_SUPPORTED
      • CIM_ERR_FAILED
      • CIM_ERR_FILTERED_ENUMERATION_NOT_SUPPORTED
      • CIM_ERR_INVALID_CLASS
      • CIM_ERR_INVALID_ENUMERATION_CONTEXT
      • CIM_ERR_INVALID_NAMESPACE
      • CIM_ERR_INVALID_OPERATION_TIMEOUT
      • CIM_ERR_INVALID_PARAMETER
      • CIM_ERR_INVALID_QUERY
      • CIM_ERR_INVALID_SUPERCLASS
      • CIM_ERR_METHOD_NOT_AVAILABLE
      • CIM_ERR_METHOD_NOT_FOUND
      • CIM_ERR_NAMESPACE_NOT_EMPTY
      • CIM_ERR_NOT_FOUND
      • CIM_ERR_NOT_SUPPORTED
      • CIM_ERR_NO_SUCH_PROPERTY
      • CIM_ERR_PULL_CANNOT_BE_ABANDONED
      • CIM_ERR_PULL_HAS_BEEN_ABANDONED
      • CIM_ERR_QUERY_LANGUAGE_NOT_SUPPORTED
      • CIM_ERR_SERVER_IS_SHUTTING_DOWN
      • CIM_ERR_SERVER_LIMITS_EXCEEDED
      • CIM_ERR_TYPE_MISMATCH
      • DEFAULT_NAMESPACE
      • DEFAULT_URL_PORT_HTTP
      • DEFAULT_URL_PORT_HTTPS
      • DEFAULT_URL_SCHEME
    • 4.6. Exceptions
      • ConnectionError
      • AuthError
      • HTTPError
        • HTTPError.cimdetails
        • HTTPError.cimerror
        • HTTPError.reason
        • HTTPError.status
      • TimeoutError
      • ParseError
      • CIMXMLParseError
      • XMLParseError
      • HeaderParseError
      • CIMError
        • CIMError.instances
        • CIMError.status_code
        • CIMError.status_code_name
        • CIMError.status_description
      • ModelError
      • Error
        • Error.conn_id
        • Error.conn_str
    • 4.7. Warnings
      • Warning
      • ToleratedServerIssueWarning
    • 4.8. WBEM operation statistics
      • Statistics
        • Statistics.__call__()
        • Statistics.__enter__()
        • Statistics.__exit__()
        • Statistics.__repr__()
        • Statistics.disable()
        • Statistics.enable()
        • Statistics.enabled
        • Statistics.formatted()
        • Statistics.get_op_statistic()
        • Statistics.reset()
        • Statistics.snapshot()
        • Statistics.start_timer()
      • OperationStatistic
        • OperationStatistic.__repr__()
        • OperationStatistic.avg_reply_len
        • OperationStatistic.avg_request_len
        • OperationStatistic.avg_server_time
        • OperationStatistic.avg_time
        • OperationStatistic.container
        • OperationStatistic.count
        • OperationStatistic.exception_count
        • OperationStatistic.formatted()
        • OperationStatistic.formatted_header()
        • OperationStatistic.max_reply_len
        • OperationStatistic.max_request_len
        • OperationStatistic.max_server_time
        • OperationStatistic.max_time
        • OperationStatistic.min_reply_len
        • OperationStatistic.min_request_len
        • OperationStatistic.min_server_time
        • OperationStatistic.min_time
        • OperationStatistic.name
        • OperationStatistic.reset()
        • OperationStatistic.start_timer()
        • OperationStatistic.stat_start_time
        • OperationStatistic.stop_timer()
    • 4.9. WBEM operation logging
      • 4.9.1. Pywbem logging overview
      • 4.9.2. Logging configuration functions
      • 4.9.3. Logging configuration examples
      • 4.9.4. Log records
      • 4.9.5. Logging related constants and functions
      • DEFAULT_LOG_DESTINATION
      • DEFAULT_LOG_DETAIL_LEVEL
      • LOGGER_API_CALLS_NAME
      • LOGGER_HTTP_NAME
      • LOGGER_SIMPLE_NAMES
      • LOG_DESTINATIONS
      • LOG_DETAIL_LEVELS
      • configure_logger()
      • configure_loggers_from_string()
    • 4.10. Mapping between ValueMap and Values qualifiers
      • ValueMapping
        • ValueMapping.__repr__()
        • ValueMapping.classname
        • ValueMapping.conn
        • ValueMapping.element
        • ValueMapping.for_method()
        • ValueMapping.for_parameter()
        • ValueMapping.for_property()
        • ValueMapping.items()
        • ValueMapping.methodname
        • ValueMapping.namespace
        • ValueMapping.parametername
        • ValueMapping.propname
        • ValueMapping.tobinary()
        • ValueMapping.tovalues()
    • 4.11. Support for PUnit and Units qualifiers
      • siunit_obj()
      • siunit()
    • 4.12. Security considerations
      • 4.12.1. Authentication types
      • 4.12.2. Verification of the X.509 server certificate
      • 4.12.3. Use of X.509 client certificates
      • 4.12.4. Authentication errors
    • 4.13. Proxy support
  • 5. WBEM server library
    • 5.1. Example
    • 5.2. WBEMServer
      • WBEMServer
        • WBEMServer.INTEROP_NAMESPACES
        • WBEMServer.NAMESPACE_CLASSNAMES
        • WBEMServer.__repr__()
        • WBEMServer.__str__()
        • WBEMServer.brand
        • WBEMServer.cimom_inst
        • WBEMServer.conn
        • WBEMServer.create_namespace()
        • WBEMServer.delete_namespace()
        • WBEMServer.get_central_instances()
        • WBEMServer.get_selected_profiles()
        • WBEMServer.interop_ns
        • WBEMServer.namespace_classname
        • WBEMServer.namespace_paths
        • WBEMServer.namespaces
        • WBEMServer.profiles
        • WBEMServer.url
        • WBEMServer.version
  • 6. WBEM indication listener
    • 6.1. WBEMListener
      • 6.1.1. Examples
      • 6.1.2. Logging in the listener
      • 6.1.3. WBEMListener class
      • WBEMListener
        • WBEMListener.__enter__()
        • WBEMListener.__exit__()
        • WBEMListener.__repr__()
        • WBEMListener.__str__()
        • WBEMListener.add_callback()
        • WBEMListener.certfile
        • WBEMListener.deliver_indication()
        • WBEMListener.host
        • WBEMListener.http_port
        • WBEMListener.http_started
        • WBEMListener.https_port
        • WBEMListener.https_started
        • WBEMListener.keyfile
        • WBEMListener.logger
        • WBEMListener.start()
        • WBEMListener.stop()
      • callback_interface()
    • 6.2. Listener exceptions
      • ListenerCertificateError
      • ListenerPortError
      • ListenerPromptError
      • ListenerError
  • 7. WBEM subscription manager
    • 7.1. WBEMSubscriptionManager
      • 7.1.1. Examples
      • WBEMSubscriptionManager
        • WBEMSubscriptionManager.__enter__()
        • WBEMSubscriptionManager.__exit__()
        • WBEMSubscriptionManager.__repr__()
        • WBEMSubscriptionManager.__str__()
        • WBEMSubscriptionManager.add_destination()
        • WBEMSubscriptionManager.add_filter()
        • WBEMSubscriptionManager.add_server()
        • WBEMSubscriptionManager.add_subscriptions()
        • WBEMSubscriptionManager.get_all_destinations()
        • WBEMSubscriptionManager.get_all_filters()
        • WBEMSubscriptionManager.get_all_subscriptions()
        • WBEMSubscriptionManager.get_owned_destinations()
        • WBEMSubscriptionManager.get_owned_filters()
        • WBEMSubscriptionManager.get_owned_subscriptions()
        • WBEMSubscriptionManager.remove_all_servers()
        • WBEMSubscriptionManager.remove_destinations()
        • WBEMSubscriptionManager.remove_filter()
        • WBEMSubscriptionManager.remove_server()
        • WBEMSubscriptionManager.remove_subscriptions()
  • 8. MOF compiler
    • 8.1. MOFCompiler Class
      • MOFCompiler
        • MOFCompiler.compile_embedded_value()
        • MOFCompiler.compile_file()
        • MOFCompiler.compile_string()
        • MOFCompiler.conn_close()
        • MOFCompiler.find_mof()
        • MOFCompiler.rollback()
    • 8.2. Repository connections
      • BaseRepositoryConnection
        • BaseRepositoryConnection.CreateClass()
        • BaseRepositoryConnection.CreateInstance()
        • BaseRepositoryConnection.DeleteClass()
        • BaseRepositoryConnection.DeleteInstance()
        • BaseRepositoryConnection.DeleteQualifier()
        • BaseRepositoryConnection.EnumerateInstanceNames()
        • BaseRepositoryConnection.EnumerateQualifiers()
        • BaseRepositoryConnection.GetClass()
        • BaseRepositoryConnection.GetQualifier()
        • BaseRepositoryConnection.ModifyClass()
        • BaseRepositoryConnection.ModifyInstance()
        • BaseRepositoryConnection.SetQualifier()
        • BaseRepositoryConnection.default_namespace
      • MOFWBEMConnection
        • MOFWBEMConnection.CreateClass()
        • MOFWBEMConnection.CreateInstance()
        • MOFWBEMConnection.DeleteClass()
        • MOFWBEMConnection.DeleteInstance()
        • MOFWBEMConnection.DeleteQualifier()
        • MOFWBEMConnection.EnumerateInstanceNames()
        • MOFWBEMConnection.EnumerateQualifiers()
        • MOFWBEMConnection.GetClass()
        • MOFWBEMConnection.GetQualifier()
        • MOFWBEMConnection.ModifyClass()
        • MOFWBEMConnection.ModifyInstance()
        • MOFWBEMConnection.SetQualifier()
        • MOFWBEMConnection.default_namespace
        • MOFWBEMConnection.getns()
        • MOFWBEMConnection.rollback()
        • MOFWBEMConnection.setns()
    • 8.3. Exceptions
      • MOFCompileError
        • MOFCompileError.__str__()
        • MOFCompileError.column
        • MOFCompileError.context
        • MOFCompileError.file
        • MOFCompileError.get_err_msg()
        • MOFCompileError.lineno
        • MOFCompileError.msg
      • MOFParseError
      • MOFDependencyError
      • MOFRepositoryError
        • MOFRepositoryError.cim_error
        • MOFRepositoryError.get_err_msg()
  • 9. Mock WBEM server
    • 9.1. Overview
    • 9.2. WBEM operations of a mock WBEM server
      • 9.2.1. Faked instance operations
      • 9.2.2. Faked association operations
      • 9.2.3. Faked method invocation operation
      • 9.2.4. Faked pull operations
      • 9.2.5. Faked iter operations
      • 9.2.6. Faked class operations
      • 9.2.7. Faked qualifier declaration operations
    • 9.3. FakedWBEMConnection class
      • FakedWBEMConnection
        • FakedWBEMConnection.__repr__()
        • FakedWBEMConnection.__str__()
        • FakedWBEMConnection.add_cimobjects()
        • FakedWBEMConnection.add_namespace()
        • FakedWBEMConnection.cimrepository
        • FakedWBEMConnection.compile_mof_file()
        • FakedWBEMConnection.compile_mof_string()
        • FakedWBEMConnection.compile_schema_classes()
        • FakedWBEMConnection.copy()
        • FakedWBEMConnection.disable_pull_operations
        • FakedWBEMConnection.display_registered_providers()
        • FakedWBEMConnection.display_repository()
        • FakedWBEMConnection.find_interop_namespace()
        • FakedWBEMConnection.install_namespace_provider()
        • FakedWBEMConnection.install_subscription_providers()
        • FakedWBEMConnection.interop_namespace_names
        • FakedWBEMConnection.is_interop_namespace()
        • FakedWBEMConnection.namespaces
        • FakedWBEMConnection.provider_dependent_registry
        • FakedWBEMConnection.register_provider()
        • FakedWBEMConnection.remove_namespace()
        • FakedWBEMConnection.response_delay
    • 9.4. Building a mocked CIM repository
      • 9.4.1. Example: Set up qualifier types and classes in DMTF CIM schema
      • 9.4.2. Example: Set up qualifier types and classes from MOF
      • 9.4.3. Example: Set up instances from single CIM objects
      • 9.4.4. DMTF CIM schema download support
        • DMTFCIMSchema
      • 9.4.5. In-memory CIM repository classes
        • InMemoryRepository
        • InMemoryObjectStore
    • 9.5. Mocking multiple CIM namespaces
    • 9.6. User-defined providers
      • 9.6.1. Creating user-defined providers
      • 9.6.2. Python operation methods in user-defined providers
      • 9.6.3. User-defined instance write providers
        • InstanceWriteProvider
      • 9.6.4. User-defined method providers
        • MethodProvider
      • 9.6.5. CIM_Namespace provider
        • CIMNamespaceProvider
    • 9.7. Registry for provider dependent files
      • ProviderDependentRegistry
        • ProviderDependentRegistry.__repr__()
        • ProviderDependentRegistry.add_dependents()
        • ProviderDependentRegistry.iter_dependents()
        • ProviderDependentRegistry.load()
    • 9.8. Configuration of mocked behavior
      • DEFAULT_MAX_OBJECT_COUNT
      • IGNORE_INSTANCE_ICO_PARAM
      • IGNORE_INSTANCE_IQ_PARAM
      • OBJECTMANAGERCREATIONCLASSNAME
      • OBJECTMANAGERNAME
      • OPEN_MAX_TIMEOUT
      • SYSTEMCREATIONCLASSNAME
      • SYSTEMNAME
  • 10. WBEM utility commands
    • 10.1. mof_compiler
  • 11. Development
    • 11.1. Repository
    • 11.2. Setting up the development environment
    • 11.3. Building the documentation
    • 11.4. Testing
    • 11.5. Testing from the source archives on Pypi or GitHub
    • 11.6. Testing installed versions of pywbem
    • 11.7. Updating the DMTF MOF Test Schema
    • 11.8. Developing PyWBEM Ipython Documentation Notebooks
    • 11.9. Contributing
    • 11.10. Core Development Team
  • 12. Appendix
    • 12.1. Special type names
    • 12.2. Profile advertisement methodologies
    • 12.3. Troubleshooting
      • 12.3.1. Installation fails with “invalid command ‘bdist_wheel’”
      • 12.3.2. Installation of lxml misses include files on Python 3.4 on native Windows
      • 12.3.3. ConnectionError raised with [SSL: UNSUPPORTED_PROTOCOL]
      • 12.3.4. ConnectionError raised with [SSL] EC lib
    • 12.4. Base classes
      • _RequestExceptionMixin
        • _RequestExceptionMixin.request_data
      • _ResponseExceptionMixin
        • _ResponseExceptionMixin.response_data
      • _CIMComparisonMixin
        • _CIMComparisonMixin.__eq__()
        • _CIMComparisonMixin.__hash__()
        • _CIMComparisonMixin.__ne__()
      • BaseRepository
        • BaseRepository.add_namespace()
        • BaseRepository.get_class_store()
        • BaseRepository.get_instance_store()
        • BaseRepository.get_qualifier_store()
        • BaseRepository.namespaces
        • BaseRepository.remove_namespace()
        • BaseRepository.validate_namespace()
      • BaseObjectStore
        • BaseObjectStore.create()
        • BaseObjectStore.delete()
        • BaseObjectStore.get()
        • BaseObjectStore.iter_names()
        • BaseObjectStore.iter_values()
        • BaseObjectStore.len()
        • BaseObjectStore.object_exists()
        • BaseObjectStore.update()
      • BaseProvider
        • BaseProvider.__repr__()
        • BaseProvider.add_namespace()
        • BaseProvider.cimrepository
        • BaseProvider.class_exists()
        • BaseProvider.filter_properties()
        • BaseProvider.find_interop_namespace()
        • BaseProvider.get_class()
        • BaseProvider.interop_namespace_names
        • BaseProvider.is_interop_namespace()
        • BaseProvider.is_subclass()
        • BaseProvider.namespaces
        • BaseProvider.remove_namespace()
        • BaseProvider.validate_namespace()
    • 12.5. Glossary
    • 12.6. References
  • 13. Change log
    • 13.1. pywbem 1.4.2
    • 13.2. pywbem 1.4.1
    • 13.3. pywbem 1.4.0
    • 13.4. pywbem 1.3.0
    • 13.5. pywbem 1.2.0
    • 13.6. pywbem 1.1.0
    • 13.7. pywbem 1.0.0
    • 13.8. pywbem 1.0.0b4
    • 13.9. pywbem 1.0.0b3
    • 13.10. pywbem 1.0.0b2
    • 13.11. pywbem 1.0.0b1
    • 13.12. pywbem 0.17.2
    • 13.13. pywbem 0.17.1
    • 13.14. pywbem 0.17.0
    • 13.15. pywbem 0.16.0
    • 13.16. pywbem 0.15.0
    • 13.17. pywbem 0.14.6
    • 13.18. pywbem 0.14.5
    • 13.19. pywbem 0.14.4
    • 13.20. pywbem 0.14.3
    • 13.21. pywbem 0.14.2
    • 13.22. pywbem 0.14.1
    • 13.23. pywbem 0.14.0
    • 13.24. pywbem 0.13.0
    • 13.25. pywbem 0.12.0
    • 13.26. pywbem 0.11.0
    • 13.27. pywbem 0.10.0
    • 13.28. pywbem 0.9.0
    • 13.29. pywbem 0.8.4
    • 13.30. pywbem 0.8.3
    • 13.31. pywbem 0.8.2
    • 13.32. pywbem 0.8.1
    • 13.33. pywbem 0.7.0
    • 13.34. pywbem 0.6
    • 13.35. pywbem 0.5
    • 13.36. pywbem 0.4
  • Index
pywbem
  • »
  • pywbem 1.4.2 documentation
  • Edit on GitHub

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

  • Introduction

    • Functionality

    • Supported environments

    • Installation

    • Package version

    • Version dependent features

    • Standards conformance

    • Deprecation and compatibility policy

    • Python namespaces

    • Configuration variables

    • WBEM servers

Functionality

The major components of pywbem are shown in this diagram:

pywbem components

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

  • 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 and pip commands operate on Python 2. There may be python3 and pip3 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 and pip commands operate on Python 3. There may be python2 and pip2 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
    

Building a compiled archive with Cython

The ‘Cython’ package allows building a wheel distribution archive containing compiled code for Python packages such as pywbem. These distribution archives are nicknamed “cythonized” wheel distribution archives. They have the wheel format, but are specific to a Python version and to the target operating system.

Since the code in a cythonized wheel archive is native machine code for the target system, this speeds up execution in compute-intensive areas of pywbem such as when parsing the CIM-XML responses of a WBEM server. The downside is that a cythonized wheel archive is significantly larger than a universal wheel archive, and the memory consumption is also larger.

The pywbem project does not provide cythonized wheel distribution archives, but allows users to build them on their own. The build process for them is part of the regular tests to ensure they can be built.

To build the cythonized wheel distribution archive of pywbem, execute:

$ make buildc

The resulting distribution archive can be installed with Pip, for example:

$ pip install dist/pywbem-1.2.0.dev1-cp38-cp38-macosx_10_15_x86_64.whl

Pip will verify that the target system and Python version matches what the wheel archive was built for.

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.4.2'

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 the ModifyClass 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 CIM-XML representation of CIM objects as produced by their tocimxml() and tocimxmlstr() 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 of CIMInstanceName and CIMClassName 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 Python warnings 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.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.

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 as IterEnumerateInstances(), 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.ENFORCE_INTEGER_RANGE = True

Enforce the allowable value range for CIM integer types (e.g. Uint8). For details, see the CIMInt 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.

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.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.

WBEM servers

Server-specific features

Pywbem supports the following features of some specific WBEM servers that are additions to the DMTF standards:

  1. 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 the pywbem.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 variant EmbeddedObject 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.

  2. SFCB (Small Footprint CIM Broker)

    • None

  3. 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

  • Concepts

    • The CIM/WBEM architecture

    • The CIM model and CIM objects

    • WBEM Operations: Communicating with the WBEM Server

    • WBEM indications and subscriptions

    • WBEM Management Profiles

The CIM/WBEM architecture

ISSUE #2669: Write this section on CIM/WBEM architecture

The CIM model and CIM objects

ISSUE #2669: Write this section on the model and CIM objects

WBEM Operations: Communicating with the WBEM Server

ISSUE #2669: Write this section on WBEM Operations

WBEM operations overview

ISSUE #2669 Write this section on WBEM operations overview

Traditional operations

ISSUE #2669 - Write this section on traditional operations

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:

  1. Prepend the traditional operation name with Open and Pull

  2. Suffix the pull operations that return both instances and paths with WithPath

  3. 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:

  1. 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.

  2. 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

  3. They limit the memory used by the client since it can define the maximum size of any response.

  4. They allow the client to terminate an enumeration early with the CloseEnumeration.

  5. 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.

  6. 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:

  1. It is the same value for open and pull requests.

  2. 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

ISSUE #2669: write this Section on indications and subscriptions

WBEM Management Profiles

ISSUE #2669: 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 or WBEM listener. All WBEM operations defined in DSP0200 can be issued across this connection. Each method of this class corresponds directly to a WBEM operation.

WBEMConnection methods targeting a server

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 methods targeting a listener

Purpose

ExportIndication()

Send an indication to a WBEM listener

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 or WBEM listener. This is the main class of the WBEM client library API.

This class is used for communication with WBEM servers and WBEM listeners, because the communication mechanisms are very similar. However, a particular object of this class will connect to only one target which is either a WBEM server or a WBEM listener, but never both.

When targeting a WBEM server, 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 or WBEM listener, and each subsequent WBEM operation performs an independent, state-less HTTP/HTTPS request. However, usage of the requests Python package causes the underlying resources such as sockets to be pooled. A close() method closes the underlying session of the requests package, releasing any sockets.

The WBEMConnection class can also be used as a context manager, which causes the connection to be closed at context manager exit:

with WBEMConnection('https://myserver') as conn:
    conn.EnumerateInstances('CIM_Foo')

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 or WBEM listener. See WBEM operations for a list of these methods. Each operation method describes whether it can be used with a WBEM server or with a WBEM listener.

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 the last_request and last_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 the last_raw_request and last_raw_reply attributes of the connection object.

The methods of this class may raise the following exceptions:

  • Exceptions indicating operational errors:

    • ConnectionError - A connection with the WBEM server or WBEM listener could not be established or broke down.

    • AuthError - Authentication failed with the WBEM server. This exception cannot occur when targeting a WBEM listener.

    • TimeoutError - The WBEM server or WBEM listener 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 or WBEM listener.

    • CIMXMLParseError - The response from the WBEM server or WBEM listener 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 or WBEM listener 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 or WBEM listener.

  • Other exceptions:

    • CIMError - The WBEM server or WBEM listener 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 or listener).

  • 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 or WBEM listener, 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

    For WBEM listeners, the port usually different and should therefore be specified in the URL.

    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 an Authorization header using HTTP Basic Authentication.

    See Authentication types for an overview.

    This parameter will be ignored when targeting a WBEM listener.

  • 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.

    This parameter will be ignored when targeting a WBEM listener.

  • x509 (dict) –

    X.509 client certificate and key file to be presented to the WBEM server or WBEM listener during the TLS/SSL handshake.

    This parameter is ignored when HTTP is used.

    If None, no client certificate is presented to the server or listener, resulting in TLS/SSL 1-way authentication to be used.

    Otherwise, the client certificate is presented to the server or listener, 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.

    The dictionary is copied.

    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 or WBEM listener.

    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.

  • no_verification (bool) –

    Disables verification of the X.509 server certificate returned by the WBEM server or WBEM listener 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 or listener.

    New in pywbem 0.8.

    If the server or listener 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. Note that as per DSP0200, WBEM servers need to return status code CIM_ERR_NOT_SUPPORTED if a pull operation is not supported. Some WBEM servers return status code CIM_ERR_FAILED in this case, which is treated by pywbem to also mean that the pull operation is not supported.

    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 (or CIM_ERR_FAILED for some WBEM servers) will be raised.

    False (default) means that the Iter…() methods will only use traditional operations.

    This parameter will be ignored when targeting a WBEM listener.

  • 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.

    This parameter will be ignored when targeting a WBEM listener.

  • proxies (dict) –

    Dictionary with the URLs of HTTP or SOCKS proxies to use for the connection to the WBEM server or WBEM listener.

    New in pywbem 1.0

    None (the default) causes the use of direct connections without using a proxy.

    An input dictionary is copied.

    This parameter is passed on to the proxies parameter of the requests package. See the Proxy support section for details.

Methods:

AssociatorNames(ObjectName[, AssocClass, ...])

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(ObjectName[, AssocClass, ...])

Retrieve the instances associated to a source instance, or the classes associated to a source class.

CloseEnumeration(context)

Close an open enumeration session, causing an early termination of an incomplete enumeration session.

CreateClass(NewClass[, namespace])

Create a class in a namespace.

CreateInstance(NewInstance[, namespace])

Create an instance in a namespace.

DeleteClass(ClassName[, namespace])

Delete a class.

DeleteInstance(InstanceName)

Delete an instance.

DeleteQualifier(QualifierName[, namespace])

Delete a qualifier type (= qualifier declaration).

EnumerateClassNames([namespace, ClassName, ...])

Enumerate the names of subclasses of a class, or of the top-level classes in a namespace.

EnumerateClasses([namespace, ClassName, ...])

Enumerate the subclasses of a class, or the top-level classes in a namespace.

EnumerateInstanceNames(ClassName[, namespace])

Enumerate the instance paths of instances of a class (including instances of its subclasses) in a namespace.

EnumerateInstances(ClassName[, namespace, ...])

Enumerate the instances of a class (including instances of its subclasses) in a namespace.

EnumerateQualifiers([namespace])

Enumerate the qualifier types (= qualifier declarations) in a namespace.

ExecQuery(QueryLanguage, Query[, namespace])

Execute a query in a namespace.

ExportIndication(NewIndication)

Send an indication to a WBEM listener.

GetClass(ClassName[, namespace, LocalOnly, ...])

Retrieve a class.

GetInstance(InstanceName[, LocalOnly, ...])

Retrieve an instance.

GetQualifier(QualifierName[, namespace])

Retrieve a qualifier type (= qualifier declaration).

InvokeMethod(MethodName, ObjectName[, Params])

Invoke a method on a target instance or on a target class.

IterAssociatorInstancePaths(InstanceName[, ...])

Retrieve the instance paths of the instances associated to a source instance, using the Python generator idiom to return the result.

IterAssociatorInstances(InstanceName[, ...])

Retrieve the instances associated to a source instance, using the Python generator idiom to return the result.

IterEnumerateInstancePaths(ClassName[, ...])

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(ClassName[, ...])

Enumerate the instances of a class (including instances of its subclasses) in a namespace, using the Python generator idiom to return the result.

IterQueryInstances(FilterQueryLanguage, ...)

Execute a query in a namespace, using the Python generator idiom to return the result.

IterReferenceInstancePaths(InstanceName[, ...])

Retrieve the instance paths of the association instances that reference a source instance, using the Python generator idiom to return the result.

IterReferenceInstances(InstanceName[, ...])

Retrieve the association instances that reference a source instance, using the Python generator idiom to return the result.

ModifyClass(ModifiedClass[, namespace])

Modify a class.

ModifyInstance(ModifiedInstance[, ...])

Modify the property values of an instance.

OpenAssociatorInstancePaths(InstanceName[, ...])

Open an enumeration session to retrieve the instance paths of the instances associated to a source instance.

OpenAssociatorInstances(InstanceName[, ...])

Open an enumeration session to retrieve the instances associated to a source instance.

OpenEnumerateInstancePaths(ClassName[, ...])

Open an enumeration session to enumerate the instance paths of instances of a class (including instances of its subclasses) in a namespace.

OpenEnumerateInstances(ClassName[, ...])

Open an enumeration session to enumerate the instances of a class (including instances of its subclasses) in a namespace.

OpenQueryInstances(FilterQueryLanguage, ...)

Open an enumeration session to execute a query in a namespace and to retrieve the instances representing the query result.

OpenReferenceInstancePaths(InstanceName[, ...])

Open an enumeration session to retrieve the instance paths of the association instances that reference a source instance.

OpenReferenceInstances(InstanceName[, ...])

Open an enumeration session to retrieve the association instances that reference a source instance.

PullInstancePaths(context, MaxObjectCount)

Retrieve the next set of instance paths from an open enumeration session.

PullInstances(context, MaxObjectCount)

Retrieve the next set of instances (without instance paths) from an open enumeration session.

PullInstancesWithPath(context, MaxObjectCount)

Retrieve the next set of instances (with instance paths) from an open enumeration session.

ReferenceNames(ObjectName[, ResultClass, Role])

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(ObjectName[, ResultClass, Role, ...])

Retrieve the association instances that reference a source instance, or the association classes that reference a source class.

SetQualifier(QualifierDeclaration[, namespace])

Create or modify a qualifier type (= qualifier declaration) in a namespace.

__enter__()

New in pywbem 1.2.

__exit__(exc_type, exc_value, traceback)

New in pywbem 1.2.

__repr__()

Return a representation of the WBEMConnection object with all attributes (except for the password in the credentials) that is suitable for debugging.

__str__()

Return a short representation of the WBEMConnection object for human consumption.

close()

Closes this connection.

copy()

New in pywbem 1.3.

is_subclass(namespace, klass, superclass)

Return boolean indicating whether a class is a (direct or indirect) subclass of a superclass, or the same class, in the specified namespace.

Attributes:

ca_certs

Selects the CA certificates (trusted certificates) for verifying the X.509 server certificate returned by the WBEM server or WBEM listener.

conn_id

connection 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 or WBEM listener, 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

unicode string: CIM-XML data of the last response received from the WBEM server or WBEM listener on this connection, formatted as it was received (=raw).

last_raw_request

unicode string: CIM-XML data of the last request sent to the WBEM server or WBEM listener on this connection, formatted as it was sent (=raw).

last_reply

unicode string: CIM-XML data of the last response received from the WBEM server or WBEM listener on this connection, formatted as prettified XML.

last_reply_len

int: The size of the HTTP body in the CIM-XML response of the last operation, in Bytes.

last_request

unicode string: CIM-XML data of the last request sent to the WBEM server or WBEM listener on this connection, formatted as prettified XML.

last_request_len

int: 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.

proxies

Dictionary with the URLs of HTTP or SOCKS proxies to use for the connection to the WBEM server or WBEM listener.

scheme

Normalized scheme of the URL of the WBEM server or WBEM listener, 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 or listener.

url

Normalized URL of the WBEM server or WBEM listener.

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 or WBEM listener during the TLS/SSL handshake.

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.

  • 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.:

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.

  • 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 a CIMInstanceName 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.

:raises Exceptions described in WBEMConnection.:

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:

  • server_context (string): Enumeration context string returned by the server. This string is opaque for the client.

  • namespace (string): Name of the CIM namespace being used for this enumeration session.

:raises Exceptions described in WBEMConnection.:

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.:

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.:

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 a CIMClassName 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.:

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.:

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.:

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.:

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.:

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 a CIMClassName 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.:

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 a CIMClassName 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() and EnumerateClassNames() 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 a CIMInstanceName 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.:

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.:

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.:

ExportIndication(NewIndication)[source]

Send an indication to a WBEM listener.

This method performs the ExportIndication export method (see DSP0200). See WBEM operations for a list of all methods performing such export methods.

If the export method succeeds, this method returns. Otherwise, this method raises an exception.

Parameters

NewIndication (CIMInstance) – A representation of the CIM indication instance to be sent.

:raises Exceptions described in WBEMConnection.:

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 a CIMClassName 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.:

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 a CIMInstanceName 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.:

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.:

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.

  • 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.:

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() and PullInstancePaths()). 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 the WBEMConnection 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 of WBEMConnection 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 code CIM_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.

  • 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 code CIM_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.

  • 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))
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() and PullInstancesWithPath()). 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 the WBEMConnection 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 of WBEMConnection 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 code CIM_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.

  • 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 code CIM_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.

  • 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()))
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() and PullInstancePaths()). 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 the WBEMConnection 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 of WBEMConnection 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 a CIMClassName 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 code CIM_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.

  • 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 code CIM_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.

  • 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))
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() and PullInstancesWithPath()). 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 the WBEMConnection 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 of WBEMConnection 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 a CIMClassName 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() and EnumerateClassNames() 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 code CIM_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.

  • 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 code CIM_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.

  • 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.: :raises 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()))
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() and PullInstances()). 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 the WBEMConnection 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 of WBEMConnection 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 code CIM_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.

  • 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 code CIM_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.

  • 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()))
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() and PullInstancePaths()). 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 the WBEMConnection 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 of WBEMConnection 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 code CIM_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.

  • 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 code CIM_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.

  • 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))
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() and PullInstancesWithPath()). 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 the WBEMConnection 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 of WBEMConnection 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 code CIM_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.

  • 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 code CIM_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.

  • 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()))
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.:

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.:

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 the CloseEnumeration() 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 code CIM_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.

  • 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 code CIM_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.

  • 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 of CIMInstanceName): 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.:

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 the CloseEnumeration() 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 code CIM_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.

  • 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 code CIM_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.

  • 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 of CIMInstance): Representations of the retrieved instances.

    The path attribute of each CIMInstance object is a CIMInstanceName 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.:

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 the CloseEnumeration() 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 a CIMClassName 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 code CIM_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.

  • 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 code CIM_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.

  • 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 of CIMInstanceName): 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))
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 the CloseEnumeration() 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 a CIMClassName 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() and EnumerateClassNames() 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 code CIM_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.

  • 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 code CIM_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.

  • 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 of CIMInstance): Representations of the retrieved instances.

    The path attribute of each CIMInstance object is a CIMInstanceName 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()))
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 the CloseEnumeration() 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 code CIM_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.

  • 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 code CIM_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.

  • 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 of CIMInstance): 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.:

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 the CloseEnumeration() 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 code CIM_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.

  • 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 code CIM_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.

  • 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 of CIMInstanceName): 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.:

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 the CloseEnumeration() 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 code CIM_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.

  • 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 code CIM_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.

  • 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 of CIMInstance): Representations of the retrieved instances.

    The path attribute of each CIMInstance object is a CIMInstanceName 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.:

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:

  • OpenEnumerateInstancePaths()

  • OpenAssociatorInstancePaths()

  • OpenReferenceInstancePaths()

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:

    • server_context (string): Enumeration context string returned by the server. This string is opaque for the client.

    • namespace (string): Name of the CIM namespace being used for this enumeration session.

  • 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 of CIMInstanceName): 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.:

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:

  • OpenQueryInstances()

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:

    • server_context (string): Enumeration context string returned by the server. This string is opaque for the client.

    • namespace (string): Name of the CIM namespace being used for this enumeration session.

  • 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 of CIMInstance): 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.:

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:

  • OpenEnumerateInstances()

  • OpenAssociatorInstances()

  • OpenReferenceInstances()

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:

    • server_context (string): Enumeration context string returned by the server. This string is opaque for the client.

    • namespace (string): Name of the CIM namespace being used for this enumeration session.

  • 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 of CIMInstance): Representations of the retrieved instances.

    The path attribute of each CIMInstance object is a CIMInstanceName 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.:

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.

  • 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.:

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.

  • 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 a CIMInstanceName 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.

: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.:

__enter__()[source]

New in pywbem 1.2.

Enter method when the class is used as a context manager. Returns the connection object.

__exit__(exc_type, exc_value, traceback)[source]

New in pywbem 1.2.

Exit method when the class is used as a context manager.

It closes the connection by calling close().

__repr__()[source]

Return a representation of the WBEMConnection object with all attributes (except for the password in the credentials) that is suitable for debugging.

__str__()[source]

Return a short representation of the WBEMConnection object for human consumption.

property ca_certs

Selects the CA certificates (trusted certificates) for verifying the X.509 server certificate returned by the WBEM server or WBEM listener.

For details, see the description of the same-named init parameter of this class.

Type

string

close()[source]

Closes this connection.

New in pywbem 1.2.

This method closes the session in the underlying requests package, causing it to close any sockets it has pooled and marks the connection closed. Any subsequent WBEM connection operation requests will generate an exception.

Raises

ConnectionError – WBEMConnection is closed

property conn_id

connection 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.

copy()[source]

New in pywbem 1.3.

Return a deep copy of the object with internal state reset.

The user-specifiable attributes of the object are deep-copied, and all other internal state (e.g. session, statistics, debug data) is reset.

Any operation recorders on the original object are also deep-copied while resetting their internal state (e.g. staged operations).

property creds

Credentials for HTTP authentication with the WBEM server.

For details, see the description of the same-named init parameter of this class.

This attribute is ignored when targeting a WBEM listener.

Type

tuple

property 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:

  • last_request

  • last_reply

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:

  • last_raw_request

  • last_raw_reply

  • last_request_len

  • last_reply_len

Type

bool

property 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.

This attribute is ignored when targeting a WBEM listener.

Type

unicode string

property host

Normalized host and port number of the WBEM server or WBEM listener, 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

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
  • namespace (string) – Namespace (case insensitive).

  • klass (CIMClass or string) – The class as a CIM object or as its class name.

  • superclass (CIMClass or string) – The superclass as a CIM object or as its class name.

Returns

Boolean indicating whether the class is a (direct or indirect) subclass of the superclass, or the same class.

Return type

bool

Raises
  • CIMError – Namespace does not exist.

  • CIMError – The class or superclass does not exist in the namespace.

property 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

property last_raw_reply

unicode string: CIM-XML data of the last response received from the WBEM server or WBEM listener 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 or WBEM listener, and is set to the prettified response when the response has been received from the WBEM server or WBEM listener, 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).

property last_raw_request

unicode string: CIM-XML data of the last request sent to the WBEM server or WBEM listener 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).

property last_reply

unicode string: CIM-XML data of the last response received from the WBEM server or WBEM listener 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 or WBEM listener, and is set to the prettified response when the response has been received from the WBEM server or WBEM listener 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.

property last_reply_len

int: 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 or WBEM listener, and is set to the size when the response has been received from the WBEM server or WBEM listener, 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).

property last_request

unicode string: CIM-XML data of the last request sent to the WBEM server or WBEM listener 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.

property last_request_len

int: 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).

property 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.

When targeting a WBEM listener, the value is always None.

Type

float

property 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

property proxies

Dictionary with the URLs of HTTP or SOCKS proxies to use for the connection to the WBEM server or WBEM listener.

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

property scheme

Normalized scheme of the URL of the WBEM server or WBEM listener, 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

property 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 the stats_enabled property on this connection object. See the WBEM operation statistics section for more details.

Type

Statistics

property 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 of WBEMConnection.

Type

bool

property timeout

Timeout in seconds, for requests sent to the server or listener.

New in pywbem 0.8.

New in pywbem 1.3.: This attribute is settable.

For details, see the description of the same-named init parameter of this class.

Type

number

property url

Normalized URL of the WBEM server or WBEM listener.

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

property 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.

This attribute is ignored when targeting a WBEM listener.

Type

bool

property x509

X.509 client certificate and key file to be presented to the WBEM server or WBEM listener during the TLS/SSL handshake.

For details, see the description of the same-named init parameter of this class.

Type

dict

class pywbem.IterQueryInstancesReturn(instances, query_result_class=None)[source]

The return data for IterQueryInstances().

Save any query_result_class and instances returned

Attributes:

generator

generator iterating CIMInstance: A generator object that iterates the CIM instances representing the query result.

query_result_class

The query result class, if requested via the ReturnQueryResultClass parameter of IterQueryInstances().

property 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.

property query_result_class

The query result class, if requested via the ReturnQueryResultClass parameter of IterQueryInstances().

None, if a query result class was not requested.

Type

CIMClass

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 value

  • dict 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.

class pywbem.NocaseDict(*args, **kwargs)[source]

NocaseDict class using nocasedict.NocaseDict, adding the following functionality:

  • hashability via nocasedict.HashableMixin

  • keyability by attribute ‘name’ via nocasedict.KeyableByMixin(‘name’)

  • the ability to allow or disallow (by default) unnamed keys via a public ‘allow_unnamed_keys’ attribute

__contains__(key)[source]

Return a boolean indicating whether the dictionary contains an item with the key (looked up case-insensitively).

Invoked when using: key in ncd

Raises

AttributeError – Key does not have a lower() method.

__delitem__(key)[source]

Delete the item with an existing key (looked up case-insensitively).

Invoked when using: del ncd[key]

Raises
  • AttributeError – Key does not have a lower() method.

  • KeyError – Key does not exist (case-insensitively).

__getitem__(key)[source]

Return the value of the item with an existing key (looked up case-insensitively).

Invoked when using e.g.: value = ncd[key]

Raises
  • AttributeError – Key does not have a lower() method.

  • KeyError – Key does not exist (case-insensitively).

__setitem__(key, value)[source]

Update the value of the item with an existing key (looked up case-insensitively), or if an item with the key does not exist, add an item with the specified key and value.

Invoked when using e.g.: ncd[key] = value

Raises

AttributeError – Key does not have a lower() method.

pop(key, default=<object object>)[source]

Remove the item with the specified key if it exists (looked up case-insensitively), and return its value.

If an item with the key does not exist, the default value is returned if specified, otherwise KeyError is raised.

Raises

KeyError – Key does not exist (case-insensitively) and no default was specified.

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 False

  • TypeError – An error in the provided argument types.

Methods:

__eq__(other)

Equality test function for two CIMInstanceName objects.

__hash__()

Return a hash value based on the public attributes of this class, taking into account any case insensitivities described for these attributes.

__ne__(other)

Non-equality test for two CIM objects.

__repr__()

Return a string representation of this CIM instance path, that is suitable for debugging.

__str__()

Return the WBEM URI string of this CIM instance path.

copy()

Return a new CIMInstanceName object that is a copy of this CIM instance path.

from_instance(class_, instance[, namespace, ...])

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(wbem_uri)

Return a new CIMInstanceName object from the specified WBEM URI string.

get(key[, default])

Return the value of a particular keybinding of this CIM instance path, or a default value.

has_key(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([format])

Return the (untyped) WBEM URI string of this CIM instance path.

tocimxml([ignore_host, ignore_namespace])

Return the CIM-XML representation of this CIM instance path, as an object of an appropriate subclass of Element.

tocimxmlstr([indent, ignore_host, ...])

Return the CIM-XML representation of this CIM instance path, as a unicode string.

update(*args, **kwargs)

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.

__eq__(other)[source]

Equality test function for two CIMInstanceName objects.

The equality is based on their public attributes:

  • 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.

__hash__()[source]

Return a hash value based on the public attributes of this class, taking into account any case insensitivities described for these attributes. This approach causes this class to be unchanged-hashable.

__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.

__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"
    
property 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

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() and copy.deepcopy() can be used to create completely shallow or completely deep copies of objects of this class.

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

CIMInstanceName

Raises

ValueError – The strict attribute is True and a key property does not exist in the instance.

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, or cimxml-wbems. Pywbem tolerates any namespace type, but issues a UserWarning 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.

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

CIM data type

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

property 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

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.

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.

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.

property 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

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.

property 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

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 corresponding CIMInstanceName object, such an object can be created by using the static method from_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

unicode string

Raises
  • TypeError – Invalid type in keybindings

  • ValueError – Invalid format argument

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
  • 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, 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.

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.

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.

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:

__eq__(other)

Equality test function for two CIMInstance objects.

__hash__()

Return a hash value based on the same public attributes of this class as used for equality comparison, taking into account any case insensitivities described for these attributes.

__ne__(other)

Non-equality test for two CIM objects.

__repr__()

Return a string representation of this CIM instance, that is suitable for debugging.

__str__()

Return a short string representation of this CIM instance, for human consumption.

copy()

Return a new CIMInstance object that is a copy of this CIM instance.

from_class(klass[, namespace, ...])

Return a new CIMInstance object from specified key property values and from the key property definitions in a class.

get(key[, default])

Return the value of a particular property of this CIM instance, or a default value.

has_key(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 the CIMProperty 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([ignore_path])

Return the CIM-XML representation of this CIM instance, as an object of an appropriate subclass of Element.

tocimxmlstr([indent, ignore_path])

Return the CIM-XML representation of this CIM instance, as a unicode string.

tomof([maxline])

Return a MOF string with the specification of this CIM instance.

update(*args, **kwargs)

Update the properties of this CIM instance.

update_existing(*args, **kwargs)

Update the values of already existing properties of this CIM instance.

values()

Return the property values (the value attribute of the CIMProperty 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.

__eq__(other)[source]

Equality test function for two CIMInstance objects.

The equality is based on some of their public attributes:

  • 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.

__hash__()[source]

Return a hash value based on the same public attributes of this class as used for equality comparison, taking into account any case insensitivities described for these attributes. This approach causes this class to be unchanged-hashable.

__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.

__str__()[source]

Return a short string representation of this CIM instance, for human consumption.

property 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

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 the properties dictionary (but not the dictionary object itself)

  • The CIMQualifier objects in the qualifiers dictionary (but not the dictionary object itself)

Note that the Python functions copy.copy() and copy.deepcopy() can be used to create completely shallow or completely deep copies of objects of this class.

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) – CIM class 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.

  • 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

CIMInstance

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

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

CIM data type

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

items()[source]

Return the properties of this CIM instance, where each item is a tuple of property name and value (the value attribute of the CIMProperty 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.

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 the CIMProperty 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.

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 the CIMProperty 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.

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.

property 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

property 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 a CIMProperty 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

property 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

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.

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 on CIMProperty 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

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.

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) or CIMInstance (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.

values()[source]

Return the property values (the value attribute of the CIMProperty 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.

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:

__eq__(other)

Equality test function for two CIMClassName objects.

__hash__()

Return a hash value based on the public attributes of this class, taking into account any case insensitivities described for these attributes.

__ne__(other)

Non-equality test for two CIM objects.

__repr__()

Return a string representation of this CIM class path, that is suitable for debugging.

__str__()

Return a WBEM URI string of this CIM class path.

copy()

Return a new CIMClassName object that is a copy of this CIM class path.

from_wbem_uri(wbem_uri)

Return a new CIMClassName object from the specified WBEM URI string.

to_wbem_uri([format])

Return the (untyped) WBEM URI string of this CIM class path.

tocimxml([ignore_host, ignore_namespace])

Return the CIM-XML representation of this CIM class path, as an object of an appropriate subclass of Element.

tocimxmlstr([indent, ignore_host, ...])

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.

__eq__(other)[source]

Equality test function for two CIMClassName objects.

The equality is based on their public attributes:

  • 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.

__hash__()[source]

Return a hash value based on the public attributes of this class, taking into account any case insensitivities described for these attributes. This approach causes this class to be unchanged-hashable.

__repr__()[source]

Return a string representation of this CIM class path, that is suitable for debugging.

__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
    
property 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

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() and copy.deepcopy() can be used to create completely shallow or completely deep copies of objects of this class.

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, or cimxml-wbems. Pywbem tolerates any namespace type, but issues a UserWarning 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.

property 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

property 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

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 corresponding CIMClassName object, such an object can be created by using the static method from_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

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
  • 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, 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.

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:

__eq__(other)

Equality test function for two CIMClass objects.

__hash__()

Return a hash value based on the public attributes of this class, taking into account any case insensitivities described for these attributes.

__ne__(other)

Non-equality test for two CIM objects.

__repr__()

Return a string representation of this CIM class, that is suitable for debugging.

__str__()

Return a short string representation of this CIM class, for human consumption.

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([indent])

Return the CIM-XML representation of this CIM class, as a unicode string.

tomof([maxline])

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.

__eq__(other)[source]

Equality test function for two CIMClass objects.

The equality is based on their public attributes:

  • 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.

__hash__()[source]

Return a hash value based on the public attributes of this class, taking into account any case insensitivities described for these attributes. This approach causes this class to be unchanged-hashable.

__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.

__str__()[source]

Return a short string representation of this CIM class, for human consumption.

property 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

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 the properties dictionary (but not the dictionary object itself)

  • The CIMMethod objects in the methods dictionary (but not the dictionary object itself)

  • The CIMQualifier objects in the qualifiers dictionary (but not the dictionary object itself)

Note that the Python functions copy.copy() and copy.deepcopy() can be used to create completely shallow or completely deep copies of objects of this class.

property 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

property 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 by WBEMConnection 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

property 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

property 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

property 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

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

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 a CIMClass 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:

__eq__(other)

Equality test function for two CIMProperty objects.

__hash__()

Return a hash value based on the public attributes of this class, taking into account any case insensitivities described for these attributes.

__ne__(other)

Non-equality test for two CIM objects.

__repr__()

Return a string representation of this CIM property, that is suitable for debugging.

__str__()

Return a short string representation of this CIM property, for human consumption.

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([indent])

Return the CIM-XML representation of this CIM property, as a unicode string.

tomof([is_instance, indent, maxline, line_pos])

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.

__eq__(other)[source]

Equality test function for two CIMProperty objects.

The equality is based on their public attributes:

  • 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.

__hash__()[source]

Return a hash value based on the public attributes of this class, taking into account any case insensitivities described for these attributes. This approach causes this class to be unchanged-hashable.

__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.

__str__()[source]

Return a short string representation of this CIM property, for human consumption.

property 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

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.

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

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 the qualifiers dictionary (but not the dictionary object itself)

Note that the Python functions copy.copy() and copy.deepcopy() can be used to create completely shallow or completely deep copies of objects of this class.

property 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 the EmbeddedInstance qualifier, indicating that the property value is an embedded instance of the class specified as the value of the EmbeddedInstance qualifier. The property value must be a CIMInstance object, or None.

  • "object": The property is declared with the EmbeddedObject qualifier, indicating that the property value is an embedded object (instance or class) of which the class name is not known. The property value must be a CIMInstance or CIMClass 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

property 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

property 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

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.

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

property 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

property 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

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
  • is_instance (bool) – If True, return MOF for a property value in a CIM instance. Else, return MOF for a property definition in a CIM class.

  • indent (integer) – Number of spaces to indent each line of the returned string, counted in the line with the property name.

Returns

MOF string.

Return type

unicode string

property 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

property 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

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:

__eq__(other)

Equality test function for two CIMMethod objects.

__hash__()

Return a hash value based on the public attributes of this class, taking into account any case insensitivities described for these attributes.

__ne__(other)

Non-equality test for two CIM objects.

__repr__()

Return a string representation of this CIM method, that is suitable for debugging.

__str__()

Return a short string representation of this CIM method, for human consumption.

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([indent])

Return the CIM-XML representation of this CIM method, as a unicode string.

tomof([indent, maxline])

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.

__eq__(other)[source]

Equality test function for two CIMMethod objects.

The equality is based on their public attributes:

  • 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.

__hash__()[source]

Return a hash value based on the public attributes of this class, taking into account any case insensitivities described for these attributes. This approach causes this class to be unchanged-hashable.

__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.

__str__()[source]

Return a short string representation of this CIM method, for human consumption.

property 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

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 the parameters dictionary (but not the dictionary object itself)

  • The CIMQualifier objects in the qualifiers dictionary (but not the dictionary object itself)

Note that the Python functions copy.copy() and copy.deepcopy() can be used to create completely shallow or completely deep copies of objects of this class.

property 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

property 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

property 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

property 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

property 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

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

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 a CIMMethod 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:

__eq__(other)

Equality test function for two CIMParameter objects.

__hash__()

Return a hash value based on the public attributes of this class, taking into account any case insensitivities described for these attributes.

__ne__(other)

Non-equality test for two CIM objects.

__repr__()

Return a string representation of this CIM parameter, that is suitable for debugging.

__str__()

Return a short string representation of this CIM parameter, for human consumption.

copy()

Return a new CIMParameter object that is a copy of this CIM parameter.

tocimxml([as_value])

Return the CIM-XML representation of this CIM parameter, as an object of an appropriate subclass of Element.

tocimxmlstr([indent, as_value])

Return the CIM-XML representation of this CIM parameter, as a unicode string.

tomof([indent, maxline])

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.

__eq__(other)[source]

Equality test function for two CIMParameter objects.

The equality is based on their public attributes:

  • 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.

__hash__()[source]

Return a hash value based on the public attributes of this class, taking into account any case insensitivities described for these attributes. This approach causes this class to be unchanged-hashable.

__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.

__str__()[source]

Return a short string representation of this CIM parameter, for human consumption.

property 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

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 the qualifiers dictionary (but not the dictionary object itself)

Note that the Python functions copy.copy() and copy.deepcopy() can be used to create completely shallow or completely deep copies of objects of this class.

property 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 the EmbeddedInstance qualifier, indicating that the parameter value is an embedded instance of the class specified as the value of the EmbeddedInstance qualifier. The property value must be a CIMInstance object, or None.

  • "object": The parameter is declared with the EmbeddedObject 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 a CIMInstance or CIMClass 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

property 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

property 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

property 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

property 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

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.

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 and embedded_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

property 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

property 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.

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, the propagated 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, the CIMQualifier objects for qualifier values that are specified in MOF represent the specified values, and their propagated property is False. The CIMQualifier objects for qualifier values that are not specified in MOF represent the effective values, and their propagated 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, and translatable). If any of these flavor properties is not None, the qualifier value represented by the CIMQualifier 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 a CIMQualifierDeclaration 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:

__eq__(other)

Equality test function for two CIMQualifier objects.

__hash__()

Return a hash value based on the public attributes of this class, taking into account any case insensitivities described for these attributes.

__ne__(other)

Non-equality test for two CIM objects.

__repr__()

Return a string representation of this CIM qualifier, that is suitable for debugging.

__str__()

Return a short string representation of this CIM qualifier, for human consumption.

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([indent])

Return the CIM-XML representation of this CIM qualifier, as a unicode string.

tomof([indent, maxline, line_pos])

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.

__eq__(other)[source]

Equality test function for two CIMQualifier objects.

The equality is based on their public attributes:

  • 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.

__hash__()[source]

Return a hash value based on the public attributes of this class, taking into account any case insensitivities described for these attributes. This approach causes this class to be unchanged-hashable.

__repr__()[source]

Return a string representation of this CIM qualifier, that is suitable for debugging.

__str__()[source]

Return a short string representation of this CIM qualifier, for human consumption.

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() and copy.deepcopy() can be used to create completely shallow or completely deep copies of objects of this class.

property 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

property 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

property 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

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.

property 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

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

property 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

property 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

property 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

property 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

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:

  • Has the EnableOverride flavor; overridable = True

  • Has the ToSubClass flavor; tosubclass = True

  • Does not have theTranslatable flavor; translatable = False

  • Does not have ToInstance flavor; toinstance = False. Not defined in DSP0004 and deprecated in the DMTF protocol specification DSP0200

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.

  • 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:

__eq__(other)

Equality test function for two CIMQualifierDeclaration objects.

__hash__()

Return a hash value based on the public attributes of this class, taking into account any case insensitivities described for these attributes.

__ne__(other)

Non-equality test for two CIM objects.

__repr__()

Return a string representation of this CIM qualifier type, that is suitable for debugging.

__str__()

Return a short string representation of this CIM qualifier type, for human consumption.

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([indent])

Return the CIM-XML representation of this CIM qualifier type, as a unicode string.

tomof([maxline])

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.

__eq__(other)[source]

Equality test function for two CIMQualifierDeclaration objects.

The equality is based on their public attributes:

  • 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.

__hash__()[source]

Return a hash value based on the public attributes of this class, taking into account any case insensitivities described for these attributes. This approach causes this class to be unchanged-hashable.

__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.

__str__()[source]

Return a short string representation of this CIM qualifier type, for human consumption.

property 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

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() and copy.deepcopy() can be used to create completely shallow or completely deep copies of objects of this class.

property 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

property 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

property 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

property 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

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.

property 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

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

property 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

property 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

property 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

property 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

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.

Attributes:

cimtype

The name of the CIM datatype, as a string.

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 the datetime.datetime object is timezone-aware (see MinutesFromUTC), 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:

__eq__(other)

Equality test function for two CIMDateTime objects.

__hash__()

Return a hash value based on the public attributes of this class.

fromtimestamp(ts[, tzi])

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([tzi])

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.

__eq__(other)[source]

Equality test function for two CIMDateTime objects.

The equality is based on their public attributes.

Note that a CIMDateTime object represents either a time interval or a point in time but never both. Therefore, an object representing an interval is never equal to an object representing a point in time.

Returns False if the other object is not a CIMDateTime object.

__hash__()[source]

Return a hash value based on the public attributes of this class. Because these attributes are not modifiable, objects of this class are hashable (and not just unchanged-hashable).

__repr__()[source]

Return a string representation suitable for debugging.

__str__()[source]

Return a string representing the object in CIM datetime format.

cimtype = 'datetime'

The name of the CIM datatype "datetime"

property datetime

The point in time represented by this object, as a datetime.datetime object.

None if this object represents a time interval.

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.

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.

property is_interval

A boolean indicating whether this object represents a time interval (True) or a point in time (False).

property 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.

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.

property 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.

property timedelta

The time interval represented by this object, as a datetime.timedelta object.

None if this object represents a 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-aware CIMDateTime type.

They are also used to provide timezone information to now() and fromtimestamp()

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(dt)

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 a datetime.timedelta object.

tzname(dt)

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(dt)

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 a datetime.timedelta object.

__repr__()[source]

Return a string representation suitable for debugging.

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 a datetime.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.

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 a datetime.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.

class pywbem.Char16(content='')[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.

Attributes:

cimtype

The name of the CIM datatype "char16"

cimtype = 'char16'

The name of the CIM datatype "char16"

class pywbem.CIMInt(*args, **kwargs)[source]

Base type for CIM integer data types. Derived from CIMType and int (for Python 3) or long (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 a ValueError. The enforcement of the valid value range can be disabled via the configuration variable ENFORCE_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

Attributes:

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.

__repr__()[source]

Return a string representation suitable for debugging.

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.

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.

class pywbem.Uint8(*args, **kwargs)[source]

A value of CIM data type uint8. Derived from CIMInt.

For details on CIM integer data types, see CIMInt.

Attributes:

cimtype

The name of the CIM datatype

maxvalue

The maximum valid value for the CIM datatype

minvalue

The minimum valid value for the CIM datatype

cimtype = 'uint8'

The name of the CIM datatype

maxvalue = 255

The maximum valid value for the CIM datatype

minvalue = 0

The minimum valid value for the CIM datatype

class pywbem.Sint8(*args, **kwargs)[source]

A value of CIM data type sint8. Derived from CIMInt.

For details on CIM integer data types, see CIMInt.

Attributes:

cimtype

The name of the CIM datatype

maxvalue

The maximum valid value for the CIM datatype

minvalue

The minimum valid value for the CIM datatype

cimtype = 'sint8'

The name of the CIM datatype

maxvalue = 127

The maximum valid value for the CIM datatype

minvalue = -128

The minimum valid value for the CIM datatype

class pywbem.Uint16(*args, **kwargs)[source]

A value of CIM data type uint16. Derived from CIMInt.

For details on CIM integer data types, see CIMInt.

Attributes:

cimtype

The name of the CIM datatype

maxvalue

The maximum valid value for the CIM datatype

minvalue

The minimum valid value for the CIM datatype

cimtype = 'uint16'

The name of the CIM datatype

maxvalue = 65535

The maximum valid value for the CIM datatype

minvalue = 0

The minimum valid value for the CIM datatype

class pywbem.Sint16(*args, **kwargs)[source]

A value of CIM data type sint16. Derived from CIMInt.

For details on CIM integer data types, see CIMInt.

Attributes:

cimtype

The name of the CIM datatype

maxvalue

The maximum valid value for the CIM datatype

minvalue

The minimum valid value for the CIM datatype

cimtype = 'sint16'

The name of the CIM datatype

maxvalue = 32767

The maximum valid value for the CIM datatype

minvalue = -32768

The minimum valid value for the CIM datatype

class pywbem.Uint32(*args, **kwargs)[source]

A value of CIM data type uint32. Derived from CIMInt.

For details on CIM integer data types, see CIMInt.

Attributes:

cimtype

The name of the CIM datatype

maxvalue

The maximum valid value for the CIM datatype

minvalue

The minimum valid value for the CIM datatype

cimtype = 'uint32'

The name of the CIM datatype

maxvalue = 4294967295

The maximum valid value for the CIM datatype

minvalue = 0

The minimum valid value for the CIM datatype

class pywbem.Sint32(*args, **kwargs)[source]

A value of CIM data type sint32. Derived from CIMInt.

For details on CIM integer data types, see CIMInt.

Attributes:

cimtype

The name of the CIM datatype

maxvalue

The maximum valid value for the CIM datatype

minvalue

The minimum valid value for the CIM datatype

cimtype = 'sint32'

The name of the CIM datatype

maxvalue = 2147483647

The maximum valid value for the CIM datatype

minvalue = -2147483648

The minimum valid value for the CIM datatype

class pywbem.Uint64(*args, **kwargs)[source]

A value of CIM data type uint64. Derived from CIMInt.

For details on CIM integer data types, see CIMInt.

Attributes:

cimtype

The name of the CIM datatype

maxvalue

The maximum valid value for the CIM datatype

minvalue

The minimum valid value for the CIM datatype

cimtype = 'uint64'

The name of the CIM datatype

maxvalue = 18446744073709551615

The maximum valid value for the CIM datatype

minvalue = 0

The minimum valid value for the CIM datatype

class pywbem.Sint64(*args, **kwargs)[source]

A value of CIM data type sint64. Derived from CIMInt.

For details on CIM integer data types, see CIMInt.

Attributes:

cimtype

The name of the CIM datatype

maxvalue

The maximum valid value for the CIM datatype

minvalue

The minimum valid value for the CIM datatype

cimtype = 'sint64'

The name of the CIM datatype

maxvalue = 9223372036854775807

The maximum valid value for the CIM datatype

minvalue = -9223372036854775808

The minimum valid value for the CIM datatype

class pywbem.CIMFloat(x=0, /)[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.

__repr__()[source]

Return a string representation suitable for debugging.

class pywbem.Real32(x=0, /)[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.

Attributes:

cimtype

The name of the CIM datatype

cimtype = 'real32'

The name of the CIM datatype

class pywbem.Real64(x=0, /)[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.

Attributes:

cimtype

The name of the CIM datatype

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'):

      • Any object supported as an init parameter for int or long (Python 2 only). This includes string values with decimal integer numbers. If the value is not supported, ValueError will be raised.

    • If type specifies one of the CIM float data types (e.g. 'real32'):

      • Any object supported as an init parameter for float. This includes string values with decimal integer or float numbers. If the value is not supported, ValueError will be raised.

    • 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 .

    • 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.

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.

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

string

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 object Uint8.

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 or CIMInstanceName).

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 in CIMError 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_ACCESS_DENIED = 2

Access to a CIM resource is not available to the client.

pywbem._cim_constants.CIM_ERR_ALREADY_EXISTS = 11

The operation cannot be invoked because an object already exists.

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_CONTINUATION_ON_ERROR_NOT_SUPPORTED = 26

The WBEM server does not support continuation on error. New in pywbem 0.9.

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_FILTERED_ENUMERATION_NOT_SUPPORTED = 25

Using a a filter query in pulled enumerations is not supported by the WBEM server. New in pywbem 0.9.

pywbem._cim_constants.CIM_ERR_INVALID_CLASS = 5

The specified class does not exist.

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_NAMESPACE = 3

The target namespace does not exist.

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_INVALID_PARAMETER = 4

One or more parameter values passed to the method are not valid.

pywbem._cim_constants.CIM_ERR_INVALID_QUERY = 15

The query is not valid for the specified query language.

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_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_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_NO_SUCH_PROPERTY = 12

The specified property does not exist.

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_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_QUERY_LANGUAGE_NOT_SUPPORTED = 14

The query language is not recognized or supported.

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.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_TYPE_MISMATCH = 13

The value supplied is not compatible with the type.

pywbem._cim_constants.DEFAULT_NAMESPACE = 'root/cimv2'

Default CIM namespace for WBEM connection

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.

pywbem._cim_constants.DEFAULT_URL_SCHEME = 'http'

Default URL scheme for 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.

Attributes:

conn_id

Connection ID of the connection in whose context the error happened.

conn_str

String that identifies the connection in exception messages.

Methods:

with_traceback

Exception.with_traceback(tb) -- set self.__traceback__ to tb and return self.

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.

Attributes:

conn_id

Connection ID of the connection in whose context the error happened.

conn_str

String that identifies the connection in exception messages.

Methods:

with_traceback

Exception.with_traceback(tb) -- set self.__traceback__ to tb and return self.

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.

Attributes:

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.

Methods:

with_traceback

Exception.with_traceback(tb) -- set self.__traceback__ to tb and return self.

property cimdetails

CIMOM-specific details on the situation reported in the CIMError header field.

The value is a dictionary with:

  • Key: header field name (e.g. PGErrorDetail).

  • Value: header field value.

Type

dict

property cimerror

Value of CIMError HTTP header field in response, if present.

None, otherwise.

See DSP0200 for a list of values.

Type

string

property reason

HTTP reason phrase.

Example: “Internal Server Error”

See RFC2616 for a list of HTTP status codes and reason phrases.

Type

string

property status

HTTP status code.

Example: 500

See RFC2616 for a list of HTTP status codes and reason phrases.

Type

integer

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.

Attributes:

conn_id

Connection ID of the connection in whose context the error happened.

conn_str

String that identifies the connection in exception messages.

Methods:

with_traceback

Exception.with_traceback(tb) -- set self.__traceback__ to tb and return self.

class pywbem.ParseError(message, conn_id=None, request_data=None, response_data=None)[source]

This exception is a base class for exceptions that indicate 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.

Attributes:

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).

Methods:

with_traceback

Exception.with_traceback(tb) -- set self.__traceback__ to tb and return self.

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.

Attributes:

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).

Methods:

with_traceback

Exception.with_traceback(tb) -- set self.__traceback__ to tb and return self.

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.

Attributes:

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).

Methods:

with_traceback

Exception.with_traceback(tb) -- set self.__traceback__ to tb and return self.

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.

Attributes:

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).

Methods:

with_traceback

Exception.with_traceback(tb) -- set self.__traceback__ to tb and return self.

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 its args instance variable. In Python 3, that ability has been removed.

In pywbem 0.9, the status_code and status_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.

Attributes:

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.

Methods:

with_traceback

Exception.with_traceback(tb) -- set self.__traceback__ to tb and return self.

property 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

property 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

property 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

property 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

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.

Derived from Error.

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.

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.

Attributes:

conn_id

Connection ID of the connection in whose context the error happened.

conn_str

String that identifies the connection in exception messages.

Methods:

with_traceback

Exception.with_traceback(tb) -- set self.__traceback__ to tb and return self.

class pywbem.Error(*args, **kwargs)[source]

Abstract base class for pywbem client 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.

Attributes:

conn_id

Connection ID of the connection in whose context the error happened.

conn_str

String that identifies the connection in exception messages.

Methods:

with_traceback

Exception.with_traceback(tb) -- set self.__traceback__ to tb and return self.

property 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

property conn_str

String that identifies the connection in exception messages.

Type

unicode string

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.

Attributes:

conn_id

Connection ID of the connection in whose context the error happened.

conn_str

String that identifies the connection in exception messages.

Methods:

with_traceback

Exception.with_traceback(tb) -- set self.__traceback__ to tb and return self.

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.

Attributes:

conn_id

Connection ID of the connection in whose context the error happened.

conn_str

String that identifies the connection in exception messages.

Methods:

with_traceback

Exception.with_traceback(tb) -- set self.__traceback__ to tb and return self.

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 its stats_enabled argument.

  • After the WBEMConnection object has been created, by modifying its stats_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

    Because the interpretation of the calculated average and min/max server times becomes incorrect if only a subset of the operations return the server response time, the statistics counting for the server time is suspended if one or more operations do not return the server response time. Resetting the statistics via reset() clears this condition again.

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 the start_timer() and stop_timer() methods of class OperationStatistic. 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 (see pywbem.WBEMConnection.stats_enabled())

This class can also be used as a context manager.

Parameters

enable (bool) – Initial enablement status for this statistics container.

Methods:

__call__(name)

This allows the name parameter to be passed when the class is used as a context manager.

__enter__()

Enter method when the class is used as a context manager.

__exit__(exc_type, exc_value, traceback)

Exit method when the class is used as a context manager.

__repr__()

Return a human readable display of the contents, for debug purposes.

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(name)

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(name)

This method is called by pywbem to start the timer for a particular operation execution.

Attributes:

enabled

Indicates whether the statistics container is enabled.

__call__(name)[source]

This allows the name parameter to be passed when the class is used as a context manager.

__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.

__repr__()[source]

Return a human readable display of the contents, for debug purposes.

disable()[source]

Disable the statistics container.

enable()[source]

Enable the statistics container.

property enabled

Indicates whether the statistics container is enabled.

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 for all operations.

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
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

reset()[source]

Reset all statistics and clear any statistic names. All statistics must be inactive before a reset will execute

Returns: True if reset, False if not

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

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 returned OperationStatistic 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

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 its get_op_statistic() and snapshot() methods.

Parameters
  • container (Statistics) – The statistics container that holds this operation statistic object.

  • name (string) – Name of the operation.

Methods:

__repr__()

Return a human readable string with the statistics values, for debug purposes.

formatted(include_server_time, include_lengths)

Return a formatted one-line string with the statistics values for the operation for which this statistics object maintains data.

formatted_header(include_server_time, ...)

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([request_len, reply_len, ...])

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()).

__repr__()[source]

Return a human readable string with the statistics values, for debug purposes.

property avg_reply_len

The average size of the HTTP body in the CIM-XML responses of the measured operations, in Bytes.

Type

float

property avg_request_len

The average size of the HTTP body in the CIM-XML requests of the measured operations, in Bytes.

Type

float

property 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

property avg_time

The average elapsed client time for execution of the measured operations, in seconds.

Type

float

property container

The statistics container that holds this statistics object.

Type

Statistics

property count

The number of measured operations.

Type

integer

property 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

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().

static formatted_header(include_server_time, include_lengths)[source]

Return a two-line header.

property max_reply_len

The maximum size of the HTTP body in the CIM-XML responses of the measured operations, in Bytes.

Type

float

property max_request_len

The maximum size of the HTTP body in the CIM-XML requests of the measured operations, in Bytes.

Type

float

property 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

property max_time

The maximum elapsed client time for execution of the measured operations, in seconds.

Type

float

property min_reply_len

The minimum size of the HTTP body in the CIM-XML responses of the measured operations, in Bytes.

Type

float

property min_request_len

The minimum size of the HTTP body in the CIM-XML requests of the measured operations, in Bytes.

Type

float

property 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

property min_time

The minimum elapsed client time for execution of the measured operations, in seconds.

Type

float

property name

Name of the operation for which this statistics object maintains data.

Type

string

reset()[source]

Reset the statistics data for this object.

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.

property 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

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, the server did not report server response time. Since this can happen in the middle of a statistics measurement interval if the corresponding config setting of the server was changed, the server time is then reset to 0 and no longer maintained during the remainder of the current statistics measurement interval. A reset of the statistics clears that condition again.

Returns

The elapsed time for the operation that just ended, or None if the statistics container holding this object is not enabled.

Return type

float

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 of WBEMConnection 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 DEBUG logging level (see Logging Levels) 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 DEBUG logging level (see Logging Levels), 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.

Data:

DEFAULT_LOG_DESTINATION

Default log destination if not supplied to the logging configuration functions.

DEFAULT_LOG_DETAIL_LEVEL

Default log detail level if not supplied to the logging configuration functions.

DEFAULT_LOG_FILENAME

Default path name of the log file to be used when logging to a file.

LOGGER_API_CALLS_NAME

Name of the pywbem API logger, which logs user-issued calls to and returns from WBEMConnection methods that drive WBEM operations.

LOGGER_HTTP_NAME

Name of the pywbem HTTP logger, which logs HTTP requests and responses between the pywbem client and WBEM servers.

LOGGER_SIMPLE_NAMES

List of the simple pywbem logger names that the logging configuration functions (see Logging configuration functions) recognize, as follows:

LOG_DESTINATIONS

List of log destinations that the logging configuration functions recognize, as follows:

LOG_DETAIL_LEVELS

List of the log detail levels that the logging configuration functions recognize, as follows:

Functions:

configure_logger(simple_name[, log_dest, ...])

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.

pywbem._logging.DEFAULT_LOG_DESTINATION = 'file'

Default log destination if not supplied to the logging configuration functions.

pywbem._logging.DEFAULT_LOG_DETAIL_LEVEL = 'all'

Default log detail level if not supplied to the logging configuration functions.

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', 'off']

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.

  • ‘off’ - Disable logging.

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.

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 of DEBUG (see Logging Levels).

    The value ‘off’ disables logging for the affected pywbem loggers.

    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 or bool 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 created WBEMConnection 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).

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 the LOGGER_SIMPLE_NAMES list.

    • log_dest: Log destination. Must be one of the strings in the LOG_DESTINATIONS list. Default is DEFAULT_LOG_DESTINATION.

    • detail_level: Log detail level. Must be one of the strings in the LOG_DETAIL_LEVELS list. Default is DEFAULT_LOG_DETAIL_LEVEL.

  • log_filename (string) – Path name of the log file (required if any log destination is ‘file’; otherwise ignored).

  • connection (WBEMConnection or bool 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 created WBEMConnection 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.

'all=off'               # Disables logging for both pywbem loggers.

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() and tobinary() methods.

Instances of this class must be created through one of the factory class methods: for_property(), for_method(), or for_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:

__repr__()

Return a representation of the ValueMapping object with all attributes, that is suitable for debugging.

for_method(server, namespace, classname, ...)

Factory method that returns a new ValueMapping instance that maps CIM method return values to the Values qualifier of that method.

for_parameter(server, namespace, classname, ...)

Factory method that returns a new ValueMapping instance that maps CIM parameter values to the Values qualifier defined on that parameter.

for_property(server, namespace, classname, ...)

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(values_str)

Return the integer value or values for a Values string, based upon this value mapping.

tovalues(element_value)

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

WBEMConnection: Connection to the WBEM server containing the CIM namespace (that contains the mapped CIM element).

element

CIMProperty, CIMMethod, or CIMParameter: 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.

__repr__()[source]

Return a representation of the ValueMapping object with all attributes, that is suitable for debugging.

property classname

Name of the CIM class defining the mapped CIM element.

Type

string

property conn

WBEMConnection: Connection to the WBEM server containing the CIM namespace (that contains the mapped CIM element).

property element

CIMProperty, CIMMethod, or CIMParameter: The mapped CIM element.

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 or WBEMServer) – 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.: :raises KeyError: The CIM method does not exist in the CIM class. :raises ModelError: The CIM method is not integer-typed. :raises ValueError: No Values qualifier defined on the CIM method. :raises ModelError: Invalid integer representation in ValueMap qualifier defined on the CIM method.

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 or WBEMServer) – 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.: :raises KeyError: The CIM method does not exist in the CIM class. :raises KeyError: The CIM parameter does not exist in the CIM method. :raises ModelError: The CIM parameter is not integer-typed. :raises ValueError: No Values qualifier defined on the CIM parameter. :raises ModelError: Invalid integer representation in ValueMap qualifier defined on the CIM parameter.

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 or WBEMServer) – 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.: :raises KeyError: The CIM property does not exist in the CIM class. :raises ModelError: The CIM property is not integer-typed. :raises ValueError: No Values qualifier defined on the CIM property. :raises ModelError: Invalid integer representation in ValueMap qualifier defined on the CIM property.

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.

property 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

property namespace

Name of the CIM namespace containing the class that defines the mapped CIM element.

Type

string

property parametername

Name of the CIM parameter that is mapped. None, if no parameter is mapped.

Type

string

property propname

Name of the CIM property that is mapped. None, if no property is mapped.

Type

string

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

CIMInt or tuple of CIMInt or None

Raises
  • ValueError – Values string outside of the set defined by Values.

  • TypeError – Values string is not a string type.

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

string or list of string

Raises
  • ValueError – Element value outside of the set defined by ValueMap.

  • TypeError – Element value is not an integer type.

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.

New in pywbem 1.1 as experimental and finalized in 1.3.

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, with two extensions:

Pywbem supports the following additional Units qualifier values that are used in the DMTF CIM Schema (as of its version 2.49) but are not defined in DSP0004:

Additional Units values

-dBm

Blocks

Percentage

Proportion

Tenths of Revolutions per Minute

Pywbem supports a slightly more flexible version of the PUnit format that is used in DMTF CIM Schema version 2.49 but not defined in DSP0004: The numeric element may appear anywhere in the formula and not just at the end.

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 or Amps 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 or Units qualifiers of the specified CIM object.

New in pywbem 1.1 as experimental and finalized in 1.3.

If the CIM object has both the PUnit and Units qualifiers set, then PUnit is used and Units is ignored.

Parameters
  • cim_obj (CIMProperty or CIMMethod or CIMParameter) – CIM object with qualifiers.

  • use_ascii (bool) – Replace any Unicode characters in the returned string with 7-bit ASCII replacements, as described above.

Returns

Human readable SI conformant unit string, or None if the CIM object has neither the PUnit nor the Units qualifiers set.

Return type

unicode string

Raises
  • TypeError – Invalid type for cim_obj

  • ValueError – Invalid format in PUnit qualifier

  • ValueError – Unknown base unit in PUnit qualifier

  • ValueError – Unknown unit in Units qualifier

Example:

>>> cls = conn.GetClass("CIM_StorageSetting", IncludeQualifiers=True)
>>> prop = cls['InterconnectSpeed']
>>> print(pywbem.siunit_obj(prop))
bit/s
pywbem.siunit(punit=None, units=None, use_ascii=False)[source]

Returns a human readable SI conformant unit string from the specified PUnit or Units qualifier values.

New in pywbem 1.1 as experimental and finalized in 1.3.

If both punit and units are specified, then punit is used and units is ignored.

Parameters
  • punit (string) – Value of the PUnit qualifier, or None.

  • units (string) – Value of the Units qualifier, or None.

  • use_ascii (bool) – Replace any Unicode characters in the returned string with 7-bit ASCII replacements, as described above.

Returns

Human readable SI conformant unit string, or None if both qualifier value input parameters were None.

Return type

unicode string

Raises
  • TypeError – Invalid type for punit or unit

  • ValueError – Invalid format in PUnit qualifier

  • ValueError – Unknown base unit in PUnit qualifier

  • ValueError – Unknown unit in Units qualifier

Examples:

>>> print(pywbem.siunit(punit="byte / second * 10^3"))
kB/s
>>> print(pywbem.siunit(punit="byte * 2^10"))
KiB
>>> print(pywbem.siunit(punit="hertz * 10^6"))
MHz
>>> print(pywbem.siunit(punit="ampere * 10^-3"))
mA
>>> print(pywbem.siunit(units="KiloBits per Second"))
kbit/s
>>> print(pywbem.siunit(units="Tenths of Degrees C"))
1/10 °C
>>> print(pywbem.siunit(units="Tenths of Degrees C", use_ascii=True))
1/10 degC

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 and WWW-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:

  1. 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.

  2. The use of HTTP Basic Authentication is strongly discouraged, because the password is sent unencrypted over the network.

  3. 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).

  4. 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.

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.

Methods:

__repr__()

Return a representation of the WBEMServer object with all attributes, that is suitable for debugging.

__str__()

Return a representation of the WBEMServer object with a subset of its attributes.

create_namespace(namespace[, verbose])

Create the specified CIM namespace in the WBEM server and update this WBEMServer object to reflect the new namespace there.

delete_namespace(namespace[, verbose])

Delete the specified CIM namespace in the WBEM server and update this WBEMServer object to reflect the removed namespace there.

get_central_instances(profile_path[, ...])

Return the instance paths of the central instances of a management profile.

get_selected_profiles([registered_org, ...])

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.

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.

__repr__()[source]

Return a representation of the WBEMServer object with all attributes, that is suitable for debugging.

__str__()[source]

Return a representation of the WBEMServer object with a subset of its attributes.

property 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.: :raises CIMError: CIM_ERR_NOT_FOUND, Interop namespace could not be determined. :raises CIMError: CIM_ERR_NOT_FOUND, Unexpected number of CIM_ObjectManager instances.

Type

string

property cimom_inst

CIM instance of class CIM_ObjectManager that represents the WBEM server.

:raises Exceptions raised by WBEMConnection.: :raises CIMError: CIM_ERR_NOT_FOUND, Interop namespace could not be determined. :raises CIMError: CIM_ERR_NOT_FOUND, Unexpected number of CIM_ObjectManager instances.

Type

CIMInstance

property conn

Connection to the WBEM server.

Type

WBEMConnection

create_namespace(namespace, verbose=False)[source]

Create the specified CIM namespace in the WBEM server and update this WBEMServer object to reflect the new namespace there.

This method cannot create an Interop namespace because creating the an Interop namespace with client operations depends on the prior existence of an Interop namespace, and creating additional Interop namespaces if one already exists is usually prevented by servers.

This method attempts the following approaches for creating the namespace, in order, until an approach succeeds:

  1. 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.

  2. 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.

  • verbose (bool) – Verbose mode: Print a message about the namespace creation.

Returns

The specified CIM namespace name in its standard format (i.e. without leading or trailing slash characters).

Return type

unicode string

:raises Exceptions raised by WBEMConnection.: :raises ModelError: An error with the model implemented by the WBEM server.

delete_namespace(namespace, verbose=False)[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 cannot delete the Interop namespace because servers will usually prevent their deletion.

This method attempts the following approaches for deleting the namespace, in order, until an approach succeeds:

  1. 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.

  • verbose (bool) – Verbose mode: Print a message about the namespace creation.

Returns

The specified CIM namespace name in its standard format (i.e. without leading or trailing slash characters).

Return type

unicode string

:raises Exceptions raised by WBEMConnection.: :raises ModelError: An error with the model implemented by the WBEM server. :raises CIMError: CIM_ERR_NOT_FOUND, Specified namespace does not exist. :raises CIMError: CIM_ERR_NAMESPACE_NOT_EMPTY, Specified namespace is not empty.

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 of CIMInstanceName

:raises Exceptions raised by WBEMConnection.: :raises ModelError: An error with the model implemented by the WBEM server. :raises ValueError: User errors regarding input parameter values. :raises TypeError: User errors regarding input parameter types.

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 of CIMInstance

:raises Exceptions raised by WBEMConnection.: :raises CIMError: CIM_ERR_NOT_FOUND, Interop namespace could not be determined. :raises ModelError: If an instance in the list of profiles is incomplete and does not include the required properties.

property interop_ns

Name of the Interop namespace of the WBEM server.

:raises Exceptions raised by WBEMConnection.: :raises CIMError: CIM_ERR_NOT_FOUND, Interop namespace could not be determined.

Type

string

property namespace_classname

Name of the CIM class that was found to represent the CIM namespaces of the WBEM server.

:raises Exceptions raised by WBEMConnection.: :raises ModelError: An error with the model implemented by the WBEM server.

Type

string

property 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.: :raises ModelError: An error with the model implemented by the WBEM server.

Type

list of CIMInstanceName

property namespaces

Names of all namespaces of the WBEM server.

:raises Exceptions raised by WBEMConnection.: :raises ModelError: An error with the model implemented by the WBEM server.

Type

list of string

property profiles

The CIM_RegisteredProfile instances representing all management profiles advertised by the WBEM server.

:raises Exceptions raised by WBEMConnection.: :raises CIMError: CIM_ERR_NOT_FOUND, Interop namespace could not be determined.

Type

list of CIMInstance

property url

URL of the WBEM server.

Type

string

property 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.: :raises CIMError: CIM_ERR_NOT_FOUND, Interop namespace could not be determined. :raises CIMError: CIM_ERR_NOT_FOUND, Unexpected number of CIM_ObjectManager instances.

Type

string

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 INFO logging level (see Logging Levels).

In addition, it will log errors at the 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 WARNING or greater to sys.stderr. So the indication and response interactions will not be printed by default, but any errors logged at the 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:

__enter__()

New in pywbem 0.12.

__exit__(exc_type, exc_value, traceback)

New in pywbem 0.12.

__repr__()

Return a representation of the WBEMListener object with all attributes, that is suitable for debugging.

__str__()

Return a representation of the WBEMListener object with a subset of its attributes.

add_callback(callback)

Add a callback function to the listener.

deliver_indication(indication, host)

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.

__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().

__repr__()[source]

Return a representation of the WBEMListener object with all attributes, that is suitable for debugging.

__str__()[source]

Return a representation of the WBEMListener object with a subset of its attributes.

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.

property 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

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.

property host

IP address or host name at which this listener can be reached.

Type

string

property http_port

HTTP port at which this listener can be reached.

None means there is no port set up for HTTP.

Type

integer

property 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

property https_port

HTTPS port at which this listener can be reached.

None means there is no port set up for HTTPS.

Type

integer

property 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

property 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

property 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 when WBEMListener is used as a context manager when leaving its scope.

In case of HTTPS, the private key file and certificate file are used. If the private key file is protected with a password, the password will be prompted for using getpass.getpass(). If the password is invalid, or if the private key file or certificate file are invalid, pywbem.ListenerCertificateError is raised.

Raises
  • pywbem.ListenerCertificateError – Error with the certificate file or its private key file when using HTTPS.

  • pywbem.ListenerPortError – WBEM listener port is already in use.

  • pywbem.ListenerPromptError – Error when prompting for the password of the private key file when using HTTPS.

  • OSError – Other error

  • IOError – Other error (Python 2.7 only)

stop()[source]

Stop the WBEM listener threads, if they 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.

Listener exceptions

class pywbem.ListenerCertificateError(message)[source]

This exception indicates an error with the certificate file or its private key file when using HTTPS.

New in pywbem 1.3.

Derived from ListenerError.

This includes bad format of the files, file not found, permission errors when accessing the files, or an invalid password for the private key file.

Parameters

message (string) – Error message (will be put into args[0]).

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.

class pywbem.ListenerPortError(message)[source]

This exception indicates that the port for the pywbem listener is already in use.

New in pywbem 1.3.

Derived from ListenerError.

Parameters

message (string) – Error message (will be put into args[0]).

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.

class pywbem.ListenerPromptError(message)[source]

This exception indicates that the prompt for the password of the private key file of the pywbem listener was interrupted or ended.

New in pywbem 1.3.

Derived from ListenerError.

Parameters

message (string) – Error message (will be put into args[0]).

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.

class pywbem.ListenerError(message)[source]

Abstract base class for exceptions raised by the pywbem listener (i.e. class WBEMListener).

New in pywbem 1.3.

Derived from Exception.

Parameters

message (string) – Error message (will be put into args[0]).

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.

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 SubscriptionManager only manages CIM/XML listener destinations and does not view, add, or remove other destinations such as files, etc.

The CIM/XML 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() or remove_all_servers(). In addition, they can be deleted by the user via the removal methods of the WBEMSubscriptionManager 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 or the client is terminated), 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 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.

Since WBEMSubscriptionManager does not directly modify existing instances of filter or destinations or subscriptions, the user must do this directly through the ModifyInstance WBEM request method and then update the local owned instances list by executing get_all_filters(), get_all_destinations(), or get_all_subscriptions().

Examples

The following example code demonstrates the use of a subscri tion 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_destination(
    server_id, listener_url, owned=True, destination_id='id1')

# 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 and thus allows identifying 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.

Raises
  • ValueError – Incorrect input parameter values.

  • TypeError – Incorrect input parameter types.

Methods:

__enter__()

New in pywbem 0.10.

__exit__(exc_type, exc_value, traceback)

New in pywbem 0.10.

__repr__()

Return a representation of the WBEMSubscriptionManager object with all attributes, that is suitable for debugging.

__str__()

Return a representation of the WBEMSubscriptionManager object with a subset of its attributes.

add_destination(server_id, listener_url[, ...])

Add a listener destination to be the target of indications sent by a WBEM server, by creating an instance of CIM class "CIM_ListenerDestinationCIMXML" in the Interop namespace of the server.

add_filter(server_id, source_namespaces, query)

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_server(server)

Register a WBEM server with the subscription manager.

add_subscriptions(server_id, filter_path[, ...])

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(server_id)

Return all listener destinations in a WBEM server.

get_all_filters(server_id)

Return all indication filters in a WBEM server.

get_all_subscriptions(server_id)

Return all indication subscriptions in a WBEM server.

get_owned_destinations(server_id)

Return the listener destinations in a WBEM server owned by this subscription manager.

get_owned_filters(server_id)

Return the indication filters in a WBEM server owned by this subscription manager.

get_owned_subscriptions(server_id)

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(server_id, destination_paths)

Remove listener destinations from a WBEM server, by deleting the listener destination instances in the server.

remove_filter(server_id, filter_path)

Remove an indication filter from a WBEM server, by deleting the indication filter instance in the WBEM server.

remove_server(server_id)

Remove a registered WBEM server from the subscription manager.

remove_subscriptions(server_id, sub_paths)

Remove indication subscription(s) from a WBEM server, by deleting the indication subscription instances in the server.

__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().

__repr__()[source]

Return a representation of the WBEMSubscriptionManager object with all attributes, that is suitable for debugging.

__str__()[source]

Return a representation of the WBEMSubscriptionManager object with a subset of its attributes.

add_destination(server_id, listener_url, owned=True, destination_id=None, name=None, persistence_type=None)[source]

Add a listener destination to be the target of indications sent by a WBEM server, by creating an instance of CIM class “CIM_ListenerDestinationCIMXML” in the Interop namespace of the server.

The Name property of the created listener destination 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 destination name (e.g. because a DMTF management profile requires a particular name).

    The name parameter can only be specified for permanent destinations.

  • indirectly by specifying the destination_id parameter.

    In this case, the value of the Name property will be:

    "pywbemdestination:" {submgr_id} ":" {destination_id}

    where:

    • {submgr_id} is the subscription manager ID

    • {destination_id} is the value of the destination_id parameter

    The destination_id parameter can only be specified for owned destinations.

    If an owned listener destination instance for the specified listener URL and PersistenceType already exists, it is returned without creating a new instance.

If a listener destination instance with the specified or generated Name property already exists, the method raises CIMError(CIM_ERR_ALREADY_EXISTS). Note that this is a more strict behavior than what a WBEM server would do, because the Name property is only one of four key properties.

Parameters
  • server_id (string) – The server ID of the WBEM server, returned by add_server().

  • listener_url (string) –

    The URL of the WBEM listener that should receive the indications.

    The WBEM listener may be a WBEMListener object or any external WBEM listener.

    The 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.

    The port is required in the listener URL.

    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 instance: If True, it will be owned. Otherwise, it will be permanent. See WBEMSubscriptionManager for details about these ownership types.

  • destination_id (string) –

    A destination ID string that is used as a component in the value of the Name property of owned destination 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.

    This parameter is required for owned destinations and is rejected for permanent destinations.

  • name (string) –

    The destination name to be used directly for the Name property of permanent destination instances, or None if the destination_id parameter is specified.

    This parameter is required for permanent destinations and is rejected for owned destinations.

  • persistence_type (string) –

    Optional string where the allowed strings are “transient” and “permanent” and the default is None. The strings are used to set the PersistenceType property, an integer property with the values of 2 (Permanent) or 3 (Transient)

    The default value is None so that the PersistenceType property is not created on the destination instance for permanent filters. and is created with PersistenceType 3 (Transient) for owned destinations.

    Most WBEM servers set the PersistenceType value to 2 (Permanent) if no value is provided.

    This method does not provide for adding the OtherPersistenceType property.

Returns

The created listener destination instance for the defined listener URL.

Return type

CIMInstance

:raises Exceptions raised by WBEMConnection.: :raises CIMError(CIM_ERR_ALREADY_EXISTS): A filter with the specified or generated Name property already exists in the server. :raises ValueError: Incorrect input parameter values.

add_filter(server_id, source_namespaces, query, query_language='WQL', owned=True, filter_id=None, name=None, source_namespace=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).

    The name parameter can only be specified for permanent filters.

  • indirectly by specifying the filter_id parameter.

    In this case, the value of the Name property will be:

    "pywbemfilter:" {submgr_id} ":" {filter_id}

    where:

    • {submgr_id} is the subscription manager ID

    • {filter_id} is the filter ID

    The filter_id parameter can only be specified for owned filters.

If an indication filter instance with the specified or generated Name property already exists, the method raises CIMError(CIM_ERR_ALREADY_EXISTS). Note that this is a more strict behavior than what a WBEM server would do, because the Name property is only one of four key properties.

Parameters
  • server_id (string) – The server ID of the WBEM server, returned by add_server().

  • source_namespaces (string, list of string, or None) – Source namespace or list of source namespaces of the indication filter. The values will be inserted into the CIM_IndicationFilter SourceNamespaces property. If None, the SourceNamespaces property will not be created. and the WBEM server will use the Interop namespace as the source namespace for 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.

    This parameter is required for owned filters and is rejected for permanent filters.

    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.

    This parameter is required for permanent filters and is rejected for owned filters.

  • source_namespace (string) – Optional source namespace of the indication filter. If the parameter is provided the value will be inserted into the CIM_IndicationFilter SourceNamespace property. Otherwise the SourceNamespace property will not be created. The SourceNamespace property is deprecated in the DMTF CIM_IndicationFilter class in favor of SourceNamespaces (see the SourceNamespaces parameter above). This parameter is provided only to support calls to add_filter() that use the source_namespace as a keyword parameter or to support very old WBEM servers (prior to DMTF schema version 2.22) that require the SourceNamespace property.

Returns

The created indication filter instance.

Return type

CIMInstance

:raises Exceptions raised by WBEMConnection.: :raises CIMError(CIM_ERR_ALREADY_EXISTS): A filter with the specified or generated Name property already exists in the server. :raises ValueError: Incorrect input parameter values. :raises TypeError: Incorrect input parameter types.

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

string

:raises Exceptions raised by WBEMConnection.: :raises ValueError: Incorrect input parameter values. :raises TypeError: Incorrect input parameter types.

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 conditionally: If the subscription instance to be added is already registered with this subscription manager and has the same path, it is not created or modified. In that case, the instance already registered is returned. This method does not modify subscriptions.

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 of CIMInstanceName) –

    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 or the instance already in the WBEM server if the new instance is owned and there is already an owned subscription with the same path.

Return type

list of CIMInstance

:raises Exceptions raised by WBEMConnection.: :raises ValueError: Incorrect input parameter values.

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 of CIMInstance

:raises Exceptions raised by WBEMConnection.:

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 of CIMInstance

:raises Exceptions raised by WBEMConnection.:

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 of CIMInstance

:raises Exceptions raised by WBEMConnection.:

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 of CIMInstance

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 of CIMInstance

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 of CIMInstance

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.:

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 of CIMInstanceName) – Instance path(s) of the listener destination instance(s) in the WBEM server.

:raises Exceptions raised by WBEMConnection.: :raises CIMError: CIM_ERR_FAILED, if there are referencing subscriptions.

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.: :raises CIMError: CIM_ERR_FAILED, if there are referencing subscriptions.

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_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 of CIMInstanceName) – Instance path(s) of the indication subscription instance(s) in the WBEM server.

:raises Exceptions raised by WBEMConnection.:

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:

  1. 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.

  2. 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).

  3. An alias must be defined before it is used. In DSP0004, no such requirement is documented. (See pywbem issue #1079).

  4. The namespace pragma only accepts CIM namespace name and not full CIM namespace path as defined in DSP0004. If the host component is part of the namespace name in a namespace pragma, the compiler generates an exception.

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 a MOFWBEMConnection 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 or FakedWBEMConnection), 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 (byte string or unicode string). The default logger function prints to stdout. If None, compiler messages are not logged.

Methods:

compile_embedded_value(mof, ns[, filename])

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(filename, ns)

Compile a MOF file into a namespace of the associated CIM repository.

compile_string(mof, ns[, filename])

Compile a string of MOF statements into a namespace of the associated CIM repository.

conn_close()

Close the underlying connection, if it is a WBEMConnection.

find_mof(classname)

Find the MOF file that defines a particular CIM class, in the search path of the MOF compiler.

rollback([verbose])

Rollback any changes to the CIM repository that were performed by compilations using this MOF compiler object, since the object was created.

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. If None, the default namespace of the connection is used. The namespace specified in this parameter must exist.

  • 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
  • filename (string) – The path name of the MOF file containing the MOF statements to be compiled.

  • ns (string) – The name of the CIM namespace in the associated CIM repository that is the target of the compilation, and is also used for lookup of any dependent CIM elements. If None, the default namespace of the connection is used. A namespace defined in a namespace pragma of the MOF superceeds this namespace from the point in the compilation unit(string/file) where it is declared. The namespace specified in this parameter or the MOF inamespace pragma must exist.

Raises
  • IOError – MOF file not found.

  • 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 the target of the compilation, and is also used for lookup of any dependent CIM elements. If None, the default namespace of the connection is used. A namespace defined in a MOF ‘#pragma namespace’ directive supersedes this namespace from the point in the compilation unit(string/file) where it is declared. The namespace specified in this parameter or in the MOF ‘#pragma namespace’ directive must exist.

  • 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.

conn_close()[source]

Close the underlying connection, if it is a WBEMConnection.

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

rollback(verbose=False)[source]

Rollback any changes to the CIM repository that were performed by compilations using this MOF compiler object, since the object was created.

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(*args, **kwargs)

Create a CIM class in a namespace of the CIM repository.

CreateInstance(*args, **kwargs)

Create a CIM instance in a namespace of the CIM repository.

DeleteClass(*args, **kwargs)

Delete a CIM class in a namespace of the CIM repository.

DeleteInstance(*args, **kwargs)

Delete a CIM instance in a namespace of the CIM repository.

DeleteQualifier(*args, **kwargs)

Delete a CIM qualifier type in a namespace of the CIM repository.

EnumerateInstanceNames(*args, **kwargs)

Enumerate the instance paths of CIM instances in a namespace of the CIM repository.

EnumerateQualifiers(*args, **kwargs)

Enumerate the CIM qualifier types in a namespace of the CIM repository.

GetClass(*args, **kwargs)

Retrieve a CIM class in a namespace of the CIM repository.

GetQualifier(*args, **kwargs)

Retrieve a CIM qualifier type in a namespace of the CIM repository.

ModifyClass(*args, **kwargs)

Modify a CIM class in a namespace of the CIM repository.

ModifyInstance(*args, **kwargs)

Modify a CIM instance in a namespace of the CIM repository.

SetQualifier(*args, **kwargs)

Create or modify a CIM qualifier type in a namespace of the CIM repository.

Attributes:

default_namespace

The default repository namespace.

abstract 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().

abstract 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().

abstract 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().

abstract 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().

abstract 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().

abstract 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().

abstract 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().

abstract 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().

abstract 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().

abstract 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().

abstract 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().

abstract 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().

property default_namespace

The default repository namespace.

This property is settable.

Type

string

class pywbem.MOFWBEMConnection(conn=None)[source]

A CIM repository connection to an in-memory repository on top of an optional underlying WBEM connection.

If a WBEM connection is provided with the conn parameter, that connection is the target for any operations that acquire CIM objects and the in-memory store acts as a cache for CIM qualifiers declarations, CIM Classes, and CIM Instances created and as a rollback log in support of rolling back the operations. This is the mode in which the MOF compiler uses this class.

If the underlying WBEM connection is not provided, the in-memory repository acts as a CIM repository that is targeted by the operations. This mode is used for testing only.

MOFWBEMConnection only implements the BaseRepositoryConnection methods required to implement the mof compiler rollback functionality.

This class implements the BaseRepositoryConnection interface.

This implementation sets the path component of instances created including keybindings using property values in the instance. It does NOT confirm that all key properties are included in the path.

Raises

The methods of this class may raise any exceptions described for class WBEMConnection.

Parameters

conn (BaseRepositoryConnection) –

The underlying repository connection.

None means that there is no underlying repository and all operations performed through this object will fail.

Methods:

CreateClass(*args, **kwargs)

Create a CIM class in the local repository of this class.

CreateInstance(*args, **kwargs)

Create a CIM instance in the local repository of this class.

DeleteClass(*args, **kwargs)

This method is only invoked by rollback() (on the underlying repository), and never by the MOF compiler, and is therefore not implemented.

DeleteInstance(*args, **kwargs)

This method is only invoked by rollback() (on the underlying repository), and never by the MOF compiler, and is therefore not implemented.

DeleteQualifier(*args, **kwargs)

This method is only invoked by rollback() (on the underlying repository), and never by the MOF compiler, and is therefore not implemented.

EnumerateInstanceNames(*args, **kwargs)

This method is used by the MOF compiler only when it creates a namespace in the course of handling CIM_ERR_NAMESPACE_NOT_FOUND.

EnumerateQualifiers(*args, **kwargs)

Enumerate the qualifier types in the local repository of this class.

GetClass(*args, **kwargs)

Retrieve a CIM class from the local repository of this class.

GetQualifier(*args, **kwargs)

Retrieve a qualifier type from the local repository of this class.

ModifyClass(*args, **kwargs)

This method is used by the MOF compiler only in the course of handling CIM_ERR_ALREADY_EXISTS after trying to create a class.

ModifyInstance(*args, **kwargs)

This method is used by the MOF compiler only in the course of handling CIM_ERR_ALREADY_EXISTS after trying to create an instance.

SetQualifier(*args, **kwargs)

Create or modify a qualifier type in the local repository of this class.

getns()

string: Return the default repository namespace to be used.

rollback([verbose])

Remove classes and instances from the underlying repository, that have been created in the local repository of this class.

setns(value)

Set the default repository namespace to be used.

Attributes:

default_namespace

The default repository namespace to be used.

CreateClass(*args, **kwargs)[source]

Create a CIM class in the local repository of this class.

For a description of the parameters, see pywbem.WBEMConnection.CreateClass().

CreateInstance(*args, **kwargs)[source]

Create a CIM instance in the local repository of this class. This implementation does not test for duplicate instances but appends each new instance to the repository.

For a description of the parameters, see pywbem.WBEMConnection.CreateInstance().

DeleteClass(*args, **kwargs)[source]

This method is only invoked by rollback() (on the underlying repository), and never by the MOF compiler, and is therefore not implemented.

DeleteInstance(*args, **kwargs)[source]

This method is only invoked by rollback() (on the underlying repository), and never by the MOF compiler, and is therefore not implemented.

DeleteQualifier(*args, **kwargs)[source]

This method is only invoked by rollback() (on the underlying repository), and never by the MOF compiler, and is therefore not implemented.

EnumerateInstanceNames(*args, **kwargs)[source]

This method is used by the MOF compiler only when it creates a namespace in the course of handling CIM_ERR_NAMESPACE_NOT_FOUND. Because the operations of this class silently create every namespace that is needed and never return that error, this method is never called, and is therefore not implemented.

EnumerateQualifiers(*args, **kwargs)[source]

Enumerate the qualifier types in the local repository of this class.

For a description of the parameters, see pywbem.WBEMConnection.EnumerateQualifiers().

GetClass(*args, **kwargs)[source]

Retrieve a CIM class from the local repository of this class.

For a description of the parameters, see pywbem.WBEMConnection.GetClass().

GetQualifier(*args, **kwargs)[source]

Retrieve a qualifier type from the local repository of this class.

For a description of the parameters, see pywbem.WBEMConnection.GetQualifier().

ModifyClass(*args, **kwargs)[source]

This method is used by the MOF compiler only in the course of handling CIM_ERR_ALREADY_EXISTS after trying to create a class. Because CreateClass() overwrites existing classes, this method is never called, and is therefore not implemented.

ModifyInstance(*args, **kwargs)[source]

This method is used by the MOF compiler only in the course of handling CIM_ERR_ALREADY_EXISTS after trying to create an instance. Because CreateInstance() overwrites existing instances, this method is never called, and is therefore not implemented. NOTE: This error means that the mof compiler logic to attempt modifyinstance if createinstance fails does not attempt the modifyinstance.

SetQualifier(*args, **kwargs)[source]

Create or modify a qualifier type in the local repository of this class.

For a description of the parameters, see pywbem.WBEMConnection.SetQualifier().

property default_namespace

The default repository namespace to be used.

The default repository namespace is the default namespace of the underlying repository connection if there is such an underlying connection, or the default namespace of this object.

Initially, the default namespace of this object is ‘root/cimv2’.

This property is settable. Setting it will cause the default namespace of the underlying repository connection to be updated if there is such an underlying connection, or the default namespace of this object.

Type

string

getns()

string: Return the default repository namespace to be used.

This method exists for compatibility. Use the default_namespace property instead.

rollback(verbose=False)[source]

Remove classes and instances from the underlying repository, that have been created in the local repository of this class.

Limitations:

1. At this point, only classes and instances will be removed, but not qualifiers.

2. This may not work with instances created by other means, ex. other mof_compilers because of amgiguity in the definition of instance names for associations (ex. The namespace component in reference properties)

3. This only removes the classes specifically defined in the compiled mof and not any classes installed as prerquisits as part of the compile (ex. superclasses, classes defined by references)

setns(value)

Set the default repository namespace to be used.

This method exists for compatibility. Use the default_namespace property instead.

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 the t 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.

Attributes:

__cause__

exception cause

__context__

exception context

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.

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.

Methods:

__delattr__(name, /)

Implement delattr(self, name).

__getattribute__(name, /)

Return getattr(self, name).

__new__(**kwargs)

__reduce__

Helper for pickle.

__repr__()

Return repr(self).

__setattr__(name, value, /)

Implement setattr(self, name, value).

__str__()

Return str(self).

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.

__str__()[source]

Return str(self).

property column

Position within the line in the MOF file or MOF string where the error occurred (1-based).

Type

integer

property 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

property 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

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

property lineno

Line number in the MOF file or MOF string where the error occurred (1-based).

Type

integer

property msg

Message text describing the error.

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 the t 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.

Attributes:

__cause__

exception cause

__context__

exception context

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.

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.

Methods:

__delattr__(name, /)

Implement delattr(self, name).

__getattribute__(name, /)

Return getattr(self, name).

__new__(**kwargs)

__reduce__

Helper for pickle.

__repr__()

Return repr(self).

__setattr__(name, value, /)

Implement setattr(self, name, value).

__str__()

Return str(self).

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.

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 the t 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.

Attributes:

__cause__

exception cause

__context__

exception context

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.

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.

Methods:

__delattr__(name, /)

Implement delattr(self, name).

__getattribute__(name, /)

Return getattr(self, name).

__new__(**kwargs)

__reduce__

Helper for pickle.

__repr__()

Return repr(self).

__setattr__(name, value, /)

Implement setattr(self, name, value).

__str__()

Return str(self).

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.

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 the t 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.

Attributes:

__cause__

exception cause

__context__

exception context

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.

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.

Methods:

__delattr__(name, /)

Implement delattr(self, name).

__getattribute__(name, /)

Return getattr(self, name).

__new__(**kwargs)

__reduce__

Helper for pickle.

__repr__()

Return repr(self).

__setattr__(name, value, /)

Implement setattr(self, name, value).

__str__()

Return str(self).

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.

property cim_error

CIM error returned by the CIM repository.

Type

CIMError

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

New in pywbem 0.12 as experimental and finalized in 1.2.

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() .

An Interop namespace can be created by adding it via add_namespace(). The Interop namespace will be initially empty, and the necessary instance(s) of a CIM namespace class will be automatically created when registering the namespace provider CIMNamespaceProvider. See Mocking multiple CIM namespaces for details.

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:

  1. All of the WBEMConnection operation methods that communicate with the WBEM server (see below for the operations supported and their limitations).

  2. Multiple CIM namespaces and a default namespace on the faked connection.

  3. Gathering time statistics and delaying responses for a predetermined time.

  4. WBEMConnection logging except that there are no HTTP entries in the log.

  5. 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:

  1. CIM-XML protocol security and security constructor parameters of WBEMConnection.

  2. 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.

  3. 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.

  4. 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, or last_reply_len.

  5. Log entries for HTTP request and response in the logging support of WBEMConnection, because it does not actually build the HTTP requests or responses.

  6. Generating CIM indications.

  7. 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 the pywbem.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:

  • IterEnumerateInstances()

  • IterEnumerateInstancePaths()

  • IterAssociatorInstances()

  • IterAssociatorInstancePaths()

  • IterReferenceInstances()

  • IterReferenceInstancePaths()

  • IterQueryInstances()

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: Behaves like ModifyClass(). The pywbem_mock implementation rejects modifications where the class to modifiy has either subclasses or instances and resolves the various qualifiers, class origin values and propagated values as the the CreateClass operation.

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, url=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.

New in pywbem 0.12 as experimental and finalized in 1.2.

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 pywbem.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 of WBEMConnection.

  • 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 of WBEMConnection.

  • 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.

url (string):

Defines a url to replace the default http://FakedURL.5988 url which is passed to the superclass. The url must be an acceptable syntax for WBEMConnection initialization. This is useful when multiple mocks are required for testing.

Raises

ValueError – Invalid arguments

Methods:

AssociatorNames(ObjectName[, AssocClass, ...])

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(ObjectName[, AssocClass, ...])

Retrieve the instances associated to a source instance, or the classes associated to a source class.

CloseEnumeration(context)

Close an open enumeration session, causing an early termination of an incomplete enumeration session.

CreateClass(NewClass[, namespace])

Create a class in a namespace.

CreateInstance(NewInstance[, namespace])

Create an instance in a namespace.

DeleteClass(ClassName[, namespace])

Delete a class.

DeleteInstance(InstanceName)

Delete an instance.

DeleteQualifier(QualifierName[, namespace])

Delete a qualifier type (= qualifier declaration).

EnumerateClassNames([namespace, ClassName, ...])

Enumerate the names of subclasses of a class, or of the top-level classes in a namespace.

EnumerateClasses([namespace, ClassName, ...])

Enumerate the subclasses of a class, or the top-level classes in a namespace.

EnumerateInstanceNames(ClassName[, namespace])

Enumerate the instance paths of instances of a class (including instances of its subclasses) in a namespace.

EnumerateInstances(ClassName[, namespace, ...])

Enumerate the instances of a class (including instances of its subclasses) in a namespace.

EnumerateQualifiers([namespace])

Enumerate the qualifier types (= qualifier declarations) in a namespace.

ExecQuery(QueryLanguage, Query[, namespace])

Execute a query in a namespace.

ExportIndication(NewIndication)

Send an indication to a WBEM listener.

GetClass(ClassName[, namespace, LocalOnly, ...])

Retrieve a class.

GetInstance(InstanceName[, LocalOnly, ...])

Retrieve an instance.

GetQualifier(QualifierName[, namespace])

Retrieve a qualifier type (= qualifier declaration).

InvokeMethod(MethodName, ObjectName[, Params])

Invoke a method on a target instance or on a target class.

IterAssociatorInstancePaths(InstanceName[, ...])

Retrieve the instance paths of the instances associated to a source instance, using the Python generator idiom to return the result.

IterAssociatorInstances(InstanceName[, ...])

Retrieve the instances associated to a source instance, using the Python generator idiom to return the result.

IterEnumerateInstancePaths(ClassName[, ...])

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(ClassName[, ...])

Enumerate the instances of a class (including instances of its subclasses) in a namespace, using the Python generator idiom to return the result.

IterQueryInstances(FilterQueryLanguage, ...)

Execute a query in a namespace, using the Python generator idiom to return the result.

IterReferenceInstancePaths(InstanceName[, ...])

Retrieve the instance paths of the association instances that reference a source instance, using the Python generator idiom to return the result.

IterReferenceInstances(InstanceName[, ...])

Retrieve the association instances that reference a source instance, using the Python generator idiom to return the result.

ModifyClass(ModifiedClass[, namespace])

Modify a class.

ModifyInstance(ModifiedInstance[, ...])

Modify the property values of an instance.

OpenAssociatorInstancePaths(InstanceName[, ...])

Open an enumeration session to retrieve the instance paths of the instances associated to a source instance.

OpenAssociatorInstances(InstanceName[, ...])

Open an enumeration session to retrieve the instances associated to a source instance.

OpenEnumerateInstancePaths(ClassName[, ...])

Open an enumeration session to enumerate the instance paths of instances of a class (including instances of its subclasses) in a namespace.

OpenEnumerateInstances(ClassName[, ...])

Open an enumeration session to enumerate the instances of a class (including instances of its subclasses) in a namespace.

OpenQueryInstances(FilterQueryLanguage, ...)

Open an enumeration session to execute a query in a namespace and to retrieve the instances representing the query result.

OpenReferenceInstancePaths(InstanceName[, ...])

Open an enumeration session to retrieve the instance paths of the association instances that reference a source instance.

OpenReferenceInstances(InstanceName[, ...])

Open an enumeration session to retrieve the association instances that reference a source instance.

PullInstancePaths(context, MaxObjectCount)

Retrieve the next set of instance paths from an open enumeration session.

PullInstances(context, MaxObjectCount)

Retrieve the next set of instances (without instance paths) from an open enumeration session.

PullInstancesWithPath(context, MaxObjectCount)

Retrieve the next set of instances (with instance paths) from an open enumeration session.

ReferenceNames(ObjectName[, ResultClass, Role])

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(ObjectName[, ResultClass, Role, ...])

Retrieve the association instances that reference a source instance, or the association classes that reference a source class.

SetQualifier(QualifierDeclaration[, namespace])

Create or modify a qualifier type (= qualifier declaration) in a namespace.

__enter__()

New in pywbem 1.2.

__exit__(exc_type, exc_value, traceback)

New in pywbem 1.2.

__repr__()

Return a representation of the WBEMConnection object with all attributes (except for the password in the credentials) that is suitable for debugging.

__str__()

Return a short representation of the WBEMConnection object for human consumption.

add_cimobjects(objects[, namespace])

Add CIM classes, instances and/or CIM qualifier types (declarations) to the specified CIM namespace of the CIM repository.

add_namespace(namespace[, verbose])

Add a CIM namespace to the CIM repository of the faked connection.

add_operation_recorder(operation_recorder)

Internal: Add an operation recorder to this connection.

close()

Closes this connection.

compile_mof_file(mof_file[, namespace, ...])

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(mof_str[, namespace, ...])

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(class_names, ...[, ...])

Compile the classes defined by class_names and all of their dependences.

copy()

New in pywbem 1.3.

display_registered_providers()

Display information on the currently registered providers.

display_repository([namespaces, dest, ...])

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(interop_namespace)

FakedWBEMConnection user method to install the namespace provider in the Interop namespace where the proposed interop_namespace is defined by the parameter interop_namespace

install_subscription_providers(interop_namespace)

FakedWBEMConnection user method to install the indication subscription providers in the Interop namespace where the proposed interop_namespace is defined by the parameter interop_namespace

is_interop_namespace(namespace)

Tests if a namespace name is a valid Interop namespace name.

is_subclass(namespace, klass, superclass)

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([pull_op])

Internal: Low-level method used by the operation-specific methods of this class.

operation_recorder_stage_pywbem_args(method, ...)

Internal: Low-level method used by the operation-specific methods of this class.

operation_recorder_stage_result(ret, exc)

Internal: Low-level method used by the operation-specific methods of this class.

register_provider(provider[, namespaces, ...])

Register the provider object for specific namespaces and CIM classes.

remove_namespace(namespace[, verbose])

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 or WBEM listener.

cimrepository

The mocked in-memory CIM repository.

conn_id

connection 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

bool: 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 or WBEM listener, in the format host:port.

interop_namespace_names

NocaseList of string: 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

unicode string: CIM-XML data of the last response received from the WBEM server or WBEM listener on this connection, formatted as it was received (=raw).

last_raw_request

unicode string: CIM-XML data of the last request sent to the WBEM server or WBEM listener on this connection, formatted as it was sent (=raw).

last_reply

unicode string: CIM-XML data of the last response received from the WBEM server or WBEM listener on this connection, formatted as prettified XML.

last_reply_len

int: The size of the HTTP body in the CIM-XML response of the last operation, in Bytes.

last_request

unicode string: CIM-XML data of the last request sent to the WBEM server or WBEM listener on this connection, formatted as prettified XML.

last_request_len

int: 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

NocaseList of string: 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

Internal: Enablement status for all operation recorders of the connection.

operation_recorders

Tuple of BaseOperationRecorder subclass objects:

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 or WBEM listener.

response_delay

number: Artifically created delay for each operation, in seconds.

scheme

Normalized scheme of the URL of the WBEM server or WBEM listener, 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 or listener.

url

Normalized URL of the WBEM server or WBEM listener.

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 or WBEM listener during the TLS/SSL handshake.

__repr__()[source]

Return a representation of the WBEMConnection object with all attributes (except for the password in the credentials) that is suitable for debugging.

__str__()[source]

Return a short representation of the WBEMConnection object for human consumption.

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 or CIMInstance or CIMQualifierDeclaration, 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.

add_namespace(namespace, verbose=False)[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.

  • verbose (bool) – Verbose mode: Print a message about the namespace creation.

Raises
  • ValueError – Namespace argument must not be None.

  • CIMError – CIM_ERR_ALREADY_EXISTS if the namespace already exists in the CIM repository.

property 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

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 CIM namespace in the associated CIM repository that is the target of the compilation, and is also used for lookup of any dependent CIM elements. If None, the default namespace of the connection is used. A namespace defined in a namespace pragma of the MOF superceeds this namespace from the point in the compilation unit(string/file) where it is declared. The namespace specified in this parameter or the MOF inamespace pragma must exist.

  • 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 CIM namespace in the associated CIM repository that is the target of the compilation, and is also used for lookup of any dependent CIM elements. If None, the default namespace of the connection is used. A namespace defined in a namespace pragma of the MOF superceeds this namespace from the point in the compilation unit(string/file) where it is declared. The namespace specified in this parameter or the MOF inamespace pragma must exist.

  • 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:

  1. Qualifier declarations defined in a single file with the name qualifiers.mof defined within the directory defined by the schema_mof_dir parameter

  2. 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.

  3. 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 from pywbem_mock.DMTFCIMSchema.schema_pragma_file.

  • namespace (string) – The name of the CIM namespace in the associated CIM repository that is the target of the compilation, and is also used for lookup of any dependent CIM elements. If None, the default namespace of the connection is used. A namespace defined in a namespace pragma of the MOF superceeds this namespace from the point in the compilation unit(string/file) where it is declared. The namespace specified in this parameter or the MOF inamespace pragma must exist.

  • 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.

copy()[source]

New in pywbem 1.3.

Return a deep copy of the object with internal state reset and reusing the same repository and registries.

The returned object uses the same repository, provider registry and provider dependent registry objects as the original object. Besides that, all other user-specifiable attributes of the object are deep-copied, and all other internal state is reset.

property disable_pull_operations

bool: 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.

display_registered_providers()[source]

Display information on the currently registered providers.

Parameters

dest (string) – File path of an output file. If None, the output is written to stdout.

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’.

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.

install_subscription_providers(interop_namespace, schema_pragma_file=None, verbose=None)[source]

FakedWBEMConnection user method to install the indication subscription providers in the Interop namespace where the proposed interop_namespace is defined by the parameter interop_namespace

Experimental: New in pywbem 1.3.0 as experimental.

Because these 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.

property interop_namespace_names

NocaseList of string: 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.

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

property namespaces

NocaseList of string: The names of the namespaces that exist in the CIM repository.

property provider_dependent_registry

The registry for provider dependent files, in context of a mock script.

Type

ProviderDependentRegistry

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:

  1. Validation that the namespaces defined for the provider exist.

  2. Validation that the superclass of the provider is consistent with the provider_type attribute defined in the provider.

  3. 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.

  4. 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.

  5. 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:

  1. provider_type = ‘instance’: defines methods for CreateInstance, ModifyInstance, and DeleteInstance requests within a subclass of the InstanceWriteProvider class.

  2. 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 or pywbem_mock.MethodProvider) – An instance of the user provider class which is a subclass of pywbem_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.

remove_namespace(namespace, verbose=False)[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.

  • verbose (bool) – Verbose mode: Print a message about the namespace deletion.

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 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

property response_delay

number: 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.

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() or compile_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:

  1. 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.

  2. Create the CIM namespaces needed, either as the default namespace or by adding namespaces, including the interop namespace.

  3. 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.

  4. 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.

  5. 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.

New in pywbem 0.13 as experimental and finalized in 1.2.

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 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:

__repr__()

Return a string representation of the DMTFCIMSchema object that is suitable for debugging.

__str__()

Return a short string representation of the DMTFCIMSchema object for human consumption.

build_schema_mof(class_names)

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.

__repr__()[source]

Return a string representation of the DMTFCIMSchema object that is suitable for debugging.

__str__()[source]

Return a short string representation of the DMTFCIMSchema object for human consumption. This displays the major properties of the object.

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 (string or list of 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.

remove()[source]

The schema_mof_dir directory is removed if it esists and the schema_zip_file is removed if it exists. If the schema_root_dir is empty after these removals that directory is removed.

property 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

property 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

property 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

property 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

property 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

property schema_zip_file

Path name of the DMTF CIM schema zip file after being downloaded from the DMTF web site.

Type

string

property schema_zip_url

URL of the DMTF CIM schema zip file that is downloaded from the DMTF web site.

Type

string

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).

New in pywbem 1.0 as experimental and finalized in 1.2.

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:

__repr__()

Display summary of the repository

add_namespace(namespace)

Add a CIM namespace to the repository.

get_class_store(namespace)

Return the CIM class object store for the namespace provided.

get_instance_store(namespace)

Return the CIM instance object store for the namespace provided.

get_qualifier_store(namespace)

Return the CIM qualifier declaration object store for the namespace provided.

load(other)

Replace the data in this object with the data from the other object.

print_repository([dest])

Print the CIM repository to a destination.

remove_namespace(namespace)

Remove a CIM namespace from the repository.

validate_namespace(namespace)

Validate if the namespace exists in the repository.

Attributes:

namespaces

NocaseList of string: The names of the namespaces that exist in this CIM repository.

__repr__()[source]

Display summary of the repository

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.

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

InMemoryObjectStore

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

InMemoryObjectStore

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

InMemoryObjectStore

Raises
  • ValueError – namespace parameter is None

  • KeyError – namespace argument does exist in therepository.

load(other)[source]

Replace the data in this object with the data from the other object.

This is used to restore the object from a serialized state, without changing its identity.

property namespaces

NocaseList of string: 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.

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.

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.

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.

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.

New in pywbem 1.0 as experimental and finalized in 1.2.

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:

__repr__()

Return repr(self).

create(name, cim_object)

Add the CIM object to the object store.

delete(name)

Delete the CIM object identified by name from the object store.

get(name[, copy])

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([copy])

Return an iterator to the CIM objects in the object store.

len()

Return the count of objects in this object store.

object_exists(name)

Test if the CIM object identified by name exists in the object store.

update(name, cim_object)

Replace the CIM object in the object store idenfified by the name argument with the CIM object defined by the cim_object argument.

__repr__()[source]

Return repr(self).

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.

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

get(name, copy=True)[source]

Get with deepcopy because the pywbem .copy is only middle level and we need to completely isolate the repository.

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

len()[source]

Return the count of objects in this object store.

Returns

Integer that is count of objects in this object store.

Return type

int

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

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.

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:

  1. 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.

  2. 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:

conn = pywbem_mock.FakedWBEMConnection(...)

. . .

interop_ns = "interop"   # or "root/interop"
conn.add_namespace(interop_ns)
ns_provider = pywbem_mock.CIMNamespaceProvider(conn.cimrepository)
conn.register_provider(ns_provider, namespaces=interop_ns)

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:

  1. 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):
    
        . . .
    
    1. Optional: It may have an __init__() method.

      The __init__() method takes as input parameters at least the cimrepository 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 with register_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)
      
    2. 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']
      
    3. 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)
      
    4. 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 of register_provider(), after the provider registration is successful.

      Example:

      def post_register_setup(self, conn):
        # code that performs post registration setup for the provider
      
  2. 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.

New in pywbem 1.0 as experimental and finalized in 1.2.

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(namespace, new_instance)

Default provider method for pywbem.WBEMConnection.CreateInstance().

DeleteInstance(InstanceName)

Default provider method for pywbem.WBEMConnection.DeleteInstance().

ModifyInstance(modified_instance[, ...])

Default provider method for pywbem.WBEMConnection.CreateInstance().

__repr__()

Return repr(self).

add_namespace(namespace[, verbose])

Add a CIM namespace to the CIM repository.

class_exists(namespace, classname)

Test if class defined by classname parameter exists in CIM repository defined by namespace parameter.

filter_properties(obj, property_list)

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(namespace, classname[, ...])

Get class from CIM repository.

is_interop_namespace(namespace)

Tests if a namespace name is a valid Interop namespace name.

is_subclass(klass, superclass, class_store)

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(conn)

Method called by provider registration after registation of provider is successful.

remove_namespace(namespace[, verbose])

Remove a CIM namespace from the CIM repository.

validate_namespace(namespace)

Validates that a namespace is defined in the CIM repository.

Attributes:

cimrepository

Instance of class that represents the CIM repository.

interop_namespace_names

NocaseList of string: The valid Interop namespace names.

namespaces

NocaseList of string: The names of the namespaces that exist in the CIM repository.

provider_type

Keyword defining the type of request the provider will service.

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).

  • The creation class of the new instance must not be an abstract class.

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

CIMInstanceName

Raises

CIMError – The provider may raise CIMError with any status code, and typically raises: - CIM_ERR_INVALID_PARAMETER - CIM_ERR_ALREADY_EXISTS

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.

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

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.

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

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.

New in pywbem 1.0 as experimental and finalized in 1.2.

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(methodname, localobject, params)

Default provider method for pywbem.WBEMConnection.InvokeMethod().

__repr__()

Return repr(self).

add_namespace(namespace[, verbose])

Add a CIM namespace to the CIM repository.

class_exists(namespace, classname)

Test if class defined by classname parameter exists in CIM repository defined by namespace parameter.

filter_properties(obj, property_list)

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(namespace, classname[, ...])

Get class from CIM repository.

is_interop_namespace(namespace)

Tests if a namespace name is a valid Interop namespace name.

is_subclass(klass, superclass, class_store)

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(conn)

Method called by provider registration after registation of provider is successful.

remove_namespace(namespace[, verbose])

Remove a CIM namespace from the CIM repository.

validate_namespace(namespace)

Validates that a namespace is defined in the CIM repository.

Attributes:

cimrepository

Instance of class that represents the CIM repository.

interop_namespace_names

NocaseList of string: The valid Interop namespace names.

namespaces

NocaseList of string: The names of the namespaces that exist in the CIM repository.

provider_type

provider_type (string): Keyword defining the type of request the provider will service.

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 or CIMClassName): 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.

  • params (pywbem.NocaseDict) –

    The input parameters for the method invocation, as a pywbem.NocaseDict object, 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 (Sequence or Mapping): Output parameters of the method invocation.

    If Sequence, the items must be CIMParameter 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.

provider_type = 'method'

provider_type (string): Keyword defining the type of request the provider will service. The type for this class is predefined as ‘method’

CIM_Namespace provider

This module implements a user-defined provider for the class CIM_Namespace

This provider manages creation and deletion of the instances of the CIM_Namespace class and limits that activity to the server environment interop classname. The CIM_Namespace class is a DMTF defined class that defines an instance for each namespace in the server environment and allows the creation and deletion of server CIM namespaces to be controlled through creation and deletion of instances of the CIM_Namespace class.

class pywbem_mock.CIMNamespaceProvider(cimrepository)[source]

Implements the user defined provider for the class CIM_Namespace.

This provider provides the create, modify, and delete methods for adding an instance of the class CIM_Namspace when a namespace is created or deleted in a pywbem mock environment.

This class and the instances of this class only exist in the WBEM server Interop namespace per DMTF definitions.

This class __init__ saves the cimrepository variable used by methods in this class and by methods of its superclasses (i.e. InstanceWriteProvider).

The provider defines the class level attribute provider_classnames (CIM_Namespace)

This provider presumes that an Interop namespace has been created before the provider object is constructed and fails the constructor if there is not interop_namespace

Parameters

cimrepository (BaseRepository or subclass) – Defines the CIM repository to be used by the provider.

Methods:

CreateInstance(namespace, new_instance)

Create an instance of the CIM_Namespace class in an Interop namespace of the CIM repository, and if not yet existing create the new namespace in the CIM repository.

DeleteInstance(InstanceName)

Delete an instance of the CIM_Namespace class in an Interop namespace of the CIM repository, and in addition delete the namespace represented by it in the CIM repository.

ModifyInstance(modified_instance[, ...])

Modification of CIM_Namespace instance not allowed

__repr__()

Return repr(self).

add_namespace(namespace[, verbose])

Add a CIM namespace to the CIM repository.

class_exists(namespace, classname)

Test if class defined by classname parameter exists in CIM repository defined by namespace parameter.

create_cimnamespace_instance(conn, ...)

Build and execute CreateInstance for an instance of CIM_Namespace using the namespace parameter as the value of the name property in the instance.

filter_properties(obj, property_list)

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(namespace, classname[, ...])

Get class from CIM repository.

is_interop_namespace(namespace)

Tests if a namespace name is a valid Interop namespace name.

is_subclass(klass, superclass, class_store)

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(conn)

Method called by FakedWBEMConnection.register_provider to complete initialization of this provider.

remove_namespace(namespace[, verbose])

Remove a CIM namespace from the CIM repository.

validate_namespace(namespace)

Validates that a namespace is defined in the CIM repository.

Attributes:

cimrepository

Instance of class that represents the CIM repository.

interop_namespace_names

NocaseList of string: The valid Interop namespace names.

namespaces

NocaseList of string: The names of the namespaces that exist in the CIM repository.

provider_classnames

provider_classnames (string): The classname for this provider

CreateInstance(namespace, new_instance)[source]

Create an instance of the CIM_Namespace class in an Interop namespace of the CIM repository, and if not yet existing create the new namespace in the CIM repository.

See ~pywbem_mock.InstanceWriteProvider.CreateInstance for documentation of validation and description of input parameters, noting extra conditions for this provider as described below:

Parameters
  • namespace (string) – Must be a valid Interop namespace.

  • new_instance (CIMInstance) –

    The following applies regarding its properties:

    • ’Name’ property: This property is required since it defines the name of the new namespace to be created.

    • ’CreationClassName’ property: This property is required and its value must match the class name of the new instance.

Raises

CIMError – (CIM_ERR_INVALID_PARAMETER) if namespace is not the Interop namespace in the CIM repository or the Name property does not exist or the other properties cannot be added to the instance.

DeleteInstance(InstanceName)[source]

Delete an instance of the CIM_Namespace class in an Interop namespace of the CIM repository, and in addition delete the namespace represented by it in the CIM repository.

See ~pywbem_mock.InstanceWriteProvider.CreateInstance for documentation of validation and description of input parameters, noting extra conditions for this provider as described below:

The namespace to be deleted must be empty and must not be the Interop namespace.

Parameters

InstanceName – (CIMInstanceName): The keybinding Name must exist; it defines the namespace to be deleted.

Raises
  • CIMError – (CIM_ERR_INVALID_PARAMETER)

  • CIMError – (CIM_ERR_NAMESPACE_NOT_EMPTY)

ModifyInstance(modified_instance, IncludeQualifiers=None)[source]

Modification of CIM_Namespace instance not allowed

__repr__()[source]

Return repr(self).

static create_cimnamespace_instance(conn, namespace, interop_namespace, klass)[source]

Build and execute CreateInstance for an instance of CIM_Namespace using the namespace parameter as the value of the name property in the instance. The instance is created in the interop_namespace

Parameters
  • namespace (string) – Namespace that this instance defines.

  • interop_namespace (string) – Interop namespace for this environment.

  • klass (CIMClass) – The CIM class CIM_Namespace which is used to create the instance.

Raises

CIMError – For errors encountered with CreateInstance

post_register_setup(conn)[source]

Method called by FakedWBEMConnection.register_provider to complete initialization of this provider. This method is called after the required classes are installed in the cim_repository

This is necessary because pywbem_mock does not allow user-defined providers for the instance read operations such as EnumerateInstances so the instance for each namespace must be exist in the repository.

This method:

  1. Inserts instances of CIM_Namespace for every namespace in the CIM repository.

provider_classnames = 'CIM_Namespace'

provider_classnames (string): The classname for this provider

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.

New in pywbem 1.1 as experimental and finalized in 1.2.

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:

__repr__()

Return repr(self).

add_dependents(mock_script_path, dependent_paths)

Add dependent files to the registry, in context of a mock script.

iter_dependents(mock_script_path)

Iterate through the path names of the dependent files that are registered for a mock script.

load(other)

Replace the data in this object with the data from the other object.

__repr__()[source]

Return repr(self).

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

load(other)[source]

Replace the data in this object with the data from the other object.

This is used to restore the object from a serialized state, without changing its identity.

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.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.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

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.OBJECTMANAGERCREATIONCLASSNAME = 'CIM_ObjectManager'

Value for the CIM_ObjectManagerCreationClassName defined in the CIM_ObjectManager class.

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.OPEN_MAX_TIMEOUT = 40

Maximum value for the OperationTimeout parameter of the Open…() methods of the mock WBEM server.

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.SYSTEMNAME = 'MockSystem_WBEMServerTest'

The name of the mock object. This string value becomes part of the CIM_ObjectNamager instance and CIM_Namespace instances

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:

  • mof_compiler

    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.

  -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.

  -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|off].
                                   (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.

Repository

The repository for pywbem is on GitHub:

https://github.com/pywbem/pywbem

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.

  1. It is recommended that you set up a virtual Python environment. Have the virtual Python environment active for all remaining steps.

  2. Make sure the following commands are available:

    • git

    • make (GNU make)

    • choco on native Windows (Chocolatey package manager)

  3. Clone the Git repo of this project and switch to its working directory:

    $ git clone git@github.com:pywbem/pywbem.git
    $ cd pywbem
    
  4. 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.

  5. 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:

  1. 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.

  2. 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.

  3. 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:

  1. Verify that the following commands are available when the system Python is active:

    $ virtualenv --version   # Python virtualenv package
    $ pip --version
    
  2. 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.

  3. Verify that in that virtual Python environment, pywbem comes from the intended installation:

    $ pip show pywbem
    
  4. 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
    
  5. 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:

  • OpenStack Git Commit Good Practice

  • How to Get Your Change Into the Linux Kernel

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, and str in Python 3)

byte string

a byte string type (str in Python 2, and bytes 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 from pywbem.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), or float.

integer

one of the integer types int or long (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 module xml.dom, with minidom specifics described in section DOM Objects of module xml.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 value

  • dict 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 a dict 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.

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 a CIMClass.

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 value

  • dict 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 a dict 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 provided CIMMethod objects.

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 a CIMMethod.

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 value

  • dict 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 a dict 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 provided CIMParameter objects.

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 a CIMInstance, and property declarations when the parent object is a CIMClass.

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 value

  • dict 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 a dict 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 provided CIMProperty objects.

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 a CIMClass 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 value

  • dict 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 a dict 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 provided CIMQualifier objects.

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.

Base classes

Some bases classes are included in this documentation in order to provide the descriptions for inherited methods and properties that are referenced from the summary tables in other class descriptions.

class pywbem._exceptions._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.

Attributes:

request_data

CIM-XML request string (settable).

property request_data

CIM-XML request string (settable). None if the exception does not store a CIM-XML request.

Type

string

class pywbem._exceptions._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.

Attributes:

response_data

CIM-XML response string (settable).

property response_data

CIM-XML response string (settable). None if the exception does not store a CIM-XML response.

Type

string

class pywbem._cim_types._CIMComparisonMixin[source]

Mixin class providing default implementations for equality test operators and hash function.

The implementations of ordering tests are also provided and raise an exception because ordering of CIM objects is not supported.

In Python 2, the rich comparison operators (e.g. __eq__()) have precedence over the traditional comparator method (__cmp__()). In Python 3, the comparator method (__cmp__()) no longer exists. Therefore, implementing the rich comparison operators works in both.

Methods:

__eq__(other)

Equality test for two CIM objects.

__hash__()

Interface definition for hash function to be provided by subclasses.

__ne__(other)

Non-equality test for two CIM objects.

__eq__(other)[source]

Equality test for two CIM objects.

The comparison must be implemented in the derived class.

__hash__()[source]

Interface definition for hash function to be provided by subclasses.

Background: In order to behave as expected in sets and other hash-based collections, the hash values of objects must be equal when the objects themselves are considered equal. The default hash function for classes is based on id() and therefore does not satisfy that requirement.

Therefore, the CIM objects need to implement a hash function that satisfies that requirement.

__ne__(other)[source]

Non-equality test for two CIM objects.

The comparison is delegated to the __eq__() method, because we require it to be implemented. See https://stackoverflow.com/a/30676267/1424462 for discussion about delegating to == vs. __eq__().

class pywbem_mock.BaseRepository[source]

An abstract base class defining the required APIs to provide access to a a CIM repository.

New in pywbem 1.0 as experimental and finalized in 1.2.

The API provides functions to:

  1. Manage CIM namespaces in the data repository including creation, deletion and getting a list of the existing namespaces.

  2. Access the object store for each CIM object type in the repository for the objects of the following CIM types: (CIMClass, CIMInstance, and CIMQualifierDeclaration) 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(namespace)

Add a CIM namespace to the repository.

get_class_store(namespace)

Return the CIM class object store for the namespace provided.

get_instance_store(namespace)

Return the CIM instance object store for the namespace provided.

get_qualifier_store(namespace)

Return the CIM qualifier declaration object store for the namespace provided.

remove_namespace(namespace)

Remove a CIM namespace from the repository.

validate_namespace(namespace)

Validate if the namespace exists in the repository.

Attributes:

namespaces

NocaseList of string: The names of the namespaces that exist in this CIM repository.

abstract 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.

abstract 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

InMemoryObjectStore

Raises
  • ValueError – Namespace argument is None.

  • KeyError – Namespace does not exist in the repository

abstract 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

InMemoryObjectStore

Raises
  • ValueError – Namespace argument is None.

  • KeyError – Namespace argument does exist in the repository.

abstract 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

InMemoryObjectStore

Raises
  • ValueError – namespace parameter is None

  • KeyError – namespace argument does exist in therepository.

abstract property namespaces

NocaseList of string: 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.

abstract 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.

abstract 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.

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.

New in pywbem 1.0 as experimental and finalized in 1.2.

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(name, cim_object)

Add the CIM object to the object store.

delete(name)

Delete the CIM object identified by name from the object store.

get(name[, copy])

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([copy])

Return an iterator to the CIM objects in the object store.

len()

Return the count of objects in this object store.

object_exists(name)

Test if the CIM object identified by name exists in the object store.

update(name, cim_object)

Replace the CIM object in the object store idenfified by the name argument with the CIM object defined by the cim_object argument.

abstract 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.

abstract 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

abstract 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

CIM object

Raises

KeyError – CIM object identified with name not in the object store

abstract 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

abstract 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

abstract len()[source]

Return the count of objects in this object store.

Returns

Integer that is count of objects in this object store.

Return type

int

abstract 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

abstract 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.

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 the FakedWBEMConnection methods that create objects in the repository (ex. compile_mof_file())

Methods:

__repr__()

Return repr(self).

add_namespace(namespace[, verbose])

Add a CIM namespace to the CIM repository.

class_exists(namespace, classname)

Test if class defined by classname parameter exists in CIM repository defined by namespace parameter.

filter_properties(obj, property_list)

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(namespace, classname[, ...])

Get class from CIM repository.

is_interop_namespace(namespace)

Tests if a namespace name is a valid Interop namespace name.

is_subclass(klass, superclass, class_store)

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(namespace[, verbose])

Remove a CIM namespace from the CIM repository.

validate_namespace(namespace)

Validates that a namespace is defined in the CIM repository.

Attributes:

cimrepository

Instance of class that represents the CIM repository.

interop_namespace_names

NocaseList of string: The valid Interop namespace names.

namespaces

NocaseList of string: The names of the namespaces that exist in the CIM repository.

__repr__()[source]

Return repr(self).

add_namespace(namespace, verbose=False)[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.

An Interop namespace can be added with this method, if an Interop namespace does not yet exist in the CIM repository.

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.

  • verbose (bool) – Verbose mode: Print a message about the namespace creation.

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.

property 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 each FakedWBEMConnection construction.

Type

BaseRepository or subclass

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

KeyError – Namespace does not exist in the CIM repository

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 or CIMInstance) – 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.

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

CIMClass

Raises
  • CIMError – (CIM_ERR_NOT_FOUND) if class not found in CIM repository.

  • CIMError – (CIM_ERR_INVALID_NAMESPACE) if namespace does not exist.

property interop_namespace_names

NocaseList of string: 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.

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

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

bool

Raises

KeyError – Class or superclass does not exist in the class store.

property namespaces

NocaseList of string: The names of the namespaces that exist in the CIM repository.

remove_namespace(namespace, verbose=False)[source]

Remove a CIM namespace from the CIM repository.

The namespace must exist in the CIM repository and must be empty.

The Interop namespace cannot be removed from the CIM repository.

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.

  • verbose (bool) – Verbose mode: Print a message about the namespace deletion.

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_INVALID_NAMESPACE if the Interop namespace was specified.

  • 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

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.

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
  • Python 2.7 Glossary

  • Python 3.4 Glossary

Change log

pywbem 1.4.2

Released: 2022-10-11

Incompatible changes:

  • The removal of internal symbols from the ‘pywbem_mock’ Python namespace may cause name errors in your code, if you were using them. (related to issue #2888)

Bug fixes:

  • Test: Mitigated incorrect version of testfixtures package on Python 3.5 by pinning it to <6.4.0 on Python 3.5. (issue #2855)

  • Excluded setuptools 61.0.0 because it breaks installation via “setup.py install” (issue #2871)

  • Resolved new issues reported by Pylint 2.13 (issue #2870)

  • Fixed that the added setup.py commands (test, leaktest, installtest) were not displayed. They are now displayed at verbosity level 1 (using ‘-v’).

  • Pinned “certifi” to <2020.6.20 on Python 2.7 because the install test using “setup.py install” started failing because it installed a version of certifi on Python 2.7 that properly declares that it requires Python >=3.6.

  • Removed internal symbols from ‘pywbem_mock’ Python namespace, and added the ‘config’ submodule to the ‘pywbem_mock’ Python namespace. (related to issue #2888)

  • Fixed invalid references in the documentation. As part of that, added class ‘MOFWBEMConnection’ to the ‘pywbem’ namespace, moved class ‘IterQueryInstancesReturn’ from the scope of method ‘pywbem.IterQueryInstances’ to the ‘pywbem’ namespace. (issue #2888).

  • Fixed new formatting issues raised by flake8 5.0.

  • Fixed a RecursionError exception raised by flake8 on Python 3.6 and 3.7. (issue #2922)

  • Added security issues 50748, 50571, 50664, 50663, 50892, 50885, 50886 to Makefile ignore list of new security issue August and September 2022.

pywbem 1.4.1

Released: 2022-02-01

Bug fixes:

  • Fix issue where the DeepInheritance parameter not passed to the mocker OpenEnumerateInstances method so the result is that the mocker always uses the default (DeepInheritance=True). (see issue #2839)

Cleanup:

  • Modified compiler and pywbem_mock to allow creating instances from abstract classes because SNIA ignored DMTF rule making this illegal and many MOF compilers also ignored it. Pywbem now issue a warning from the MOF compiler if an instance of an abstract class is compiled but complete the compile and another warning from pywbem_mock.CreateInstance if the instance is for an abstract class. (see issue #2825)

pywbem 1.4.0

Released: 2022-01-01

Bug fixes:

  • Aligned minimum versions of pip,setuptools,wheel with pywbemtools, nocasedict,nocaselist. This increased the minimum version of pip on Python 3.5 to fix an issue.

Enhancements:

  • Improved verbosity of namespace creation and deletion: Added optional ‘verbose’ parameters to the create_namecpace() and delete_namespace() methods of WBEMServer, and to the add_namecpace() and remove_namespace() methods of FakedWBEMConnection (and subsequently to BaseProvider) in the mock support.

pywbem 1.3.0

This version contains all fixes up to version 1.2.1.

Released: 2021-12-04

Incompatible changes:

  • The WBEMListener.start() method may raise new exceptions pywbem.ListenerPortError, pywbem.ListenerPromptError and pywbem.ListenerCertificateError. The OSError and IOError exceptions raised in earlier versions may still be raised for other, less common cases. For details, see the corresponding item in the Enhancements section, below.

  • Changed ‘SubscriptionManager.add_filter()’ method to use the ‘SourceNamespaces’ property (allows multiple namespaces) of the ‘CIM_IndicationFilter’ class instead of the deprecated ‘SourceNamespace’ property (allows only single namespace). This changed the name of the positional ‘source_namespace’ parameter to ‘source_namespaces`. The new parameter allows both string and list of strings as values.

    This change brings the subscription manager in line with the incorporation of the ‘SourceNamespaces’ property made to this CIM class definition by DMTF CIM schema release 2.22.0.

    An optional ‘source_namespace’ keyword parameter has been added to the ‘add_filter()’method to account for any case where a WBEM Server cannot handle the SourceNamespaces property. The primary incompatibility will be that the instance created for CIM_Indication filter now has a property named ‘SourceNamespaces’ instead of ‘SourceNamespace’. See further comments below and issue #2725.

  • Changed the ‘SubscriptionManager.add_filter()’ method to no longer allow specifying the ‘filter_id’ parameter for permanent filters. The documentation had already disallowed that case, but the code allowed it. (issue #2757)

  • Added code to fail compile or creation in pywbem_mock of instance of Abstract class. Before this the WBEM server might fail the attempt but the MOF compiler and pywbem_mock would build the instance (see issue # 2742).

  • The new simplified format of the automatically generated ‘Name’ property of owned indication filters causes existing filters with the old format to be ignored and a Python warning of type ‘pywbem.OldNameFilterWarning’ will be issued. Such owned filter instances need to be either removed as owned filters with a prior version of pywbem, or as permanent filters with this version of pywbem. (issue #2765)

  • Removed the ‘pywbem.WBEMSubscriptionManager.add_listener_destinations()’ method, because the new naming approach for listener destinations requires either a name or an ID and that does not work well with supporting multiple destinations in one method call. Use the new ‘add_destination()’ method instead. (issue #2766)

  • The new simplified format of the automatically generated ‘Name’ property of owned listener destinations causes existing destinations with the old format to be ignored and a Python warning of type ‘pywbem.OldNameDestinationWarning’ will be issued. Such owned destination instances need to be either removed as owned destinations with a prior version of pywbem, or as permanent destinations with this version of pywbem. (issue #2766)

Bug fixes:

  • Fixes bug in compiler where log of ModifyClass request failure was not surrounded by verbose test (if p.parse.verbose:). See pywbemcli issue #395,

  • Fixes several issues in WBEMSubscriptionManager:

    • Fixed the discrepancy between documentation and code in add_filter() regarding ‘filter_id’, ‘name’ and ownership type: The only allowed combinations are now owned filters with ‘filter_id’ and permanent filters with ‘name’. (issue #2757)

    • add_filter() and add_destinations() methods can no longer modify existing instances on the WBEM server. They can only create new instances.

    • Modified the algorithm to determine owned filters and instances so they are are correctly recovered from the WBEM server when the WBEMSubscriptionManager is restarted (before this they could be returned as not-owned object).

    • Change to use WBEM server systemname as the value of the SystemName property.

    • Removed code that built instance path for new filter and destination instances since that was used only to try to determine if instance existed to make the create/modify decision.

    • Added the client host as a component of the Name property for owned filters and destinations. (issue #2701).

    • Fix issue where windows indication throughput is very slow. It is in the range of 1 indication every 2 seconds. The issue is not pywbem but windows itself apparently because of hosts file and DNS configuration such that using localhost builds in a delay. This can be fixed by using an IP address 127.0.0.1 for the indication listener or modifying the hosts table in windows. For this test we chose to just change the host name See issue #528)

    • Fixes issue with SubscriptionManager class where add_destinations loses the input parameter owned if there are multiple urls in the listener_urls parameter (see issue #2715)

    • Fixes issue where add_subscription returned wrong instance if the instance already exists. (See issue #2719)

    • Fix issues in SubscriptionManager.add_destination to add optional parameter which populates the destination PersistenceType property. (See issue #2712)

    • Add capability to mock subscription providers to execute ModifyInstance (See issue #2722)

    • Fixed pywbem_mock and the MOF_compiler to test for creation or compile of an instance with a creation class that has the Abstract qualifier. This will fail since abstract classes cannot be instantiated. (see issue #2742)

    • Removed use of unittest.Mock in pywbem_mock.FakedWBEMConnection to use mock versions of _imethodcall and _methodcall and simply duck typed the methods. (see issue #2755)

    • Fixed issue in pywbem SubscriptionManager where duplicate add_destination() resulted in good return rather than CIMError. The code where the Name property is different but the URL the same was modified to test for both URL and persistence type equality before returning the existing instance. (See issue $ 2782)

  • Fixes MOF compiler issue where the compiler was allowing array properties to have corresponding instances instantiated with non-array values and vice-versa. This now causes a parse error. (See issue # 2786)

  • Docs: Fixed an error with the autodocsumm and Sphinx 4.0.0. (issue #2697)

  • Jupyter Notebook: Ignored safety issues 40380..40386 in order to continue supporting it with Python 2.7. (issue #2703)

  • Windows: Removed dependency on bash command in pip upgrade in Makefile. (issue #2713)

  • WBEM listener: Fixed the incorrect Content-Type header value ‘text/html’ that was set in its export responses by changing that to ‘text/xml’. (part of issue #2729)

  • WBEM listener: Removed the incorrect check for the Accept-Encoding header value when processing export requests to be consistent with DSP0200 which requires that WBEM listeners must support any value. (part of issue #2729)

  • Fixed installation with setup.py on ubuntu for Python 2.7, 3.4, 3.5, by pinning yamlloader to <1.0.0. (issue #2745)

  • Mitigated Pylint issue ‘deprecated-method’ when using time.perf_counter() on Python versions 3.6 and 3.7. (issue #2768)

  • Mitigated new Pylint error ‘not-an-iterable’ when using ‘WBEMServer’ properties that return lists and use deferred initialization. (issue #2770)

  • Security - Added 42218 42253 42254 42297 42298 42203 to safety ignore list. These were new safety issues 1 Nov 2021. The modules are all in development, and Jupyter notebook.

  • Fix incompatibility between Sphinx 1.8.5 (version for python <= 3.5) and docutils 0.18. (See issue # 2787).

  • Modified dev-requirements and rtd-requirements to require Sphinx >= 3.54.

  • Modify dev-requirements.txt to limit version of more-itertools to < 8.10.1 for python < 3.6. See issue #2796

  • Fixed new issues raised by Pylint 2.12.1.

  • Fixed error when installing virtualenv in install test on Python 2.7.

Enhancements:

  • Improved the running of indication listeners via WBEMListener.start():

    • The method will now raise a new exception pywbem.ListenerPortError when the port is in use, instead of the previous socket.error on Python 2 and OSError on Python 3 that had confusing or unspecific error messages.

    • The method will now raise a new exception pywbem.ListenerCertificateError when using HTTPS and there is an issue with the server certificate file, private key file, or invalid password for the private key file, instead of the previous ssl.SSLError or OSError that had confusing or unspecific error messages.

    • The method will now raise a new exception pywbem.ListenerPromptError when using HTTPS and the prompt for the password of the private key file was interrupted or ended, instead of the previous IOError or OSError that had unspecific error messages.

    • If the private key file is protected with a password, the password prompt now states the path name of the private key file in the prompt message.

    • Add optional initialization parameter url to pywbem_mock FakedWBEMConnection class. This allows a different URL than the default http://FakedWBEMConnection:5988. With this, tests can be executed with multiple simultaneous mock environments pywbem. (See issue #2711)

  • Test: Added support for validating the structure of user-defined properties in the easy-server server and vault files. As part of that, increased the minimum version of the ‘pytest-easy-server’ package to 0.8.0. (issue #2660)

  • Added providers to the pywbem_mock environment for the 3 classes required to manage subscriptions in a WBEM server. (See issue #2704)

  • Finalized the support for SI units that was experimental so far, i.e. the ‘pywbem.siunit()’ and ‘pywbem.siunit_obj()’ functions. (issue #2653)

  • Modify ‘SubscriptionManager.add_filter()’ to use the CIM_IndicationFilter property ‘SourceNamespaces’ in place of the deprecated ‘SourceNamespace’. (see issue #2725 and the Incompatible changes: section above)

  • Added support for the ExportIndication export operation by extending ‘WBEMConnection’ to be able of targeting a WBEM listener instead of a WBEM server, and by adding an ‘ExportIndication()’ method to ‘WBEMConnection’. The ‘default_namespace’ and ‘use_pull_operations’ init parameters and properties are ignored when targeting a WBEM listener. (issue #2729)

  • Test: Improved diff display when assertion in test_recorder.py fails.

  • Added toleration support for WBEM servers that return a CIM status CIM_ERR_FAILED when pywbem issues a pull operation and the server does not support it. Note that DSP0200 requires the use of CIM status CIM_ERR_NOT_SUPPORTED in this case, but at least one WBEM server returns CIM_ERR_FAILED. (issue #2736)

  • Added a ‘copy()’ method to ‘WBEMConnection’, ‘FakedWBEMConnection’, ‘LogOperationRecorder’, and ‘TestClientRecorder’. The ‘copy()’ method returns a copy of the object where user-specified attributes are copied and any additional internal state is reset. In case of ‘FakedWBEMConnection’, the repository and registries of the original object are reused by the new object. (issue #2750)

  • The init methods of ‘WBEMConnection’ and ‘LogOperationRecorder’ now copy any mutable input arguments in order to ensure the new object is decoupled from the user-provided objects. (related to issue #2750)

  • Changed the WBEMConnection.timeout property to be settable. This allows adjusting the timeout after the connection has been created. (issue #2752)

  • Pylint: Removed pinning of Pylint to <2.7.0 because the performance issue can also be addressed by disabling the similarity checker, and addressed Pylint issues reported by Pylint 2.9. (issue #2672)

  • Simplified the format of the automatically generated ‘Name’ property of owned indication filters from: "pywbemfilter:" {ownership} ":" {client_host} ":" {submgr_id} ":" {filter_id} ":" {guid} to: "pywbemfilter:" {submgr_id} ":" {filter_id}. The client host was removed in order to allow different client systems to be used. The ownership was removed because filters with an auto-generated Name are always owned. The GUID was removed to make the name predictable and the uniqueness it attempted to guarantee is now achieved by rejecting the creation of filters with the same name. Overall, this change makes the name much more suitable for use in CLI tools such as pywbemcli. (issue #2765)

  • Added a ToleratedSchemaIssueWarning class with its base class Warning. The new ToleratedSchemaIssueWarning is expected to be used where the MOF compiler or code detects issues in the CIM Schema that are either tolerated or corrected.

  • Added a ‘pywbem.WBEMSubscriptionManager.add_destination()’ method that makes the way the ‘Name’ property is created for listener destination intances consistent with how that is now done for indication filters: There is a new parameter ‘name’ that directly sets the ‘Name’ property for permanent destinations, and a new parameter ‘destination_id’ that is used for creating the ‘Name’ property for owned destinations. The format of the generated ‘Name’ property has been changed from: "pywbemdestination:" {ownership} ":" {client_host} ":" {submgr_id} ":" {guid} to: "pywbemdestination:" {submgr_id} ":" {destination_id}. The client host was removed in order to allow different client systems to be used. The ownership was removed because destinations with an auto-generated Name are always owned. The GUID was removed to make the name predictable and the uniqueness it attempted to guarantee is now achieved by rejecting the creation of destinations with the same name. Overall, this change makes the name much more suitable for use in CLI tools such as pywbemcli. (issue #2766)

  • Fixed install error of PyYAML 6.0b1 on Python 2.7 during installtest, by pinning it to <6.0.

  • Fixed install error of wrapt 1.13.0 on Python 2.7 on Windows due to lack of MS Visual C++ 9.0 on GitHub Actions, by pinning it to <1.13.

  • Fixed install error of yanked jsonschema 4.0.0 on Python <3.7, by excluding it.

  • Enhanced test matrix on GitHub Actions to always include Python 2.7 and Python 3.4 on Ubuntu, and Python 2.7 and Python 3.5 on macOS and Windows.

  • Support for Python 3.10: Added Python 3.10 in GitHub Actions tests, and in package metadata.

Cleanup:

  • Extend tests for SubscriptionManager to utilize pytest and cover error cases.

pywbem 1.2.0

This version contains all fixes up to pywbem 1.1.3.

Released: 2021-04-26

Incompatible changes:

  • Unsupported CIM infrastructure versions returned in CIM-XML responses from WBEM servers are now raised as a new exception pywbem.CIMVersionError, and were previously raised as pywbem.CIMXMLParseError. Unsupported DTD versions and CIM-XML protocol versions returned in CIM-XML responses from WBEM servers are now raised as new exceptions pywbem.DTDVersionError and pywbem.ProtocolVersionError, and were previously ignored by pywbem. Since these new exceptions are derived from pywbem.VersionError which is derived from pywbem.VersionError, this change is only incompatible if such unsupported versions were specifically handled by users.

  • The pywbem.WBEMServer.get_selected_profiles() method now raises pywbem.ModelError instead of KeyError when required properties were found to be missing. This is an incompatible change for users that catch this exception. (related to issue #2580).

  • The operation recorder support added in pywbem 0.9 as an experimental feature was changed to become internal. As part of this, the “WBEM operation recording” section has been removed from the documentation, the operation recorder specific classes are no longer documented, and the operation recorder specific attributes and methods of the ‘WBEMConnection’ class have been declared to be internal and have been removed from the documentation. The logging support which uses the operation recorder remains publicly available. If you are using the operation recorder, please create an issue in the issue tracker describing how you use it.

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: Suppressed pylint warning about ‘tracemalloc’ methods on PyPy.

  • Test: Disabled leaktest in travis also on PyPy3 (in addition to PyPy2).

  • Test: Disabled ‘make resourcetest’ in Travis on Pypy2+3, and suppressed Pylint issues about using ‘tracemalloc’ methods and disabled its unit tests.

  • Fixed the bug that pywbem allowed reference typed CIMQualifier and CIMQualifierDeclaration objects. DSP0004 disallows reference types on qualifiers and qualifier declarations. This fix now causes CIM-XML responses received from a WBEM server with reference typed qualifier values and qualifier declarations to raise pywbem.CIMXMLParseError from WBEMConnection operations.

  • Fixed a DeprecationWarning issued by urllib3 about using the whitelist_methods parameter of Retry.

  • Security: Increased minimum version of ‘PyYAML’ to 5.2 on Python 3.4 and to 5.3.1 on Python 2.7 and >=3.5 to address security issues reported by safety. The relevant functions of ‘PyYAML’ are not used by pywbem, though.

  • Security: Increased minimum version of ‘urllib3’ to 1.24.2 on Python 3.4 and to 1.25.9 on Python 2.7 and >=3.5 to address security issues reported by safety. To support these versions of ‘urllib3’, increased minimum version of ‘requests’ to 2.20.1 on Python 3.4 and to 2.22.0 on Python 2.7 and >=3.5.

  • Security: Increased minimum versions of several packages that are needed only for test or development of pywbem to address security issues reported by safety: requests-toolbelt to 0.8.0; lxml to 4.6.2 (except for Python 3.4); pylint to 2.5.2 and astroid to 2.4.0 on Python >=3.5; typed-ast to 1.3.2 on Python 3.4; twine to 3.0.0 on Python >=3.6; pkginfo to 1.4.2; bleach to 3.1.2 on Python 3.4 and to 3.1.4 on Python 2.7 and Python >=3.5.

  • 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.

  • Test: Add tests to test_mof_compiler to test for errors where the namespace name component of the namespace pragma is missing.

  • In CIMNamespaceProvider.post_register_setup(), fixed an AttributeError when accessing the ‘Name’ property of a CIM instance (related to issue #2580).

  • In the MOFCompiler class, fixed that if a MOF instance already exists, the ModifyInstance operation failed because the instance path was not specified. The fix is to construct the instance path from the key properties in instance specified in MOF. That fix has the limitation that it does not account for instance providers that add key properties or that ignore provided key properties (e.g. InstanceID). (issue #2586)

  • Corrected issue in pywbem_mock where DeleteQualifier() was not checking whether the qualifier was used in any classes in the namespace before being deleted. (see #2585)

  • Fixed an incorrect calculation of the min/max values for the server response time in the statistics support of pywbem (issue #2599)

  • Security - Add safety issue 40072 (lxml version 4.6,3) to safety ignore list. No change to pywbem since we apparently do not use the affected component (see issue #2645)

  • Test: Pinned decorator package to python <=5.0.0 on Python 2+3.4 because decorator 5.0.0 does not support python < 3.5 (see issue #2647)

  • Fix pywem_mock issue with Delete class not calling providers to handle the DeleteInstance (see issue #2643)

  • Test: Workaround for BadStatusLine issue in test_WBEMListener_send_indications test function. This is not a fix for the root cause of the issue. For details, see pywbem issue #2659.

  • Fixed installation of ‘pywinpty’ package on Python 2.7 by pinning it to <1.0. It failed because it does not declare its supported Python versions. (see issue #2680)

  • Fixed that the test workflow ignored errors that occurred during ‘make install’ and ‘make develop’, by splitting the multiple commands in these steps into separate steps.

Enhancements:

  • Finalized the pywbem mock support. (issue #2651)

  • Logging: Added a value ‘off’ for the log destination in the pywbem.configure_logging() function that disables logging. (part of issue #86)

  • 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)

  • Reduced memory consumption of CIM objects and CIM types by defining their attributes to use Python slots. (see issue #2509)

  • Reduced memory consumption of CIM objects by using lazy initialization of dictionary-type attributes. This resulted in significant savings when the attribute is typically unused, for example in CIMInstance.qualifiers. (see issue #2511)

  • Added Python 3.9 to the supported Python versions and added tests for it on Travis.

  • Added a check for the DTDVERSION attribute value in CIM-XML responses from WBEM servers to start with ‘2.’. A different version of the CIM-XML DTD standard DSP0203 was never published, so this is not expected to be an incompatible change.

  • Unsupported versions for CIM infrastructure, DTD or protocol version returned in CIM-XML responses from WBEM servers are now raised as new exceptions pywbem.CIMVersionError, pywbem.DTDVersionError, and pywbem.ProtocolVersionError, respectively. These new exceptions are derived from the existing exception pywbem.VersionError. Previously, unsupported CIM infrastructure versions were raised as pywbem.CIMXMLParseError, and unsupported DTD or protocol versions were ignored by pywbem.

  • Removed the pinning of Pylint to 2.5.2 on Python >=3.5. Disabled the following warnings that were newly reported by the latest version (2.6.0) of Pylint: ‘signature-differs’ because it does not recognize compatible signature changes; ‘raise-missing-from’ and ‘super-with-arguments’ because these issues cannot reasonably be addressed as long as Python 2.7 is supported.

  • In the makefile, added an ignore list for issues reported by safety along with the reasons why each issue is ignored. This allowed enforcing that the safety command reports no issues.

  • Migrated from Travis and Appveyor to GitHub Actions. This required several changes in package dependencies for development.

  • Docs: Added examples to the pywbem.siunit() and pywbem.siunit_obj() functions.

  • Extend the MOF compiler so that the pywbem_mock can compile MOF containing the namespace pragma that defines a namespace other than the one defined in the compile_mof_string() or compile_mof_file() methods namespace parameter if the namespace exists. Extend documentation on use of the namespace parameter to reflect the behavior if the MOF contains a namespace pragma. Since the code gives precedence to tha pragma over the namespace specified in in the namespace parameter, the documentation reflects this. (see issue #2256 partial fix).

  • The pywbem.siunit() function supported the PUnit format as defined in DSP0004. It turned out that the CIM Schema used PUnit qualifiers with a slightly extended format where the numeric modifiers were the middle instead of just at the end. Extened the PUnit format supported by the siunit() function accordingly. (issue #2574)

  • Improved and fixed the messages in the compile log of class MOFCompiler and ensured that the target namespace of the compiled objects is included in the messages and added messages for changes to the target namespace caused by ‘pragma namespace’ directives.

  • The ‘mof_compiler’ script now displays the compiled objects and their target namespace when specifying verbose mode (-v option).

  • Improvements in pywbem_mock.CIMNamespaceProvider and pywbem.WBEMServer to more cleanly handle Interop namespaces (related to issue #2580).

  • Improvements in the log messages of the MOFCompiler class. (related to issue #2586)

  • Added a close() method to pywbem.WBEMConnection that closes the underlying session of the ‘requests’ package. This avoids the ResourceWarning ‘unclosed socket’ that the ‘requests’ package issued so far when the Python process terminates. Added the ability for pywbem.WBEMConnection to be used as a context manager, that closes the connection at the end. (see issue #2591)

  • Added a mechanism to suspend the statistics counting of server time if one or more operations do not return the server response time, in order to prevent incorrect interpretations of the counters when only a subset of the operations returned server response time. (issue #2603)

  • Added validation tests to pywbem_mock ModifyClass to limit classes that can be modified (no subclasses, and no instances exist, and correct superclass) (see issue #2447)

  • Docs: Used ‘autodocsumm’ Sphinx extension for generating attribute and method summary tables for classes in the documentation. Moved documentation of some base classes into a new ‘Base Classes’ section in the appendix.

  • Added a conn_close() method to the pywbem.MOFCompiler class that closes the underlying connection. Used that function in the ‘mof_compiler’ script to remove a ResourceWarning about unclosed sockets. (issue #2610)

  • Added ‘make perftest’ to run performance tests. At this point, the performance tests measure the sending of indications to the pywbem.WBEMListener.

  • Test: Added support for end2end testing of WBEM servers based on server and vault files of the ‘easy-server’ Python package. The server files can specify WBEM servers and their expected supported functions. WBEM servers can be somewhere in the network or can be containers on DockerHub which are automatically pulled and started. At this point, the OpenPegasus container on DockerHub is used and the end2end tests are run in the GitHub Actions test workflow on Ubuntu (Docker is not available in GHithub Actions on Windows or MacOS).

Cleanup:

  • Test: Fixed all remaining ResourceWarnings during test. (issue #86)

  • Test: Cleaned up DeprecationWarning for the propagation of key property values introduced in pywbem 1.1.0. (see issue #2498)

  • Add index section to generated documentation.

  • Fixed new issues reported by pylint 2.7.0. At the same time, needed to temporarily pin pylint to <2.7.0 and astroid to <2.5.0 due to massive elongation of the run time of pylint in the pywbem project.

  • Added tests for pywbem_mock ModifyClass request operation to test the validation exceptions and correctness of modified class. (see issue #2210)

  • Cleaned up TODOs noted in pywbem and pywbem_mock to fix any that were actually bugs, etc. and either create issues or mark the others as FUTURE with more explanation. (See issue #2491)

  • Enforced that the pywbem source code does not contain any TODOs (pylint fixme). Note that the pywbem test code may still contain TODOs.

  • Removed remove_duplicate_setuptools.py script since the project is no longer using Travis.

Known issues:

  • On Python 3.4, the urllib3 package is pinned to <1.25.8 because 1.25.9 removed Python 3.4 support. As a consequence, safety issue 38834 cannot be addressed on Python 3.4.

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() to WBEMConnection that checks whether a class is a subclass of a class. Both classes can be specified as classnames or as CIMClass objects.

  • Added support for translating the values of PUnit and Units qualifiers into human readable SI conformant unit strings, via new functions pywbem.siunit_obj() and pywbem.siunit(). These new functions are marked as experimental. (See issue #2423)

  • Mock: Added a new property provider_dependent_registry to FakedWBEMConnection 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:

    1. reference classes (classes defined in reference properties or parameters)

    2. 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 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 the pywbem.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 to WBEMConnection 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 using repr() easier for pywbem users, and it also helps in some unit test cases of pywbem itself.

  • Made sure that str() on CIMInstanceName 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 the reference_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() in tupleparse.py, a number of attributes of the new CIMProperty 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)

Document Index


© Copyright . Revision df8f3abd.

Built with Sphinx using a theme provided by Read the Docs.
Read the Docs v: stable_1.4
Versions
latest
stable
stable_1.4
stable_1.3
stable_1.2
stable_1.1
stable_1.0
stable_0.9
stable_0.17
stable_0.16
stable_0.15
stable_0.14
stable_0.13
stable_0.12
stable_0.11
stable_0.10
Downloads
html
On Read the Docs
Project Home
Builds