6. 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.
6.1. 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.
6.1.1. 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.
6.1.2. 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.
6.1.3. 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 to which this listener is bound (i.e.
at which this listener can be reached). Setting the host address to IP address 0.0.0.0 defines a listener that binds to all network interfaces.
- 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. Both the http and https ports can 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:
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:
File path of the certificate file used as server certificate during SSL/TLS handshake when creating the secure HTTPS connection.
IP address or host name to which this listener is bound.
HTTP port at which this listener can be reached.
Boolean indicating whether the listener is started for the HTTP port.
HTTPS port at which this listener can be reached.
Boolean indicating whether the listener is started for the HTTPS port.
File path of the private key file used by the server during SSL/TLS handshake when creating the secure HTTPS connection.
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
- 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 to which this listener is bound. If IP adress 0.0.0.0, this listener is not bound to a particular IP address and accepts requests from any host on any network.
- Type
- property http_port
HTTP port at which this listener can be reached.
None means there is no port set up for HTTP.
- Type
- 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
- property https_port
HTTPS port at which this listener can be reached.
None means there is no port set up for HTTPS.
- Type
- 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
- 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
- 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
- start()[source]
Start the WBEM listener threads, if they are not yet running.
A thread serving CIM-XML over HTTP is started if an HTTP port was specified for the listener. A thread serving CIM-XML over HTTPS is started if an HTTPS port was specified for the listener.
These server threads will handle the ExportIndication export message described in DSP0200 and they will invoke the registered callback functions for any received CIM indications.
The listener must be stopped again in order to free the TCP/IP port it listens on. The listener can be stopped explicitly using the
stop()
method. The listener will be automatically stopped when the main thread terminates (i.e. when the Python process terminates), or whenWBEMListener
is used as a context manager when leaving its scope.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)
- 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.
6.2. 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.