sushy package

Subpackages

Submodules

sushy.auth module

class sushy.auth.AuthBase(username=None, password=None)

Bases: object

authenticate()

Perform authentication.

Raises

RuntimeError

abstract can_refresh_session()

Method to assert if session based refresh can be done.

close()

Shutdown Redfish authentication object

Undoes whatever should be undone to cancel authenticated session.

set_context(root_resource, connector)

Set the context of the authentication object.

Parameters
  • root_resource – Root sushy object

  • connector – Connector for http connections

class sushy.auth.BasicAuth(username=None, password=None)

Bases: sushy.auth.AuthBase

Basic Authentication class.

This is a class used to encapsulate a basic authentication session.

Parameters
  • username – User account with admin/server-profile access privilege.

  • password – User account password.

can_refresh_session()

Method to assert if session based refresh can be done.

class sushy.auth.SessionAuth(username=None, password=None)

Bases: sushy.auth.AuthBase

Session Authentication class.

This is a class used to encapsulate a redfish session.

can_refresh_session()

Method to assert if session based refresh can be done.

close()

Close the Redfish Session.

Attempts to close an established RedfishSession by deleting it from the remote Redfish controller.

get_session_key()

Returns the session key.

Returns

The session key.

get_session_resource_id()

Returns the session resource id.

Returns

The session resource id.

refresh_session()

Method to refresh a session to a Redfish controller.

This method is called to create a new session after a session that has already been established has timed-out or expired.

Raises

MissingXAuthToken

Raises

ConnectionError

Raises

AccessError

Raises

HTTPError

reset_session_attrs()

Reset active session related attributes.

class sushy.auth.SessionOrBasicAuth(username=None, password=None)

Bases: sushy.auth.SessionAuth

refresh_session()

Method to refresh a session to a Redfish controller.

This method is called to create a new RedfishSession if we have previously established a RedfishSession and the previous session has timed-out or expired. If we did not previously have an established session, we simply return our BasicAuthentication requests.Session.

sushy.connector module

class sushy.connector.Connector(url, username=None, password=None, verify=True, response_callback=None, server_side_retries=0, server_side_retries_delay=0)

Bases: object

check_retry_on_exception(exception_msg)

Checks whether retry on exception is required.

close()

Close this connector and the associated HTTP session.

delete(path='', data=None, headers=None, blocking=False, timeout=60, **extra_session_req_kwargs)

HTTP DELETE method.

Parameters
  • path – Optional sub-URI path to the resource.

  • data – Optional JSON data.

  • headers – Optional dictionary of headers.

  • blocking – Whether to block for asynchronous operations.

  • timeout – Max time in seconds to wait for blocking async call.

  • extra_session_req_kwargs – Optional keyword argument to pass requests library arguments which would pass on to requests session object.

Returns

The response object from the requests library.

Raises

ConnectionError

Raises

HTTPError

get(path='', data=None, headers=None, blocking=False, timeout=60, **extra_session_req_kwargs)

HTTP GET method.

Parameters
  • path – Optional sub-URI path to the resource.

  • data – Optional JSON data.

  • headers – Optional dictionary of headers.

  • blocking – Whether to block for asynchronous operations.

  • timeout – Max time in seconds to wait for blocking async call.

  • extra_session_req_kwargs – Optional keyword argument to pass requests library arguments which would pass on to requests session object.

Returns

The response object from the requests library.

Raises

ConnectionError

Raises

HTTPError

patch(path='', data=None, headers=None, etag=None, blocking=False, timeout=60, **extra_session_req_kwargs)

HTTP PATCH method.

Parameters
  • path – Optional sub-URI path to the resource.

  • data – Optional JSON data.

  • headers – Optional dictionary of headers.

  • etag – Optional eTag string.

  • blocking – Whether to block for asynchronous operations.

  • timeout – Max time in seconds to wait for blocking async call.

  • extra_session_req_kwargs – Optional keyword argument to pass requests library arguments which would pass on to requests session object.

Returns

The response object from the requests library.

Raises

ConnectionError

Raises

HTTPError

post(path='', data=None, headers=None, blocking=False, timeout=60, **extra_session_req_kwargs)

HTTP POST method.

