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.
The listener receives indications from an indication sender, validates the formatting of the indication and queues each received indication into an interprocess queue (indication queue). A seperate thread monitors this queue and calls registered callback functions for each indication in the queue.
This insures that timing in the callback functions does not interfere with the reception of indications from the indication sender.
6.1.1. Examples
The following example creates and runs a listener:
import logging
from pywbem import WBEMListener
def process_indication(indication, host):
'''This function gets called when an indication is received.'''
print(f"Received CIM indication from {host}: {indication!r}")
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'
# Set host name to wildcard host address to recieve indications on
# any network address defined for this system.
listener = WBEMListener(host="",
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.
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.
6.1.3. Listener indication flood
The pywbem listener processes indications through an interprocess queue (indication queue) between the listener thread that receives the indication over the network and the callback thread in which the user-provided callback function runs.
If the callback processing takes longer, indications can pile up in the indication queue. While this is not normally an issue, a flood of indications from the sender could result in more indications in the queue than the memory of the listener can support.
The handling of this situation in pywbem has improved over time:
Before pywbem 1.8.0, the indication queue had no size limit, and grew larger until memory limits were reached.
Starting with pywbem 1.8.0, the
pywbem.WBEMListenerclass added an optional init parametermax_ind_queue_sizeto specify a size limit for the indication queue. When the size limit was reached, the listener and callback threads terminated and thepywbem.WBEMListener.start()method raisedpywbem.ListenerQueueFullError. No CIM-XML error response was sent back to the sender for the indication that caused the queue to become full. This approach was meant to protect from memory full conditions but had the drawback that the listener stopped and the sender got no information as to why that happened.Starting with pywbem 1.9.0, the behavior has been improved: When the size limit of the indication queue is reached, the indication is not put into the queue, a CIM-XML error response with status
CIM_ERR_FAILEDis sent back to the sender and the listener and callback threads continue to run. As a result, no exception indicating that the queue is full is raised anymore from thepywbem.WBEMListener.start()method. For backwards compatibility reasons, thepywbem.ListenerQueueFullErrorexception is still defined (but is no longer raised). In addition, the default for themax_ind_queue_sizeinput parameter has been changed from 0 (unlimited) to a reasonable limit.
The following example creates and runs a listener:
import logging
from pywbem import WBEMListener
def process_indication(indication, host):
'''This function gets called when an indication is received.'''
print(f"Received CIM indication from {host}: {indication!r}")
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'
# Set host name to wildcard host address to recieve indications on
# any network address defined for this system.
listener = WBEMListener(host="",
http_port=5990,
https_port=5991,
certfile=certkeyfile,
keyfile=certkeyfile)
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()
6.1.4. WBEMListener class
- class pywbem.WBEMListener(host, http_port=None, https_port=None, certfile=None, keyfile=None, max_ind_queue_size=5000)[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.
The listener validates the syntax of the received CIM instance but does not validate the values of received the MESSAGE_ID or SEQUENCE_NUMBER of incoming indications. Therefore, it does not know if any indications are missing from a sequence. The callback function must do any such processing., etc. that confirms if indications are in the proper sequence and none were lost.
- Parameters:
host (str) –
IP address or host name to which this listener is bound (i.e. at which this listener can be reached). If a listener is bound to a particular IP address it will only receive indications addressed to that IP address (or to any IP address on the network interface containing that address) depending on the OS.
Network wildcard addressing enables receiving indications from all IP addresses on the system by binding the listener to certain special addresses. The IPV4 wildcard IP address is “0.0.0.0” and the IPV6 wildcard IP address is “::”. Setting the host parameter to an empty string (i.e. “”) is equivalent to using the wildcard address with the default IP addressing family.
HTTP port at which this listener can be reached. 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 at which this listener can be reached.
None means not to set up a port for HTTPS.
certfile (str) –
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 (str) –
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.
max_ind_queue_size (int) –
A positive integer which defines the maximum size of the indication queue. If an indication is received and the queue is full, the indication is not put into the queue and a CIM-XML response with status
CIM_ERR_FAILEDis sent back to the sender, indicating that the indication could not be accepted. The listener and callback threads continue to run.A value of 0 indicates that the queue has no maximum size. In this case, the queue size will grow as needed (until the listener process is out of memory), and all indications will be accepted.
For a reliable operation of the listener, it is recommended to define a maximum queue size.
- Raises:
TypeError – port, max_ind_queue_size arguments invalid type.
ValueError – No connection port specified, max_ind_queue_size invalid integer.
Methods:
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 representation of the
WBEMListenerobject with all attributes, that is suitable for debugging.__str__()Return a representation of the
WBEMListenerobject with a subset of its attributes.add_callback(callback)Add a callback function to the listener.
Returns whether the indication queue is empty.
Returns whether the indication queue exists.
Returns the number of indications currently in the indication queue.
start()Start the WBEM listener.
stop()Stop the WBEM listener gracefully.
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.
The maximum size of the indication queue.
- __enter__()[source]
Enter method when the class is used as a context manager.
New in pywbem 0.12.
Returns the listener object. Note that the enter method does not start the listener.
- __exit__(exc_type, exc_value, traceback)[source]
Exit method when the class is used as a context manager.
New in pywbem 0.12.
Stops the listener by calling
stop().
- __repr__()[source]
Return a representation of the
WBEMListenerobject with all attributes, that is suitable for debugging.
- __str__()[source]
Return a representation of the
WBEMListenerobject 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.
Multiple callback functions may be defined by repeating this function with each callback function required.
All of the defined callbacks will be executed for each indication. They will be executed serially in the order that they were added and on the same thread.
The callback interface is defined in the callback_interface function.
- 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:
- 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:
- ind_queue_empty()[source]
Returns whether the indication queue is empty.
- Returns:
True if the indication queue is empty; otherwise False. If the indication queue does not exist, None is returned.
- Return type:
- ind_queue_exists()[source]
Returns whether the indication queue exists.
- Returns:
True if the indication queue exists; otherwise False.
- Return type:
- ind_queue_size()[source]
Returns the number of indications currently in the indication queue.
Note that the number of indications in the queue can vary quickly as indications flow.
- Returns:
Number of indications currently in the indication queue. If the indication queue does not exist, None is returned.
- Return 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:
- property max_ind_queue_size
The maximum size of the indication queue.
A value of 0 means that the indication queue will grow as needed, limited only by the available memory in the listener process.
- Type:
- start()[source]
Start the WBEM listener.
The WBEM listener must not already be running.
When the WBEM listener is started, first the callback thread is started that will lateron call the registered callback functions for each indication that is received. Then, the listener threads for HTTP and HTTPS are started (depending on which ports have been specified) to enable the receiving of indications from a sender.
The listener threads will handle the CIM-XML ExportIndication export message described in DSP0200 and they will put each indication received into the indication queue of the WBEM listener. The callback thread will get the indications from the queue and will pass them to registered callback functions.
The listener must be stopped by the user in order to free the TCP/IP ports 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 whenWBEMListeneris 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.ListenerCertificateErroris raised.If this method raises an exception, the callback thread and listener threads are cleaned up again.
Starting with pywbem 1.9.0, this method no longer raises the
pywbem.ListenerQueueFullErrorexception.- 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 gracefully.
This method can also be called when the WBEM listener was already stopped.
When stopping the WBENM listener, the listener threads are first stopped to make sure that no new indications can be received. Then, the callback thread completes its delivery of indications that are in the indication queue, and when the queue is empty, the callback thread is stopped.
- 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 (str) – 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. The exception is not passed back from the callback thread.
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 (str) – Error message (will be put into args[0]).
- Variables:
args – A tuple (message, ) set from the corresponding init argument.
Methods:
add_noteException.add_note(note) -- add a note to the exception
with_tracebackException.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
ListenerStartError.- Parameters:
message (str) – Error message (will be put into args[0]).
- Variables:
args – A tuple (message, ) set from the corresponding init argument.
Methods:
add_noteException.add_note(note) -- add a note to the exception
with_tracebackException.with_traceback(tb) -- set self.__traceback__ to tb and return self.
- class pywbem.ListenerStartError(message)[source]
This exception indicates a problem with starting the listener.
New in pywbem 1.9.
Derived from
ListenerError.- Parameters:
message (str) – Error message (will be put into args[0]).
- Variables:
args – A tuple (message, ) set from the corresponding init argument.
Methods:
add_noteException.add_note(note) -- add a note to the exception
with_tracebackException.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 (str) – Error message (will be put into args[0]).
- Variables:
args – A tuple (message, ) set from the corresponding init argument.
Methods:
add_noteException.add_note(note) -- add a note to the exception
with_tracebackException.with_traceback(tb) -- set self.__traceback__ to tb and return self.
- class pywbem.ListenerQueueFullError(message)[source]
Starting with pywbem 1.8.0, this exception indicated that the indication delivery queue has reached its maximum size. Starting with pywbem 1.9.0, this exception is no longer raised.
New in pywbem 1.8; No longer used starting with pywbem 1.9.0
Derived from
ListenerError.- Parameters:
message (str) – Error message (will be put into args[0]).
- Variables:
args – A tuple (message, ) set from the corresponding init argument.
Methods:
add_noteException.add_note(note) -- add a note to the exception
with_tracebackException.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 (str) – Error message (will be put into args[0]).
- Variables:
args – A tuple (message, ) set from the corresponding init argument.
Methods:
add_noteException.add_note(note) -- add a note to the exception
with_tracebackException.with_traceback(tb) -- set self.__traceback__ to tb and return self.