Embedding
Cluster is the node behind the module functions. Make one to choose the configuration in code, or to run more than one node in a process:
from clusterio import Cluster
with Cluster(node="a", peers={"a": "127.0.0.1:7001"}, data=".clusterio/a") as cluster:
users = cluster.dict("users")
users["ada"] = 1
print(dict(users), cluster.leader)peers lists every node, this one included, as CLUSTERIO_PEERS does. An argument left out falls back to its environment variable.
Cluster#
Cluster(node=None, peers=None, data=None, timeout=5.0)| Argument | Meaning |
|---|---|
node | This node's name; else CLUSTERIO_NODE, else local |
peers | {name: "host:port"} for every node; else CLUSTERIO_PEERS, else this node alone |
data | Directory for the database; else CLUSTERIO_DATA, else .clusterio/<node> |
timeout | Seconds a write waits for a majority before it raises Unavailable |
A Cluster starts its node in a background thread when it is made. It has the module's functions as methods (dict, list, open, listdir, remove, transaction, lock, now), and:
leader | The node this node follows, or None during an election |
close() | Stop the node; with Cluster(...) closes it on exit |
Transactions with a Cluster#
cluster.transaction(fn) makes a transaction that writes through that node. Inside the function, use the module functions: while a transaction runs, clusterio.dict and the rest read and write the state of the entry being applied, whichever node applies it.
import clusterio
from clusterio import Cluster
def claim(job_id, worker):
owners = clusterio.dict("owners") # the entry's state, on every node
if job_id in owners:
return False
owners[job_id] = worker
return True
with Cluster(node="a", peers={"a": "127.0.0.1:7002"}, data=".clusterio/a2") as cluster:
claim_on_a = cluster.transaction(claim)
print(claim_on_a("report", "a"), claim_on_a("report", "b")) # True FalseIn tests#
A one-node Cluster on a temporary directory is a fast, real cluster for unit tests; three in one process test failover. clusterio's own tests do both: see tests/test_cluster.py.