Parameters
  • path – Optional sub-URI path to the resource.

  • data – Optional JSON data.

  • headers – Optional dictionary of headers.

  • blocking – Whether to block for asynchronous operations.

  • timeout – Max time in seconds to wait for blocking async call.

  • extra_session_req_kwargs – Optional keyword argument to pass requests library arguments which would pass on to requests session object.

Returns

The response object from the requests library.

Raises

ConnectionError

Raises

HTTPError

put(path='', data=None, headers=None, blocking=False, timeout=60, **extra_session_req_kwargs)

HTTP PUT method.

Parameters
  • path – Optional sub-URI path to the resource.

  • data – Optional JSON data.

  • headers – Optional dictionary of headers.

  • blocking – Whether to block for asynchronous operations.

  • timeout – Max time in seconds to wait for blocking async call.

  • extra_session_req_kwargs – Optional keyword argument to pass requests library arguments which would pass on to requests session object.

Returns

The response object from the requests library.

Raises

ConnectionError

Raises

HTTPError

set_auth(auth)

Sets the authentication mechanism for our connector.

set_http_basic_auth(username, password)

Sets the http basic authentication information.

set_http_session_auth(session_auth_token)

Sets the session authentication information.

sushy.exceptions module

exception sushy.exceptions.AccessError(method, url, response)

Bases: sushy.exceptions.HTTPError

exception sushy.exceptions.ArchiveParsingError(message=None, **kwargs)

Bases: sushy.exceptions.SushyError

message = 'Failed parsing archive "%(path)s": %(error)s'
exception sushy.exceptions.BadRequestError(method, url, response)

Bases: sushy.exceptions.HTTPError

exception sushy.exceptions.ConnectionError(message=None, **kwargs)

Bases: sushy.exceptions.SushyError

message = 'Unable to connect to %(url)s. Error: %(error)s'
exception sushy.exceptions.ExtensionError(message=None, **kwargs)

Bases: sushy.exceptions.SushyError

message = 'Sushy Extension Error: %(error)s'
exception sushy.exceptions.HTTPError(method, url, response)

Bases: sushy.exceptions.SushyError

Basic exception for HTTP errors

body = None

Error JSON body, if present.

code = 'Base.1.0.GeneralError'

Error code defined in the Redfish specification, if present.

detail = None

Error message defined in the Redfish specification, if present.

extended_info = None

Extended information provided in the response.

message = 'HTTP %(method)s %(url)s returned code %(code)s. %(error)s Extended information: %(ext_info)s'
property related_properties

List of properties related to the error.

status_code = None

HTTP status code.

exception sushy.exceptions.InvalidParameterValueError(message=None, **kwargs)

Bases: sushy.exceptions.SushyError

message = 'The parameter "%(parameter)s" value "%(value)s" is invalid. Valid values are: %(valid_values)s'
exception sushy.exceptions.MalformedAttributeError(message=None, **kwargs)

Bases: sushy.exceptions.SushyError

message = 'The attribute %(attribute)s is malformed in the resource %(resource)s: %(error)s'
exception sushy.exceptions.MissingActionError(message=None, **kwargs)

Bases: sushy.exceptions.SushyError

message = 'The action %(action)s is missing from the resource %(resource)s'
exception sushy.exceptions.MissingAttributeError(message=None, **kwargs)

Bases: sushy.exceptions.SushyError

message = 'The attribute %(attribute)s is missing from the resource %(resource)s'
exception sushy.exceptions.MissingHeaderError(message=None, **kwargs)

Bases: sushy.exceptions.SushyError

message = 'Response to %(target_uri)s did not contain a %(header)s header'
exception sushy.exceptions.MissingXAuthToken(method, url, response)

Bases: sushy.exceptions.HTTPError

message = 'No X-Auth-Token returned from remote host when attempting to establish a session. Error: %(error)s'
exception sushy.exceptions.OEMExtensionNotFoundError(message=None, **kwargs)

Bases: sushy.exceptions.SushyError

message = 'No %(resource)s OEM extension found by name "%(name)s".'
exception sushy.exceptions.ResourceNotFoundError(method, url, response)

Bases: sushy.exceptions.HTTPError

