Python API
Using the service's Python client / SDK bindings
This page documents the Python client library for Trilio Site Recovery, the triliositerecovery package. The client library lets you drive every DR workflow — site registration, protection group lifecycle, failover, failback, reconciliation, replication health checks, and operation monitoring — directly from Python code without shelling out to the CLI. It follows standard OpenStack client conventions: it authenticates through keystoneauth1, discovers the service endpoint from the Keystone catalogue, and returns all results as plain Python dicts. This page covers installation, session construction, the manager API, error handling, and complete runnable examples for the primary workflows.
Before using the Python client, ensure you have:
- Python 3.8 or later
- The
python3-triliositerecoveryDebian package installed on the machine running your code (see Installation), or thetriliositerecoverydistribution installed in your Python environment - A working OpenStack environment with Trilio Site Recovery deployed and registered in the Keystone catalogue
- Keystone credentials with at least the
memberanddr_operatorroles on your project; site-admin operations additionally requiredr_site_admin - Both Keystone roles (
dr_operatoranddr_site_admin) must already exist in Keystone — trust creation fails if either is missing - The
keystoneauth1library available in your Python environment (installed as a dependency of the client package) - Network connectivity from your machine to port 8788 (protector API) and port 5000 (Keystone) on each site
The client library is shipped as the python3-triliositerecovery Debian package from the Trilio apt repository. Install it on any machine that will run Python code against the API — this is separate from the service packages on the controller nodes.
1. Add the Trilio apt repository (if not already present):
echo 'deb [trusted=yes] https://apt.fury.io/trilio-os-site-recovery-master/ /' \
| sudo tee /etc/apt/sources.list.d/trilio-site-recovery.list
sudo apt-get update
2. Install the client package:
sudo apt-get install python3-triliositerecovery
This installs the triliositerecovery Python library under /usr/lib/python3/dist-packages/triliositerecovery and registers the openstack dr CLI plugin.
3. Verify the installation:
from triliositerecovery.v1.client import Client
print("triliositerecovery client imported successfully")
Upgrading the client independently of the service:
If your CLI or client machine is not managed by the Juju charm, you must upgrade the client package separately whenever the service is upgraded:
sudo apt-get install --only-upgrade python3-triliositerecovery
The Juju charm's upgrade-packages action upgrades the service unit only; it does not reach machines running only the client.
The Python client is stateless — it holds no configuration files. All behaviour is determined by how you construct the Client object and the keystoneauth1 session you pass to it.
Import path
Always import from triliositerecovery.v1.client:
from triliositerecovery.v1.client import Client
Do not import from the package root — that path does not expose Client.
Client constructor parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
session | keystoneauth1.adapter.Adapter | Yes | An authenticated Adapter pinned to the protector service endpoint |
endpoint | str | Yes | The base URL of the protector API (e.g. http://host:8788/v1/PROJECT_ID) |
region_name | str | No | OpenStack region name, used for endpoint discovery |
Omitting endpoint causes every request URL to begin with the literal string "None/" and fail immediately. The endpoint must be the full versioned base URL including the tenant path segment.
Session construction
The recommended pattern uses keystoneauth1.adapter.Adapter with a session and endpoint_override so catalogue discovery is pinned:
from keystoneauth1 import session as ks_session
from keystoneauth1.identity import v3 as ks_identity
from keystoneauth1 import adapter
from triliositerecovery.v1.client import Client
auth = ks_identity.Password(
auth_url='https://keystone.site1.example.com:5000/v3',
username='myuser',
password='mypassword',
project_name='myproject',
user_domain_name='Default',
project_domain_name='Default',
)
sess = ks_session.Session(auth=auth)
# Discover the endpoint from the catalogue
endpoint = sess.get_endpoint(
service_type='protector',
interface='public',
region_name='RegionOne',
)
adp = adapter.Adapter(
session=sess,
endpoint_override=endpoint,
)
client = Client(
session=adp,
endpoint=endpoint,
region_name='RegionOne',
)
Return types
Every manager method returns parsed JSON — plain Python dicts and lists, never resource objects. Access fields with resource['field'], not resource.field. The latter raises AttributeError.
Mapping arguments
Network and flavor mappings are passed as Python dicts, not 'src=dst' strings. The = separator is a CLI-only convention that argparse parses into a dict before passing to the library. Passing a string to the library sends it directly to the wire and causes a TypeError server-side:
# Correct
kwargs['network_mapping'] = {'source-net-name': 'target-net-id'}
# Wrong — string is a CLI-only convention
kwargs['network_mapping'] = 'source-net-name=target-net-id'
Positional vs keyword arguments
Manager methods take the resource ID as a positional argument. Passing it as a keyword argument causes a TypeError:
# Correct
client.operations.failover(pg_id, failover_type='planned')
# Wrong — pg_id= is not a valid keyword here
client.operations.failover(protection_group_id=pg_id)
Affected methods: operations.failover, operations.failback, operations.test_failover, operations.cleanup_test_failover, operations.reconcile, protection_groups.add_member, protection_groups.replication_health, protection_groups.recovery_points.
Manager overview
The Client object exposes one manager per resource type:
| Attribute | Manager class | Covers |
|---|---|---|
client.sites | SiteManager | Site CRUD, local site, resources, replication audit, site failover |
client.protection_groups | ProtectionGroupManager | PG CRUD, member management, sync, replication health, recovery points |
client.operations | OperationManager | DR operations: failover, failback, test failover, reconcile, cancel |
client.tenant_mappings | TenantMappingManager | Cross-site tenant ID translation |
client.mappings | ResourceMappingManager | Network, flavor, and floating IP mappings |
client.site_operations | SiteOperationManager | Site-level (all-PG) operation records |
client.usage | UsageManager | Usage and billing reports |
DR operations are on client.operations, not client.protection_groups
This is the most common mistake. Failover, failback, test failover, cleanup, and reconcile are all methods on client.operations (OperationManager), not on client.protection_groups:
# Correct
operation = client.operations.failover(pg_id, failover_type='planned')
# Wrong — ProtectionGroupManager has no failover() method
operation = client.protection_groups.failover(pg_id)
Protection group creation
Use volume_type_id (not volume_type) when creating a protection group. The --volume-type CLI flag maps to the volume_type_id body field. For async replication, volume_type_id is required; for active_dr it is not:
# async replication — volume_type_id required
pg = client.protection_groups.create(
name='web-tier-pg',
primary_site_id=primary_site_id,
secondary_site_id=secondary_site_id,
replication_type='async',
volume_type_id='8b2c3d4e-...',
)
# active_dr replication — volume_type_id not required
pg = client.protection_groups.create(
name='db-tier-pg',
primary_site_id=primary_site_id,
secondary_site_id=secondary_site_id,
replication_type='active_dr',
)
Polling operations
DR operations (failover, failback, test failover, reconcile) are asynchronous. The action endpoint returns HTTP 202 with status 'pending' as soon as the operation is accepted. Poll client.operations.get(operation_id) until the status field reaches a terminal value.
Terminal statuses: completed, failed, cancelled, error, partial_success.
The progress field (integer 0–100) is real and can be shown while polling. There is no estimated completion time — the service does not compute one.
import time
def wait_for_operation(client, operation_id, timeout=1800, poll_interval=5):
deadline = time.time() + timeout
terminal = {'completed', 'failed', 'cancelled', 'error', 'partial_success'}
while True:
op = client.operations.get(operation_id)
status = (op.get('status') or '').lower()
if status in terminal:
return op
if time.time() >= deadline:
raise TimeoutError(
f"Operation {operation_id} still {status} after {timeout}s; "
f"progress: {op.get('progress', 0)}%"
)
time.sleep(min(poll_interval, max(0, deadline - time.time())))
Source site and target site in operation records
The source_site and target_site fields in operation records show the site name, falling back to the site ID. Both fields are present in operation show output:
op = client.operations.get(operation_id)
print(op.get('source_site')) # e.g. 'site-london'
print(op.get('target_site')) # e.g. 'site-frankfurt'
Tenant mapping fallback
A tenant mapping is not required before performing DR operations. When no mapping exists, the engine assumes the same project UUID on the peer site. This assumption holds for a shared or federated Keystone but essentially never for two independent deployments. Omitting a mapping in that case causes cross-site trust operations to fail with a project-not-found error at runtime, which is harder to diagnose than a misconfigured mapping. Create explicit tenant mappings for independent deployments.
Instance names after failover and failback
Recovered instances are renamed by the engine:
- Failover creates the instance as
<original-name>-failover - Failback creates the instance as
<original-name>-restored
The member row retains the original instance_name. A round trip therefore never restores the workload to its original name — update any external systems (DNS, monitoring, CMDB) that key on the instance name.
1. Build a client from environment credentials
import os
from keystoneauth1 import session as ks_session
from keystoneauth1.identity import v3 as ks_identity
from keystoneauth1 import adapter
from triliositerecovery.v1.client import Client
auth = ks_identity.Password(
auth_url=os.environ['OS_AUTH_URL'],
username=os.environ['OS_USERNAME'],
password=os.environ['OS_PASSWORD'],
project_name=os.environ['OS_PROJECT_NAME'],
user_domain_name=os.environ.get('OS_USER_DOMAIN_NAME', 'Default'),
project_domain_name=os.environ.get('OS_PROJECT_DOMAIN_NAME', 'Default'),
)
sess = ks_session.Session(auth=auth)
endpoint = sess.get_endpoint(
service_type='protector',
interface='public',
region_name=os.environ.get('OS_REGION_NAME', 'RegionOne'),
)
adp = adapter.Adapter(session=sess, endpoint_override=endpoint)
client = Client(
session=adp,
endpoint=endpoint,
region_name=os.environ.get('OS_REGION_NAME', 'RegionOne'),
)
2. List sites and find the local site
# All registered sites — returns a list of dicts
sites = client.sites.list()
for site in sites:
# Access fields with dict syntax — site.id raises AttributeError
print(site['id'], site['name'])
# The site this protector instance is configured as
local = client.sites.local()
print('Local site:', local['name'] if local else 'not configured')
3. Register a peer site
site = client.sites.create(
name='site-frankfurt',
auth_url='https://keystone.frankfurt.example.com:5000/v3',
region_name='frankfurt',
service_username='protector',
service_password='secret',
service_project_name='service',
service_user_domain_name='Default',
service_project_domain_name='Default',
protector_api_url='http://protector.frankfurt.example.com:8788/v1',
)
print('Created site:', site['id'])
4. Create a protection group (async replication)
primary_site_id = 'aaa-...'
secondary_site_id = 'bbb-...'
vol_type_id = 'ccc-...'
pg = client.protection_groups.create(
name='web-tier-pg',
description='Web tier workloads',
primary_site_id=primary_site_id,
secondary_site_id=secondary_site_id,
replication_type='async',
volume_type_id=vol_type_id, # required for async; use volume_type_id, not volume_type
)
print('Protection group status:', pg['status']) # 'creating' — creation is async
5. Add a member and check replication health
pg_id = pg['id']
instance_id = 'ddd-...'
member = client.protection_groups.add_member(
pg_id, # positional — do not pass as a keyword argument
instance_id,
boot_order=1,
)
print('Member status:', member['status'])
# Check replication health (storage lag, RPO compliance)
health = client.protection_groups.replication_health(pg_id)
print('Ready for failover:', health.get('failover_ready'))
print('Replication lag (s):', health.get('replication_lag_seconds'))
# --probe: also asks the target site whether the group's networks,
# security groups and flavors resolve there, as the project it recovers into.
# Slower because it talks to the peer; run this before a planned failover window.
health_probed = client.protection_groups.replication_health(pg_id, probe=True)
6. Execute a planned failover and wait for completion
import time
def wait_for_operation(client, operation_id, timeout=1800):
terminal = {'completed', 'failed', 'cancelled', 'error', 'partial_success'}
deadline = time.time() + timeout
while True:
op = client.operations.get(operation_id)
status = (op.get('status') or '').lower()
if status in terminal:
return op
progress = op.get('progress', 0)
print(f' status={status} progress={progress}%')
if time.time() >= deadline:
raise TimeoutError(
f'Operation {operation_id} still {status} '
f'({progress}%) after {timeout}s'
)
time.sleep(5)
# Failover is on client.operations, not client.protection_groups
operation = client.operations.failover(
pg_id, # positional
failover_type='planned',
)
print('Operation accepted, id:', operation['id'], 'status:', operation['status'])
final = wait_for_operation(client, operation['id'])
print('Final status:', final['status'])
print('Source site:', final.get('source_site'))
print('Target site:', final.get('target_site'))
# progress is real (0-100); there is no estimated completion time
print('Progress at completion:', final.get('progress'), '%')
7. Failover with explicit network and flavor mapping
# Network and flavor mappings are dicts, not 'src=dst' strings
operation = client.operations.failover(
pg_id,
failover_type='planned',
# Key is the source network NAME (not UUID) — instance metadata carries names
network_mapping={'internal-net': 'target-internal-net-id'},
flavor_mapping={'m1.large': 'dr-large-id'},
)
8. Failback after a failover
# failback is on client.operations, not client.protection_groups
operation = client.operations.failback(
pg_id,
failback_type='planned',
)
final = wait_for_operation(client, operation['id'])
print('Failback status:', final['status'])
# Note: failback waits up to 120s per volume for Nova attachments to release
# before unmanaging volumes. A slow failback is the wait working, not a hang.
9. Reconcile a protection group after an interrupted failover
# reconcile is on client.operations, not client.protection_groups
# It works even when the primary site is unreachable.
# reconcile is synchronous: the action endpoint returns HTTP 200 with the
# reconcile result, not an operation id to poll.
result = client.operations.reconcile(pg_id)
print('Reconcile result:', result)
# The reconcile is also recorded in operation history (operation_type RECONCILE)
# and appears in client.operations.list().
10. Run a test failover and clean it up
# Test failover — does not affect production
operation = client.operations.test_failover(
pg_id,
network_mapping={'internal-net': 'test-net-id'},
)
test_op_id = operation['id']
final = wait_for_operation(client, test_op_id)
print('Test failover status:', final['status'])
# Clean up the test failover — sends wire key 'test_cleanup'
cleanup = client.operations.cleanup_test_failover(pg_id)
wait_for_operation(client, cleanup['id'])
11. Create a tenant mapping for independent deployments
# Without a mapping, the engine assumes the same project UUID on the peer site.
# For independent (non-federated) deployments, create an explicit mapping.
mapping = client.tenant_mappings.create(
local_tenant_id='eee-...local-project-id...',
remote_site_id='bbb-...secondary-site-id...',
remote_tenant_id='fff-...remote-project-id...',
description='Primary project to DR project',
)
print('Mapping id:', mapping['id'])
12. List recent operations filtered by protection group
ops = client.operations.list(pg_id=pg_id)
for op in ops:
print(
op['operation_type'],
op['status'],
f"{op.get('progress', 0)}%",
op.get('source_site', ''),
'->', op.get('target_site', ''),
)
13. Replication audit — volumes replicating outside any protection group
# Returns a dict of volumes being replicated that have no protection group.
# These consume array capacity and have no managed recovery points.
audit = client.sites.replication_audit()
# Inspect and clean up unprotected replicas as appropriate.
14. Site-level failover (all protection groups at a site)
# Requires dr_site_admin role
site_op = client.sites.failover(
site_id,
failover_type='planned',
)
print('Site operation id:', site_op['id'])
# Poll with client.site_operations.get, not client.operations.get
detail = client.site_operations.get(site_op['id'])
print('Status:', detail['status'])
for child in detail.get('child_operations') or []:
print(' Child:', child.get('operation_type'), child.get('status'))
AttributeError: 'dict' object has no attribute 'id'
Symptom: Code like site.id or pg.name raises AttributeError.
Cause: Every manager returns plain Python dicts, not resource objects.
Fix: Use dict access: site['id'], pg['name'], op.get('status').
TypeError: failover() missing 1 required positional argument: 'pg_id'
Symptom: Calling client.operations.failover(protection_group_id=pg_id) raises TypeError.
Cause: Manager methods that take a resource ID expect it as a positional argument. **kwargs swallows any other keyword arguments silently, so the positional is still missing.
Fix: Pass the ID positionally: client.operations.failover(pg_id, failover_type='planned').
Request URLs begin with 'None/' and all calls fail immediately
Symptom: Every request fails with a URL like None/v1/.../sites.
Cause: The endpoint argument was omitted when constructing Client.
Fix: Always pass endpoint to the constructor. Retrieve it from the session before constructing the client:
endpoint = sess.get_endpoint(service_type='protector', interface='public')
client = Client(session=adp, endpoint=endpoint)
Network mapping silently does nothing; wrong network used after failover
Symptom: The failover completes but VMs attach to the wrong network despite passing --network-mapping or a network_mapping dict.
Cause (CLI): A colon (:) was used instead of equals (=) as the separator. argparse accepts the colon-separated string as one opaque key with no value, so the mapping is never applied and resolution falls back to name matching.
Cause (library): A 'src=dst' string was passed instead of a dict. The library sends it directly to the wire, where it causes a TypeError on the server.
Fix: Use = as the separator in CLI calls; use a dict in library calls. The key must be the source network name (not UUID) — instance metadata carries network names:
# CLI
openstack dr failover my-pg --network-mapping internal-net=target-net-id
# Library
client.operations.failover(pg_id, network_mapping={'internal-net': 'target-net-id'})
Trust creation fails with a missing role error
Symptom: The first DR operation fails with an error naming a Keystone role that does not exist.
Cause: The dr_operator or dr_site_admin role does not exist in Keystone on one or both sites. Trust creation fails and names the missing role rather than skipping it.
Fix: Create both roles in Keystone on both sites before any DR operation:
openstack role create dr_operator
openstack role create dr_site_admin
The Juju charm creates these roles automatically via its keystone-requested-roles configuration, but bare-metal and OpenShift deployments require manual creation.
Operation polling never terminates; --wait returned immediately with status 'pending'
Symptom: An operation started with --wait returned immediately, or your polling loop runs forever.
Cause: DR action endpoints return HTTP 202 immediately when the operation is dispatched. Waiting must be done client-side by polling client.operations.get(operation_id). Terminal statuses are completed, failed, cancelled, error, and partial_success. Missing partial_success from the terminal set caused loops to continue indefinitely on site-level failovers that partially succeeded.
Fix: Use the wait_for_operation helper shown in the Examples section, which includes all five terminal statuses. With the CLI, use --wait and --wait-timeout.
Failback appears to hang; volumes are slow to detach
Symptom: Failback is running but progress is slow with no error.
Cause: Failback waits up to 120 seconds per volume for Nova to release the Cinder attachment after deleting the DR instance. Nova releases attachments asynchronously. This wait is intentional — without it, Cinder rejects the unmanage call with an "attached" error and strands the volume in error_deleting.
Fix: No action required. The delay is proportional to the number of volumes and how quickly your Nova releases attachments. A volume still attached at the 120-second deadline is unmanaged anyway (logged but not fatal), so failback is never aborted by a slow detach.
Project UUID mismatch causes cross-site operations to fail
Symptom: Cross-site operations fail with a trust or project-not-found error long after setup appeared to succeed.
Cause: No tenant mapping was configured. Without a mapping, the engine assumes the same project UUID exists on the peer site. For two independent OpenStack deployments, this assumption is almost always wrong.
Fix: Create an explicit tenant mapping with client.tenant_mappings.create() or openstack dr tenant mapping create. See Example 11 above.
RecoveryPointNotFound (404) when specifying a recovery point
Symptom: Failover with a recovery_point argument returns HTTP 404.
Cause: The recovery point name or suffix does not match any available snapshot for this protection group.
Fix: List available recovery points first:
points = client.protection_groups.recovery_points(pg_id)
for p in points.get('recovery_points', []):
print(p)
Then pass a valid point name or suffix to client.operations.failover().
LUKS-encrypted volume rejected when adding a member
Symptom: add_member fails with an InvalidInput error mentioning LUKS or encryption.
Cause: LUKS-encrypted volumes are not supported in protection groups. Cinder's manage API cannot associate Barbican keys on the DR site, so an encrypted volume cannot be recovered.
Fix: Use array-side encryption (Pure Storage data-at-rest encryption) instead of host-side LUKS. All other member volumes can be added normally.
ResourceConflict (409) when creating a site or protection group
Symptom: Create returns HTTP 409 with a message about an existing resource.
Cause: A resource with the same name already exists, or a soft-deleted resource still holds the name.
Fix: Use client.sites.list() or client.protection_groups.list() to check for existing resources. If the name is held by a deleted resource, choose a different name or contact your cloud administrator to purge the deleted record.