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

Methods

delete Perform the HTTP DELETE method against the resource identified by a URI.
get Perform the HTTP GET 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.
is_logon Return a boolean indicating whether the session is currently logged on to the HMC.
logoff Make sure the session is logged off from the HMC.
logon Make sure the session is logged on to the HMC.
post Perform the HTTP POST method against the resource identified by a URI, using a provided request body.

Attributes

base_url string – Base URL of the HMC in this session.
default_rt_config
get_password The password retrieval function, or None.
headers header dict – HTTP headers to be used in each request.
host string – HMC host, in one of the following formats:
port integer – HMC TCP port to be used.
retry_timeout_config RetryTimeoutConfig – 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.
session stringrequests.Session object for this session.
session_id string – Session ID for this session, returned by the HMC.
time_stats_keeper The time statistics keeper (for a usage example, see section Time Statistics).
userid string – Userid of the HMC user to be used.

Details

__repr__()[source]

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

host

string – 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
port

integer – HMC TCP port to be used.

userid

string – Userid of the HMC user to be used.

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

get_password

The password retrieval function, or None.

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

retry_timeout_config

RetryTimeoutConfig – 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

string – Base URL of the HMC in this session.

Example:

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

header dict – 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: ...
time_stats_keeper

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

session_id

string – Session ID for this session, returned by the HMC.

session

stringrequests.Session object for this session.

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

Methods

check_for_completion Check once for completion of the job and return completion status and result if it has completed.
wait_for_completion 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.

Attributes

op_method string – Name of the HTTP method of the operation that is executing asynchronously on the HMC.
op_uri string – Canonical URI of the operation that is executing asynchronously on the HMC.
session Session – Session with the HMC.
uri string – Canonical URI of the job on the HMC.

Details

session

Session – Session with the HMC.

uri

string – Canonical URI of the job on the HMC.

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

op_method

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

Example: "POST"

op_uri

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

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

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

Attributes

Details

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

Methods

get_inventory Returns a JSON object with the requested resources and their properties, that are managed by the HMC.
query_api_version The Query API Version operation returns information about the level of Web Services API supported by the HMC.
version_info Returns API version information for the HMC.
wait_for_available Wait for the Console (HMC) this client is connected to, to become available.

Attributes