message = 'Resource %(url)s not found'
exception sushy.exceptions.ServerSideError(method, url, response)

Bases: sushy.exceptions.HTTPError

exception sushy.exceptions.SushyError(message=None, **kwargs)

Bases: Exception

Basic exception for errors raised by Sushy

message = None
exception sushy.exceptions.UnknownDefaultError(message=None, **kwargs)

Bases: sushy.exceptions.SushyError

message = 'Failed at determining default for "%(entity)s": %(error)s'
sushy.exceptions.raise_for_response(method, url, response)

Raise a correct error class, if needed.

sushy.main module

class sushy.main.LazyRegistries(service_root)

Bases: collections.abc.MutableMapping

Download registries on demand.

Redfish message registries can be very large. On top of that, they are not used frequently. Thus, let’s not pull them off the BMC unless the consumer is actually trying to use them.

Parameters

service_root (sushy.main.Sushy) – Redfish service root object

property registries
class sushy.main.ProtocolFeaturesSupportedField(*args, **kwargs)

Bases: sushy.resources.base.CompositeField

excerpt_query = <sushy.resources.base.Field object>

The excerpt query parameter is supported

expand_query = <sushy.resources.base.Field object>

The expand query parameter is supported

filter_query = <sushy.resources.base.Field object>

The filter query parameter is supported

only_member_query = <sushy.resources.base.Field object>

The only query parameter is supported

select_query = <sushy.resources.base.Field object>

The select query parameter is supported

class sushy.main.Sushy(base_url, username=None, password=None, root_prefix='/redfish/v1/', verify=True, auth=None, connector=None, public_connector=None, language='en', server_side_retries=10, server_side_retries_delay=3)

Bases: sushy.resources.base.ResourceBase

create_session(username=None, password=None)

Creates a session without invoking SessionService.

For use when a new connection is to be established. Removes prior Session and authentication data before making the request.

Parameters
  • username – The username to utilize to create a session with the remote endpoint.

  • password – The password to utilize to create a session with the remote endpoint.

Returns

A session key and uri in the form of a tuple

Raises

MissingXAuthToken

Raises

ConnectionError

Raises

AccessError

Raises

HTTPError

Raises

MissingAttributeError

get_certificate_service()

Get the CertificateService object

Returns

The CertificateService object

get_chassis(identity=None)

Given the identity return a Chassis object

Parameters

identity – The identity of the Chassis resource. If not given, sushy will default to the single available chassis or fail if there appear to be more or less then one Chassis listed.

Raises

UnknownDefaultError if default system can’t be determined.

Returns

The Chassis object

get_chassis_collection()

Get the ChassisCollection object

Raises

MissingAttributeError, if the collection attribute is not found

Returns

a ChassisCollection object

get_composition_service()

Get the CompositionService object

Raises

MissingAttributeError, if the composition service attribute is not found

Returns

The CompositionService object

get_event_service()

Get the EventService object

Raises

MissingAttributeError, if the EventService is not found

Returns

The EventService object

get_fabric(identity)

Given the identity return a Fabric object

Parameters

identity – The identity of the Fabric resource

Returns

The Fabric object

get_fabric_collection()

Get the FabricCollection object

Raises

MissingAttributeError, if the collection attribute is not found

Returns

a FabricCollection object

get_manager(identity=None)

Given the identity return a Manager object

Parameters

identity – The identity of the Manager resource. If not given, sushy will default to the single available Manager or fail if there appear to be more or less then one Manager listed.

Returns

The Manager object

get_manager_collection()

Get the ManagerCollection object

Raises

MissingAttributeError, if the collection attribute is not found

Returns

a ManagerCollection object

get_session(identity)

Given the identity return a Session object

Parameters

identity – The identity of the session resource

Returns

The Session object

get_session_service()

Get the SessionService object

Raises

MissingAttributeError, if the collection attribute is not found

Returns

as SessionCollection object

get_sessions_path()

Returns the Sessions url

get_system(identity=None)

Given the identity return a System object

Parameters

identity – The identity of the System resource. If not given, sushy will default to the single available System or fail if there appear to be more or less then one System listed.

Raises

UnknownDefaultError if default system can’t be determined.

