ironic.common.redfish package¶
Submodules¶
- ironic.common.redfish.auth module
- ironic.common.redfish.connector module
AsyncConnectorAsyncConnector.check_retry_on_exception()AsyncConnector.close()AsyncConnector.delete()AsyncConnector.get()AsyncConnector.patch()AsyncConnector.post()AsyncConnector.put()AsyncConnector.set_auth()AsyncConnector.set_http_basic_auth()AsyncConnector.set_http_session_auth()AsyncConnector.set_sessions_uri()
- ironic.common.redfish.exceptions module
- ironic.common.redfish.resource module
- ironic.common.redfish.taskmonitor module
AsyncTaskMonitorAsyncTaskMonitor.cancellableAsyncTaskMonitor.check_is_processing()AsyncTaskMonitor.from_response()AsyncTaskMonitor.is_processingAsyncTaskMonitor.refresh()AsyncTaskMonitor.responseAsyncTaskMonitor.sleep_forAsyncTaskMonitor.task_monitor_uriAsyncTaskMonitor.task_resourceAsyncTaskMonitor.wait()
Module contents¶
Async Redfish client for Ironic.
A lightweight asynchronous Redfish client built on httpx with dynamic resource access. Provides async/await patterns for interacting with Redfish resources.
Example usage:
from ironic.common import redfish
async with redfish.AsyncRedfishClient(
'https://bmc.example.com',
username='admin',
password='password',
auth_type='auto'
) as client:
# Get the only system (when you know there's exactly one)
systems = await client.collection('Systems')
system = await systems.one()
print(f"Manufacturer: {system.field('Manufacturer')}")
print(f"Power state: {system.field('PowerState')}")
# Get all systems in a collection
systems = await client.collection('Systems')
for system in await systems.get_all():
print(f"System: {system.field('Name')}")
# Get resources by name
update_service = await client.resource('UpdateService')
print(f"Enabled: {update_service.field('ServiceEnabled')}")
# Get resources by absolute path
bios = await client.resource('/redfish/v1/Systems/1/Bios')
print(f"Boot mode: {bios.field('BootMode')}")
- class ironic.common.redfish.AsyncBasicAuth(username=None, password=None, root_prefix=None)[source]¶
Bases:
AsyncAuthBaseHTTP Basic Authentication.
Uses HTTP Basic authentication for all requests.
- class ironic.common.redfish.AsyncConnector(url, verify=True, default_request_timeout=60, response_callback=None, server_side_retries=3, server_side_retries_delay=2, connect_timeout=None)[source]¶
Bases:
objectAsync HTTP connector using httpx.AsyncClient.
Provides asynchronous HTTP operations for Redfish BMC communication.
- check_retry_on_exception(response)[source]¶
Check if the exception in response should be retried.
This method checks for vendor-specific error conditions that should trigger a retry (e.g., iDRAC not ready, iLO not ready).
- Parameters:
response – httpx.Response object.
- Returns:
True if the request should be retried, False otherwise.
- async delete(path='', headers=None, timeout=None)[source]¶
Async HTTP DELETE method.
- Parameters:
path – Optional sub-URI path to the resource.
headers – Optional dictionary of headers.
timeout – Optional timeout in seconds.
- Returns:
httpx.Response object.
- Raises:
ConnectionError on request failures.
- Raises:
Various HTTP exceptions on HTTP errors.
- async get(path='', headers=None, timeout=None)[source]¶
Async HTTP GET method.
Returns the response object rather than the parsed body so that callers can read headers (notably ETag, needed for conditional updates) and the status code. This matches the other verbs.
- Parameters:
path – Optional sub-URI path to the resource.
headers – Optional dictionary of headers.
timeout – Optional timeout in seconds.
- Returns:
httpx.Response object.
- Raises:
ConnectionError on request failures.
- Raises:
Various HTTP exceptions on HTTP errors.
- async patch(path='', data=None, headers=None, etag=None, timeout=None)[source]¶
Async HTTP PATCH method.
- Parameters:
path – Optional sub-URI path to the resource.
data – Optional JSON data for request body.
headers – Optional dictionary of headers.
etag – Optional eTag string.
timeout – Optional timeout in seconds.
- Returns:
httpx.Response object.
- Raises:
ConnectionError on request failures.
- Raises:
Various HTTP exceptions on HTTP errors.
- async post(path='', data=None, headers=None, timeout=None)[source]¶
Async HTTP POST method.
- Parameters:
path – Optional sub-URI path to the resource.
data – Optional JSON data for request body.
headers – Optional dictionary of headers.
timeout – Optional timeout in seconds.
- Returns:
httpx.Response object.
- Raises:
ConnectionError on request failures.
- Raises:
Various HTTP exceptions on HTTP errors.
- async put(path='', data=None, headers=None, timeout=None)[source]¶
Async HTTP PUT method.
- Parameters:
path – Optional sub-URI path to the resource.
data – Optional JSON data for request body.
headers – Optional dictionary of headers.
timeout – Optional timeout in seconds.
- Returns:
httpx.Response object.
- Raises:
ConnectionError on request failures.
- Raises:
Various HTTP exceptions on HTTP errors.
- set_auth(auth)[source]¶
Set the authentication mechanism.
- Parameters:
auth – Authentication object (AsyncAuthBase instance).
- set_http_basic_auth(username, password)[source]¶
Set HTTP Basic authentication.
- Parameters:
username – Username for basic auth.
password – Password for basic auth.
- set_http_session_auth(session_auth_token)[source]¶
Set session-based authentication.
- Parameters:
session_auth_token – Session authentication token.
- set_sessions_uri(sessions_uri)[source]¶
Record where the Sessions collection lives.
Set by session authentication once it has resolved the URI, so that
_is_sessions_path()can recognise the login request itself rather than guessing from the path.- Parameters:
sessions_uri – URI of the Sessions collection.
- class ironic.common.redfish.AsyncResource(connector, path, json_data=None)[source]¶
Bases:
objectLightweight asynchronous Redfish resource.
This is a dynamic alternative to sushy’s static field-based resources. Instead of declaring all fields upfront, it provides methods to access fields, execute actions, and navigate links on-demand.
Example usage:
system = AsyncResource(connector, '/redfish/v1/Systems/1') await system.refresh() # Get simple fields manufacturer = system.field('Manufacturer') # Get nested fields with slash notation boot_target = system.field('Boot/BootSourceOverrideTarget') # Apply adapters to field values power_state = system.field('PowerState', adapter=str.lower) # Execute actions await system.action('Reset', {'ResetType': 'ForceRestart'}) # PATCH resources await system.patch({'AssetTag': 'new-tag'}) # Navigate to subresources bios = await system.link('Bios') boot_mode = bios.field('BootMode')
- async action(name, payload=None)[source]¶
Execute a Redfish action on this resource.
- Parameters:
name – Action name (e.g., ‘Reset’, ‘ComputerSystem.Reset’)
payload – Optional dict payload for the action
- Returns:
Response from the action POST request
- Raises:
ValueError if action is not found or has no target
Example:
await system.action('Reset', {'ResetType': 'ForceRestart'}) payload = {'Image': 'http://example.com/image.iso'} await virtual_media.action('InsertMedia', payload)
- collection(name='Members', expand=False)[source]¶
Get a collection of resources from a collection field.
- Parameters:
name – Collection field name (e.g., ‘Members’, ‘Drives’)
expand – If True, append
$expand=.($levels=1)to each member path so sub-resources are fetched inline when the collection is iterated. Each member strips the query back off inAsyncResource.__init__, so it never reaches a PATCH target and is never appended twice.
- Returns:
AsyncResourceCollection instance
Example:
# Get all systems from a collection systems_collection_resource = await client.resource( '/redfish/v1/Systems' ) systems_collection = systems_collection_resource.collection() systems = await systems_collection.get_all() for system in systems: print(system.field('Manufacturer')) # Get all drives from a storage resource with expansion storage = await client.resource('/redfish/v1/Systems/1/Storage/1') drives_collection = storage.collection('Drives', expand=True) drives = await drives_collection.get_all()
- property etag¶
Get the cached ETag value.
- property expanded¶
Whether this resource is fetched with
$expandby default.
- field(name, adapter=None, default=None)[source]¶
Get a field value from the resource JSON.
Supports nested field access using slash notation.
- Parameters:
name – Field name or path (e.g., ‘Manufacturer’ or ‘Boot/BootSourceOverrideTarget’)
adapter – Optional callable to process the field value
default – Default value if field is not found
- Returns:
Field value, optionally processed by adapter
- Example:
manufacturer = resource.field(‘Manufacturer’) boot_target = resource.field(‘Boot/BootSourceOverrideTarget’) power_watts = resource.field(‘PowerWatts’, adapter=int)
- property json¶
Get the raw JSON data.
- async link(name, default=Ellipsis, expand=False)[source]¶
Get a linked subresource.
Navigates to a linked resource via @odata.id reference. Supports links in the ‘Links’ object or as direct properties.
- Parameters:
name – Link name (e.g., ‘Bios’, ‘Storage’, ‘Processors’)
default – Default value if link is not found (defaults to raising ValueError)
expand – If True, fetch the linked resource with
$expand=.($levels=1)to inline sub-resources in a single request. Mirrors sushy’schassis_expanded/storage_expandedproperties.
- Returns:
AsyncResource instance for the linked resource, or default
- Raises:
ValueError if link is not found and no default provided
Example:
bios = await system.link('Bios') boot_mode = bios.field('BootMode') storage_collection = await system.link('Storage', expand=True) members = storage_collection.field('Members', default=[]) # Optional link that may not exist thermal = await chassis.link('Thermal', default=None) if thermal: fans = thermal.field('Fans', default=[])
- async patch(payload, etag=None)[source]¶
PATCH this resource with the given payload.
The resource is deliberately not re-fetched afterwards. A BMC that is still settling after an update can answer the follow-up GET with a 5xx, and raising that here would report a PATCH that in fact succeeded as a failure, leaving the caller unable to tell the two apart. Instead, when the BMC returns the updated representation in the PATCH response it is adopted directly – the same shortcut sushy takes with
refresh(json_doc=...). Otherwisejsonkeeps the pre-PATCH document, and a caller that needs the new state callsrefresh()itself, where a failure is unambiguously a failure to read.- Parameters:
payload – Dict of fields to update
etag – Optional ETag for conditional updates. If not provided, uses the ETag from the last refresh (if available)
- Returns:
Response from the PATCH request
- Example:
await system.patch({‘AssetTag’: ‘new-tag’}) await system.patch({‘Boot’: {‘BootSourceOverrideTarget’: ‘Pxe’}})
- property path¶
Get the resource path.
- async refresh(expand=None)[source]¶
Refresh the resource data from the server.
- Parameters:
expand – Whether to request
$expand=.($levels=1)so that sub-resources are fetched inline (mirrors sushy’s_expandedproperties).None, the default, keeps whatever this resource was built with, so a member of a collection taken withexpand=Truestays expanded when it is refreshed.TrueorFalseoverride that and become the resource’s new default, keepingexpandedin step with the document injson.- Returns:
self for method chaining
- class ironic.common.redfish.AsyncResourceCollection(connector, paths)[source]¶
Bases:
objectHelper for working with collections of resources.
This is returned when accessing collection links that contain multiple @odata.id references.
- Supports async iteration:
- async for resource in collection:
print(resource.field(‘Name’))
- Can be iterated multiple times:
- async for resource in collection:
# First iteration
- async for resource in collection:
# Second iteration (independent)
- async get(index)[source]¶
Get a single resource by index.
- Parameters:
index – Index in the collection
- Returns:
AsyncResource instance with refreshed data
- async get_all()[source]¶
Fetch all resources in the collection.
- Returns:
List of AsyncResource instances with refreshed data
- async one()[source]¶
Get the single resource from this collection.
- Returns:
AsyncResource instance with refreshed data
- Raises:
UnknownDefaultError if collection doesn’t have exactly 1 item
- Example:
# Get the only system (useful when you know there’s exactly one) systems = await client.collection(‘Systems’) system = await systems.one()
- property paths¶
Returns a list of all paths in the collection.
- class ironic.common.redfish.AsyncSessionAuth(username=None, password=None, root_prefix=None)[source]¶
Bases:
AsyncAuthBaseRedfish Session Authentication.
Creates and manages a Redfish session for authentication.
- can_refresh_session()[source]¶
Check if session can be refreshed.
- Returns:
True if session key and resource ID are available.
- async close()[source]¶
Close the Redfish session.
Attempts to DELETE the session from the BMC. A session the BMC has already dropped, by expiry or reboot, answers 404, which is the outcome this method wants rather than a failure: the goal is that the session no longer exists.
- get_session_key()[source]¶
Get the session authentication key.
- Returns:
Session key (X-Auth-Token value).
- get_session_resource_id()[source]¶
Get the session resource ID/URI.
- Returns:
Session resource URI for deletion.
- async refresh_session()[source]¶
Refresh the Redfish session.
Creates a new session after the previous one has expired.
- Raises:
MissingHeaderError if X-Auth-Token not in response.
- Raises:
ConnectionError on connection failures.
- Raises:
AccessError on authentication failures.
- Raises:
HTTPError on other HTTP errors.
- class ironic.common.redfish.AsyncSessionOrBasicAuth(username=None, password=None, root_prefix=None)[source]¶
Bases:
AsyncSessionAuthSession authentication with fallback to basic auth.
Attempts to use session-based authentication. If session creation fails, falls back to HTTP Basic authentication.
- class ironic.common.redfish.AsyncTaskMonitor(connector, task_monitor_uri, response=None)[source]¶
Bases:
objectMonitor for asynchronous Redfish operations.
This class tracks the progress of long-running Redfish operations that return HTTP 202 Accepted with a task monitor URI.
- property cancellable¶
Check if the task can be cancelled.
Reports False until the monitor has polled at least once, the same answer it gives for a task whose response carries no Allow header: permission to DELETE is something the BMC states, not something to assume on its behalf. A caller that needs this on a monitor built from a URI alone should
refresh()first.- Returns:
True if task is cancellable, False otherwise
- async check_is_processing()[source]¶
Refresh and check if the task is still processing.
- Returns:
True if task is processing, False otherwise
- async static from_response(connector, response, target_uri)[source]¶
Create TaskMonitor from an HTTP response.
- Parameters:
connector – AsyncConnector instance
response – httpx.Response from async operation
target_uri – URI that initiated the async operation
- Returns:
AsyncTaskMonitor instance
- Raises:
MissingHeaderError if Location header is missing
- property is_processing¶
Check if the task is still processing.
A monitor built from a task monitor URI alone has not polled the BMC yet, and an unpolled task counts as still processing. The other answer is far worse: reporting a task as finished before anything has been asked would let
wait()return immediately and callers treat an operation still running on the BMC as complete. The firstrefresh()replaces the assumption with what the BMC actually says.- Returns:
True if task is processing, False otherwise
- async refresh()[source]¶
Refresh the task state.
Retrieves the current state of the task from the BMC.
- Raises:
ConnectionError on request failures
- Raises:
Various HTTP exceptions on HTTP errors
- property response¶
Get the raw response.
- Returns:
httpx.Response object
- property sleep_for¶
Get recommended sleep duration before next poll.
Uses Retry-After header if present, defaults to 1 second. Before the first poll there is no response to take a hint from, so the default applies there too.
- Returns:
Number of seconds to wait before next poll
- property task_monitor_uri¶
Get the task monitor URI.
- Returns:
The task monitor URI
- property task_resource¶
Get the task resource.
- Returns:
AsyncResource for the task, or None if not available
- async wait(timeout_sec)[source]¶
Wait for the task to complete.
Polls the task monitor URI until the task completes or the timeout expires. Before every poll the Retry-After hint of the response currently held is honoured, so the first poll does not happen before the BMC asked for it. The sleep is capped to the time left of the budget, so a Retry-After longer than the timeout cannot stretch the wait: the deadline still buys one last poll, and the task is only declared timed out once that poll reports it as still processing.
Each poll is bounded too, so an unresponsive BMC cannot stretch the wait either. Without that bound a single poll could occupy the connector’s whole retry chain - several attempts of its default request timeout plus backoff - and run for minutes regardless of the budget given here. A poll is allowed the time left of the budget, or
MIN_POLL_TIMEOUTwhen the budget is already spent, which puts the worst case for this call attimeout_secplus one poll. Abandoning a poll loses nothing: it is a GET, and the next one re-reads the same state.Note that the bound applies to this call, not to the BMC. Callers that hold a resource for the duration still want their own deadline around it.
- Parameters:
timeout_sec – Maximum time to wait in seconds
- Raises:
ConnectionError when timeout is reached