Higher Level Zookeeper Client providing distributed coordination and configuration management primitives.
—
Comprehensive exception hierarchy for handling all Zookeeper error conditions, including connection issues, node state conflicts, authentication failures, and protocol errors. Each exception includes appropriate error codes and context information for robust error handling.
Foundation exception classes providing the hierarchy for all Kazoo library errors with common error handling patterns and context information.
class KazooException(Exception):
"""Base exception for all Kazoo library exceptions."""
class ZookeeperError(KazooException):
"""
Base exception for errors originating from Zookeeper server.
Attributes:
- code (int): Zookeeper error code
"""
class CancelledError(KazooException):
"""Raised when a process is cancelled by another thread."""
class ConfigurationError(KazooException):
"""Raised if configuration arguments are invalid."""
class ZookeeperStoppedError(KazooException):
"""Raised when kazoo client is stopped during operation."""
class ConnectionDropped(KazooException):
"""Internal error for jumping out of connection loops."""
class LockTimeout(KazooException):
"""Raised if failed to acquire a lock within timeout."""
class WriterNotClosedException(KazooException):
"""Raised if writer unable to close when requested."""
class SASLException(KazooException):
"""Raised if SASL encountered a local error."""Errors related to network connectivity, session management, and client-server communication with specific handling for different failure scenarios.
class ConnectionLoss(ZookeeperError):
"""
Connection to server lost (code: -4).
Raised when network connection is interrupted or server becomes
unreachable. Operations may be retried after reconnection.
"""
class SessionExpiredError(ZookeeperError):
"""
Session expired (code: -112).
Raised when Zookeeper session expires due to timeout or network
issues. Client must reconnect and re-establish watches and ephemeral nodes.
"""
class SessionMovedError(ZookeeperError):
"""
Session moved to another server (code: -118).
Raised when session is transferred between servers in the ensemble.
"""
class ConnectionClosedError(ZookeeperError):
"""
Connection is closed.
Raised when attempting operations on a closed client connection.
"""
class OperationTimeoutError(ZookeeperError):
"""
Operation timed out (code: -7).
Raised when operation exceeds configured timeout period.
"""Errors specific to node CRUD operations including existence conflicts, version mismatches, and hierarchy violations.
class NoNodeError(ZookeeperError):
"""
Node does not exist (code: -101).
Raised when attempting operations on non-existent nodes.
"""
class NodeExistsError(ZookeeperError):
"""
Node already exists (code: -110).
Raised when creating a node that already exists without
using sequence or overwrite options.
"""
class BadVersionError(ZookeeperError):
"""
Version conflict (code: -103).
Raised when node version doesn't match expected version
in conditional operations.
"""
class NotEmptyError(ZookeeperError):
"""
Node has children (code: -111).
Raised when attempting to delete a node that has children
without using recursive deletion.
"""
class NoChildrenForEphemeralsError(ZookeeperError):
"""
Ephemeral nodes cannot have children (code: -108).
Raised when attempting to create children under ephemeral nodes.
"""Security-related errors covering authentication failures, authorization denials, and ACL violations with detailed error context.
class AuthFailedError(ZookeeperError):
"""
Authentication failed (code: -115).
Raised when authentication credentials are invalid or
authentication scheme is not supported.
"""
class NoAuthError(ZookeeperError):
"""
Not authenticated (code: -102).
Raised when attempting operations requiring authentication
without proper credentials.
"""
class InvalidACLError(ZookeeperError):
"""
Invalid ACL (code: -114).
Raised when ACL format is invalid or contains unsupported
permissions or schemes.
"""Low-level protocol errors and system-level failures including serialization issues, implementation errors, and server-side problems.
class SystemZookeeperError(ZookeeperError):
"""
System error in Zookeeper (code: -1).
Raised for internal Zookeeper server errors.
"""
class RuntimeInconsistency(ZookeeperError):
"""
Runtime inconsistency detected (code: -2).
Raised when Zookeeper detects internal inconsistencies.
"""
class DataInconsistency(ZookeeperError):
"""
Data inconsistency detected (code: -3).
Raised when data corruption or inconsistency is detected.
"""
class MarshallingError(ZookeeperError):
"""
Error marshalling/unmarshalling data (code: -5).
Raised when serialization or deserialization fails.
"""
class UnimplementedError(ZookeeperError):
"""
Unimplemented operation (code: -6).
Raised when attempting unsupported operations.
"""
class BadArgumentsError(ZookeeperError):
"""
Invalid arguments provided (code: -8).
Raised when operation parameters are invalid.
"""
class APIError(ZookeeperError):
"""
General API error (code: -100).
Raised for general API usage errors.
"""
class InvalidCallbackError(ZookeeperError):
"""
Invalid callback (code: -113).
Raised when callback function is invalid or malformed.
"""Errors related to atomic transactions, ensemble reconfiguration, and advanced Zookeeper operations with specific error handling requirements.
class RolledBackError(ZookeeperError):
"""
Transaction rolled back (code: 0).
Raised when atomic transaction fails and all operations
are rolled back. Contains details of failed operations.
"""
class NewConfigNoQuorumError(ZookeeperError):
"""
New config has no quorum (code: -13).
Raised during ensemble reconfiguration when new configuration
cannot establish quorum.
"""
class ReconfigInProcessError(ZookeeperError):
"""
Reconfiguration in process (code: -14).
Raised when attempting reconfiguration while another
reconfiguration is already in progress.
"""
class NotReadOnlyCallError(ZookeeperError):
"""
Not a read-only call (code: -119).
Raised when attempting write operations on read-only connections.
"""
class QuotaExceededError(ZookeeperError):
"""
Quota exceeded (code: -125).
Raised when operation would exceed configured quotas.
"""Errors specific to different async handler implementations including timeout handling and concurrency management.
class KazooTimeoutError(Exception):
"""
Timeout exception for threading handler.
Raised when operations timeout in threading-based handlers.
"""
class TimeoutError(Exception):
"""
Timeout exception for eventlet handler.
Raised when operations timeout in eventlet-based handlers.
"""Utility for mapping Zookeeper error codes to appropriate exception classes with comprehensive coverage of all protocol errors.
# Error code constants
EXCEPTIONS = {
0: RolledBackError,
-1: SystemZookeeperError,
-2: RuntimeInconsistency,
-3: DataInconsistency,
-4: ConnectionLoss,
-5: MarshallingError,
-6: UnimplementedError,
-7: OperationTimeoutError,
-8: BadArgumentsError,
-13: NewConfigNoQuorumError,
-14: ReconfigInProcessError,
-100: APIError,
-101: NoNodeError,
-102: NoAuthError,
-103: BadVersionError,
-108: NoChildrenForEphemeralsError,
-110: NodeExistsError,
-111: NotEmptyError,
-112: SessionExpiredError,
-113: InvalidCallbackError,
-114: InvalidACLError,
-115: AuthFailedError,
-118: SessionMovedError,
-119: NotReadOnlyCallError,
-125: QuotaExceededError
}The following exceptions are available from kazoo.retry module for handling retry logic:
from kazoo.retry import ForceRetryError, RetryFailedError, InterruptedError
class ForceRetryError(Exception):
"""Raised when recipe logic wants to force a retry."""
class RetryFailedError(KazooException):
"""Raised when retrying ultimately failed."""
class InterruptedError(RetryFailedError):
"""Raised when retry is forcibly interrupted."""from kazoo.client import KazooClient
from kazoo.exceptions import (
NoNodeError, NodeExistsError, ConnectionLoss,
SessionExpiredError, AuthFailedError
)
zk = KazooClient()
try:
zk.start(timeout=10)
# Handle node existence
try:
data, stat = zk.get("/nonexistent")
except NoNodeError:
print("Node does not exist, creating it...")
zk.create("/nonexistent", b"data", makepath=True)
# Handle node creation conflicts
try:
zk.create("/existing", b"data")
except NodeExistsError:
print("Node already exists, updating instead...")
zk.set("/existing", b"new data")
except ConnectionLoss:
print("Connection lost, retrying...")
# Implement retry logic
except SessionExpiredError:
print("Session expired, reconnecting...")
zk.restart()
except AuthFailedError:
print("Authentication failed, check credentials")
finally:
if zk.connected:
zk.stop()from kazoo.client import KazooClient
from kazoo.exceptions import RolledBackError, BadVersionError
zk = KazooClient()
zk.start()
try:
# Create transaction with error handling
transaction = zk.transaction()
transaction.create("/app/counter", b"0")
transaction.create("/app/status", b"active")
transaction.check("/app", version=0)
try:
results = transaction.commit()
print("Transaction successful")
except RolledBackError as e:
print(f"Transaction failed: {e}")
# Handle rollback - examine which operations failed
except BadVersionError:
print("Version mismatch in transaction")
# Handle version conflicts
finally:
zk.stop()from kazoo.client import KazooClient
from kazoo.protocol.states import KazooState
from kazoo.exceptions import ConnectionLoss, SessionExpiredError
def connection_listener(state):
if state == KazooState.LOST:
print("Connection lost!")
elif state == KazooState.SUSPENDED:
print("Connection suspended")
elif state == KazooState.CONNECTED:
print("Connected to Zookeeper")
zk = KazooClient()
zk.add_listener(connection_listener)
try:
zk.start()
# Monitor for connection issues during operations
while True:
try:
# Perform operations
data, stat = zk.get("/some/path")
# Process data
except ConnectionLoss:
print("Connection lost during operation")
# Wait for reconnection or retry
zk.retry(lambda: zk.get("/some/path"))
except SessionExpiredError:
print("Session expired, restarting client")
zk.restart()
# Re-establish watches and ephemeral nodes
except KeyboardInterrupt:
print("Shutting down...")
finally:
zk.stop()from kazoo.client import KazooClient
from kazoo.retry import KazooRetry
from kazoo.exceptions import ConnectionLoss, OperationTimeoutError
import time
zk = KazooClient()
zk.start()
# Create retry policy
retry = KazooRetry(max_tries=3, delay=1, backoff=2)
def safe_operation():
"""Operation with comprehensive error handling."""
try:
# Attempt operation with retry
result = retry(zk.get, "/important/data")
return result
except ConnectionLoss:
print("Connection issues, operation failed after retries")
return None
except OperationTimeoutError:
print("Operation timed out after retries")
return None
except Exception as e:
print(f"Unexpected error: {type(e).__name__}: {e}")
return None
try:
result = safe_operation()
if result:
data, stat = result
print(f"Got data: {data}")
else:
print("Operation failed")
finally:
zk.stop()Install with Tessl CLI
npx tessl i tessl/pypi-kazoo