Returns

The System object

get_system_collection()

Get the SystemCollection object

Raises

MissingAttributeError, if the collection attribute is not found

Returns

a SystemCollection object

get_task_monitor(task_monitor_uri)

Used to retrieve a TaskMonitor by task monitor URI.

Parameters

task_monitor_uri – Task monitor URI

Returns

A task monitor.

get_task_service()

Get the TaskService object

Returns

The TaskService object

get_update_service()

Get the UpdateService object

Returns

The UpdateService object

identity = <sushy.resources.base.Field object>

The Redfish root service identity

property lazy_registries

Gets and combines all message registries together

Fetches all registries if any provided by Redfish service and combines together with packaged standard registries.

Returns

dict of combined message registries where key is Registry_name.Major_version.Minor_version and value is registry itself.

name = <sushy.resources.base.Field object>

The Redfish root service name

product = <sushy.resources.base.Field object>

The product associated with this Redfish service

protocol_features_supported = <sushy.main.ProtocolFeaturesSupportedField object>

The information about protocol features supported by the service

property registries

Gets and combines all registries together

Fetches all registries if any provided by Redfish service and combines together with packaged standard registries. Both message and attribute registries are supported from the Redfish service.

Returns

dict of combined registries keyed by both the registry name (Registry_name.Major_version.Minor_version) and the registry file identity, with the value being the actual registry itself.

uuid = <sushy.resources.base.Field object>

The Redfish root service UUID

sushy.taskmonitor module

class sushy.taskmonitor.TaskMonitor(connector, task_monitor_uri, redfish_version=None, registries=None, response=None)

Bases: object

property cancellable

The amount of time to sleep before retrying

Returns

A Boolean indicating if the Task is cancellable.

property check_is_processing

Refreshes task and check if it is still processing

Returns

A boolean indicating if the task is still processing.

static from_response(conn, response, target_uri, redfish_version=None, registries=None)

Construct TaskMonitor instance from received response.

Response

Unprocessed response

Target_uri

URI used to initiate async operation

Redfish_version

Redfish version. Optional when used internally.

Registries

Redfish registries. Optional when used internally.

Returns

TaskMonitor instance

Raises

MissingHeaderError if Location is missing in response

get_task()

Construct Task instance from task monitor URI.

Returns

Task instance.

property is_processing

Indicates if the task is still processing

Returns

A boolean indicating if the task is still processing.

refresh()

Refresh the Task

Freshly retrieves/fetches the Task. :raises: ResourceNotFoundError :raises: ConnectionError :raises: HTTPError

property response

Unprocessed response.

Intended to be used internally. :returns: Unprocessed response.

property sleep_for

Seconds the client should wait before querying the operation status

Defaults to 1 second if Retry-After not specified in response.

Returns

The number of seconds to wait

property task

The executing task

Returns

The Task being executed.

property task_monitor_uri

The TaskMonitor URI

Returns

The TaskMonitor URI.

wait(timeout_sec)

Waits until task is completed or it times out.

Parameters

timeout_sec – Timeout to wait

Raises

ConnectionError when times out

sushy.utils module

sushy.utils.bool_or_none(x)

Given a value x this method returns either a bool or None

Parameters

x – The value to transform and return

Returns

Either None or x cast to a bool

sushy.utils.cache_clear(res_selfie, force_refresh, only_these=None)

Clear some or all cached values of the resource.

If the cache variable refers to a resource instance then the invalidate() method is called on that. Otherwise it is set to None. Should there be a need to force refresh the resource and its sub-resources, “cascading refresh”, force_refresh is to be set to True.

This is the complimentary method of cache_it decorator.

Parameters
  • res_selfie – the resource instance.

  • force_refresh – force_refresh argument of invalidate() method.

  • only_these – expects a sequence of specific method names for which the cached value/s need to be cleared only. When None, all the cached values are cleared.

sushy.utils.cache_it(res_accessor_method)

Utility decorator to cache the return value of the decorated method.

This decorator is to be used with any Sushy resource class method. This will internally create an attribute on the resource namely _cache_<decorated_method_name>. This is referred to as the “caching attribute”. This attribute will eventually hold the resultant value from the method invocation (when method gets first time called) and for every subsequent calls to that method this cached value will get returned. It expects the decorated method to contain its own logic of evaluation.

