6. Notifications

The HMC supports the publishing of notifications for specific topics. This includes for example asynchronous job completion, property or status changes, and operating system messages issued in an LPAR or DPM partition.

The zhmcclient package supports receiving HMC notifications in an easy-to-use way, as shown in the following example that receives and displays OS messages for a DPM partition:

import zhmcclient

hmc = ...
userid = ...
password = ...

session = zhmcclient.Session(hmc, userid, password)
client = zhmcclient.Client(session)
cpc = client.cpcs.find(name=cpcname)
partition = cpc.partitions.find(name=partname)

topic = partition.open_os_message_channel(include_refresh_messages=True)

print("Subscribing for OS messages for partition %s on CPC %s using "
      "notifications..." % (partition.name, cpc.name))

receiver = zhmcclient.NotificationReceiver(
    topic, hmc, session.session_id, session.session_credential)

while True:
    try:
        for headers, message in receiver.notifications():
            print("HMC notification #%s:" % headers['session-sequence-nr'])
            os_msg_list = message['os-messages']
            for os_msg in os_msg_list:
                msg_txt = os_msg['message-text'].strip('\n')
                msg_id = os_msg['message-id']
                print("OS message #%s:\n%s" % (msg_id, msg_txt))
    except zhmcclient.NotificationError as exc:
        print("Notification Error: {} - reconnecting".format(exc))
        continue
    except stomp.exception.StompException as exc:
        print("STOMP Error: {} - reconnecting".format(exc))
        continue
    except KeyboardInterrupt:
        print("Keyboard Interrupt - leaving")
        receiver.close()
        break
    else:
        print("Receiver has been closed  - leaving")
        break

When running this example code in one terminal, and stopping or starting the partition in another terminal, one can monitor the shutdown or boot messages issued by the operating system. The following commands use the zhmc CLI provided in the zhmccli project to do that:

$ zhmc partition stop {cpc-name} {partition-name}
$ zhmc partition start {cpc-name} {partition-name}
class zhmcclient.NotificationReceiver(topic_names, host, userid, password, port=61612, stomp_rt_config=None)[source]

A class for receiving HMC notifications that are published to particular HMC notification topics.

Experimental: This class is considered experimental at this point, and its API may change incompatibly as long as it is experimental.

Creating an object of this class establishes a JMS session with the HMC and subscribes for the specified HMC notification topic(s).

Notification topic strings are created by the HMC in context of a particular client session (i.e. Session object). However, these topic strings can be used by any JMS message listener that knows the topic string and that authenticates under some valid HMC userid. The HMC userid used by the JMS listener does not need to be the one that was used for the client session in which the notification topic was originally created.

Parameters:
  • topic_names (string or list/tuple thereof) – Name(s) of the HMC notification topic(s). Must not be None.

  • host (string) – HMC host. For valid formats, see the host property. Must not be None.

  • userid (string) –

    Userid for logging on to the HMC message broker. Must not be None.

    If the HMC userid is configured to use MFA, this must be the session ID of a session that user has with the HMC. Otherwise, it can either be the session ID, or the HMC userid.

  • password (string) –

    Password for logging on to the HMC message broker. Must not be None.

    If userid specifies a session ID, this must be the session credential for that session ID. If userid specifies an HMC userid, this must be the password for that userid.

  • port (integer) – STOMP TCP port. Defaults to DEFAULT_STOMP_PORT.

  • stomp_rt_config (StompRetryTimeoutConfig) –

    The STOMP retry/timeout configuration for this session, overriding any defaults.

    None for an attribute in that configuration object means that the default value will be used for that attribute.

    None for the entire stomp_rt_config parameter means that a default configuration will be used with the default values for all of its attributes.

    See Constants for the default values.

connect()[source]

Create a listener, connect to the HMC and subscribe for the specified topics.

If a connection exists with the HMC, it is first closed.

Note: STOMP does not nicely recover when just performing a STOMP connect after a connection loss, because there are occurrences of ssl.SSLError: PROTOCOL_IS_SHUTDOWN. Therefore, we create a new listener as well.

Raises:
  • NotificationConnectionError – STOMP connection failed.

  • NotificationSubscriptionError – STOMP subscription failed.

is_connected()[source]

Return whether this notification receiver is currently connected to the HMC.

subscribe(topic_name)[source]

Subscribe this notification receiver for a topic.

Parameters:

topic_name (string) – Name of the HMC notification topic. Must not be None.

Returns:

Subscription ID

Return type:

string

Raises:

NotificationSubscriptionError – STOMP subscription failed.

unsubscribe(topic_name)[source]

Unsubscribe this notification receiver from a topic.

If the topic is not currently subscribed for by this receiver, SubscriptionNotFound is raised.

Parameters:

topic_name (string) – Name of the HMC notification topic. Must not be None.

Raises:
  • SubscriptionNotFound – Topic is not currently subscribed for.

  • NotificationSubscriptionError – STOMP unsubscription failed.

is_subscribed(topic_name)[source]

Return whether this notification receiver is currently subscribed for a topic.

Parameters:

topic_name (string) – Name of the HMC notification topic. Must not be None.

get_subscription(topic_name)[source]

Return the subscription ID for a topic this notification receiver is subscribed for.

If the topic is not currently subscribed for by this receiver, SubscriptionNotFound is raised.

Parameters:

topic_name (string) – Name of the HMC notification topic. Must not be None.

notifications()[source]

