Cluster¶
- class aerospike_sdk.aio.cluster.Cluster[source]¶
Bases:
ClusterBase[Session,TransactionalSession,Node]Live connection to a cluster, obtained from
ClusterDefinition.connect().Owns a connected
Clientand exposescreate_session()/transaction()(both inherited fromClusterBase). Preferasync with ClusterDefinition(...).connect() as clustersoclose()runs on exit.Example:
async with ClusterDefinition("localhost", 3100).connect() as cluster: session = cluster.create_session(Behavior.DEFAULT)
See also
- __init__(sdk_client)[source]¶
Initialize a Cluster instance.
- Parameters:
sdk_client (
Client) – The underlying Client instance
Note
This should not be called directly. Use ClusterDefinition.connect() instead.
- async register_udf(body, server_path, language=UDFLang.LUA, *, policy=None)[source]¶
Register a UDF package from in-memory bytes or text on the cluster.
- Raises:
RuntimeError – If not connected.
AerospikeError – On cluster errors (via PNC).
- Return type:
RegisterTask
- async register_udf_from_file(client_path, server_path, language=UDFLang.LUA, *, policy=None)[source]¶
Register a UDF by reading module bytes from a local file.
- Raises:
RuntimeError – If not connected.
AerospikeError – On cluster errors (via PNC).
- Return type:
RegisterTask
- async register_udf_from_resource(package, resource, server_path, language=UDFLang.LUA, *, policy=None)[source]¶
Register a UDF from a Python package resource.
- Raises:
RuntimeError – If not connected.
AerospikeError – On cluster errors (via PNC).
- Return type:
RegisterTask
- async remove_udf(server_path, *, policy=None)[source]¶
Remove a registered UDF package from the cluster.
- Raises:
RuntimeError – If not connected.
AerospikeError – On cluster errors (via PNC).
- Return type:
UdfRemoveTask
- async list_udf()[source]¶
List the UDF modules registered on the cluster.
- Raises:
RuntimeError – If not connected.
AerospikeError – On cluster errors (via PNC).
- async list_indexes()[source]¶
List the secondary indexes defined on the cluster.
- Raises:
RuntimeError – If not connected.
AerospikeError – On cluster errors (via PNC).
- add_exporter(exporter)[source]¶
Register an exporter; snapshots are pushed to each one registered.
Registered exporters receive the push while
metrics.exporteriscustom;file(the default) andnoneleave them uncalled. They receive every snapshot in registration order. One that keeps raising is suspended and periodically retried without affecting the others. The cluster never closes an exporter registered here – the application owns its lifecycle.- Parameters:
exporter (
Any) – AnAsyncMetricsExporter(async def export).- Raises:
TypeError – If
exporterhas noexportmethod or defines a synchronous one.- Return type:
Example:
exporter = MetricsWriter("/var/log/aerospike") cluster.add_exporter(exporter)
See also
- remove_exporter(exporter)[source]¶
Unregister an exporter previously passed to
add_exporter().
- enable_metrics(policy=None)[source]¶
Enable metrics collection for this cluster.
Collection is off until enabled. Re-enabling with a changed latency unit or histogram shape discards the accumulated latency samples; counters are retained.
- Parameters:
policy (
Optional[MetricsPolicy]) – Collection configuration. Defaults toMetricsPolicy’s milliseconds/7-column scheme with every command recorded.- Raises:
AerospikeError – With
PARAMETER_ERRORwhen a loaded configuration file setsmetrics.enabled; the file owns the switch.- Return type:
Example:
cluster.enable_metrics(MetricsPolicy(sampler=Sampler.probability(0.1)))
See also
- disable_metrics()[source]¶
Disable metrics collection. Accumulated data is retained.
Stops the export push after one last snapshot, so the window since the previous export still reaches the exporters. The snapshot is taken before collection stops; delivering it is IO, so it runs as a task and this method returns before the exporters have received it.
close()waits for that delivery. Exporters the application registered stay registered and are not closed – their lifecycle belongs to the application.Call it from the event loop’s thread: the closing delivery is scheduled on the running loop.
- Raises:
AerospikeError – With
PARAMETER_ERRORwhen a loaded configuration file setsmetrics.enabled; the file owns the switch.RuntimeError – If called off the event loop’s thread while metrics are enabled and an exporter is registered.
Example:
cluster.disable_metrics() # ... the closing snapshot is delivered in the background ... await cluster.close() # returns once it has been
See also
- Return type:
- async close()[source]¶
Close the SDK client and release cluster resources.
Invoked automatically when used as an async context manager. With metrics enabled, exporters receive one closing snapshot first.
- Return type:
- property cluster_name: str | None¶
The cluster name the servers report.
When the connection was built with
ClusterDefinition.cluster_name(), nodes reporting any other name were rejected, so this equals the validated name.Example:
print(f"connected to {cluster.cluster_name}") # connected to prod-east
- Returns:
The server’s
cluster-name, orNonewhen the servers are configured without one.
See also
nodes(): The nodes making up this cluster.
- create_session(behavior=None)¶
Open a session on this cluster with optional behavior.
A session is a logical connection carrying behavior settings (timeouts, retry policies, consistency levels, …) that govern how operations run.
- Parameters:
behavior (
Optional[Behavior]) – Policy bundle for the session. Defaults toDEFAULT.- Return type:
TypeVar(_S)- Returns:
A session bound to this cluster’s SDK client.
Example:
session = cluster.create_session(Behavior.DEFAULT)
See also
transaction(): Open a multi-record transaction instead.
- get_node(name)¶
Look up one node by its name.
Example:
node = cluster.get_node("BB9D4EB574A8DA6") print(node.version, node.address)
- Parameters:
name (
str) – The node name, as reported by a node’snameor the*_per_nodeinfo helpers.- Return type:
TypeVar(_N, bound=NodeBase)- Returns:
The matching node view.
- Raises:
InvalidNodeError – If no active node has that name.
RuntimeError – If not connected.
See also
nodes(): Every node at once.
- property is_connected: bool¶
Whether the cluster connection is currently active.
- Returns:
Trueif the underlying client reports a live connection.
Example:
assert cluster.is_connected
See also
close(): Release the connection.
- metrics_snapshot()¶
Snapshot the accumulated cluster metrics.
Available whether or not collection is on. Values are cumulative since metrics were enabled and frozen while collection is off; connection gauges are point-in-time. Snapshotting drains and aggregates per-node state, so poll at an export interval rather than per operation.
- Return type:
- Returns:
A
MetricsSnapshot; zeroed counters if metrics were never enabled.
Example:
snapshot = cluster.metrics_snapshot() reads = snapshot.latency(LatencyType.READ) print(f"{reads.count} reads, avg {reads.average:.1f}")
See also
enable_metrics(): Start collection.
- node_names()¶
The names of the nodes currently in the cluster.
Example:
names = cluster.node_names() print(f"{len(names)} nodes: {', '.join(names)}")
- Return type:
- Returns:
One name per active node.
- Raises:
RuntimeError – If not connected.
See also
nodes(): The nodes themselves.
- nodes()¶
The nodes currently in the cluster.
Example:
versions = {node.name: str(node.version) for node in cluster.nodes()} if len(set(versions.values())) > 1: print(f"rolling upgrade in progress: {versions}")
- Return type:
- Returns:
One node view per active node.
- Raises:
RuntimeError – If not connected.
See also
get_node(): Look up one node by name.node_names(): Just the names.
- server_version()¶
The minimum server version across connected nodes.
- Return type:
Optional[Version]- Returns:
The least-capable node’s
Version, orNonewhen the cluster reports no nodes. Guarding against the minimum is what makes a feature check safe on a mixed-version or mid-upgrade cluster.
Example:
v = cluster.server_version() if v is not None and (v.major, v.minor, v.patch) >= (8, 2, 0): ...
See also
nodes(): Each node’s own version.
- supports_ael()¶
Whether every node parses server-compiled AEL (filters, exp reads/writes).
- Return type:
- supports_query_operations()¶
Whether every node supports read operations inside an index query.
- Return type:
- supports_query_selection()¶
Whether every node supports server-led index selection (>= 8.2.0).
- Return type:
- supports_string_operations()¶
Whether every node supports the server-side string operations.
Example:
if cluster.supports_string_operations(): await session.upsert(key).bin("s").str_append("!").execute()
- Return type:
- transaction(behavior=None)¶
Open a transactional session for a multi-record transaction (MRT).
Operations run inside the returned context manager use behavior (or
DEFAULTwhen omitted) and auto-participate in a freshTxn, committed on clean exit and aborted if an exception propagates. Requires a strong-consistency (SC) namespace.- Parameters:
behavior (
Optional[Behavior]) – Policy bundle for operations inside the transaction. Defaults toBehavior.DEFAULT.- Return type:
TypeVar(_TS)- Returns:
The tree’s transactional session, bound to this cluster’s client.
Example:
with cluster.transaction() as tx: tx.upsert(accounts.id("A")).bin("balance").set_to(100).execute()
See also
create_session(): Non-transactional session.