This also assigns a variable named _cache_attr_names on the resource. This variable maintains a collection of all the existing “caching attribute” names.

To invalidate or clear the cache use cache_clear(). Usage:

class SomeResource(base.ResourceBase):
  ...
  @cache_it
  def get_summary(self):
    # do some calculation and return the result
    # and this result will be cached.
    return result
  ...
  def _do_refresh(self, force):
    cache_clear(self, force)

If the returned value is a Sushy resource instance or a sequence whose element is of type Sushy resource it handles the case of calling the refresh() method of that resource. This is done to avoid unnecessary recreation of a new resource instance which got already created at the first place in contrast to fresh retrieval of the resource json data. Again, the force argument is deliberately set to False to do only the “light refresh” of the resource (only the fresh retrieval of resource) instead of doing the complete exhaustive “cascading refresh” (resource with all its nested subresources recursively).

class SomeResource(base.ResourceBase):
  ...
  @property
  @cache_it
  def nested_resource(self):
    return NestedResource(
      self._conn, "Path/to/NestedResource",
      redfish_version=self.redfish_version)
  ...
  def _do_refresh(self, force):
    # selective attribute clearing
    cache_clear(self, force, only_these=['nested_resource'])

Do note that this is not thread safe. So guard your code to protect it from any kind of concurrency issues while using this decorator.

Parameters

res_accessor_method – the resource accessor decorated method.

sushy.utils.camelcase_to_underscore_joined(camelcase_str)

Convert camelCase string to underscore_joined string

Parameters

camelcase_str – The camelCase string

Returns

the equivalent underscore_joined string

sushy.utils.get_members_identities(members)

Extract and return a tuple of members identities

Parameters

members – A list of members in JSON format

Returns

A tuple containing the members paths

sushy.utils.get_sub_resource_path_by(resource, subresource_name, is_collection=False)

Helper function to find the subresource path

Parameters
  • resource – ResourceBase instance on which the name gets queried upon.

  • subresource_name – name of the resource field to fetch the @odata.id’ from.

  • is_collection – if True, expect a list of resources to fetch the @odata.id’ from.

Returns

Resource path (if is_collection is False) or a list of resource paths (if is_collection is True).

sushy.utils.int_or_none(x)

Given a value x it cast as int or None

Parameters

x – The value to transform and return

Returns

Either None or x cast to an int

sushy.utils.max_safe(iterable, default=0)

Helper wrapper over builtin max() function.

This function is just a wrapper over builtin max() w/o key argument. The default argument specifies an object to return if the provided iterable is empty. Also it filters out the None type values.

Parameters
  • iterable – an iterable

  • default – 0 by default

sushy.utils.process_apply_time_input(payload, apply_time, maint_window_start_time, maint_window_duration)

Validates apply time input for asynchronous operations

Parameters
  • payload – Payload for which to process apply time settings

  • apply_time – When to update the attribute. Optional. An sushy.ApplyTime value.

  • maint_window_start_time – The start time of a maintenance window, datetime. Required when updating during maintenance window and default maintenance window not set by the system.

  • maint_window_duration – Duration of maintenance time since maintenance window start time in seconds. Required when updating during maintenance window and default maintenance window not set by the system.

Raises

ValueError – When input apply time settings incorrect

Returns

Payload with adjusted apply time settings if valid

sushy.utils.revert_dictionary(dictionary)

Given a dictionary revert it’s mapping

Parameters

dictionary – A dictionary to be reverted

Returns

A dictionary with the keys and values reverted

sushy.utils.sanitize(item)

Remove passwords from the item.

sushy.utils.setdefaultattr(obj, name, default)

Python’s dict.setdefault applied on Python objects.

If name is an attribute with obj, return its value. If not, set name attribute with a value of default and return default.

Parameters
  • obj – a python object

  • name – name of attribute

  • default – default value to be set

sushy.utils.synchronized(wrapped)

Simple synchronization decorator.

Decorating a method like so:

@synchronized
def foo(self, *args):
  ...

ensures that only one thread will execute the foo method at a time.

