Coordination
Threads in one process coordinate with threading and queue. clusterio has the same objects for threads anywhere in the cluster, with the same methods and exceptions:
| In one process | Across the cluster |
|---|---|
threading.Lock() | clusterio.lock("name", ttl=10) |
threading.BoundedSemaphore(10) | clusterio.semaphore("name", 10, ttl=10) |
threading.Event() | clusterio.event("name") |
threading.Barrier(5) | clusterio.barrier("name", 5) |
queue.Queue(maxsize) | clusterio.queue("name", maxsize) |
set() | clusterio.set("name") |
Each is named, as clusterio.dict is: every node that asks for clusterio.queue("jobs") gets the same queue. Each change is one transaction, so every node agrees on it, and a blocking call waits for this node to apply a change that may let it through, with no polling.
import clusterio
jobs = clusterio.queue("jobs")
jobs.put({"url": "https://example.com"})
print(jobs.get(timeout=5))
members = clusterio.set("members")
members.add("ada")
print("ada" in members, len(members))
ready = clusterio.event("ready")
ready.set()
print(ready.wait(timeout=1))Locks and semaphores#
A lock has one holder in the cluster at a time; a semaphore has at most value.
import clusterio
with clusterio.lock("scheduler"):
print("one scheduler, wherever it runs")
api = clusterio.semaphore("api", 10)
if api.acquire(timeout=5):
try:
print("one of at most ten calls in flight")
finally:
api.release()A node can die while it holds a permit, so a permit is a lease. While it is held, a thread renews it every ttl / 3 seconds. If the holder dies, or loses touch with the majority, the permit lapses after ttl seconds and another may take it.
Pick ttl longer than a pause your holder might take (a garbage collection, a slow disk), and much longer than the difference between the nodes' clocks: a lease's expiry is the time of the entry that granted it, and a holder decides it still holds the lease by its own clock.
A Lock or Semaphore object is one holder. Two clusterio.lock("x") objects in one process exclude each other, as two hosts do. Every user of a semaphore's name must give the same value; a different one raises ValueError. A lock and a semaphore of the same name are separate.
| Method | Meaning |
|---|---|
acquire(blocking=True, timeout=...) | Take a permit; False if none came in timeout seconds, or at once when not blocking |
release() | Give it back: RuntimeError for a lock not held, ValueError for a semaphore released too often |
locked() | A lock only: whether some holder holds it, as this node sees it |
with ...: | acquire(), then release() |
token | The fencing token of the permit this object holds, or None |
A lease guarantees one holder only as far as clocks and pauses allow: a holder paused longer than ttl wakes still believing it holds the lock. Two ways to be exact, whatever the clocks:
- When the work writes to clusterio, do the write in a transaction that checks the condition it depends on.
- When it writes elsewhere, send the lock's fencing token with each request. Tokens grow with every grant of the name, so the resource keeps the highest token it has seen and refuses lower ones: a holder whose lease lapsed has a lower token than the one that took over.
import clusterio
storage = {"token": 0, "value": None} # stands for a database or a service
def write(token, value):
if token < storage["token"]:
raise PermissionError("a newer holder has written")
storage.update(token=token, value=value)
with clusterio.lock("writer") as lock:
write(lock.token, "hello")
print(storage)Events#
set(), clear(), is_set() and wait(timeout=None), as threading.Event. wait returns as soon as this node applies the set.
Barriers#
clusterio.barrier(name, parties, timeout=None) releases its parties together once parties of them, on any nodes, have called wait(), which returns each its index, 0 to parties - 1. A party that times out breaks the barrier, and every waiting party gets clusterio.BrokenBarrierError, which is threading.BrokenBarrierError. reset(), abort(), n_waiting and broken are as in threading. A barrier can be used again once released.
import clusterio
start = clusterio.barrier("start", 1)
print(start.wait()) # 0: the only partyA party that dies while others wait leaves them waiting until their timeout, as a thread would; then the barrier breaks.
Queues#
clusterio.queue(name, maxsize=0) is a FIFO queue of JSON values. Each item goes to exactly one get, on whichever node. put, get, put_nowait, get_nowait, qsize, empty and full are those of queue.Queue, and raise queue.Empty and queue.Full. maxsize bounds the queue when positive; every user of a name must give the same one.
task_done and join are not there: a worker that dies holding an item cannot mark it done. For work that must survive a dying worker, record it in a transaction with the result.
Without a majority, put and get raise clusterio.Unavailable, as every write does, and as every write it may still be applied: a put that raised may have put its item, and a get that raised may have taken one that no caller receives. An item is never got twice.
Sets#
clusterio.set(name) is a collections.abc.MutableSet of JSON values, as set: add, discard, remove, pop, clear, update, in, len, iteration and the comparisons and operators, which give a builtin set. Elements are equal as Python counts them, so 1, 1.0 and True are one element. Each method is atomic; pop gives each element to one caller.
With asyncio#
clusterio.aio has the same types with the interfaces of asyncio: queue, lock, semaphore, event and barrier, and transaction, wait_for and sync, as coroutines. A waiting coroutine never blocks the event loop; it is woken when the node applies entries.
import asyncio
from clusterio import aio
async def main():
jobs = aio.queue("jobs")
await jobs.put({"n": 1})
print(await jobs.get())
async with aio.lock("scheduler"):
print("one scheduler")
asyncio.run(main())| In one process | Across the cluster |
|---|---|
asyncio.Queue(maxsize) | aio.queue("name", maxsize): raises asyncio.QueueEmpty and asyncio.QueueFull |
asyncio.Lock() | aio.lock("name", ttl=10) |
asyncio.BoundedSemaphore(10) | aio.semaphore("name", 10, ttl=10) |
asyncio.Event() | aio.event("name") |
asyncio.Barrier(5) | aio.barrier("name", 5) |
Cancelling is safe: a get cancelled after it took an item puts the item back at the front, and an acquire cancelled after it took a permit gives it back. A barrier party cancelled while it waits breaks the barrier. A put or a transaction already sent may still be applied, as after Unavailable. For another node than the default, use Cluster.aio, as in cluster.aio.queue("jobs").
The writes that set(), release(), put_nowait() and get_nowait() make take about a millisecond, and block the loop meanwhile, as SQLite reads do for less.
Their state#
The state of each lives in dicts and lists whose names start with clusterio., which are reserved: a clusterio.queue("jobs") is not clusterio.list("jobs").