4. Reference: General features

4.1. Session

Session class: A session to the HMC, optionally in context of an HMC user.

class zhmcclient.Session(host, userid=None, password=None, session_id=None, get_password=None, retry_timeout_config=None, port=6794, verify_cert=True)[source]

A session to the HMC, optionally in context of an HMC user.

The session supports operations that require to be authenticated, as well as operations that don’t (e.g. obtaining the API version).

The session can keep statistics about the elapsed time for issuing HTTP requests against the HMC API. Instance variable time_stats_keeper is used to enable/disable the measurements, and to print the statistics.

Creating a session object will not immediately cause a logon to be attempted; the logon is deferred until needed.

There are several alternatives for specifying the authentication related parameters:

  • userid/password only: The session is initially in a logged-off state and subsequent operations that require logon will use the specified userid and password to automatically log on. The returned session-id will be stored in this session object. Subsequent operations that require logon will use that session-id. Once the HMC expires that session-id, subsequent operations that require logon will cause a re-logon with the specified userid and password.

  • userid/password and session_id: The specified session-id will be stored in this session object, so that the session is initially in a logged-on state. Subsequent operations that require logon will use that session-id. Once the HMC expires that session-id, subsequent operations that require logon will cause a re-logon with the specified userid/password. In this case, the host parameter must specify the single HMC that has that session.

  • session_id only: The specified session-id will be stored in this session object, so that the session is initially in a logged-on state. Subsequent operations that require logon will use the stored session-id. Once the HMC expires the session-id, subsequent operations that require logon will cause an ServerAuthError to be raised (because userid/password have not been specified, so an automatic re-logon is not possible). In this case, the host parameter must specify the single HMC that has that session.

  • Neither userid/password nor session_id: Only operations that do not require logon, are possible.

Parameters:
  • host (string or iterable of string) – HMC host or list of HMC hosts to try from. For valid formats, see the host property. If session_id is specified, this must be the single HMC that has that session. Must not be None.

  • userid (string) – Userid of the HMC user to be used, or None.

  • password (string) – Password of the HMC user to be used, if userid was specified.

  • session_id (string) – Session-id to be used for this session, or None.

  • get_password (callable) –

    A password retrieval function, or None.

    If provided, this function will be called if a password is needed but not provided. This mechanism can be used for example by command line interfaces for prompting for the password.

    The password retrieval function must follow the interface defined in get_password_interface().

  • retry_timeout_config (RetryTimeoutConfig) –

    The retry/timeout configuration for this session for use by any of its HMC operations, 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 retry_timeout_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.

  • port (integer) – HMC TCP port. Defaults to DEFAULT_HMC_PORT. For details, see the port property.

  • verify_cert (bool or string) –

    Controls whether and how the client verifies the server certificate presented by the HMC during SSL/TLS handshake:

    • False: Do not verify the HMC certificate. Not verifying the HMC certificate means the zhmcclient will not detect hostname mismatches, expired certificates, revoked certificates, or otherwise invalid certificates. Since this mode makes the connection vulnerable to man-in-the-middle attacks, it is insecure and should not be used in production environments.

    • True: Verify the HMC certificate using the CA certificates from the first of these locations:

      • The file or directory in the REQUESTS_CA_BUNDLE env.var, if set

      • The file or directory in the CURL_CA_BUNDLE env.var, if set

      • The Python ‘certifi’ package (which contains the Mozilla Included CA Certificate List).

    • string: Path name of a certificate file or directory. Verify the HMC certificate using the CA certificates in that file or directory.

    For details, see the HMC certificate section.

    Added in version 0.31

Methods:

__repr__()

Return a string with the state of this session, for debug purposes.

logon([verify])

Make sure this session object is logged on to the HMC.

logoff([verify])

Make sure this session object is logged off from the HMC.

is_logon([verify])

Return a boolean indicating whether this session object is logged on to the HMC.

get(uri[, resource, logon_required, ...])

Perform the HTTP GET method against the resource identified by a URI.

post(uri[, resource, body, logon_required, ...])

Perform the HTTP POST method against the resource identified by a URI, using a provided request body.

delete(uri[, resource, logon_required, ...])

Perform the HTTP DELETE method against the resource identified by a URI.

get_notification_topics()

The 'Get Notification Topics' operation returns a structure that describes the JMS notification topics associated with this session.

auto_update_subscribed()

Return whether this session is currently subscribed for Auto-updating.

subscribe_auto_update()

Subscribe this session for Auto-updating, if not currently subscribed.

unsubscribe_auto_update()

Unsubscribe this session from Auto-updating, if currently subscribed.

Attributes:

host

HMC host or redundant HMC hosts to use.

actual_host

The HMC host that is actually used for this session, if the session is in the logged-on state.

port

HMC TCP port that is used for this session.

userid

HMC userid that is used for this session.

verify_cert

Controls whether and how the client verifies server certificate presented by the HMC during SSL/TLS handshake.

get_password

The password retrieval function, or None.

retry_timeout_config

The effective retry/timeout configuration for this session for use by any of its HMC operations, taking into account the defaults and the session-specific overrides.

base_url

Base URL of the HMC that is actually used for this session, if the session is in the logged-on state.

headers

HTTP headers that are used in requests sent for this session.

time_stats_keeper

The time statistics keeper (for a usage example, see section Time Statistics).

session_id

Session ID (= HMC session token) used for this session, if the session is in the logged-on state.

session_credential

Session credential for this session returned by the HMC, if the session is in the logged-on state.

session

requests.Session object for this session, if the session is in the logged-on state.

object_topic

Name of the notification topic the HMC will use to send object-related notification messages to this session, if the session is in the logged-on state.

job_topic

Name of the notification topic the HMC will use to send job notification messages to this session, if the session is in the logged-on state.

auto_updater

Updater for Auto-updating of resource and manager objects.

__repr__()[source]

Return a string with the state of this session, for debug purposes.

property host

HMC host or redundant HMC hosts to use. The first working HMC from this list will actually be used. The working state of the HMC is detrmined using the ‘Query API Version’ operation for which no authentication is needed.

Each host will be in one of the following 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

Type:

string or list of string

property actual_host

The HMC host that is actually used for this session, if the session is in the logged-on state. None, if the session is in the logged-off state.

The HMC host will be in one of the following 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

Type:

string or None

property port

HMC TCP port that is used for this session.

Type:

integer

property userid

HMC userid that is used for this session.

If None, only operations that do not require authentication, can be performed.

Type:

string

property verify_cert

Controls whether and how the client verifies server certificate presented by the HMC during SSL/TLS handshake.

For details, see the same-named init parameter.

Type:

bool or string

property get_password

The password retrieval function, or None.

The password retrieval function must follow the interface defined in get_password_interface().

property retry_timeout_config

The effective retry/timeout configuration for this session for use by any of its HMC operations, taking into account the defaults and the session-specific overrides.

Type:

RetryTimeoutConfig

property base_url

Base URL of the HMC that is actually used for this session, if the session is in the logged-on state. None, if the session is in the logged-off state.

Example:

https://myhmc.acme.com:6794
Type:

string or None

property headers

HTTP headers that are used in requests sent for this session.

Initially, this is the following set of headers:

