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:

python
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#

text
Cluster(node=None, peers=None, data=None, timeout=5.0)
ArgumentMeaning
nodeThis node's name; else CLUSTERIO_NODE, else local
peers{name: "host:port"} for every node; else CLUSTERIO_PEERS, else this node alone
dataDirectory for the database; else CLUSTERIO_DATA, else .clusterio/<node>
timeoutSeconds 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:

leaderThe 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.

python
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 False

In 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.