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 formtting of the indication and queues each received indication into an interprocess queue. A seperate thread monitors this queue and calls the 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
A listener processes indications through an interprocess queue so a flood of indications from the indication sender where the callback processing was taking longer than indication reception could over time result in indications piling up in the received 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 client can support. Effective with version 1.8.0, an optional argument was added to the listener initialization (max_ind_queue_size) that causes generation of an exception (ListenerQueueFullError) and stopping of sending indication reception. Since this effectively stops the listener, it should only be used if the number of indications in the queue is a threat to the memory in the client, not for temporary slowdown of the flow of indications from the indication sender.
It closes the listener connections and discards indications in the queue.
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,
max_ind_queue_size=5000,
)
listener.add_callback(process_indication)
try:
listener.start()
# process_indication() will be called for each received indication
. . . # wait for some condition to end listening
except ListenerQueueFullError:
print("Indication listener failed. Indication queue full.")
listener.stop()
finally:
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=0)[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 (string) –
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 wild card IP address is “::”.
Setting the host parameter to an empty string (i.e. “”) is equivalent to using at least the IPV4 wildcard address.
http_port (string or integer) –
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 (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.
max_ind_queue_size (integer) –
A positive integer which defines the maximum number of the received indications that can be in the received indication queue. If the queue of received indications reaches this size, the queue is blocked and the
ConnectionError
is raised.The default is 0 which disables the test for queue full.
If set, this should be a large number since the goal is to stop receiving indications on the connection and may result in an indication receive failure on the WBEM server indication export function.
- Raises:
pywbem.ListenerQueueFullError – if number of indications in the listener queue exceeds max_ind_queue_size.
TypeError – port, max_ind_queue_size arguments invalid type.
ValueError – No connection port specified, max_ind_queue_size invalid integer.
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_to_callbacks
(indication, host)This function is called to deliver a single indication to all registered callback functions.
deliver_indications_forever
(ind_queue)Deliver indications from delivery_queue to the defined consumer.
handle_indication
(indication, host)Entry point from the listener server threads with a single indication.
Return boolean True if the indication queue is empty.
Return an integer with the approximate count of the number of indications currently in the received indication queue for this listener.
start
()Start the WBEM listener and callback threads, if they are not yet running.
stop
()Stop the WBEM listeners, the WBEM listener threads and callback thread, if they are running.
stop_indication_delivery
([immediate])Stop the indication delivery thread and the queue and handle indications in the queue.
Stop the WBEM listener threads.
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.
Return a positive integer the maximum queue size.
- __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.
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:
- deliver_indication_to_callbacks(indication, host)[source]
This function is called to deliver a single indication to all registered callback functions. 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.
- deliver_indications_forever(ind_queue)[source]
Deliver indications from delivery_queue to the defined consumer.
This function runs a loop in its own thread and only returns when the stop_event is set.
It delivers indications as fast as the callbacks complete while indications exist in the queue and waits for time defined by self.queue_get_timeout for indications to arrive if ind_delivery_queue is empty.
If stop_event.is_set() and the queue is emtpy it returns. This should only happen if the listener is stopped.
- handle_indication(indication, host)[source]
Entry point from the listener server threads with a single indication. Puts the indication in the received indication queue.
If the self.queue_full parameter is not 0, an exception will be executed if the queue contains the number of indication defined by the listener max_ind_queue_size parameter. This completely stops the indication receive thread because this function does not return.
- 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_delivery_queue_empty()[source]
Return boolean True if the indication queue is empty. Otherwise return False. This is available becasue the queue_size attribute only returns an approximation.
- 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
Return a positive integer the maximum queue size. If this value is not 0, an exception will be generated when this queue size is reached. If it is zero the exception is disabled.
- queue_size()[source]
Return an integer with the approximate count of the number of indications currently in the received indication queue for this listener.
- start()[source]
Start the WBEM listener and callback threads, if they are not yet running.
A interthread queue for holding indications recieved from a server thread and a thread for delivering indications from the queue to the callback functions are defined and the callback thread is started.
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 pass each indication received to the callback queue. A separate thread handles passing received messages from this queue to the callback functions defined.
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)
- stop()[source]
Stop the WBEM listeners, the WBEM listener threads and callback thread, if they are running.
- stop_indication_delivery(immediate=False)[source]
Stop the indication delivery thread and the queue and handle indications in the queue.
If immediate is True, indications are cleared from the queue without calling the callbacks.
If force is False, indications are forwarded to the callback until the queue is empty before stopping delivery.
- 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. 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 (string) – Error message (will be put into args[0]).
- Variables:
args – A tuple (message, ) set from the corresponding init argument.
Methods:
add_note
Exception.add_note(note) -- add a note to the exception
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:
add_note
Exception.add_note(note) -- add a note to the exception
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:
add_note
Exception.add_note(note) -- add a note to the exception
with_traceback
Exception.with_traceback(tb) -- set self.__traceback__ to tb and return self.
- class pywbem.ListenerQueueFullError(message)[source]
This exception indicates that the listener received indication queue has reached the maximum count of indications defined in the listener creation max_queue_size parameter.
New in pywbem 1.8.
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:
add_note
Exception.add_note(note) -- add a note to the exception
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:
add_note
Exception.add_note(note) -- add a note to the exception
with_traceback
Exception.with_traceback(tb) -- set self.__traceback__ to tb and return self.