Module contents

class sushy.Sushy(base_url, username=None, password=None, root_prefix='/redfish/v1/', verify=True, auth=None, connector=None, public_connector=None, language='en', server_side_retries=10, server_side_retries_delay=3)

Bases: sushy.resources.base.ResourceBase

create_session(username=None, password=None)

Creates a session without invoking SessionService.

For use when a new connection is to be established. Removes prior Session and authentication data before making the request.

Parameters
  • username – The username to utilize to create a session with the remote endpoint.

  • password – The password to utilize to create a session with the remote endpoint.

Returns

A session key and uri in the form of a tuple

Raises

MissingXAuthToken

Raises

ConnectionError

Raises

AccessError

Raises

HTTPError

Raises

MissingAttributeError

get_certificate_service()

Get the CertificateService object

Returns

The CertificateService object

get_chassis(identity=None)

Given the identity return a Chassis object

Parameters

identity – The identity of the Chassis resource. If not given, sushy will default to the single available chassis or fail if there appear to be more or less then one Chassis listed.

Raises

UnknownDefaultError if default system can’t be determined.

Returns

The Chassis object

get_chassis_collection()

Get the ChassisCollection object

Raises

MissingAttributeError, if the collection attribute is not found

Returns

a ChassisCollection object

get_composition_service()

Get the CompositionService object

Raises

MissingAttributeError, if the composition service attribute is not found

Returns

The CompositionService object

get_event_service()

Get the EventService object

Raises

MissingAttributeError, if the EventService is not found

Returns

The EventService object

get_fabric(identity)

Given the identity return a Fabric object

Parameters

identity – The identity of the Fabric resource

Returns

The Fabric object

get_fabric_collection()

Get the FabricCollection object

Raises

MissingAttributeError, if the collection attribute is not found

Returns

a FabricCollection object

get_manager(identity=None)

Given the identity return a Manager object

Parameters

identity – The identity of the Manager resource. If not given, sushy will default to the single available Manager or fail if there appear to be more or less then one Manager listed.

Returns

The Manager object

get_manager_collection()

Get the ManagerCollection object

Raises

MissingAttributeError, if the collection attribute is not found

Returns

a ManagerCollection object

get_session(identity)

Given the identity return a Session object

Parameters

identity – The identity of the session resource

Returns

The Session object

get_session_service()

Get the SessionService object

Raises

MissingAttributeError, if the collection attribute is not found

Returns

as SessionCollection object

get_sessions_path()

Returns the Sessions url

get_system(identity=None)

Given the identity return a System object

Parameters

identity – The identity of the System resource. If not given, sushy will default to the single available System or fail if there appear to be more or less then one System listed.

Raises

UnknownDefaultError if default system can’t be determined.

Returns

The System object

get_system_collection()

Get the SystemCollection object

Raises

MissingAttributeError, if the collection attribute is not found

Returns

a SystemCollection object

get_task_monitor(task_monitor_uri)

Used to retrieve a TaskMonitor by task monitor URI.

Parameters

task_monitor_uri – Task monitor URI

Returns

A task monitor.

get_task_service()

Get the TaskService object

Returns

The TaskService object

get_update_service()

Get the UpdateService object

Returns

The UpdateService object

identity = <sushy.resources.base.Field object>

The Redfish root service identity

property lazy_registries

Gets and combines all message registries together

Fetches all registries if any provided by Redfish service and combines together with packaged standard registries.

Returns

dict of combined message registries where key is Registry_name.Major_version.Minor_version and value is registry itself.

name = <sushy.resources.base.Field object>

The Redfish root service name

product = <sushy.resources.base.Field object>

The product associated with this Redfish service

protocol_features_supported = <sushy.main.ProtocolFeaturesSupportedField object>

The information about protocol features supported by the service

property registries

Gets and combines all registries together

Fetches all registries if any provided by Redfish service and combines together with packaged standard registries. Both message and attribute registries are supported from the Redfish service.

Returns

dict of combined registries keyed by both the registry name (Registry_name.Major_version.Minor_version) and the registry file identity, with the value being the actual registry itself.

uuid = <sushy.resources.base.Field object>

The Redfish root service UUID