Generator method that yields all HMC notifications (= JMS messages) received by this notification receiver.

The method connects to the HMC if needed, so after raising NotificationConnectionError or stomp.exception.StompException, it can simply be called again to reconnect and resume waiting for notifications.

This method returns only when the receiver is closed (using close()) by some other thread; any errors do not cause the method to return but always cause an exception to be raised.

For an example how to use this method, see Notifications or the example scripts.

Yields:

A tuple (headers, message) representing one HMC notification, with:

  • headers (dict): The notification header fields.

    Some important header fields (dict items) are:

    • ‘notification-type’ (string): The HMC notification type (e.g. ‘os-message’, ‘job-completion’, or others).

    • ‘session-sequence-nr’ (string): The sequence number of this HMC notification within the session created by this notification receiver object. This number starts at 0 when this receiver object is created, and is incremented each time an HMC notification is published to this receiver.

    • ‘class’ (string): The class name of the HMC resource publishing the HMC notification (e.g. ‘partition’).

    • ‘object-id’ (string) or ‘element-id’ (string): The ID of the HMC resource publishing the HMC notification.

    For a complete list of notification header fields, see section “Message format” in chapter 4. “Asynchronous notification” in the HMC API book.

  • message (JSON object): Body of the HMC notification, converted into a JSON object. None for notifications that have no content in their response body.

    The properties of the JSON object vary by notification type.

    For a description of the JSON properties, see the sub-sections for each notification type within section “Notification message formats” in chapter 4. “Asynchronous notification” in the HMC API book.

Returns:

None

Raises:
  • NotificationJMSError – Received JMS error from the HMC.

  • NotificationParseError – Cannot parse JMS message body as JSON.

  • NotificationConnectionError – Issue with STOMP connection to HMC. Detecting lost connections requires that heartbeating is enabled in the stomp retry/timeout configuration.

  • NotificationSubscriptionError – STOMP subscription failed.

close()[source]

Close the receiver and cause its notifications() method to return.

This also disconnects the STOMP session from the HMC, unsubscribing for any topics.

Raises:

stomp.exception.StompException – From stomp.Connection.disconnect()

class zhmcclient.StompRetryTimeoutConfig(connect_timeout=None, connect_retries=None, reconnect_sleep_initial=None, reconnect_sleep_increase=None, reconnect_sleep_max=None, reconnect_sleep_jitter=None, keepalive=None, heartbeat_send_cycle=None, heartbeat_receive_cycle=None, heartbeat_receive_check=None)[source]

A configuration setting that specifies various retry and timeout related parameters for STOMP connections to the HMC for receiving notifictions.

For all parameters, None means that this object does not specify a value for the parameter, and that a default value will be used (see Constants).

All parameters are available as instance attributes.

Parameters:
  • connect_timeout (number) – STOMP connect timeout in seconds. This timeout applies to making a connection at the socket level. The special value 0 means that no timeout is set.

  • connect_retries (integer) – Number of retries (after the initial attempt) for STOMP connection-related issues. These retries are performed for failed DNS lookups, failed socket connections, and socket connection timeouts. The special value -1 means that there are infinite retries.

  • reconnect_sleep_initial (number) – Initial STOMP reconnect sleep delay in seconds. The reconnect sleep delay is the time to wait before reconnecting.

  • reconnect_sleep_increase (number) – Factor by which the reconnect sleep delay is increased after each connection attempt. For example, 0.5 means to wait 50% longer than before the previous attempt, 1.0 means wait twice as long, and 0.0 means keep the delay constant.

  • reconnect_sleep_max (number) – Maximum reconnect sleep delay in seconds, regardless of the reconnect_sleep_increase value.

  • reconnect_sleep_jitter (number) – Random additional time to wait before a reconnect to avoid stampeding, as a percentage of the current reconnect sleep delay. For example, a value of 0.1 means to wait an extra 0%-10% of the delay calculated using the previous three parameters.

  • keepalive (bool) – Enable keepalive at the socket level.

  • heartbeat_send_cycle (number) – Cycle time in which the client will send heartbeats to the HMC, in seconds. This time is sent to the HMC as the minimum cycle time the client can do, and the HMC returns that time as the cycle time in which it wants to receive heartbeats. The cycle time should not be less than 0.2 sec; a few seconds is a reasonable value. The special value 0 disables the sending of heartbeats to the HMC.

  • heartbeat_receive_cycle (number) – Cycle time in which the HMC will send heartbeats to the client, in seconds. This time is sent to the HMC as the cycle time in which the client wants to receive heartbeats, and the HMC uses that time to send heartbeats. The cycle time should not be less than 0.2 sec; a few seconds is a reasonable value. The special value 0 disables heartbeat sending by the HMC and checking on the client side.

  • heartbeat_receive_check (number) – Additional time for checking the heartbeats received from the HMC on the client, as a percentage of the ‘heartbeat_receive_cycle’ time. For example, a value of 0.5 means to wait an extra 50% of the ‘heartbeat_receive_cycle’ time. This value should not be less than 0.5, and a value of 1 or 2 is a reasonable value.

override_with(override_config)[source]

Return a new configuration object that represents the configuration from this configuration object acting as a default, and the specified configuration object overriding that default for any of its attributes that are not None.

Parameters:

override_config (StompRetryTimeoutConfig) – The configuration object overriding the defaults defined in this configuration object.

Returns:

A new configuration object representing this configuration object, overridden by the specified configuration object.

Return type:

StompRetryTimeoutConfig