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.

  • 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).

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

Parameters
  • host (string) – HMC host. For valid formats, see the host property. 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 the session is logged on to the HMC.

logoff([verify])

Make sure the session is logged off from the HMC.

is_logon([verify])

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

get(uri[, logon_required])

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

post(uri[, body, logon_required, …])

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

delete(uri[, 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 the API session.

auto_update_subscribed()

Return whether this session is currently subscribed for auto-updating of resources.

subscribe_auto_update()

Subscribe this session for auto-updating of resources, if not currently subscribed.

unsubscribe_auto_update()

Unsubscribe this session from auto-updating of resources, if currently subscribed.

Attributes:

host

HMC host, in one of the following formats:

port

HMC TCP port to be used.

userid

Userid of the HMC user to be used.

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 in this session.

headers

HTTP headers to be used in each request.

time_stats_keeper

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

session_id

Session ID for this session, returned by the HMC.

session

requests.Session object for this session.

object_topic

Name of the notification topic the HMC will use to send object-related notification messages to this API session.

job_topic

Name of the notification topic the HMC will use to send job notification messages to this API session.

resource_updater

Resource updater for auto-updating of resources.

__repr__()[source]

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

property host

HMC host, 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

property port

HMC TCP port to be used.

Type

integer

property userid

Userid of the HMC user to be used.

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 in this session.

Example:

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

string

property headers

HTTP headers to be used in each request.

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 for this session, returned by the HMC.

Type

string

property session

requests.Session object for this session.

Type

string

property object_topic

Name of the notification topic the HMC will use to send object-related notification messages to this API session.

When not logged on, this property is None.

The associated topic type is “object-notification”.

Type

string

property job_topic

Name of the notification topic the HMC will use to send job notification messages to this API session.

When not logged on, this property is None.

The associated topic type is “job-notification”.

Type

string

property resource_updater

Resource updater for auto-updating of resources.

Type

ResourceUpdater

logon(verify=False)[source]

Make sure the session is logged on to the HMC.

By default, this method checks whether there is a session-id set and considers that sufficient for determining that the session is logged on. The verify parameter can be used to verify the validity of a session-id that is already set, by issuing a dummy operation (“Get Console Properties”) to the HMC.

After successful logon to the HMC, the following is stored in this session object for reuse in subsequent operations:

  • the HMC session-id, in order to avoid extra userid authentications,

  • a requests.Session object, in order to enable connection pooling. Connection pooling avoids repetitive SSL/TLS handshakes.

Parameters

verify (bool) – If a session-id is already set, verify its validity.

Raises
logoff(verify=False)[source]

Make sure the session is logged off from the HMC.

After successful logoff, the HMC session-id and requests.Session object stored in this object are reset.

Parameters

verify (bool) – If a session-id is already set, verify its validity.

Raises
is_logon(verify=False)[source]

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

By default, this method checks whether there is a session-id set and considers that sufficient for determining that the session is logged on. The verify parameter can be used to verify the validity of a session-id that is already set, by issuing a dummy operation (“Get Console Properties”) to the HMC.

Parameters

verify (bool) – If a session-id is already set, verify its validity.

get(uri, logon_required=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.

Returns

json object with the operation result.

Raises
post(uri, body=None, logon_required=True, wait_for_completion=False, operation_timeout=None)[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) – JSON object to be used as the HTTP request body (payload). 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.

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, logon_required=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.

Raises
get_notification_topics()[source]

The ‘Get Notification Topics’ operation returns a structure that describes the JMS notification topics associated with the API 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 of resources.

Returns

Indicates whether session is subscribed.

Return type

bool

subscribe_auto_update()[source]

Subscribe this session for auto-updating of resources, if not currently subscribed.

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 of resources, 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:

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.

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

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
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. ResourceUpdater

Resource updater for auto-updating of resources.

class zhmcclient.ResourceUpdater(session)[source]

A class that updates the properties of zhmcclient resource objects that are enabled for auto-updating.

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-update (via its subscribe_auto_update() method).

Creating an object of this class 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 properties of zhmcclient resource objects to be updated that are registered to this class as a result of enabling auto-update for the resorce object (via their enable_auto_update() method).

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

Parameters

session (Session) – Session for which the resource updater should do its work. This defines the HMC host and credentials that are used to establish the JMS session with the HMC.

Methods:

close()

Disconnect and close the JMS session with the HMC.

register_object(resource_obj)

Register a resource object to this resource updater.

unregister_object(resource_obj)

Unregister a resource object from this resource updater.

registered_objects(resource_uri)

Generator that yields the resource objects for the specified URI.

has_objects()

Return boolean indicating whether there are any resource objects registered.

close()[source]

Disconnect and close the JMS session with the HMC.

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

register_object(resource_obj)[source]

Register a resource object to this resource updater.

If this resource object (by id) is already registered, nothing is done.

unregister_object(resource_obj)[source]

Unregister a resource object from this resource updater.

If this resource object (by id) is already unregistered, nothing is done.

registered_objects(resource_uri)[source]

Generator that yields the resource 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.

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.

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.

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 resources with their properties, for the requested resource classes and resource classifiers.

Return type

JSON object

Example

resource_classes = [‘partition’, ‘adapter’] result_dict = 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.

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.

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.

find_by_name(name)

Find a resource by name (i.e.

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.

flush()

Invalidate the Name-URI cache of this manager.

invalidate_cache()

Invalidate the Name-URI cache of this manager.

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.

class_name

The resource class 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.

__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.

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-update is currently enabled for the resource object.

disable_auto_update()

Disable auto-update for this resource object, if currently enabled.

enable_auto_update()

Enable auto-update 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 present in this Python object, without retrieving them from 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 it does not exist.

pull_full_properties()

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

update_properties_local(properties)

Update the values of a set of resource properties on this Python object without propagating the updates 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, …)

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]
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)

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]
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

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

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-update 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 exceptions.Exception.

Methods:

str_def()

Interface definition for the corresponding method derived exception classes.

__str__()

Return str(self).

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.

__str__()

Return str(self).

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.

__str__()

Return str(self).

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.

__str__()

Return str(self).

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.

__str__()

Return str(self).

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).

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.

__str__()

Return str(self).

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.

__str__()

Return str(self).

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.

__str__()

Return str(self).

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.

__str__()

Return str(self).

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.

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.

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.

__str__()

Return str(self).

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.

__str__()

Return str(self).

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, manager)[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.

  • manager (BaseManager) –

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

    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.

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.

__str__()

Return str(self).

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

__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.

__str__()

Return str(self).

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={}

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 = 900

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

This is used as a default value in asynchronous methods of the Lpar class that change its status (e.g. zhmcclient.Lpar.activate())).

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.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