consoles ConsoleManager – Manager object for the (one) Console representing the HMC this client is connected to.
cpcs CpcManager – Manager object for the CPCs in scope of this client.
metrics_contexts MetricsContextManager – Manager object for the Metrics Contexts in scope of this client (i.e.
session Session – Session with the HMC.

Details

session

Session – Session with the HMC.

cpcs

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

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

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

Methods

disable Disable the statistics keeper.
enable Enable the statistics keeper.
get_stats Get the time statistics for a name.
snapshot Return a snapshot of the time statistics of this keeper.

Attributes

enabled Indicates whether the statistics keeper is enabled.

Details

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.

Methods

begin This method must be called before invoking the operation.
end This method must be called after the operation returns.
reset Reset the time statistics data for the operation.

Attributes

avg_time float – The average elapsed time for invoking the operation, in seconds.
count integer – The number of invocations of the operation.
keeper TimeStatsKeeper – The time statistics keeper holding this time statistics.
max_time float – The maximum elapsed time for invoking the operation, in seconds.
min_time float – The minimum elapsed time for invoking the operation, in seconds.
name string – Name of the operation this time statistics has data for.

Details

name

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

keeper

TimeStatsKeeper – The time statistics keeper holding this time statistics.

count

integer – The number of invocations of the operation.

avg_time

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

min_time

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

max_time

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

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.5. 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_groups:
    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
            m_type = m_def.type
            print("      {:30}  {} {}".
                  format(m_name, m_value, m_unit.encode('utf-8')))

# 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

create Create a Metrics Context resource in the HMC this client is connected to.
find 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 Find a resource by name (i.e.
findall 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.
list List the Metrics Context resources that were created through this manager object.
resource_object Return a minimalistic Python resource object for this resource class, that is scoped to this manager.

Attributes

class_name The resource class name
client Client – The client defining the scope for this manager.
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.

Details

__repr__()[source]

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

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.

Methods

delete Delete this Metrics Context resource.
get_metrics Retrieve the current metric values for this Metrics Context resource from the HMC.
get_property Return the value of a resource property.
prop 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.

Attributes

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).
metric_group_definitions dict – The metric definitions for the metric groups of this Metrics Context resource, as a dictionary of MetricGroupDefinition objects, by metric group name.
name string – The name of the resource.
properties dict – The properties of this resource that are currently present in this
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 string – The canonical URI path of the resource.

Details

metric_group_definitions

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

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

class zhmcclient.MetricDefinition[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.

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.

Methods

Attributes

metric_group_values list – The list of MetricGroupValues objects representing the metric groups in this metric response.
metrics_context MetricsContext object for this metric response.

Details

metrics_context

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

metric_group_values

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

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.

Methods

Attributes

name string – The metric group name.
object_values list – The MetricObjectValues objects in this metric group.

Details

name

string – The 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.

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.

Methods

Attributes

client Client – Client object, for retrieving the actual resource.
metric_group_definition MetricGroupDefinition – Metric group definition for this set of metric values.
metrics dict – The metric values, as a dictionary of the (Python typed) metric values, by metric name.
resource BaseResource
resource_uri string – The canonical URI path 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).

Details

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 – The canonical URI path of the resource these metric values apply to.

Example: /api/cpcs/12345

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.

resource

BaseResource

The Python resource object of the
resource these metric values apply to.
Raises:NotFound – No resource found for this URI in the management scope of the HMC.

4.6. Logging

This package supports logging using the standard Python logging module. The logging support provides two Logger objects:

  • ‘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 interactions between zhmcclient and the HMC, at the debug level.

In addition, there are loggers for each module with the module name, for situations like errors or warnings.

For HMC operations and API calls that contain the HMC password, 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 = 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.7. Exceptions

Exceptions that can be raised by the client.

class zhmcclient.Error(*args)[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.

Details

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.

Methods

str_def string: The exception as a string in a Python definition-style format, e.g.

Attributes

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

Details

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.

Methods

str_def string: The exception as a string in a Python definition-style format, e.g.

Attributes

args
connect_retries integer – The number of connect retries.
connect_timeout integer – The connect timeout in seconds.
details The original exception caught by this package, providing more information about the problem.
message

Details

connect_timeout

integer – The connect timeout in seconds.

connect_retries

integer – The number of connect retries.

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

Methods

str_def string: The exception as a string in a Python definition-style format, e.g.

Attributes

args
details The original exception caught by this package, providing more information about the problem.
message
read_retries integer – The number of read retries.
read_timeout integer – The read timeout in seconds.

Details

read_timeout

integer – The read timeout in seconds.

read_retries

integer – The number of read retries.

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

Methods

str_def string: The exception as a string in a Python definition-style format, e.g.

Attributes

args
connect_retries integer – The number of connect retries.
details The original exception caught by this package, providing more information about the problem.
message

Details

connect_retries

integer – The number of connect retries.

__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(*args)[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_def Interface definition for the corresponding method derived exception classes.

Attributes

args
message

Details

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

str_def string: The exception as a string in a Python definition-style format, e.g.

Attributes

args
message

Details

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

Methods

str_def string: The exception as a string in a Python definition-style format, e.g.

Attributes

args
details The original exception describing details about the error.
message

Details

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.

Methods

str_def string: The exception as a string in a Python definition-style format, e.g.

Attributes

args
column integer – The 1-based column number of the error location within the JSON payload.
line integer – The 1-based line number of the error location within the JSON payload.
message

Details

line

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

None indicates that the error location is not available.

column

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

None indicates that the error location is not available.

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

Methods

str_def string: The exception as a string in a Python definition-style format, e.g.

Attributes

api_version HMC API version – The actual HMC API version supported by the HMC.
args
message
min_api_version HMC API version – The minimum HMC API version required to perform the function that raised this exception.

Details

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.

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

Methods

str_def string: The exception as a string in a Python definition-style format, e.g.

Attributes

args
error_details string – A nested object that provides additional operation-specific error information.
http_status integer – Numeric HTTP status code (e.g.
message string – Message describing the error.
reason integer – Numeric HMC reason code.
request_authenticated_as string – 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 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 bool – Indicates whether the request_body_as_string property contains only part of the request body (True) or the entire request body (False).
request_headers header-info object – HTTP headers specified on the request.
request_method string – The HTTP method (DELETE, GET, POST, PUT) that caused this error response.
request_query_parms List of query-parm-info objects – URI query parameters specified on the request.
request_uri string – The URI that caused this error response.
stack string – Internal HMC diagnostic information for the error.

Details

http_status

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

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

reason

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

message

string – Message describing the error.

This message is not currently localized.

request_method

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

request_uri

string – The URI that caused this error response.

request_query_parms

List of query-parm-info objects – 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.

request_headers

header-info object – HTTP headers specified on the request.

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

request_authenticated_as

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

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.

request_body_as_string

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.

request_body_as_string_partial

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

stack

string – Internal HMC diagnostic information for the error.

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

error_details

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

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

Methods

str_def string: The exception as a string in a Python definition-style format, e.g.

Attributes

args
message
operation_timeout integer – The operation timeout in seconds.

Details

operation_timeout

integer – The operation timeout in seconds.

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

Methods

str_def string: The exception as a string in a Python definition-style format, e.g.

Attributes

actual_status string – The actual status (at the point in time when the status timeout expired).
args
desired_statuses iterable of string – The desired status values that were supposed to be reached.
message
status_timeout number – The status timeout (in seconds) that has expired.

Details

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.

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

Methods

str_def string: The exception as a string in a Python definition-style format, e.g.

Attributes

args
filter_args dict – Dictionary of filter arguments by which the resource was attempted to be found.
manager BaseManager – The manager of the resource, in whose scope the resource was attempted to be found.
message

Details

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.

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

Methods

str_def string: The exception as a string in a Python definition-style format, e.g.

Attributes

args
filter_args dict – Dictionary of filter arguments by which the resource was attempted to be found.
manager BaseManager – The manager of the resource, in whose scope the resource was attempted to be found.
message
resource_uris List of URIs of the resources that matched the filter.
resources List of BaseResource – The resources that matched the filter.

Details

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.

resources

List of BaseResource – The resources that matched the filter.

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.8. 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_STOMP_PORT = 61612

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

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

HTTP reason code – Web Services API is not enabled on the HMC.

zhmcclient._constants.HTML_REASON_OTHER = 999

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

4.9. Utilities

Utility functions.

zhmcclient.datetime_from_timestamp(ts)[source]

Convert an HMC timestamp number into a datetime object.

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.

Returns:Point in time as a timezone-aware Python datetime object for timezone UTC.
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