Content-type: application/json
Accept: */*

When the session is logged on to the HMC, the session token is added to these headers:

X-API-Session: ...
Type:

header dict

property time_stats_keeper

The time statistics keeper (for a usage example, see section Time Statistics).

property session_id

Session ID (= HMC session token) used for this session, if the session is in the logged-on state. None, if the session is in the logged-off state.

In the logged-off state, any request that requires logon will first cause a session to be created on the HMC and will store the session ID returned by the HMC in this property.

In the logged-on state, the session ID stored in this property will be used for any requests to the HMC.

Type:

string or None

property session_credential

Session credential for this session returned by the HMC, if the session is in the logged-on state. None, if the session is in the logged-off state.

Type:

string or None

property session

requests.Session object for this session, if the session is in the logged-on state. None, if the session is in the logged-off state.

Type:

string or None

property object_topic

Name of the notification topic the HMC will use to send object-related notification messages to this session, if the session is in the logged-on state. None, if the session is in the logged-off state.

The associated topic type is “object-notification”.

Type:

string or None

property job_topic

Name of the notification topic the HMC will use to send job notification messages to this session, if the session is in the logged-on state. None, if the session is in the logged-off state.

The associated topic type is “job-notification”.

Type:

string or None

property auto_updater

Updater for Auto-updating of resource and manager objects.

Type:

AutoUpdater

logon(verify=False)[source]

Make sure this session object is logged on to the HMC.

If verify=False, this method determines the logged-on state of this session object based on whether there is a session ID set in this session object. If a session ID is set, it is assumed to be valid and no new session is created on the HMC. Otherwise, a new session will be created on the HMC.

If verify=True, this method determines the logged-on state of this session object in addition by performing a read operation on the HMC that requires to be logged on but no specific authorizations. If a session ID is set and if that operation succeeds, no new session is created on the HMC. Any failure of that read operation will be ignored. Otherwise, a new session will be created on the HMC.

When a new session has been successfully created on the HMC, the session_id attribute of this session object will be set to the session ID returned by the HMC to put it into the logged-on state.

Any exceptions raised from this method are always related to the creation of a new session on the HMC - any failures of the read operation in the verification case are always ignored.

Parameters:

verify (bool) – Verify the validity of an existing session ID.

Raises:
logoff(verify=False)[source]

Make sure this session object is logged off from the HMC.

If a session ID is set in this session object, its session will be deleted on the HMC. If that delete operation fails due to an invalid session ID, that failure will be ignored. Any other failures of that delete operation will be raised as exceptions.

When the session has been successfully deleted on the HMC, the session_id attribute of this session object will be set to None to put it into the logged-off state.

Parameters:

verify (bool) – Deprecated: This parameter will be ignored.

Raises:
is_logon(verify=False)[source]

Return a boolean indicating whether this session object is logged on to the HMC.

If verify=False, this method determines the logged-on state based on whether there is a session ID set in this object. If a session ID is set, it is assumed to be valid, and True is returned. Otherwise, False is returned. In that case, no exception is ever raised.

If verify=True, this method determines the logged-on state in addition by verifying a session ID that is set, by performing a read operation on the HMC that requires to be logged on but no specific authorizations. If a session ID is set and if that read operation succeeds, True is returned. If no session ID is set or if that read operation fails due to an invalid session ID, False is returned. Any other failures of that read operation are raised as exceptions, because that indicates that a verification with the HMC could not be performed.

Parameters:

verify (bool) – Verify the validity of an existing session ID.

Raises:
get(uri, resource=None, logon_required=True, renew_session=True)[source]

Perform the HTTP GET method against the resource identified by a URI.

A set of standard HTTP headers is automatically part of the request.

If the HMC session token is expired, this method re-logs on and retries the operation.

Parameters:
  • uri (string) – Relative URI path of the resource, e.g. “/api/session”. This URI is relative to the base URL of the session (see the base_url property). Must not be None.

  • logon_required (bool) – Boolean indicating whether the operation requires that the session is logged on to the HMC. For example, the API version retrieval operation does not require that.

  • renew_session (bool) – Boolean indicating whether the session should be renewed in case it is expired.

Returns:

json object with the operation result.

Raises:
post(uri, resource=None, body=None, logon_required=True, wait_for_completion=False, operation_timeout=None, renew_session=True)[source]

Perform the HTTP POST method against the resource identified by a URI, using a provided request body.

A set of standard HTTP headers is automatically part of the request.

HMC operations using HTTP POST are either synchronous or asynchronous. Asynchronous operations return the URI of an asynchronously executing job that can be queried for status and result.

Examples for synchronous operations:

  • With no result: “Logon”, “Update CPC Properties”

  • With a result: “Create Partition”

Examples for asynchronous operations:

  • With no result: “Start Partition”

The wait_for_completion parameter of this method can be used to deal with asynchronous HMC operations in a synchronous way.

If executing the operation reveals that the HMC session token is expired, this method re-logs on and retries the operation.

The timeout and retry

Parameters:
  • uri (string) – Relative URI path of the resource, e.g. “/api/session”. This URI is relative to the base URL of the session (see the base_url property). Must not be None.

  • body (json object or string or file-like object) – The HTTP request body (payload). If a JSON object (=dict) is provided, it will be serialized into a UTF-8 encoded binary string. If a Unicode string is provided, it will be encoded into a UTF-8 encoded binary string. If a binary string is provided, it will be used unchanged. If a file-like object is provided, it must return binary strings, i.e. the file must have been opened in binary mode. None means the same as an empty dictionary, namely that no HTTP body is included in the request.

  • logon_required (bool) – Boolean indicating whether the operation requires that the session is logged on to the HMC. For example, the “Logon” operation does not require that.

  • wait_for_completion (bool) –

    Boolean controlling whether this method should wait for completion of the requested asynchronous HMC operation.

    A value of True will cause an additional entry in the time statistics to be created that represents the entire asynchronous operation including the waiting for its completion. That time statistics entry will have a URI that is the targeted URI, appended with “+completion”.

    For synchronous HMC operations, this parameter has no effect on the operation execution or on the return value of this method, but it should still be set (or defaulted) to False in order to avoid the additional entry in the time statistics.

  • operation_timeout (number) –

    Timeout in seconds, when waiting for completion of an asynchronous operation. The special value 0 means that no timeout is set. None means that the default async operation timeout of the session is used.

    For wait_for_completion=True, a OperationTimeout is raised when the timeout expires.

    For wait_for_completion=False, this parameter has no effect.

  • renew_session (bool) – Boolean indicating whether the session should be renewed in case it is expired.

Returns:

A json object or None or a Job object, as follows:

  • For synchronous HMC operations, and for asynchronous HMC operations with wait_for_completion=True:

    If this method returns, the HMC operation has completed successfully (otherwise, an exception is raised). For asynchronous HMC operations, the associated job has been deleted.

    The return value is the result of the HMC operation as a json object, or None if the operation has no result. See the section in the HMC API book about the specific HMC operation for a description of the members of the returned JSON object.

  • For asynchronous HMC operations with wait_for_completion=False:

    If this method returns, the asynchronous execution of the HMC operation has been started successfully as a job on the HMC (if the operation could not be started, an exception is raised).

    The return value is a Job object representing the job on the HMC.

Raises:
delete(uri, resource=None, logon_required=True, renew_session=True)[source]

Perform the HTTP DELETE method against the resource identified by a URI.

A set of standard HTTP headers is automatically part of the request.

If the HMC session token is expired, this method re-logs on and retries the operation.

Parameters:
  • uri (string) – Relative URI path of the resource, e.g. “/api/session/{session-id}”. This URI is relative to the base URL of the session (see the base_url property). Must not be None.

  • logon_required (bool) – Boolean indicating whether the operation requires that the session is logged on to the HMC. For example, for the logoff operation, it does not make sense to first log on.

  • renew_session (bool) – Boolean indicating whether the session should be renewed in case it is expired. For example, for the logoff operation, it does not make sense to do that.

Raises:
get_notification_topics()[source]

The ‘Get Notification Topics’ operation returns a structure that describes the JMS notification topics associated with this session.

Returns:

A list with one item for each notification topic. Each item is a dictionary with the following keys:

  • "topic-type" (string): Topic type, e.g. “job-notification”.

  • "topic-name" (string): Topic name; can be used for subscriptions.

  • "object-uri" (string): When topic-type is “os-message-notification”, this item is the canonical URI path of the Partition for which this topic exists. This field does not exist for the other topic types.

  • "include-refresh-messages" (bool): When the topic-type is “os-message-notification”, this item indicates whether refresh operating system messages will be sent on this topic.

auto_update_subscribed()[source]

Return whether this session is currently subscribed for Auto-updating.

Returns:

Indicates whether session is subscribed.

Return type:

bool

subscribe_auto_update()[source]

Subscribe this session for Auto-updating, if not currently subscribed.

When not yet subscribed, the session is also logged on.

When subscribed, object notifications will be sent by the HMC as resource objects on the HMC change their properties or come or go. These object notifications will be received by the client and will then update the properties of any Python resource objects that are enabled for auto-updating.

This method is automatically called by enable_auto_update() and thus does not need to be called by the user.

unsubscribe_auto_update()[source]

Unsubscribe this session from Auto-updating, if currently subscribed.

When unsubscribed, object notifications are no longer sent by the HMC.

This method is automatically called by disable_auto_update() and thus does not need to be called by the user.

class zhmcclient.Job(session, uri, op_method, op_uri)[source]

A job on the HMC that performs an asynchronous HMC operation.

This class supports checking the job for completion, and waiting for job completion.

Parameters:
  • session (Session) – Session with the HMC. Must not be None.

  • uri (string) –

    Canonical URI of the job on the HMC. Must not be None.

    Example: "/api/jobs/{job-id}"

  • op_method (string) –

    Name of the HTTP method of the operation that is executing asynchronously on the HMC. Must not be None.

    Example: "POST"

  • op_uri (string) –

    Canonical URI of the operation that is executing asynchronously on the HMC. Must not be None.

    Example: "/api/partitions/{partition-id}/stop"

Attributes:

session

Session with the HMC.

uri

Canonical URI of the job on the HMC.

op_method

Name of the HTTP method of the operation that is executing asynchronously on the HMC.

op_uri

Canonical URI of the operation that is executing asynchronously on the HMC.

Methods:

query_status()

Get the current status of this job, and if completed also the operation results.

delete()

Delete this ended job on the HMC.

check_for_completion()

Check once for completion of the job and return completion status and result if it has completed.

wait_for_completion([operation_timeout])

Wait for completion of the job, then delete the job on the HMC and return the result of the original asynchronous HMC operation, if it completed successfully.

cancel()

Attempt to cancel this job.

property session

Session with the HMC.

Type:

Session

property uri

Canonical URI of the job on the HMC.

Example: "/api/jobs/{job-id}"

Type:

string

property op_method

Name of the HTTP method of the operation that is executing asynchronously on the HMC.

Example: "POST"

Type:

string

property op_uri

Canonical URI of the operation that is executing asynchronously on the HMC.

Example: "/api/partitions/{partition-id}/stop"

Type:

string

query_status()[source]

Get the current status of this job, and if completed also the operation results.

This method performs the “Query Job Status” operation on the job.

This is a low level operation, consider using check_for_completion() or wait_for_completion() instead.

If the job no longer exists, HTTPError is raised with status code 404 and reason code 1.

Returns:

With the following items:

  • job_status(string): Job status, one of:

    • ”running” - indicates that the job was found and it has not ended at the time of the query.

    • ”cancel-pending” - indicates that the job was found and it has not ended but cancellation has been requested.

    • ”canceled” - indicates that the job’s normal course of execution was interrupted by a cancel request, and the job has now ended.

    • ”complete” - indicates that the job was found and has completed the operation, and the job has now ended.

  • op_status(int): HTTP status code of the operation performed by the job. Will be None if the job has not ended.

  • op_reason(int): HTTP reason code of the operation performed by the job. Will be None if the job has not ended.

  • op_result(dict): Result of the operation performed by the job, as described in the zhmcclient method that performed the operation. Will be None if the job has not ended.

Return type:

tuple(job_status, op_status, op_reason, op_result)

Raises:
delete()[source]

Delete this ended job on the HMC.

This method performs the “Delete Completed Job Status” operation on the job.

This is a low level operation, consider using check_for_completion() or wait_for_completion() instead, which delete the ended job.

If the job has not ended (i.e. its status property is not “canceled” or”complete”), HTTPError is raised with status code 409 and reason code 40.

If the job no longer exists, HTTPError is raised with status code 404 and reason code 1.

Raises:
check_for_completion()[source]

Check once for completion of the job and return completion status and result if it has completed.

If the job completed in error, an HTTPError exception is raised.

Returns:

A tuple (status, result) with:

  • status (string): Completion status of the job, as returned in the status field of the response body of the “Query Job Status” HMC operation, as follows:

    • "complete": Job completed (successfully).

    • any other value: Job is not yet complete.

  • result (json object or None): None for incomplete jobs. For completed jobs, the result of the original asynchronous operation that was performed by the job, from the job-results field of the response body of the “Query Job Status” HMC operation. That result is a json object as described for the asynchronous operation, or None if the operation has no result.

Raises:
wait_for_completion(operation_timeout=None)[source]

Wait for completion of the job, then delete the job on the HMC and return the result of the original asynchronous HMC operation, if it completed successfully.

If the job completed in error, an HTTPError exception is raised.

Parameters:

operation_timeout (number) –

Timeout in seconds, when waiting for completion of the job. The special value 0 means that no timeout is set. None means that the default async operation timeout of the session is used.

If the timeout expires, a OperationTimeout is raised.

This method gives completion of the job priority over strictly achieving the timeout. This may cause a slightly longer duration of the method than prescribed by the timeout.

Returns:

The result of the original asynchronous operation that was performed by the job, from the job-results field of the response body of the “Query Job Status” HMC operation. That result is a json object as described for the asynchronous operation, or None if the operation has no result.

Return type:

json object or None

Raises:
cancel()[source]

Attempt to cancel this job.

This method performs the “Cancel Job” operation on the job.

The specific nature of the job and its current state of execution can affect the success of the cancellation.

Not all jobs support cancellation; this is described in each zhmcclient method that can return a job.

If the job exists, supports cancellation and has not yet completed (i.e. its status property is “running”), the cancellation is made pending for the job and its status property is changed to “cancel-pending”.

If the operation performed by the job does not support cancellation, HTTPError is raised with status code 404 and reason code 4.

If the job supports cancellation and exists, but already has a cancellation request pending (i.e. its status property is “cancel-pending”), HTTPError is raised with status 409 and reason code 42.

If the job supports cancellation and exists, but already has ended (i.e. its status property is “complete” or “canceled”), HTTPError is raised with status code 409 and reason code 41.

If the job supports cancellation but no longer exists, HTTPError is raised with status code 404 and reason code 1.

Raises:
zhmcclient.get_password_interface(host, userid)[source]

Interface to the password retrieval function that is invoked by Session if no password is provided.

Parameters:
  • host (string) – Hostname or IP address of the HMC

  • userid (string) – Userid on the HMC

Returns:

Password of the userid on the HMC

Return type:

string

4.2. Retry / timeout configuration

class zhmcclient.RetryTimeoutConfig(connect_timeout=None, connect_retries=None, read_timeout=None, read_retries=None, max_redirects=None, operation_timeout=None, status_timeout=None, name_uri_cache_timetolive=None)[source]

A configuration setting that specifies verious retry counts and timeout durations.

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

All parameters are available as instance attributes.

Parameters:
  • connect_timeout (number) – Connect timeout in seconds. This timeout applies to making a connection at the socket level. The same socket connection is used for sending an HTTP request to the HMC and for receiving its HTTP response. The special value 0 means that no timeout is set.

  • connect_retries (integer) – Number of retries (after the initial attempt) for connection-related issues. These retries are performed for failed DNS lookups, failed socket connections, and socket connection timeouts.

  • read_timeout (number) – Read timeout in seconds. This timeout applies to reading at the socket level, when receiving an HTTP response. The special value 0 means that no timeout is set.

  • read_retries (integer) – Number of retries (after the initial attempt) for read-related issues. These retries are performed for failed socket reads and socket read timeouts. A retry consists of resending the original HTTP request. The zhmcclient restricts these retries to just the HTTP GET method. For other HTTP methods, no retry will be performed.

  • max_redirects (integer) – Maximum number of HTTP redirects.

  • operation_timeout (number) – Asynchronous operation timeout in seconds. This timeout applies when waiting for the completion of asynchronous HMC operations. The special value 0 means that no timeout is set.

  • status_timeout (number) – Resource status timeout in seconds. This timeout applies when waiting for the transition of the status of a resource to a desired status. The special value 0 means that no timeout is set.

  • name_uri_cache_timetolive (number) – Time to the next automatic invalidation of the Name-URI cache of manager objects, in seconds since the last invalidation. The special value 0 means that no Name-URI cache is maintained (i.e. the caching is disabled).

Methods:

override_with(override_config)

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.

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.

Parameters:

override_config (RetryTimeoutConfig) – 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:

RetryTimeoutConfig

4.3. AutoUpdater

Support for the Auto-updating of Python zhmcclient resource and manager objects based on HMC notifications.

class zhmcclient.AutoUpdater(session)[source]

A class that automatically updates

  • the properties of zhmcclient resource objects that are enabled for auto-updating

  • the list of zhmcclient resource objects in manager objects that are enabled for auto-updating

based on respective notifications from the HMC.

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

Note: The user should not create any objects of this class nor invoke any methods of this class, because the objects are created automatically when a Session object is subscribed for auto-updating via its subscribe_auto_update() method.

Creating an object of this class performs a logon to the HMC to retrieve the notification topics, and then establishes a JMS session with the HMC and subscribes for the object notification topic of the session. This causes the HMC to emit status notifications, property notifications, and inventory notifications, which are processed by this class and cause the updates to happen.

Resource objects can be enabled for auto-updating via their enable_auto_update() method.

Manager objects can be enabled for auto-updating via their enable_auto_update() method.

Zhmcclient resource objects or manager objects that are not enabled for auto-updating remain unchanged.

Parameters:

session (Session) – Session for which the auto updater should do its work. This defines the HMC host and credentials that are used to establish the JMS session with the HMC. The session may or may not be logged on.

Methods:

open()

Open the JMS session with the HMC.

close()

Close the JMS session with the HMC.

is_open()

Return whether the JMS session with the HMC is open.

register_object(obj)

Register a resource or manager object to this auto updater.

unregister_object(obj)

Unregister a resource or manager object from this auto updater.

registered_objects(uri)

Generator that yields the resource or manager objects for the specified URI.

has_objects()

Return boolean indicating whether there are any resource objects registered.

open()[source]

Open the JMS session with the HMC.

This creates a STOMP connection with the actual HMC of the session and subscribes to the object notification topic.

If the session does not yet have an object notification topic set, the session is logged on.

close()[source]

Close the JMS session with the HMC.

This implicitly unsubscribes from the object notification topic this auto updater was created for.

is_open()[source]

Return whether the JMS session with the HMC is open.

register_object(obj)[source]

Register a resource or manager object to this auto updater.

If this object (identified by its Python id) is already registered, nothing is done.

unregister_object(obj)[source]

Unregister a resource or manager object from this auto updater.

If this object (identified by its Python id) is already unregistered, nothing is done.

registered_objects(uri)[source]

Generator that yields the resource or manager objects for the specified URI.

has_objects()[source]

Return boolean indicating whether there are any resource objects registered.

4.4. Client

Client class: A client to an HMC.

class zhmcclient.Client(session)[source]

A client to an HMC.

This is the main class for users of this package.

Parameters:

session (Session) – Session with the HMC.

Attributes:

session

Session: Session with the HMC.

cpcs

CpcManager: Manager object for the CPCs in scope of this client.

consoles

ConsoleManager: Manager object for the (one) Console representing the HMC this client is connected to.

metrics_contexts

MetricsContextManager: Manager object for the Metrics Contexts in scope of this client (i.e. in scope of its HMC).

Methods:

version_info()

Returns API version information for the HMC.

query_api_version()

The Query API Version operation returns information about the level of Web Services API supported by the HMC.

get_inventory(resources)

Returns a JSON object with the requested resources and their properties, that are managed by the HMC.

wait_for_available([operation_timeout])

Wait for the Console (HMC) this client is connected to, to become available.

to_hmc_yaml()

Inspect the HMC of this client and return the HMC and its resources as an HMC definition YAML string.

to_hmc_dict()

Inspect the HMC of this client and return the HMC and its resources as an HMC definition dictionary.

dump()

Dump this Client with its properties and child resources (recursively) as a resource definition.

property session

Session: Session with the HMC.

property cpcs

CpcManager: Manager object for the CPCs in scope of this client. This includes managed and unmanaged CPCs.

property consoles

ConsoleManager: Manager object for the (one) Console representing the HMC this client is connected to.

property metrics_contexts

MetricsContextManager: Manager object for the Metrics Contexts in scope of this client (i.e. in scope of its HMC).

version_info()[source]

Returns API version information for the HMC.

This operation does not require authentication.

Returns:

The HMC API version supported by the HMC.

Return type:

HMC API version

Raises:
query_api_version()[source]

The Query API Version operation returns information about the level of Web Services API supported by the HMC.

This operation does not require authentication.

Returns:

A JSON object with members api-major-version, api-minor-version, hmc-version and hmc-name. For details about these properties, see section ‘Response body contents’ in section ‘Query API Version’ in the HMC API book.

Return type:

json object

Raises:
get_inventory(resources)[source]

Returns a JSON object with the requested resources and their properties, that are managed by the HMC.

This method performs the ‘Get Inventory’ HMC operation.

If resources cannot be fully inventoried, the returned list contains items describing the errors. They can be identified by their ‘class’ property having a value of ‘inventory-error’. Note that the presence of such error items does not cause any exceptions to be raised.

Parameters:

resources (iterable of string) –

Resource classes and/or resource classifiers specifying the types of resources that should be included in the result. For valid values, see the ‘Get Inventory’ operation in the HMC API book.

Element resources of the specified resource types are automatically included as children (for example, requesting ‘partition’ includes all of its ‘hba’, ‘nic’ and ‘virtual-function’ element resources).

Must not be None.

Returns:

The list of resources for the requested resource

classes and resource classifiers. Each list item is a dictionary with the resource properties using the HMC property names.

Return type:

list of dict

Example

resource_classes = [‘partition’, ‘adapter’] resource_list = client.get_inventory(resource_classes)

Raises:
wait_for_available(operation_timeout=None)[source]

Wait for the Console (HMC) this client is connected to, to become available. The Console is considered available if the query_api_version() method succeeds.

If the Console does not become available within the operation timeout, an OperationTimeout exception is raised.

Parameters:

operation_timeout (number) –

Timeout in seconds, when waiting for the Console to become available. The special value 0 means that no timeout is set. None means that the default async operation timeout of the session is used.

If the timeout expires, a OperationTimeout is raised.

Raises:

OperationTimeout – The timeout expired while waiting for the Console to become available.

to_hmc_yaml()[source]

Inspect the HMC of this client and return the HMC and its resources as an HMC definition YAML string.

This method can be used on clients for sessions to real HMCs and faked sessions.

The returned YAML string can be used to instantiate a faked session using zhmcclient_mock.FakedSession.from_hmc_yaml().

The returned HMC definition YAML string has the following format:

hmc_definition:

  # Internal state:
  host: hmc1
  api_version: '2.20'
  metric_group_definitions: [...]
  metric_values: [...]

  # Child resources:
  metrics_contexts:
  - properties: {...}
  consoles:
  - properties: {...}
    storage_groups:
    - properties: {...}
    ...
  cpcs:
  - properties: {...}
    partitions:
    - properties: {...}
    ...
Returns:

HMC definition YAML string.

Return type:

string

to_hmc_dict()[source]

Inspect the HMC of this client and return the HMC and its resources as an HMC definition dictionary.

This method can be used on clients for sessions to real HMCs and faked sessions.

The returned dictionary has only items of type dict, list, string, int, float, bool or None. That makes it convertible to simple formats such as JSON or YAML, so it can be externalized (e.g. persisted).

The returned dictionary can be used to instantiate a faked session using zhmcclient_mock.FakedSession.from_hmc_dict().

The returned HMC definition dictionary has the following format:

{
    "hmc_definition": {

        # Internal state:
        "host": "hmc1",
        "api_version": "2.20",
        "metric_group_definitions": [...],
        "metric_values": [...],

        # Child resources:
        "metrics_contexts": [...],
        "consoles": [...],
        "cpcs": [...],
    }
}
Returns:

HMC definition dictionary.

Return type:

dict

dump()[source]

Dump this Client with its properties and child resources (recursively) as a resource definition.

The returned resource definition has the following format:

{
    # Internal state:
    "host": "hmc1",
    "api_version": "2.20",
    "metric_values": [...],

    # Child resources:
    "metrics_contexts": [...],
    "consoles": [...],
    "cpcs": [...],
}
Returns:

Resource definition of this Client.

Return type:

dict

4.5. Time Statistics

The TimeStatsKeeper class allows measuring the elapsed time of accordingly instrumented code and keeps a statistics of these times.

The Session class uses this class for keeping statistics about the time to issue HTTP requests against the HMC API (see its time_stats_keeper property).

The TimeStats class is a helper class that contains the actual measurement data for all invocations of a particular HTTP request. Its objects are under control of the TimeStatsKeeper class.

Example:

import zhmcclient

session = zhmcclient.Session(hmc, userid, password)
session.time_stats_keeper.enable()

# Some operations that are being measured
client = zhmcclient.Client(session)
cpcs = client.cpcs.list()

print(session.time_stats_keeper)
class zhmcclient.TimeStatsKeeper[source]

Statistics keeper for elapsed times.

The statistics keeper can hold multiple time statistics (see TimeStats), that are identified by a name.

The statistics keeper can be in a state of enabled or disabled. If enabled, it accumulates the elapsed times between subsequent calls to the begin() and end() methods of class TimeStats. If disabled, calls to these methods do not accumulate any time.

Initially, the statistics keeper is disabled.

Attributes:

enabled

Indicates whether the statistics keeper is enabled.

Methods:

enable()

Enable the statistics keeper.

disable()

Disable the statistics keeper.

get_stats(name)

Get the time statistics for a name.

snapshot()

Return a snapshot of the time statistics of this keeper.

__str__()

Return a human readable string with the time statistics for this keeper.

property enabled

Indicates whether the statistics keeper is enabled.

enable()[source]

Enable the statistics keeper.

disable()[source]

Disable the statistics keeper.

get_stats(name)[source]

Get the time statistics for a name. If a time statistics for that name does not exist yet, create one.

Parameters:

name (string) – Name of the time statistics.

Returns:

The time statistics for the specified name. If the statistics keeper is disabled, a dummy time statistics object is returned, in order to save resources.

Return type:

TimeStats

snapshot()[source]

Return a snapshot of the time statistics of this keeper.

The snapshot represents the statistics data at the time this method is called, and remains unchanged even if the statistics of this keeper continues to be updated.

Returns:

A dictionary of the time statistics by operation, where:

  • key (string): Name of the operation

  • value (TimeStats): Time statistics for the operation

Return type:

dict

__str__()[source]

Return a human readable string with the time statistics for this keeper. The operations are sorted by decreasing average time.

Example result, if keeper is enabled:

Time statistics (times in seconds):
Count  Average  Minimum  Maximum  Operation name
    1  0.024    0.024    0.024    get /api/cpcs
    1  0.009    0.009    0.009    get /api/version
class zhmcclient.TimeStats(keeper, name)[source]

Elapsed time statistics for all invocations of a particular named operation.

All invocations of the operation will be accumulated into the statistics data kept by an object of this class.

Objects of this class don’t need to (and in fact, are not supposed to) be created by the user. Instead, the zhmcclient.TimeStatsKeeper.get_stats() method should be used to create objects of this class.

Parameters:
  • keeper (TimeStatsKeeper) – The statistics keeper that holds this time statistics.

  • name (string) – Name of the operation.

Attributes:

name

Name of the operation this time statistics has data for.

keeper

The time statistics keeper holding this time statistics.

count

The number of invocations of the operation.

avg_time

The average elapsed time for invoking the operation, in seconds.

min_time

The minimum elapsed time for invoking the operation, in seconds.

max_time

The maximum elapsed time for invoking the operation, in seconds.

Methods:

reset()

Reset the time statistics data for the operation.

begin()

This method must be called before invoking the operation.

end()

This method must be called after the operation returns.

__str__()

Return a human readable string with the time statistics for this operation.

property name

Name of the operation this time statistics has data for.

This name is used by the TimeStatsKeeper object holding this time statistics as a key.

Type:

string

property keeper

The time statistics keeper holding this time statistics.

Type:

TimeStatsKeeper

property count

The number of invocations of the operation.

Type:

integer

property avg_time

The average elapsed time for invoking the operation, in seconds.

Type:

float

property min_time

The minimum elapsed time for invoking the operation, in seconds.

Type:

float

property max_time

The maximum elapsed time for invoking the operation, in seconds.

Type:

float

reset()[source]

Reset the time statistics data for the operation.

begin()[source]

This method must be called before invoking the operation. Note that this method is not to be invoked by the user; it is invoked by the implementation of the Session class.

If the statistics keeper holding this time statistics is enabled, this method takes the current time, so that end() can calculate the elapsed time between the two method calls.

If the statistics keeper holding this time statistics is disabled, this method does nothing, in order to save resources.

end()[source]

This method must be called after the operation returns. Note that this method is not to be invoked by the user; it is invoked by the implementation of the Session class.

If the statistics keeper holding this time statistics is enabled, this method takes the current time, calculates the duration of the operation since the last call to begin(), and updates the time statistics to reflect the new operation.

If the statistics keeper holding this time statistics is disabled, this method does nothing, in order to save resources.

If this method is called without a preceding call to begin(), a RuntimeError is raised.

Raises:

RuntimeError

__str__()[source]

Return a human readable string with the time statistics for this operation.

Example result:

TimeStats: count=1 avg=1.000s min=1.000s max=1.000s get /api/cpcs

4.6. Metrics

The HMC supports the retrieval of metrics values for resources of a IBM Z or LinuxONE computer. This section describes the zhmcclient API for retrieving such metrics from the HMC.

A resource termed Metrics Context is associated with any metrics retrieval. These resources are user-created definitions of the kinds of metrics that are intended to be retrieved. A metrics context mostly defines the names of the metric groups to be retrieved. The available metric groups are described in section ‘Metric Groups’ in the HMC API book.

The zhmcclient API for metrics provides access to the metric values and to their definitions, so that clients using the metric values do not need to have intimate knowledge about the specific metric values when just displaying them.

The basic usage of the metrics API is shown in this example:

# Create a Metrics Context for the desired metric groups:
metric_groups = ['dpm-system-usage-overview', 'partition-usage']
mc = client.metrics_contexts.create(
    {'anticipated-frequency-seconds': 15,
     'metric-groups': metric_groups})

# Retrieve the current metric values:
mr_str = mc.get_metrics()

# Display the metric values:
print("Current metric values:")
mr = zhmcclient.MetricsResponse(mc, mr_str)
for mg in mr.metric_group_values:
    mg_name = mg.name
    mg_def = mc.metric_group_definitions[mg_name]
    print("  Metric group: {}".format(mg_name))
    for ov in mg.object_values:
        print("    Resource: {}".format(ov.resource_uri))
        print("    Timestamp: {}".format(ov.timestamp))
        print("    Metric values:")
        for m_name in ov.metrics:
            m_value = ov.metrics[m_name]
            m_def = mg_def.metric_definitions[m_name]
            m_unit = m_def.unit or ''
            print("      {:30}  {} {}".format(m_name, m_value, m_unit))
    if not mg.object_values:
        print("    No resources")

# Delete the Metrics Context:
mc.delete()
class zhmcclient.MetricsContextManager(client)[source]

Manager providing access to the Metrics Context resources that were created through this manager object.

Derived from BaseManager; see there for common methods and attributes.

Objects of this class are not directly created by the user; they are accessible via the metrics_contexts attribute of the Client object connected to the HMC.

Methods:

__repr__()

Return a string with the state of this manager object, for debug purposes.

list([full_properties])

List the Metrics Context resources that were created through this manager object.

create(properties)

Create a Metrics Context resource in the HMC this client is connected to.

add_resources_local(resource_obj_list)

Add a resource object to the local auto-updated list of resources.

auto_update_enabled()

Return whether Auto-updating is currently enabled for the manager object.

auto_update_needs_pull()

Return whether there is a need to pull the resources from the HMC, in the list() method.

auto_update_trigger_pull()

Trigger the need to pull the resources from the HMC, in the list() method.

disable_auto_update()

Disable Auto-updating for this manager object, if currently enabled.

dump()

Dump the resources of this resource manager as a resource definition.

enable_auto_update()

Enable Auto-updating for this manager object, if currently disabled.

find(**filter_args)

Find exactly one resource in scope of this manager, by matching resource properties against the specified filter arguments, and return its Python resource object (e.g. for a CPC, a Cpc object is returned).

find_by_name(name)

Find a resource by name and return its Python resource object (e.g. for a CPC, a Cpc object is returned).

find_local(name, uri[, properties])

Return a local resource object without fetching it from the HMC.

findall(**filter_args)

Find zero or more resources in scope of this manager, by matching resource properties against the specified filter arguments, and return a list of their Python resource objects (e.g. for CPCs, a list of Cpc objects is returned).

flush()

Invalidate the Name-URI cache of this manager.

invalidate_cache()

Invalidate the Name-URI cache of this manager.

list_resources_local()

List the resource objects from the local auto-updated list of resources.

remove_resource_local(resource_uri)

Remove the resource object for a resource URI from the local auto-updated list of resources.

resource_object(uri_or_oid[, props])

Return a minimalistic Python resource object for this resource class, that is scoped to this manager.

Attributes:

client

Client: The client defining the scope for this manager.

case_insensitive_names

bool: Indicates whether the names of the resources are treated case insensitively.

class_name

The resource class name

name_prop

The name of the resource property indicating the resource name

parent

Subclass of BaseResource: Parent resource defining the scope for this manager.

resource_class

The Python class of the parent resource of this manager.

session

Session: Session with the HMC.

supports_properties

bool: Indicates whether the "Get Properties" operation for this type of resource supports the 'properties' query parameter in the latest released version of the HMC.

uri

The canonical URI path of the manager.

__repr__()[source]

Return a string with the state of this manager object, for debug purposes.

property client

Client: The client defining the scope for this manager.

list(full_properties=False)[source]

List the Metrics Context resources that were created through this manager object.

Note that the HMC does not provide a way to enumerate the existing Metrics Context resources. Therefore, this method will only list the Metrics Context resources that were created through this manager object. For example, Metrics Context resources created through a second Client object will not be listed.

Parameters:

full_properties (bool) – This parameter exists for compatibility with other resource classes, but for this class, it has no effect on the result.

Returns:

A list of MetricsContext objects.

Raises:
create(properties)[source]

Create a Metrics Context resource in the HMC this client is connected to.

Parameters:

properties (dict) – Initial property values. Allowable properties are defined in section ‘Request body contents’ in section ‘Create Metrics Context’ in the HMC API book.

Returns:

The resource object for the new Metrics Context resource.

Return type:

MetricsContext

Raises:
class zhmcclient.MetricsContext(manager, uri, name=None, properties=None)[source]

Representation of a Metrics Context resource.

A Metrics Context resource specifies a list of metrics groups for which the current metric values can be retrieved using the get_metrics() method.

The properties of this resource are the response fields described for the ‘Create Metrics Context’ operation in the HMC API book.

This class is derived from BaseResource; see there for common methods and attributes.

Objects of this class can be created by the user with the zhmcclient.MetricsContextManager.create() method.

Attributes:

metric_group_definitions

The metric definitions for the metric groups of this Metrics Context resource, as a dictionary of MetricGroupDefinition objects, by metric group name.

ceased_existence

Indicates that the corresponding object on the HMC no longer exists, if auto-update is enabled for the resource.

full_properties

A boolean indicating whether or not the resource properties in this object are the full set of resource properties.

manager

Subclass of BaseManager: Manager object for this resource (and for all resources of the same type in the scope of that manager).

name

The name of the resource.

properties

The properties of this resource that are currently present in this Python object, as a dictionary.

properties_timestamp

The point in time of the last update of the resource properties cached in this object, as Unix time (an integer that is the number of seconds since the Unix epoch).

uri

The canonical URI path of the resource.

Methods:

get_metrics()

Retrieve the current metric values for this Metrics Context resource from the HMC.

delete()

Delete this Metrics Context resource.

__repr__()

Return a string with the state of this resource, for debug purposes.

__str__()

Return a human readable string representation of this resource.

auto_update_enabled()

Return whether Auto-updating is currently enabled for the resource object.

cease_existence_local()

Update this Python object to indicate that the corresponding HMC object no longer exists.

disable_auto_update()

Disable Auto-updating for this resource object, if currently enabled.

dump()

Dump this resource with its properties and child resources (recursively) as a resource definition.

enable_auto_update()

Enable Auto-updating for this resource object, if currently disabled.

get_properties_local(names[, defaults])

Return the values of a set of resource properties, using default values for those that are not cached in this Python object, without retrieving them from the HMC.

get_properties_pulled(names)

Return a set of resource properties with the values they currently have on the HMC.

get_property(name)

Return the value of a resource property.

prop(name[, default])

Return the value of a resource property, applying a default if the resource does not have a property with that name.

pull_full_properties()

Retrieve the full set of resource properties from the HMC and cache them in this Python object.

pull_properties(properties)

Retrieve the specified set of resource properties from the HMC and cache them in this Python object.

update_properties_local(properties)

Update the values of a set of resource properties on this Python object without propagating the updates to the HMC.

property metric_group_definitions

The metric definitions for the metric groups of this Metrics Context resource, as a dictionary of MetricGroupDefinition objects, by metric group name.

Type:

dict

get_metrics()[source]

Retrieve the current metric values for this Metrics Context resource from the HMC.

The metric values are returned by this method as a string in the MetricsResponse format described with the ‘Get Metrics’ operation in the HMC API book.

The MetricsResponse class can be used to process the MetricsResponse string returned by this method, and provides structured access to the metrics values.

Returns:

The current metric values, in the MetricsResponse string format.

Return type:

string

Raises:
delete()[source]

Delete this Metrics Context resource.

Raises:
class zhmcclient.MetricGroupDefinition(name, resource_class, metric_definitions)[source]

A namedtuple representing definitional information for a metric group.

Parameters:
  • name (string) – Metric group name, as defined in section ‘Metric groups’ in the HMC API book.

  • resource_class (string) – A string identifying the resource class to which this metric group belongs, using the values from the ‘class’ property of resource objects.

  • metric_definitions (dict) – Metric definitions for the metrics in this metric group, as a dictionary where the key is the metric name and the value is the MetricDefinition object for the metric.

All these parameters are also available as same-named attributes.

Methods:

__new__(cls, name, resource_class, ...)

param name:

Metric group name, as defined in section 'Metric groups' in the

count(value, /)

Return number of occurrences of value.

index(value[, start, stop])

Return first index of value.

Attributes:

metric_definitions

Alias for field number 2

name

Alias for field number 0

resource_class

Alias for field number 1

static __new__(cls, name, resource_class, metric_definitions)[source]
Parameters:
  • name (string) – Metric group name, as defined in section ‘Metric groups’ in the HMC API book.

  • resource_class (string) – A string identifying the resource class to which this metric group belongs, using the values from the ‘class’ property of resource objects.

  • metric_definitions (dict) – Metric definitions for the metrics in this metric group, as a dictionary where the key is the metric name and the value is the MetricDefinition object for the metric.

All these parameters are also available as same-named attributes.

class zhmcclient.MetricDefinition(index, name, type, unit)[source]

A namedtuple representing definitional information for a single metric.

Parameters:
  • index (integer) – 0-based index (=position) of the metric in a MetricsResponse value row.

  • name (string) – Metric field name, as shown in the tables defining the metric groups in section ‘Metric groups’ in the HMC API book.

  • type (callable) –

    Python type for the metric value. The type must be a constructor (callable) that takes the metrics value from the MetricsResponse string as its only argument, using the following Python types for the metric group description types shown in the HMC API book:

    Description type

    Python type

    Boolean

    bool

    Byte

    integer

    Short

    integer

    Integer

    integer

    Long

    integer

    Double

    float

    String, String Enum

    unicode string

  • unit (string) – Unit of the metric value.

All these parameters are also available as same-named attributes.

Methods:

__new__(cls, index, name, type, unit)

param index:

0-based index (=position) of the metric in a MetricsResponse value

count(value, /)

Return number of occurrences of value.

Attributes:

index

Alias for field number 0

name

Alias for field number 1

type

Alias for field number 2

unit

Alias for field number 3

static __new__(cls, index, name, type, unit)[source]
Parameters:
  • index (integer) – 0-based index (=position) of the metric in a MetricsResponse value row.

  • name (string) – Metric field name, as shown in the tables defining the metric groups in section ‘Metric groups’ in the HMC API book.

  • type (callable) –

    Python type for the metric value. The type must be a constructor (callable) that takes the metrics value from the MetricsResponse string as its only argument, using the following Python types for the metric group description types shown in the HMC API book:

    Description type

    Python type

    Boolean

    bool

    Byte

    integer

    Short

    integer

    Integer

    integer

    Long

    integer

    Double

    float

    String, String Enum

    unicode string

  • unit (string) – Unit of the metric value.

All these parameters are also available as same-named attributes.

class zhmcclient.MetricsResponse(metrics_context, metrics_response_str)[source]

Represents the metric values returned by one call to the get_metrics() method, and provides structured access to the data.

Parameters:
  • metrics_context (MetricsContext) – The MetricsContext object that was used to retrieve the metrics response string. It defines the structure of the metric values in the metrics response string.

  • metrics_response_str (string) – The metrics response string, as returned by the get_metrics() method.

Attributes:

metrics_context

MetricsContext object for this metric response.

metric_group_values

The list of MetricGroupValues objects representing the metric groups in this metric response.

property metrics_context

MetricsContext object for this metric response. This can be used to access the metric definitions for this response.

property metric_group_values

The list of MetricGroupValues objects representing the metric groups in this metric response.

Each MetricGroupValues object contains a list of MetricObjectValues objects representing the metric values in this group (each for a single resource and point in time).

Type:

list

class zhmcclient.MetricGroupValues(name, object_values)[source]

Represents the metric values for a metric group in a MetricsResponse string.

Parameters:
  • name (string) – Metric group name.

  • object_values (list) – The MetricObjectValues objects in this metric group. Each of them represents the metric values for a single resource at a single point in time.

Attributes:

name

The metric group name.

object_values

The MetricObjectValues objects in this metric group.

property name

The metric group name.

Type:

string

property object_values

The MetricObjectValues objects in this metric group. Each of them represents the metric values for a single resource at a single point in time.

Type:

list

class zhmcclient.MetricObjectValues(client, metric_group_definition, resource_uri, timestamp, metrics)[source]

Represents the metric values for a single resource at a single point in time.

Parameters:
  • client (Client) – Client object, for retrieving the actual resource.

  • metric_group_definition (MetricGroupDefinition) – Metric group definition for this set of metric values.

  • resource_uri (string) – Resource URI of the resource these metric values apply to.

  • timestamp (datetime.datetime) – Point in time when the HMC captured these metric values (as a timezone-aware datetime object).

  • metrics (dict) – The metric values, as a dictionary of the (Python typed) metric values, by metric name.

Attributes:

client

Client object, for retrieving the actual resource.

metric_group_definition

Metric group definition for this set of metric values.

resource_uri

The canonical URI path of the resource these metric values apply to.

timestamp

Point in time when the HMC captured these metric values (as a timezone-aware datetime object).

metrics

The metric values, as a dictionary of the (Python typed) metric values, by metric name.

resource

The Python resource object of the

Methods:

dump()

Dump these metric values as a resource definition.

property client

Client object, for retrieving the actual resource.

Type:

Client

property metric_group_definition

Metric group definition for this set of metric values.

Type:

MetricGroupDefinition

property resource_uri

The canonical URI path of the resource these metric values apply to.

Example: /api/cpcs/12345

Type:

string

property timestamp

Point in time when the HMC captured these metric values (as a timezone-aware datetime object).

Type:

datetime.datetime

property metrics

The metric values, as a dictionary of the (Python typed) metric values, by metric name.

Type:

dict

property resource
The Python resource object of the

resource these metric values apply to.

Raises:
  • MetricsResourceNotFound – The resource for the

  • resource URI of the resource these metric values apply to, was not

  • found on the HMC.

Type:

BaseResource

dump()[source]

Dump these metric values as a resource definition.

The timestamp of the object is represented as an ISO8601 string using this format:

YYYY-MM-DD HH:MM:SS[.ssssss]shh:mm

Where:

  • YYYY-MM-DD - is year, month and day.

  • HH:MM:SS - is hour in 24-hour format, minutes and seconds.

  • .ssssss - is an optional part specifying microseconds. It is not created when the timestamp microsecond value is 0.

  • shh:mm - is the timezone offset from UTC with sign, hours (hh) and minutes (mm). Since the FakedMetricObjectValues class ensures that the timestamp is always timezone-aware, this part is always created.

Returns:

Resource definition of this object.

Return type:

dict

4.7. Logging

The zhmcclient supports logging using the standard Python logging module, using standard Python Logger objects with these names:

  • ‘zhmcclient.api’ for user-issued calls to zhmcclient API functions, at the debug level. Internal calls to API functions are not logged.

  • ‘zhmcclient.hmc’ for operations from zhmcclient to the HMC, at the debug level.

  • ‘zhmcclient.jms’ for notifications from the HMC to zhmcclient, at the debug, info, warning and error level. At this point, this logger is used only for the Auto-updating support, but not for the NotificationReceiver class.

For HMC operations and API calls that contain the HMC password or HMC session tokens, the password is hidden in the log message by replacing it with a few ‘*’ characters.

All these loggers have a null-handler (see NullHandler) and have no log formatter (see Formatter).

As a result, the loggers are silent by default. If you want to turn on logging, add a log handler (see addHandler(), and logging.handlers for the handlers included with Python) and set the log level (see setLevel(), and Logging Levels for the defined levels).

If you want to change the default log message format, use setFormatter(). Its form parameter is a format string with %-style placeholders for the log record attributes (see Python section LogRecord attributes).

Examples:

  • To output the log records for all HMC operations to stdout in a particular format, do this:

    import logging
    
    handler = logging.StreamHandler()
    format_string = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
    handler.setFormatter(logging.Formatter(format_string))
    logger = logging.getLogger('zhmcclient.hmc')
    logger.addHandler(handler)
    logger.setLevel(logging.DEBUG)
    
  • This example uses the basicConfig() convenience function that sets the same format and level as in the previous example, but for the root logger. Therefore, it will output all log records, not just from this package:

    import logging
    
    format_string = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
    logging.basicConfig(format=format_string, level=logging.DEBUG)
    

4.8. Exceptions

Exceptions that can be raised by the client.

class zhmcclient.Error[source]

Abstract base class for exceptions specific to this package.

Exceptions of this class are not raised; only derived exceptions are raised.

Derived from Exception.

Methods:

str_def()

Interface definition for the corresponding method derived exception classes.

__str__()

Return str(self).

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.

str_def()[source]

Interface definition for the corresponding method derived exception classes.

string: The exception as a string in a Python definition-style format, e.g. for parsing by scripts.

For the exact format returned by derived exception classes, see the same-named methods there.

class zhmcclient.ConnectionError(msg, details)[source]

This exception indicates a problem with the connection to the HMC, below the HTTP level. HTTP errors are indicated via HTTPError.

A retry by the user code is not likely to be successful, unless connect or read retries had been disabled when creating the session (see Session).

Even though this class has exceptions derived from it, exceptions of this class may also be raised (if no other derived class matches the circumstances).

Derived from Error.

Parameters:
  • msg (string) – A human readable message describing the problem.

  • details (Exception) – The original exception describing details about the error.

args[0] will be set to the msg parameter.

Attributes:

details

The original exception caught by this package, providing more information about the problem.

Methods:

__repr__()

Return a string with the state of this exception object, for debug purposes.

str_def()

string: The exception as a string in a Python definition-style format, e.g. for parsing by scripts:.

__str__()

Return str(self).

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.

property details

The original exception caught by this package, providing more information about the problem.

This will be one of the following exceptions:

  • Any exception derived from requests.exceptions.RequestException.

__repr__()[source]

Return a string with the state of this exception object, for debug purposes.

str_def()[source]

string: The exception as a string in a Python definition-style format, e.g. for parsing by scripts:

classname={}; message={};
class zhmcclient.ConnectTimeout(msg, details, connect_timeout, connect_retries)[source]

This exception indicates that a connection to the HMC timed out after exhausting the connect retries (see zhmcclient.RetryTimeoutConfig.connect_retries).

Further retrying by the user code is not likely to be successful, unless connect retries had been disabled when creating the session (see Session).

Derived from ConnectionError.

Parameters:
  • msg (string) – A human readable message describing the problem.

  • details (Exception) – The original exception describing details about the error.

  • connect_timeout (integer) – The connect timeout in seconds.

  • connect_retries (integer) – The number of connect retries.

args[0] will be set to the msg parameter.

Attributes:

connect_timeout

The connect timeout in seconds.

connect_retries

The number of connect retries.

details

The original exception caught by this package, providing more information about the problem.

Methods:

__repr__()

Return a string with the state of this exception object, for debug purposes.

str_def()

string: The exception as a string in a Python definition-style format, e.g. for parsing by scripts:.

__str__()

Return str(self).

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.

property connect_timeout

The connect timeout in seconds.

Type:

integer

property connect_retries

The number of connect retries.

Type:

integer

__repr__()[source]

Return a string with the state of this exception object, for debug purposes.

str_def()[source]

string: The exception as a string in a Python definition-style format, e.g. for parsing by scripts:

classname={}; connect_timeout={}; connect_retries={}; message={};
class zhmcclient.ReadTimeout(msg, details, read_timeout, read_retries)[source]

This exception indicates that reading an HTTP response from the HMC timed out after exhausting the read retries (see zhmcclient.RetryTimeoutConfig.read_retries).

Further retrying by the user code is not likely to be successful, unless read retries had been disabled when creating the session (see Session).

Derived from ConnectionError.

Parameters:
  • msg (string) – A human readable message describing the problem.

  • details (Exception) – The original exception describing details about the error.

  • read_timeout (integer) – The read timeout in seconds.

  • read_retries (integer) – The number of read retries.

args[0] will be set to the msg parameter.

Attributes:

read_timeout

The read timeout in seconds.

read_retries

The number of read retries.

details

The original exception caught by this package, providing more information about the problem.

Methods:

__repr__()

Return a string with the state of this exception object, for debug purposes.

str_def()

string: The exception as a string in a Python definition-style format, e.g. for parsing by scripts:.

__str__()

Return str(self).

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.

property read_timeout

The read timeout in seconds.

Type:

integer

property read_retries

The number of read retries.

Type:

integer

__repr__()[source]

Return a string with the state of this exception object, for debug purposes.

str_def()[source]

string: The exception as a string in a Python definition-style format, e.g. for parsing by scripts:

classname={}; read_timeout={}; read_retries={}; message={};
class zhmcclient.RetriesExceeded(msg, details, connect_retries)[source]

This exception indicates that the maximum number of retries for connecting to the HMC, sending HTTP requests or reading HTTP responses was exceeded, for reasons other than connect timeouts (see ConnectTimeout) or read timeouts (see ReadTimeout).

Further retrying by the user code is not likely to be successful, unless connect or read retries had been disabled when creating the session (see Session).

Derived from ConnectionError.

Parameters:
  • msg (string) – A human readable message describing the problem.

  • details (Exception) – The original exception describing details about the error.

  • connect_retries (integer) – The number of connect retries.

args[0] will be set to the msg parameter.

Attributes:

connect_retries

The number of connect retries.

details

The original exception caught by this package, providing more information about the problem.

Methods:

__repr__()

Return a string with the state of this exception object, for debug purposes.

str_def()

string: The exception as a string in a Python definition-style format, e.g. for parsing by scripts:.

__str__()

Return str(self).

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.

property connect_retries

The number of connect retries.

Type:

integer

__repr__()[source]

Return a string with the state of this exception object, for debug purposes.

str_def()[source]

string: The exception as a string in a Python definition-style format, e.g. for parsing by scripts:

classname={}; connect_retries={}; message={};
class zhmcclient.AuthError[source]

This exception indicates erors related to authentication.

Exceptions of this class are not raised; only derived exceptions are raised.

Derived from Error.

Methods:

__str__()

Return str(self).

add_note

Exception.add_note(note) -- add a note to the exception

str_def()

Interface definition for the corresponding method derived exception classes.

with_traceback

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

class zhmcclient.ClientAuthError(msg)[source]

This exception indicates an authentication related problem detected on the client side.

Derived from AuthError.

Parameters:

msg (string) – A human readable message describing the problem.

args[0] will be set to the msg parameter.

Methods:

__repr__()

Return a string with the state of this exception object, for debug purposes.

str_def()

string: The exception as a string in a Python definition-style format, e.g. for parsing by scripts:.

__str__()

Return str(self).

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.

__repr__()[source]

Return a string with the state of this exception object, for debug purposes.

str_def()[source]

string: The exception as a string in a Python definition-style format, e.g. for parsing by scripts:

classname={}; message={};
class zhmcclient.ServerAuthError(msg, details)[source]

This exception indicates an authentication error with the HMC.

Derived from AuthError.

Parameters:
  • msg (string) – A human readable message describing the problem.

  • details (Exception) – The HTTPError exception describing the error returned by the HMC.

args[0] will be set to the msg parameter.

Attributes:

details

The original exception describing details about the error.

Methods:

__repr__()

Return a string with the state of this exception object, for debug purposes.

str_def()

string: The exception as a string in a Python definition-style format, e.g. for parsing by scripts:.

__str__()

Return str(self).

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.

property details

The original exception describing details about the error.

This may be one of the following exceptions:

__repr__()[source]

Return a string with the state of this exception object, for debug purposes.

str_def()[source]

string: The exception as a string in a Python definition-style format, e.g. for parsing by scripts:

classname={}; request_method={}; request_uri={}; http_status={}; reason={}; message={};
class zhmcclient.ParseError(msg)[source]

This exception indicates a parsing error while processing the JSON payload in a response from the HMC.

Derived from Error.

The error location within the payload is automatically determined by parsing the error message for the pattern:

: line {line} column {column}
Parameters:

msg (string) –

A human readable message describing the problem.

This should be the message of the ValueError exception raised by methods of the json.JSONDecoder class.

args[0] will be set to the msg parameter.

Attributes:

line

The 1-based line number of the error location within the JSON payload.

column

The 1-based column number of the error location within the JSON payload.

Methods:

__repr__()

Return a string with the state of this exception object, for debug purposes.

str_def()

string: The exception as a string in a Python definition-style format, e.g. for parsing by scripts:.

__str__()

Return str(self).

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.

property line

The 1-based line number of the error location within the JSON payload.

None indicates that the error location is not available.

Type:

integer

property column

The 1-based column number of the error location within the JSON payload.

None indicates that the error location is not available.

Type:

integer

__repr__()[source]

Return a string with the state of this exception object, for debug purposes.

str_def()[source]

string: The exception as a string in a Python definition-style format, e.g. for parsing by scripts:

classname={}; line={}; column={}; message={};
class zhmcclient.VersionError(msg, min_api_version, api_version)[source]

This exception indicates that a function of the client requires a minimum HMC API version which is not supported by the HMC.

Derived from Error.

Parameters:
  • msg (string) – A human readable message describing the problem.

  • min_api_version (HMC API version) – The minimum HMC API version required to perform the function that raised this exception.

  • api_version (HMC API version) – The actual HMC API version supported by the HMC.

args[0] will be set to the msg parameter.

Attributes:

min_api_version

The minimum HMC API version required to perform the function that raised this exception.

api_version

The actual HMC API version supported by the HMC.

Methods:

__repr__()

Return a string with the state of this exception object, for debug purposes.

str_def()

string: The exception as a string in a Python definition-style format, e.g. for parsing by scripts:.

__str__()

Return str(self).

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.

property min_api_version

The minimum HMC API version required to perform the function that raised this exception.

Type:

HMC API version

property api_version

The actual HMC API version supported by the HMC.

Type:

HMC API version

__repr__()[source]

Return a string with the state of this exception object, for debug purposes.

str_def()[source]

string: The exception as a string in a Python definition-style format, e.g. for parsing by scripts:

classname={}; min_api_version={}; api_version={}; message={};
class zhmcclient.HTTPError(body)[source]

This exception indicates that the HMC returned an HTTP response with a bad HTTP status code.

Derived from Error.

Parameters:

body (json object) – Body of the HTTP error response.

args[0] will be set to the ‘message’ item of the body, or to None if not present.

Attributes:

http_status

Numeric HTTP status code (e.g. 500).

reason

Numeric HMC reason code.

message

Message describing the error.

request_method

The HTTP method (DELETE, GET, POST, PUT) that caused this error response.

request_uri

The URI that caused this error response.

request_query_parms

URI query parameters specified on the request.

request_headers

HTTP headers specified on the request.

request_authenticated_as

Name of the HMC user associated with the API session under which the request was issued.

request_body

The request body, in the form of a JSON document.

request_body_as_string

The complete request body, or some portion of the request body, exactly as it was submitted by the API client program, if the request_body property is None.

request_body_as_string_partial

Indicates whether the request_body_as_string property contains only part of the request body (True) or the entire request body (False).

stack

Internal HMC diagnostic information for the error.

error_details

A nested object that provides additional operation-specific error information.

Methods:

__str__()

Return a human readable string representation of this exception object.

__repr__()

Return a string with the state of this exception object, for debug purposes.

str_def()

string: The exception as a string in a Python definition-style format, e.g. for parsing by scripts:.

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.

property http_status

Numeric HTTP status code (e.g. 500).

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

Type:

integer

property reason

Numeric HMC reason code.

HMC reason codes provide more details as to the nature of the error than is provided by the HTTP status code. This HMC reason code is treated as a sub-code of the HTTP status code and thus must be used in conjunction with the HTTP status code to determine the error condition.

Standard HMC reason codes that apply across the entire API are described in section ‘Common request validation reason codes’ in the HMC API book. Additional operation-specific reason codes may also be documented in the description of specific API operations in the HMC API book.

The articial reason code 999 is used when the response from the HMC contains an HTML-formatted error message.

Type:

integer

property message

Message describing the error.

This message is not currently localized.

Type:

string

property request_method

The HTTP method (DELETE, GET, POST, PUT) that caused this error response.

Type:

string

property request_uri

The URI that caused this error response.

Type:

string

property request_query_parms

URI query parameters specified on the request.

Each query-parm-info object identifies a single query parameter by its name and includes its value(s).

An empty list, if the request did not specify any query parameters.

Type:

List of query-parm-info objects

property request_headers

HTTP headers specified on the request.

An empty list, if the request did not specify any HTTP headers.

Type:

header-info object

property request_authenticated_as

Name of the HMC user associated with the API session under which the request was issued.

None, if the request was issued without an established session or there is no HMC user bound to the session.

Type:

string

property request_body

The request body, in the form of a JSON document. Note that, since it is in the form of a JSON document, this may not be exactly what was submitted by the API client program, but it is semantically equivalent.

If the request body could not be parsed or some other error prevented the creation of a JSON document from the request body, this property is None and the request body is instead available in the request_body_as_string property.

property request_body_as_string

The complete request body, or some portion of the request body, exactly as it was submitted by the API client program, if the request_body property is None. Otherwise, None.

The request_body_as_string_partial property indicates whether the complete request body is provided in this property.

Type:

string

property request_body_as_string_partial

Indicates whether the request_body_as_string property contains only part of the request body (True) or the entire request body (False). None, if the request_body_as_string property is None.

Type:

bool

property stack

Internal HMC diagnostic information for the error.

This field is supplied only on selected 5xx HTTP status codes. None, if not supplied.

Type:

string

property error_details

A nested object that provides additional operation-specific error information. This field is provided by selected operations, and the format of the nested object is as described by that operation.

Type:

string

__str__()[source]

Return a human readable string representation of this exception object.

__repr__()[source]

Return a string with the state of this exception object, for debug purposes.

str_def()[source]

string: The exception as a string in a Python definition-style format, e.g. for parsing by scripts:

classname={}; request_method={}; request_uri={}; http_status={}; reason={}; message={};
class zhmcclient.OperationTimeout(msg, operation_timeout)[source]

This exception indicates that the waiting for completion of an asynchronous HMC operation has timed out.

Derived from Error.

Parameters:
  • msg (string) – A human readable message describing the problem.

  • operation_timeout (integer) – The operation timeout in seconds.

args[0] will be set to the msg parameter.

Attributes:

operation_timeout

The operation timeout in seconds.

Methods:

__repr__()

Return a string with the state of this exception object, for debug purposes.

str_def()

string: The exception as a string in a Python definition-style format, e.g. for parsing by scripts:.

__str__()

Return str(self).

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.

property operation_timeout

The operation timeout in seconds.

Type:

integer

__repr__()[source]

Return a string with the state of this exception object, for debug purposes.

str_def()[source]

string: The exception as a string in a Python definition-style format, e.g. for parsing by scripts:

classname={}; operation_timeout={}; message={};
class zhmcclient.StatusTimeout(msg, actual_status, desired_statuses, status_timeout)[source]

This exception indicates that the waiting for reaching a desired LPAR or Partition status has timed out.

The possible status values for an LPAR are:

  • "not-activated" - The LPAR is not active.

  • "not-operating" - The LPAR is active but no operating system is running in the LPAR.

  • "operating" - The LPAR is active and an operating system is running in the LPAR.

  • "exceptions" - The LPAR or its CPC has one or more unusual conditions.

The possible status values for a Partition are described in the ‘status’ property of the data model for the partition resource in the HMC API book.

Derived from Error.

Parameters:
  • msg (string) – A human readable message describing the problem.

  • actual_status (string) – The actual status (at the point in time when the status timeout expired).

  • desired_statuses (iterable of string) – The desired status values that were supposed to be reached.

  • status_timeout (number) – The status timeout (in seconds) that has expired.

args[0] will be set to the msg parameter.

Attributes:

actual_status

The actual status (at the point in time when the status timeout expired).

desired_statuses

The desired status values that were supposed to be reached.

status_timeout

The status timeout (in seconds) that has expired.

Methods:

__repr__()

Return a string with the state of this exception object, for debug purposes.

str_def()

string: The exception as a string in a Python definition-style format, e.g. for parsing by scripts:.

__str__()

Return str(self).

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.

property actual_status

The actual status (at the point in time when the status timeout expired).

Type:

string

property desired_statuses

The desired status values that were supposed to be reached.

Type:

iterable of string

property status_timeout

The status timeout (in seconds) that has expired.

Type:

number

__repr__()[source]

Return a string with the state of this exception object, for debug purposes.

str_def()[source]

string: The exception as a string in a Python definition-style format, e.g. for parsing by scripts:

classname={}; actual_status={}; desired_statuses={}; status_timeout={}; message={};
class zhmcclient.NotFound(filter_args=None, manager=None, message=None)[source]

This exception indicates that a resource was not found.

Derived from Error.

Parameters:
  • filter_args (dict) –

    Dictionary of filter arguments by which the resource was attempted to be found. Keys are the resource property names, values are the match values for that property.

    May be None if the message parameter is None. Will be ignored if the message parameter is not None.

  • manager (BaseManager) –

    The manager of the resource, in whose scope the resource was attempted to be found.

    Must not be None if the message parameter is None. Will be ignored if the message parameter is not None.

  • message (string) –

    The exception message.

    If None, the message will be automatically created from the filter_args and manager parameters.

args[0] will be set to an exception message that is automatically constructed from the input parameters.

Attributes:

filter_args

Dictionary of filter arguments by which the resource was attempted to be found.

manager

The manager of the resource, in whose scope the resource was attempted to be found.

Methods:

__repr__()

Return a string with the state of this exception object, for debug purposes.

str_def()

string: The exception as a string in a Python definition-style format, e.g. for parsing by scripts:.

__str__()

Return str(self).

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.

property filter_args

Dictionary of filter arguments by which the resource was attempted to be found. Keys are the resource property names, values are the match values for that property.

Will be None if the message init parameter was not None.

Type:

dict

property manager

The manager of the resource, in whose scope the resource was attempted to be found.

Will be None if the message init parameter was not None.

Type:

BaseManager

__repr__()[source]

Return a string with the state of this exception object, for debug purposes.

str_def()[source]

string: The exception as a string in a Python definition-style format, e.g. for parsing by scripts:

classname={}; resource_classname={}; filter_args={}; parent_classname={}; parent_name={}; message={};
class zhmcclient.NoUniqueMatch(filter_args, manager, resources)[source]

This exception indicates that more than one resource matched the filter arguments.

Derived from Error.

Parameters:
  • filter_args (dict) – Dictionary of filter arguments by which the resource was attempted to be found. Keys are the resource property names, values are the match values for that property.

  • manager (BaseManager) –

    The manager of the resource, in whose scope the resource was attempted to be found.

    Must not be None.

  • resources (iterable of BaseResource) –

    The resources that did match the filter.

    Must not be None.

args[0] will be set to an exception message that is automatically constructed from the input parameters.

Attributes:

filter_args

Dictionary of filter arguments by which the resource was attempted to be found.

manager

The manager of the resource, in whose scope the resource was attempted to be found.

resources

The resources that matched the filter.

resource_uris

List of URIs of the resources that matched the filter.

Methods:

__repr__()

Return a string with the state of this exception object, for debug purposes.

str_def()

string: The exception as a string in a Python definition-style format, e.g. for parsing by scripts:.

__str__()

Return str(self).

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.

property filter_args

Dictionary of filter arguments by which the resource was attempted to be found. Keys are the resource property names, values are the match values for that property.

Type:

dict

property manager

The manager of the resource, in whose scope the resource was attempted to be found.

Type:

BaseManager

property resources

The resources that matched the filter.

Type:

List of BaseResource

property resource_uris

List of URIs of the resources that matched the filter.

__repr__()[source]

Return a string with the state of this exception object, for debug purposes.

str_def()[source]

string: The exception as a string in a Python definition-style format, e.g. for parsing by scripts:

classname={}; resource_classname={}; filter_args={}; parent_classname={}; manager_name={}; message={}; resource_uris={}
class zhmcclient.CeasedExistence(resource_uri)[source]

This exception indicates that the corresponding HMC resource for an auto-updated zhmcclient resource no longer exists.

This exception will only be raised for zhmcclient resources that are enabled for Auto-updating.

Derived from Error.

Parameters:

resource_uri (string) – URI of the resource that no longer exists.

args[0] will be set to a default message.

Attributes:

resource_uri

The URI of the resource that no longer exists.

Methods:

__repr__()

Return a string with the state of this exception object, for debug purposes.

__str__()

Return str(self).

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.

str_def()

string: The exception as a string in a Python definition-style format, e.g. for parsing by scripts:.

property resource_uri

The URI of the resource that no longer exists.

Type:

string

__repr__()[source]

Return a string with the state of this exception object, for debug purposes.

str_def()[source]

string: The exception as a string in a Python definition-style format, e.g. for parsing by scripts:

classname={}; message={}; resource_uri={}

4.9. Constants

Public constants.

These constants are not meant to be changed by the user, they are made available for inspection and documentation purposes only.

For technical reasons, the online documentation shows these constants in the zhmcclient._constants namespace, but they are also available in the zhmcclient namespace and should be used from there.

zhmcclient._constants.DEFAULT_CONNECT_TIMEOUT = 30

Default HTTP connect timeout in seconds, if not specified in the retry_timeout_config init argument to Session.

zhmcclient._constants.DEFAULT_CONNECT_RETRIES = 3

Default number of HTTP connect retries, if not specified in the retry_timeout_config init argument to Session.

zhmcclient._constants.DEFAULT_HMC_PORT = 6794

Default HMC port number

zhmcclient._constants.DEFAULT_READ_TIMEOUT = 3600

Default HTTP read timeout in seconds, if not specified in the retry_timeout_config init argument to Session.

Note: The default value for this parameter has been increased to a large value in order to mitigate the behavior of the ‘requests’ module to retry HTTP methods even if they are not idempotent (e.g. DELETE). See zhmcclient issue #249.

zhmcclient._constants.DEFAULT_READ_RETRIES = 0

Default number of HTTP read retries, if not specified in the retry_timeout_config init argument to Session.

Note: The default value for this parameter has been set to 0 in order to mitigate the behavior of the ‘requests’ module to retry HTTP methods even if they are not idempotent (e.g. DELETE). See zhmcclient issue #249.

zhmcclient._constants.DEFAULT_STOMP_PORT = 61612

Default port on which the HMC issues JMS over STOMP messages.

zhmcclient._constants.DEFAULT_MAX_REDIRECTS = 30

Default max. number of HTTP redirects, if not specified in the retry_timeout_config init argument to Session.

zhmcclient._constants.DEFAULT_OPERATION_TIMEOUT = 3600

Default timeout in seconds for waiting for completion of an asynchronous HMC operation, if not specified in the retry_timeout_config init argument to Session.

This is used as a default value in asynchronous methods on resource objects (e.g. zhmcclient.Partition.start()), in the zhmcclient.Job.wait_for_completion() method, and in the low level method zhmcclient.Session.post().

zhmcclient._constants.DEFAULT_STATUS_TIMEOUT = 60

Default timeout in seconds for waiting for completion of deferred status changes for LPARs and Partitions, if not specified in the retry_timeout_config init argument to Session.

zhmcclient._constants.DEFAULT_NAME_URI_CACHE_TIMETOLIVE = 300

Default time to the next automatic invalidation of the Name-URI cache of manager objects, in seconds since the last invalidation, if not specified in the retry_timeout_config init argument to Session.

The special value 0 means that no Name-URI cache is maintained (i.e. the caching is disabled).

zhmcclient._constants.HMC_LOGGER_NAME = 'zhmcclient.hmc'

Name of the Python logger that logs HMC operations.

zhmcclient._constants.JMS_LOGGER_NAME = 'zhmcclient.jms'

Name of the Python logger that logs JMS notifications.

zhmcclient._constants.API_LOGGER_NAME = 'zhmcclient.api'

Name of the Python logger that logs zhmcclient API calls made by the user.

zhmcclient._constants.HTML_REASON_WEB_SERVICES_DISABLED = 900

Web Services API is not enabled on the HMC.

Type:

HTTP reason code

zhmcclient._constants.HTML_REASON_OTHER = 999

Other HTML-formatted error response. Note that over time, there may be more specific reason codes introduced for such situations.

Type:

HTTP reason code

4.10. Utilities

Utility functions.

zhmcclient.datetime_from_timestamp(ts, tzinfo=<UTC>)[source]

Convert an HMC timestamp number into a datetime object. The resulting object will be timezone-aware and will be represented in the specified timezone, defaulting to UTC.

The HMC timestamp number must be non-negative. This means the special timestamp value -1 cannot be represented as datetime and will cause ValueError to be raised.

The date and time range supported by this function has the following bounds:

  • The upper bounds is determined by datetime.datetime.max and additional limitations, as follows:

    • 9999-12-31 23:59:59 UTC, for 32-bit and 64-bit CPython on Linux and OS-X.

    • 3001-01-01 07:59:59 UTC, for 32-bit and 64-bit CPython on Windows, due to a limitation in gmtime() in Visual C++.

    • 2038-01-19 03:14:07 UTC, for some 32-bit Python implementations, due to the Year 2038 problem.

  • The lower bounds is the UNIX epoch: 1970-01-01 00:00:00 UTC.

Parameters:
  • ts (timestamp) –

    Point in time as an HMC timestamp number.

    Must not be None.

  • tzinfo (datetime.tzinfo) –

    Timezone in which the returned object will be represented. This may be any object derived from datetime.tzinfo, including but not limited to objects returned by pytz.timezone().

    Note that this parameter does not affect how the HMC timestamp value is interpreted; i.e. the effective point in time represented by the returned object is not affected. What is affected by this parameter is for example the timezone in which the point in time is shown when printing the returned object.

    Must not be None.

Returns:

Point in time as a timezone-aware Python datetime object for the specified timezone.

Return type:

datetime

Raises:

ValueError

zhmcclient.timestamp_from_datetime(dt)[source]

Convert a datetime object into an HMC timestamp number.

The date and time range supported by this function has the following bounds:

  • The upper bounds is datetime.datetime.max, as follows:

    • 9999-12-31 23:59:59 UTC, for 32-bit and 64-bit CPython on Linux and OS-X.

    • 2038-01-19 03:14:07 UTC, for some 32-bit Python implementations, due to the Year 2038 problem.

  • The lower bounds is the UNIX epoch: 1970-01-01 00:00:00 UTC.

Parameters:

dt (datetime) –

Point in time as a Python datetime object. The datetime object may be timezone-aware or timezone-naive. If timezone-naive, the UTC timezone is assumed.

Must not be None.

Returns:

Point in time as an HMC timestamp number.

Return type:

timestamp

Raises:

ValueError