Tooz Coordination Library

8.1.0 · active · verified Fri Apr 17

Tooz is a Python library designed to provide distributed systems primitives such as group membership, leader election, distributed locking, and distributed messaging. It offers a unified API over various backend drivers like Redis, ZooKeeper, and Etcd. Currently at version 8.1.0, it is actively maintained as part of the OpenStack ecosystem with regular updates.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize a `tooz` driver using `DriverFactory` and acquire a distributed lock. It uses a file-based driver by default for easy local testing, but can be configured with a `TOOZ_BACKEND` environment variable for real backends like Redis or Zookeeper. The example shows how to acquire a lock with a timeout and ensures proper cleanup.

import os
import time
from tooz.drivers import DriverFactory

# Use a file-based driver for local testing or set an environment variable for a real backend
# e.g., export TOOZ_BACKEND="redis://localhost:6379/0" (for Redis DB 0)
# e.g., export TOOZ_BACKEND="zookeeper://localhost:2181"
connection_string = os.environ.get("TOOZ_BACKEND", "file:///tmp/tooz_locks_example")

# Group ID for coordination primitives, must be bytes
group_id = b"my_application_group"

driver = None
try:
    # Initialize the driver factory. This will select the appropriate driver
    # based on the connection string prefix (e.g., 'redis://', 'file://').
    driver = DriverFactory(connection_string, group_id)
    print(f"Connected to tooz backend: {connection_string}")

    # Example: Acquire a distributed lock
    lock_name = b"my_critical_section"
    
    # `timeout` specifies how long to wait to acquire the lock.
    # `heartbeat_timeout` specifies how often to renew the lock if acquired.
    lock = driver.get_lock(lock_name, timeout=5, heartbeat_timeout=1)

    print(f"Attempting to acquire lock '{lock_name.decode()}'...")
    if lock.acquire():
        print("Lock acquired successfully! Performing critical work...")
        # Simulate some work
        time.sleep(2)
        print("Work done, releasing lock.")
        # Lock is automatically released by the 'finally' block when driver disconnects
        # or can be explicitly released with lock.release()
    else:
        print("Could not acquire lock within timeout.")

finally:
    if driver:
        # Ensure the driver is disconnected to release resources and locks.
        driver.disconnect()
        print("Disconnected from tooz backend.")

view raw JSON →