Examples
Each example is a plain Python module, started with clusterio run, and each runs in clusterio's tests, on one node and on three.
A key-value server#
An etcd-like store over HTTP: GET, PUT, DELETE, and compare-and-set with ?prev=. Run it on three hosts and any of them serves any key.
sh
$ PORT=8080 clusterio run examples/kv.py:serve
$ curl -X PUT localhost:8080/greeting -d hello
hello
$ curl -X PUT 'localhost:8080/greeting?prev=hello' -d hi
hi
$ curl -X PUT 'localhost:8080/greeting?prev=hello' -d hey # 409: it changed
hiexamples/kv.py
"""An etcd-like key-value store over HTTP.
clusterio run examples/kv.py:serve # PORT=8080 by default
curl -X PUT localhost:8080/greeting -d hello
curl localhost:8080/greeting
curl -X PUT 'localhost:8080/greeting?prev=hello' -d hi # compare-and-set: 409 if it changed
curl -X DELETE localhost:8080/greeting
"""
import os
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.parse import parse_qs, urlsplit
import clusterio
store = clusterio.dict("kv")
@clusterio.transaction
def compare_and_set(key, prev, value):
if store.get(key) != prev:
return False
store[key] = value
return True
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
key = urlsplit(self.path).path
if key in store:
self.reply(200, store[key])
else:
self.reply(404, "")
def do_PUT(self):
url = urlsplit(self.path)
value = self.rfile.read(int(self.headers.get("Content-Length", 0))).decode()
prev = parse_qs(url.query).get("prev")
if prev is None:
store[url.path] = value
self.reply(200, value)
elif compare_and_set(url.path, prev[0], value):
self.reply(200, value)
else:
self.reply(409, store.get(url.path, ""))
def do_DELETE(self):
self.reply(200, store.pop(urlsplit(self.path).path, ""))
def reply(self, status, body):
data = body.encode()
self.send_response(status)
self.send_header("Content-Length", str(len(data)))
self.end_headers()
self.wfile.write(data)
def log_message(self, *args):
pass
def serve():
ThreadingHTTPServer(("127.0.0.1", int(os.environ.get("PORT", 8080))), Handler).serve_forever()A work queue#
Producers put jobs on a shared queue; workers on any node get each job once.
sh
$ clusterio run examples/work_queue.py:produce
$ clusterio run examples/work_queue.py:workexamples/work_queue.py
"""A work queue: producers put jobs, workers on any node get each job once.
clusterio run examples/work_queue.py:produce
clusterio run examples/work_queue.py:work
"""
import queue
import clusterio
jobs = clusterio.queue("jobs")
results = clusterio.dict("results")
def produce(count=10):
for n in range(count):
jobs.put({"n": n})
def work(idle_exit=1.0):
while True:
try:
job = jobs.get(timeout=idle_exit)
except queue.Empty:
return
results[str(job["n"])] = job["n"] ** 2A cron scheduler#
Every node runs the scheduler, and each job runs once per period, on one node, whichever nodes are up. Each node tries to claim the jobs that are due; the claim is a transaction keyed by the job and its time slot, so exactly one claim wins.
sh
$ CLUSTERIO_NODE=a clusterio run examples/cron.py:main
a runs heartbeat
a runs reportexamples/cron.py
"""A cron scheduler: run on every node, and each job runs once per period, on one node.
clusterio run examples/cron.py:main
Each node wakes every second and tries to claim the jobs that are due. The
claim is a transaction, so for each job and period exactly one node wins,
whichever nodes are up.
"""
import os
import time
import clusterio
JOBS = {"heartbeat": 2, "report": 5} # name: period in seconds
@clusterio.transaction
def claim(job, period, node):
slot = int(clusterio.now() // period)
last = clusterio.dict("cron.last")
if last.get(job, -1) >= slot:
return False
last[job] = slot
clusterio.list("cron.runs").append({"job": job, "slot": slot, "node": node})
return True
def main(seconds=None):
node = os.environ.get("CLUSTERIO_NODE", "local")
seconds = seconds or float(os.environ.get("CRON_SECONDS", "inf"))
start = time.monotonic()
while time.monotonic() - start < seconds:
for job, period in JOBS.items():
if claim(job, period, node):
print(f"{node} runs {job}", flush=True)
time.sleep(1)More ideas#
- Leader election: hold
clusterio.lock("leader"); the holder does the work, and another takes over withinttlif it dies. - Service discovery: each service writes its address to
clusterio.dict("services")and renews a timestamp; readers skip stale ones. - Feature flags and configuration: a
dictevery host reads locally, at the cost of a SQLite query. - Rate limits and quotas: a transaction that counts requests per key and time slot.
- Exactly-once jobs: claim each job in a transaction before running it, as the cron scheduler does.