We are going to design a distributed locking service that provides:
Leader election: Multiple nodes can compete to become the leader. Only one leader at a time.
Lock acquisition with lease renewal: The leader must renew its lease periodically to maintain leadership.
Fencing tokens: When a new leader is elected, it gets a fencing token (monotonically increasing) that can be used to fence off old leaders.
We'll assume we have a distributed consensus system (like Raft) or a shared storage system (like ZooKeeper) to coordinate.
However, for the sake of this design, we'll abstract the coordination mechanism and focus on the algorithm.
Steps:
Leader Election:
We can use a consensus algorithm to elect a leader. Alternatively, we can use a shared storage with compare-and-set (CAS).
Let's assume we have a shared storage that supports atomic operations (like a key-value store with atomic increment and compare-and-set).
We can have a key called "leader" that stores the current leader's ID and a lease expiration time (or a sequence number for fencing).
However, to avoid split-brain, we need to ensure that only one leader can hold the lease at a time.
Approach with lease and fencing token:
We can have two keys:
"lock": stores the current leader's node ID and the lease expiration time (or a sequence number for fencing token).
"fencing_token": a counter that increases every time a new leader is elected.
But we want to combine: when a node becomes leader, it gets a fencing token (which is a monotonically increasing number) and sets the lock with that token and an expiration time.
Alternatively, we can have one key that stores:
{ "leader_id": "node1", "fencing_token": 123, "expiration": 1678900000 }
How to elect:
Each node tries to atomically set the key if it doesn't exist or if the current expiration is in the past.
But we also need to generate a new fencing token. We can have a separate counter for fencing tokens.
However, if we use a shared storage that supports atomic increment, we can do:
Step 1: Atomically increment a counter (to get a new fencing token) and then try to set the lock with that token and a new expiration (current time + lease duration).
But we want to do it atomically: we want to get a new token and set the lock only if the lock is free (or expired). We can use a transaction.
Alternatively, we can have:
We have a key "fencing_token_counter" that we atomically increment to get a new token.
Then we try to set the lock key with a condition: either the lock does not exist, or the lock's expiration is in the past.
But there is a race: after we get the token, someone else might set the lock.
So we need to do:
Option 1: Use a compare-and-set (CAS) on the lock key, and if we succeed, we set the token and expiration.
However, if we do CAS and it fails, we have a token that we didn't use. That's okay because we can just discard it? But then the fencing token counter will increase even if we fail.
Alternatively, we can have a two-phase commit: but that's complex.
Option 2: Use a consensus algorithm (like Raft) to elect a leader and assign a term (which can be the fencing token). Then we don't need a separate counter.
Since the problem asks for an abstraction, let's assume we have a way to do atomic operations and we want to minimize the complexity.
Let's design with a shared storage that supports:
atomic increment of a counter (returns the new value)
compare-and-set (CAS) on a key: set the key to a new value only if the current value matches an expected old value.
Steps for leader election:
Let the lock key be "lock". The value is a structure: { leader_id, fencing_token, expiration }
We also have a separate key "fencing_token_counter" that we use to generate new tokens.
Algorithm for a node that wants to become leader:
code
while true:
current_time = now()
# Read the current lock
current_lock = read("lock")
if current_lock is None or current_lock.expiration < current_time:
# The lock is free or expired, try to acquire
new_token = atomic_increment("fencing_token_counter")
new_lock = { leader_id: my_id, fencing_token: new_token, expiration: current_time + lease_duration }
# Try to set the lock with CAS: only if the current_lock is still the same as we read (or None if we read None)
success = CAS("lock", current_lock, new_lock)
if success:
return new_token # We are the leader with token=new_token
else:
# Someone else set the lock, we loop again
continue
else:
# The lock is held by someone else and not expired, we wait and try again
sleep(random_time)
continue
However, note: when we read the lock and then try to CAS, the lock might have been taken by someone else in between. But that's why we use CAS.
But what if the lock we read was expired? We read it, then before we CAS, someone else might have taken it? Then our CAS would fail because the value changed.
So we are safe.
But there's a problem: if two nodes read the lock at the same time (expired) and both try to CAS, one will succeed and the other will fail. The one that fails will loop.
This is acceptable.
Lease Renewal:
The leader must periodically renew its lease to avoid being overthrown.
The leader knows its own fencing_token. When renewing, it must update the expiration time of the lock, but only if the lock's fencing_token is still the same (to prevent a rogue leader from renewing after being ousted).
Renewal algorithm:
while leader:
current_time = now()
current_lock = read("lock")
if current_lock.leader_id != my_id or current_lock.fencing_token != my_token:
# We are not the leader anymore (maybe someone took over with a higher token)
step_down()
break
if current_lock.expiration < current_time + safe_margin:
# We need to renew
new_lock = { leader_id: my_id, fencing_token: my_token, expiration: current_time + lease_duration }
success = CAS("lock", current_lock, new_lock)
if not success:
# We lost the lock, step down
step_down()
break
sleep(renewal_interval)
We set the renewal_interval to be less than the lease_duration, and we set a safe_margin to account for network delays.
Fencing tokens:
The fencing token is a monotonically increasing number. When a new leader is elected, it gets a higher token than the previous leader.
How do we use the fencing token?
The leader can use the fencing token to fence off old leaders in the system. For example, if we have a shared resource that the leader is managing (like a database), we can use the fencing token to reject requests from old leaders.
The idea:
When the leader wants to perform an operation on the shared resource, it must present its current fencing token.
The shared resource (or a proxy) will keep track of the highest fencing token it has seen.
Any request with a fencing token lower than the highest seen is rejected.
Alternatively, the shared resource can store the highest fencing token it has accepted and reject any request with a token lower than that.
But note: the leader's token is stored in the distributed lock service. How does the shared resource know the current token?
We can have the leader pass its token to the shared resource. But the shared resource might be separate and not have access to the lock service.
We can have a two-phase commit:
Phase 1: The leader asks the lock service for the current fencing token (but that's just the one it has) and then tells the shared resource to update its fencing token to that value.
But the shared resource might be updated by a previous leader that is still around (network partition). We want to avoid that.
Alternatively, we can have the shared resource read the lock from the lock service? But that would be a lot of traffic.
Another idea: the lock service can push the fencing token to the shared resource? But that couples them.
Let's think: the purpose of fencing is to prevent old leaders from making changes. So the shared resource must know what the current fencing token is.
We can have:
The lock service, when electing a new leader, writes the new fencing token to a separate key that the shared resource can read.
But then the shared resource has to poll? Not good.
Alternatively, we can have the leader, when it acquires the lock, also write the fencing token to the shared resource. But then an old leader might write an old token? No, because the old leader doesn't have the lock.
Actually, the fencing token is only written by the current leader (when it renews). But the shared resource might not see the latest token if it's updated by the leader only during operations.
We need the shared resource to know the current fencing token at all times. So we can have:
The leader, when it renews the lease, also updates the fencing token in the shared resource.
But then we have two writes: lock service and shared resource. What if one fails?
Core Architecture
python
Protected Resource Example
python
class FencedResource:
"""
Example resource that uses fencing tokens for safety.
Any resource that needs protection should implement similar pattern.
"""
def __init__(self, resource_name: str, lock_manager: LockManager):
self.resource_name = resource_name
self.lock_manager = lock_manager
self._current_token: Optional[int] = None
self._operation_count = 0
def protected_operation(self, fencing_token: int, operation_func, *args, **kwargs):
"""
Execute operation with fencing token validation.
Raises FencingViolationError if token is stale.
"""
# Validate token against current lock state
if not self.lock_manager.validate_fencing_token(
self.resource_name, fencing_token, "write"
):
raise FencingViolationError(
f"Stale fencing token {fencing_token} for resource {self.resource_name}"
)
# Token is valid, execute operation
self._current_token = fencing_token
try:
result = operation_func(*args, **kwargs)
self._operation_count += 1
return result
finally:
self._current_token = None
def read_operation(self, fencing_token: int, operation_func, *args, **kwargs):
"""Read operation with optional token validation (can be relaxed for reads)"""
# For reads, we might skip token validation depending on consistency needs
# But for linearizable reads, validate token
if not self.lock_manager.validate_fencing_token(
self.resource_name, fencing_token, "read"
):
raise FencingViolationError(
f"Stale fencing token {fencing_token} for read on {self.resource_name}"
)
return operation_func(*args, **kwargs)
class FencingViolationError(Exception):
"""Raised when fencing token validation fails"""
pass
Leader Election: Uses Raft consensus for strong consistency. Only the leader can propose lock changes.
Lease-Based Locking:
Locks have automatic expiration (lease_duration)
Leader must renew before expiration
Automatic renewal thread runs at renewal_interval
Fencing Tokens:
Monotonically increasing (using Raft log index)
Included in every lock state transition
Resources validate tokens before operations
Higher tokens always win (newer leader)
Safety Guarantees:
Linearizable operations: Through Raft consensus
No split-brain: Only Raft leader can modify lock state
Fencing: Stale leaders rejected by resources
Session safety: Same session can renew, but different session requires new token
Failure Handling:
Lease expiration automatically releases locks
Renewal failures cause immediate release
Network partitions resolved by Raft leader election
Client crashes → lease expires → lock available
Performance:
Renewals are cheap (single Raft proposal)
Tokens cached locally (no network call for validation)
Background renewal thread
Production Considerations
Clock Synchronization: Lease durations assume loosely synchronized clocks (NTP). Consider using hybrid logical clocks or Raft time for critical systems.
Raft Integration: The raft_node.propose() must be linearizable. In real implementations:
Use Raft's leadership_transfer for平滑过渡
Implement snapshotting for log compaction
Add metrics and monitoring
Resource Implementation: All shared resources must:
Validate fencing tokens before state changes
Never trust client-provided tokens alone
Cache current token with timestamp
Implement idempotent operations
Scalability:
Lock granularity (fine-grained vs coarse)
Lock sharding for high contention
Read-only operations can bypass validation with weaker consistency
Observability:
Track lock acquisition latency
Monitor renewal success rates
Alert on frequent leader changes
Track fencing violations (indicates split-brain or network issues)
This design provides a robust foundation for distributed locking with strong safety guarantees through the combination of consensus-based state management and fencing tokens.
We can make the shared resource update idempotent and eventually consistent.
However, for strong fencing, we want the shared resource to reject any operation that doesn't have the current fencing token.
How about:
The shared resource stores the highest fencing token it has ever seen. When the leader wants to perform an operation, it must provide a fencing token that is >= the stored token. If it's higher, the shared resource updates its stored token.
But then an old leader (with an old token) might try to do an operation and the shared resource will reject because its token is higher.
However, if the old leader has a token that is higher (because it was the leader before and then lost, but then the new leader hasn't updated the shared resource yet) then the old leader could do an operation.
To avoid that, we need the shared resource to be updated immediately when a new leader is elected.
So we can have:
The leader, upon acquiring the lock (with a new token), must update the shared resource's fencing token to the new token.
And then, when the leader performs an operation, it uses that token. The shared resource will only accept operations with the current token (or higher, but higher only if the leader is newer? Actually, the token is monotonically increasing, so if the token is higher than the one stored, it means it's a newer leader).
But what if the leader fails to update the shared resource? Then the shared resource still has the old token and the old leader (if it's still around) could do operations? But the old leader's token is old, so it would be rejected because the shared resource has a higher token (from the new leader that didn't update the shared resource?).
Wait, if the new leader fails to update the shared resource, then the shared resource still has the old token (from the previous leader). Then the new leader, when it tries to do an operation, will have a higher token (because it's a new token) and the shared resource will update its token and accept the operation.
But the old leader might try to do an operation with its old token and the shared resource will reject because the old token is less than the new token (if the new leader has updated the shared resource). But if the new leader hasn't updated, then the old token might be accepted? That's a problem.
So we need to make sure that when a new leader is elected, it immediately updates the shared resource's fencing token.
But if that update fails, the new leader should not consider itself the leader? Or at least, it should not perform operations until it updates the fencing token.
We can make the leader election depend on updating the shared resource? But then we are coupling the lock service and the shared resource.
Alternatively, we can have the shared resource be part of the lock service? That is, the lock service also manages the fencing token for the shared resource.
But the problem says "distributed locking abstraction", so we are building a locking service that can be used by any resource.
So the locking service should not update the shared resource. Instead, the leader (the client of the locking service) is responsible for updating the shared resource.
And the shared resource must be designed to use fencing tokens.
How about:
The locking service provides:
- acquire_lock() -> returns a lock object that contains: leader_id, fencing_token, and a renew() method.
- renew_lock() -> renews the lease and returns the current fencing_token (might be the same or might change? Actually, the token doesn't change on renew, only the expiration. But if we lose and reacquire, we get a new token.)
The leader, when it acquires the lock, gets a fencing_token. Then, before performing any operation on the shared resource, it must:
code
1. Check that it still holds the lock (by trying to renew? but that might be heavy). Alternatively, it can assume it's the leader until it fails to renew.
2. When performing an operation on the shared resource, it must send the fencing_token.
The shared resource must:
code
- Store the highest fencing_token it has ever accepted.
- When receiving an operation with a token:
if token < stored_token: reject
else: accept and if token > stored_token, update stored_token to token.
But what if the leader is renewed and the token doesn't change? Then the shared resource already has that token, so it's fine.
However, if a new leader is elected (with a new token) and it hasn't updated the shared resource yet, then the old leader (with old token) might try to do an operation and the shared resource will reject because the old token is less than the new token that the shared resource has? Not necessarily, because the shared resource hasn't seen the new token.
Wait, the shared resource only updates its stored token when it sees a higher token. So if the old leader tries with an old token and the shared resource has the old token, it will accept. But we don't want that.
So we need the new leader to update the shared resource as soon as it gets the lock.
But what if the new leader fails to update the shared resource? Then the shared resource still has the old token, and the old leader (if it's still around) can do operations.
That's a problem.
To solve this, we need to make the update of the shared resource's fencing token part of the lock acquisition. But then we are coupling.
Alternatively, we can have the shared resource read the lock from the lock service every time? That would be heavy.
Another idea: the lock service can have a separate key for the shared resource's fencing token, and the leader must update that key when it acquires the lock. But then the lock service is coupled to the shared resource.
Since the problem says "abstraction", we can design the locking service to support fencing tokens, and then the client (the shared resource) must use the fencing token provided by the lock service.
But the client must be able to get the current fencing token from the lock service. We can have:
The lock service exposes an endpoint to get the current lock (which includes the fencing_token). Then the shared resource, when it receives an operation, can check the current lock's fencing_token? But that would require a read from the lock service for every operation.
That might be too heavy.
Alternatively, the leader can cache the fencing token and the shared resource can be told by the leader what the current token is. But then the shared resource must trust the leader? No, the shared resource must not trust the leader, it must verify with the lock service.
So the shared resource must have a way to get the current fencing token from the lock service.
We can have:
The lock service stores the current fencing token in a well-known key (e.g., "current_fencing_token"). The shared resource reads that key.
Then:
When the leader acquires the lock, it updates the "current_fencing_token" key to its token.
The shared resource, when it receives an operation, reads the "current_fencing_token" and compares it with the token provided by the leader.
But then the leader must update the shared resource's fencing token key as part of lock acquisition? And then the shared resource will read that key.
However, the shared resource might read an old token if the leader hasn't updated? But the leader updates the token as soon as it gets the lock.
But what if the leader gets the lock and then crashes before updating the shared resource's token? Then the shared resource still has the old token, and the old leader (if it's still around) can do operations.
That's a problem.
We need to make the update of the shared resource's fencing token and the lock acquisition atomic? But they are in different systems.
This is a classic problem in distributed systems.
One solution is to have the shared resource be the lock service? That is, the lock is stored in the shared resource. Then the shared resource knows the current token.
But the problem says "distributed locking abstraction", so we are building a locking service that can be used by multiple resources.
Alternatively, we can use a consensus algorithm to store the lock and the shared resource's fencing token in the same log? But then the shared resource is coupled to the lock service.
Since the problem is about an abstraction, we can assume that the shared resource is designed to use the locking service and must be updated by the leader.
And we accept that there is a small window where the old leader can still operate if the new leader fails to update the shared resource.
But we can try to minimize that window by having the leader update the shared resource's fencing token immediately after acquiring the lock.
And if the leader fails to update, then it should step down because it cannot safely operate.
So in the leader election algorithm, after acquiring the lock, the leader must update the shared resource's fencing token. If that update fails, the leader should not consider itself the leader and should release the lock? But it already holds the lock? We can have the leader try to update the shared resource and if it fails, it tries to release the lock? But then someone else can take the lock.
Alternatively, we can have the lock acquisition and the shared resource update in a two-phase commit:
Phase 1: Acquire the lock (with CAS) and get the token.
Phase 2: Update the shared resource's token.
If phase 2 fails, then we release the lock (by setting the lock's expiration to now? but we don't want to release if we are the leader). Actually, we can set the lock's expiration to now+lease_duration? But then we are still the leader until the lease expires.
This is getting messy.
Given the complexity, let's assume that the shared resource is designed to read the current fencing token from the lock service (by reading the lock key) and the leader does not update a separate key.
Then:
The shared resource, when it receives an operation with a token, reads the current lock from the lock service and checks:
code
if current_lock.fencing_token > provided_token: reject
else: accept
But note: the current_lock might have been taken by a new leader with a higher token, so the provided_token (from the old leader) will be lower and rejected.
However, if the current_lock is held by the same leader (same token) then it's accepted.
But what if the current_lock is expired? Then the current_lock might be None or expired. Then we would accept any token? That's not safe.
So the shared resource must also check that the current_lock is held by the leader that provided the token? But we don't know the leader_id? We only have the token.
Actually, the token is unique per leader election. So if the token is the same, then it's the same leader.
But if the lock is expired, then there is no leader. Then we should reject all operations? Because there is no current leader.
But then how does a new leader acquire the lock and then perform operations? The new leader will have a new token, and when it tries to operate, the shared resource will see that the current lock is expired (so no current leader) and then what? We can't accept because we don't have a current leader.
We can have the shared resource accept operations from a leader only if the current lock's token matches the provided token. But if the lock is expired, then the current lock might be None, so we reject.
But then the new leader, after acquiring the lock, will have a token, but the shared resource will see the current lock (which is held by the new leader) and the token will match, so it will accept.
However, there is a race: the new leader acquires the lock and then immediately tries to operate. The shared resource might not have seen the new lock yet (because of replication delay). Then it might see the old lock (expired) and reject.
So we need the shared resource to read the lock with linearizability? That is, it must read the latest value.
This is getting into the consistency model.
Given the complexity, let's simplify:
We assume that the lock service provides linearizable reads. So when the shared resource reads the lock, it gets the latest value.
Then:
The shared resource, for each operation:
code
token_provided = ... from the leader
current_lock = read_lock() # linearizable read
if current_lock is None or current_lock.expiration < now():
reject (because there is no current leader)
if current_lock.fencing_token != token_provided:
reject (because the token doesn't match the current leader)
else:
accept
But note: the leader might have renewed the lock and the token hasn't changed, so it's the same.
However, what if the leader lost the lock and a new leader with a new token acquired? Then the current_lock.fencing_token will be the new token, and the old leader's token will be rejected.
This seems safe.
But what about the leader that just acquired the lock? It will have a new token. When it tries to operate, the shared resource will read the lock and see the new token and accept.
However, if the shared resource reads the lock before the leader's write has been replicated? Then it might see the old lock (expired) and reject. But the leader just acquired, so the lock should be there.
We need the lock write to be linearizable and the read to be linearizable. Then it should be safe.
So the design:
Lock service:
- Provides a lock key (with leader_id, fencing_token, expiration)
- Provides a way to atomically increment a fencing_token_counter (but we don't need that if we use the token from the lock? Actually, we need to generate a new token when we acquire the lock. We can use the atomic increment on the lock key? Not directly.
We can change the lock acquisition to:
code
We have a separate key for the fencing token counter? Or we can use the lock's token as the counter? But we need to generate a new token that is higher than any previous.
We can store the highest fencing token ever used in a key, and then when we acquire, we read that key, set the new token to that+1, and then CAS the lock with the new token? But then we have to update the highest token key? That's two writes.
Alternatively, we can use the atomic increment on the lock key? But the lock key is a structure.
We can have:
code
Let the lock key be a number that represents the fencing token? And then we store the leader_id and expiration in a separate key? Not good.
We can have:
code
We have a key "fencing_token" that is a number. We atomically increment it to get a new token. Then we try to set the lock with that token.
But then we have to store the token in the lock key as well? We can have:
code
Lock key: { leader_id, expiration } and then the fencing token is stored in a separate key? Then we have to update two keys atomically? That's hard.
Alternatively, we can combine: the lock key is a structure that includes the fencing token, and we generate the fencing token by atomically incrementing a separate counter.
while true:
current_time = now()
current_lock = read("lock")
if current_lock is None or current_lock.expiration < current_time:
new_token = atomic_increment("fencing_token_counter")
new_lock = { leader_id: my_id, fencing_token: new_token, expiration: current_time + lease_duration }
if CAS("lock", current_lock, new_lock):
return new_token
sleep(random)
Steps for renewal:
while leader:
current_time = now()
current_lock = read("lock")
if current_lock.leader_id != my_id or current_lock.fencing_token != my_token:
step_down()
break
if current_lock.expiration < current_time + safe_margin:
new_lock = { leader_id: my_id, fencing_token: my_token, expiration: current_time + lease_duration }
if not CAS("lock", current_lock, new_lock):
step_down()
break
sleep(renewal_interval)
Steps for the shared resource:
For each operation:
code
token_provided = from the leader (the leader must provide the token it got from the lock service)
current_lock = read("lock") # linearizable read
if current_lock is None or current_lock.expiration < now():
reject (no current leader)
if current_lock.fencing_token != token_provided:
reject (token doesn't match current leader)
else:
accept and perform operation
But note: the leader might have renewed and the token is the same, so it's okay.
However, what if the leader is in the middle of renewing and the shared resource reads the lock during that? The leader's token is still the same, so it's okay.
What if the leader loses the lock and a new leader with a new token acquires? Then the shared resource will see the new token and reject the old leader's operations.
This seems safe.
But what about the leader that just acquired the lock? It will have a new token. When it tries to operate, the shared resource will read the lock and see the new token and accept.
However, there is a window: the leader acquires the lock and then the shared resource might still see the old lock (if the read is not linearizable). But we assume linearizability.
If we don't have linearizable reads, then we have a problem.
So we assume the lock service provides linearizable reads.
Alternatively, we can have the leader write the token to a separate key that the shared resource reads, and we make that read linearizable. But then we have to update that key on every renewal? Not necessary because the token doesn't change on renewal.
Actually, the token only changes when a new leader is elected. So we can have:
The leader, upon acquiring the lock, writes the token to a key called "current_fencing_token". Then the shared resource reads that key.
But then we have to update that key on every acquisition? And what about renewal? The token doesn't change, so we don't need to update.
But if the leader fails to update "current_fencing_token", then the shared resource still has the old token.
And then the new leader (with new token) will try to operate and the shared resource will reject because the token is old? Actually, the new leader will have a new token, and if the shared resource has the old token, then the new leader's token is higher and the shared resource will update its stored token? In the shared resource logic above, we compare the provided token with the current lock's token. But if we use a separate key, then we are comparing with the "current_fencing_token" key.
Let me rephrase:
code
The shared resource reads the "current_fencing_token" key (which is written by the leader) and compares with the provided token.
If the provided token is >= the read token, then accept and update the read token? But then the shared resource is updating its own state? Actually, the shared resource can store the highest token it has seen.
But the "current_fencing_token" key is written by the leader and we assume it's the current leader's token.
Then:
current_token = read("current_fencing_token")
if token_provided >= current_token:
accept and set current_token = token_provided (if higher)
else:
reject
But then if the leader fails to update the "current_fencing_token", then the old token is there and the new leader's token is higher, so it will be accepted and update the stored token.
However, what if the old leader (with old token) tries to operate? It will have token_provided = old_token, and current_token (if updated by the new leader) will be higher, so it will be rejected.
But if the new leader hasn't updated the "current_fencing_token", then current_token is the old token and the old leader will be accepted.
So we are back to the same problem.
So the key is: the shared resource must read the lock from the lock service, not from a separate key written by the leader.
And we assume the lock service provides linearizable reads.
Therefore, the shared resource reads the lock key and uses that to validate the token.
This way, even if the leader hasn't updated a separate key, the shared resource reads the lock directly and sees the current leader's token.
So we don't need the leader to update a separate key. The shared resource reads the lock.
But then the shared resource must have access to the lock service and perform a read for every operation.
That might be acceptable if the shared resource is a database that can read from the lock service? Or if the lock service is co-located.
Alternatively, the leader can provide the lock's content (the whole lock structure) to the shared resource? But then the shared resource must trust the leader? No, it must verify.
So the shared resource must read the lock from the lock service.
Given the above, let's summarize:
Lock service:
- Provides atomic increment of a counter (fencing_token_counter)
- Provides CAS on the lock key.
Leader election and renewal as above.
Shared resource:
- For each operation, reads the lock key (linearizable) and checks the fencing_token.
This design requires the shared resource to have low-latency access to the lock service for reads.
Alternatively, we can have the leader cache the fencing token and the shared resource can be told by the leader what the current token is, and the shared resource can periodically re-read the lock to update its cache? But then there is a window where the cache is stale.
Given the requirement for fencing, we want to reject old leaders as soon as possible. So the shared resource must read the lock for every operation? That might be too heavy.
We can have the shared resource read the lock only when it receives an operation with a token that it hasn't seen before? But then an old leader with an old token that it used before (and was accepted) might try again and the shared resource will accept because it has cached that token? But the token might be old now.
So we need to check the current leader's token for every operation? Or at least, we need to know when the token changes.
We can have the lock service push updates to the shared resource? That's complex.
Given the constraints, let's stick with the shared resource reading the lock for every operation.
If the read is too heavy, we can have the shared resource read the lock once and then cache the token until it sees a change (by reading periodically). But then there is a window.
We can have the shared resource read the lock at the beginning of each operation and then cache the token for the duration of the operation? But if the operation is long, the token might change.
Actually, we want the entire operation to be atomic with respect to the leader change. So we should check the token at the beginning and then perform the operation. If the token changes during the operation, we don't care because we already checked? But what if the operation is a multi-step and the old leader is still the leader when we started but then loses leadership? Then the operation might be partially done and then the new leader does something else? That's a problem.
So the operation should be short and we check the token at the beginning.
Alternatively, we can have the shared resource read the lock at the beginning and then again at the end? But that doesn't help.
Actually, the fencing token is meant to prevent old leaders from making changes. If the old leader starts an operation and then loses leadership, the operation might still be in progress. But the new leader will have a new token and when it tries to operate, it will be rejected? No, the new leader will have a new token and the shared resource will accept because the token is current.
But the old leader's operation might still be modifying the shared resource. We want to prevent that.
So we need to ensure that once a leader loses leadership, it stops all operations. That's why we have the lease renewal: the leader must renew periodically, and if it fails, it steps down.
But there is a window between when the leader loses the lock and when it stops operations.
That's where the fencing token helps: the shared resource will reject any operation from the old leader as soon as the new leader's token is seen.
So if the old leader tries to do an operation after the new leader has updated the lock, the shared resource will reject.
But if the old leader is in the middle of an operation when the new leader takes over, the old leader might have already passed the token check (at the beginning of the operation) and then the shared resource might not check again. Then the operation might complete even though the leader is no longer the leader.
That's a problem.
To avoid that, we need the shared resource to check the token for every operation, and if the operation is multi-step, we need to check the token at every step? That's not practical.
Alternatively, we can design the shared resource to only allow one operation at a time and each operation is atomic. Then we check the token at the beginning of the operation and if the token changes during the operation, we still complete the operation because we already passed the check? But then the old leader might complete an operation that should have been aborted.
So we need to make the operation short and hope that the leader doesn't lose the lock in the middle of an operation.
Given the lease duration, the leader will lose the lock if it doesn't renew for more than lease_duration. So we set the lease duration to be longer than the maximum operation time.
Then, if an operation takes less than the lease duration, the leader will still be the leader during the operation. And if the lease expires during the operation, then the leader will have already failed to renew and should have stopped.
But what if the leader is in the middle of an operation and the lease expires? Then it will try to renew and fail, and then step down. But the operation might still be running? We need the leader to stop all operations when it steps down.
So the leader must be designed to stop operations when it loses the lock.
Therefore, we assume that the leader will not start new operations after it loses the lock, and it will try to finish the current operation quickly? But if the operation is long, we have a problem.
So we must design the operations to be short, or we must have a way to interrupt operations when the leader steps down.
This is application-specific.
Given the above, the fencing token check at the shared resource is only at the beginning of the operation. If the leader loses the lock during the operation, the operation might still complete. But we accept that because the operation was started when the leader was valid.
Alternatively, we can have the shared resource check the token at the beginning and then also set a deadline (based on the lock's expiration) and if the operation takes longer than that, abort? But then we need to know the expiration.
We can have the shared resource store the token and the expiration when it accepts an operation, and then if a new leader comes with a higher token, it can interrupt long-running operations? That's complex.
Given the complexity, let's stick with:
The shared resource checks the token at the beginning of the operation and assumes that the leader will step down if it loses the lock.
Shared resource:
- For each operation:
read the lock (linearizable)
if lock is None or expired -> reject
if lock.fencing_token != token_provided by leader -> reject
else -> accept and perform operation
We assume that the leader provides the token it got from the lock service when it acquired the lock (or last renewed? Actually, the token doesn't change on renew, so it's the same).
And we assume that the leader will not provide an old token (because it knows its own token).
But what if the leader is a bad actor? Then it might provide an old token? But the shared resource will check against the current lock.
So it's safe.
Let's code the lock service abstraction.
We'll define:
class LockService:
def init(self, storage):
self.storage = storage # storage must support: get(key), compare_and_set(key, expected, new), atomic_increment(key)
code
def acquire_lock(self, node_id, lease_duration):
# returns (success, fencing_token) or (False, None)
while True:
now = time.time()
current_lock = self.storage.get("lock")
if current_lock is None or current_lock.expiration < now:
new_token = self.storage.atomic_increment("fencing_token_counter")
new_lock = {
"leader_id": node_id,
"fencing_token": new_token,
"expiration": now + lease_duration
}
if self.storage.compare_and_set("lock", current_lock, new_lock):
return (True, new_token)
time.sleep(random.random() * 0.1)
def renew_lock(self, node_id, fencing_token, lease_duration):
# returns True if renewed, False if lost
while True:
now = time.time()
current_lock = self.storage.get("lock")
if current_lock is None:
return False
if current_lock.leader_id != node_id or current_lock.fencing_token != fencing_token:
return False
if current_lock.expiration < now + 0.9 * lease_duration: # renew if within 90% of lease
new_lock = {
"leader_id": node_id,
"fencing_token": fencing_token,
"expiration": now + lease_duration
}
if self.storage.compare_and_set("lock", current_lock, new_lock):
return True
else:
# not time to renew yet, but we are still the leader
return True
time.sleep(0.1)
def release_lock(self, node_id, fencing_token):
# We don't need an explicit release because the lease will expire.
# But if we want to release early, we can try to set the lock to None only if we are the leader.
current_lock = self.storage.get("lock")
if current_lock and current_lock.leader_id == node_id and current_lock.fencing_token == fencing_token:
self.storage.compare_and_set("lock", current_lock, None)
But note: the renew_lock might fail because the lock was taken by someone else, then we return False.
The leader should call renew_lock periodically and if it returns False, it steps down.
However, the above renew_lock does a busy wait until it succeeds? That's not good. We should do one attempt and then sleep.
Let's change:
def renew_lock(self, node_id, fencing_token, lease_duration):
now = time.time()
current_lock = self.storage.get("lock")
if current_lock is None:
return False
if current_lock.leader_id != node_id or current_lock.fencing_token != fencing_token:
return False
if current_lock.expiration < now + 0.9 * lease_duration:
new_lock = {
"leader_id": node_id,
"fencing_token": fencing_token,
"expiration": now + lease_duration
}
return self.storage.compare_and_set("lock", current_lock, new_lock)
else:
return True
Then the leader should call renew_lock periodically (every, say, lease_duration/5) and if it returns False, it steps down.
But what if the lock expires between the time we check and the time we try to renew? Then the CAS might fail because the lock has changed? Actually, if the lock has expired, then someone else might have taken it. Then the CAS will fail because the current_lock we read is different from the current value.
So we are safe.
Now, the shared resource:
class SharedResource:
def init(self, lock_service):
self.lock_service = lock_service
code
def do_operation(self, token_provided, operation):
current_lock = self.lock_service.storage.get("lock") # assume linearizable read
now = time.time()
if current_lock is None or current_lock.expiration < now:
raise Exception("No current leader")
if current_lock.fencing_token != token_provided:
raise Exception("Invalid token: not the current leader")
# perform the operation
operation()
However, note: the shared resource reads the lock from the lock service's storage. We assume that the lock service's storage provides linearizable reads.
But the lock service's acquire and renew use CAS, which is linearizable. So if the shared resource reads from the same storage, and the storage is linearizable, then it's safe.
But what if the shared resource is in a different data center? Then the read might not be linearizable? We need to ensure that the shared resource reads from the same quorum as the lock service? That's deployment-specific.
We assume the storage is a linearizable key-value store (like etcd, ZooKeeper with linearizable reads, or a Raft-based store).
We can implement this with a real storage, but that's beyond the scope.
This is the abstraction.
Note: the leader election algorithm might have many retries. We can add a backoff.
Also, we assume that the lease_duration is long enough to cover network delays and operation times.
We set the safe_margin for renewal to 90% of lease_duration.
This design should meet the requirements.
However, note: the fencing_token_counter will keep increasing even if we have many election attempts. That's acceptable.
Let's test with a simple scenario:
Node1 and Node2 both try to acquire.
Node1 reads lock (None), increments token to 1, sets lock to {node1, 1, expiration}. Success.
Node2 reads lock (node1,1,expiration) and it's not expired, so it waits.
Then Node1 fails to renew, so it steps down. Node2 will eventually see the lock expired and acquire with token=2.
Then Node1 (old leader) tries to do an operation with token=1. The shared resource reads the lock (node2,2,expiration) and sees token=2, so rejects.
Good.
What if Node1 acquires and then Node2 acquires at the same time? Only one will succeed because of CAS.
What if Node1 renews at the same time as Node2 tries to acquire? Node2 will see the lock with node1 and token1 and not expired, so it waits. Node1 renews successfully.
Good.
What if Node1 is renewing and the lease expires during the renew? Then Node2 might see the lock expired and try to acquire. But Node1's renew might still be in progress? The CAS in Node1's renew will fail because the lock has changed (Node2 set it). Then Node1 will step down.
Good.
So the design seems sound.
Let's write the code for the lock service and the shared resource.
We'll assume the storage is given.
Note: The shared resource must read the lock from the same storage that the lock service uses.
We'll pass the storage to both.
Alternatively, the lock service can expose a method for the shared resource to read the current fencing token? But we already have the storage.
We can have:
lock_service.get_current_lock() -> returns the current lock (linearizable read)
Then the shared resource uses lock_service.get_current_lock().
That way, the shared resource doesn't need direct access to the storage.
Let's do that.
Code structure:
class LockService:
def init(self, storage):
self.storage = storage
def start(self):
self.running = True
success, self.fencing_token = self.lock_service.acquire(self.node_id, self.lease_duration)
if not success:
# Could not become leader
return
# Now we are the leader
while self.running:
time.sleep(self.lease_duration / 5)
if not self.lock_service.renew(self.node_id, self.fencing_token, self.lease_duration):
self.running = False
break
def stop(self):
self.running = False
def do_operation(self, operation):
# The leader performs an operation on the shared resource.
# We assume the shared resource is available and we have a reference.
# But the leader might not have a reference to the shared resource? Actually, the leader is the one that is using the shared resource.
# So the leader must have the shared resource and its fencing token.
# We can pass the shared resource to the leader.
# Alternatively, the leader can be the one that holds the lock and then uses the shared resource.
# So we can have:
# shared_resource.operate(self.fencing_token, operation)
pass
But note: the leader might lose the lock while it is performing the operation? Then the shared resource might still accept because it checked at the beginning? But then the leader is no longer the leader and it should not be doing operations.
So the leader must check before each operation that it still holds the lock? Or it can rely on the shared resource to reject? But if the leader loses the lock, it should stop all operations.
We can have the leader check in a separate thread (the renew loop) and set a flag. Then before doing an operation, it checks the flag.
Alternatively, the leader can do:
if not self.running:
return
But the renew loop sets self.running to False when it fails.
However, there is a race: the renew loop might fail and set self.running to False while the leader is in the middle of an operation? Then the operation might still be running.
We can have the leader check the lock before each operation by doing a non-blocking renew? But that might be heavy.
Alternatively, we can have the leader do:
with self.lock:
# do operation
But we don't have a lock.
Given that the operations are short, we can assume that the leader will not lose the lock during an operation because the lease is long and we renew frequently.
But to be safe, the leader can check the lock before each operation by reading the lock? But that's heavy.
We can have the leader cache the expiration and check if the current time is beyond the expiration? But the expiration might be updated by a renew.
Actually, the leader knows the expiration because it set it in the renew. But it might not know if someone else took the lock.
So the leader must check the lock.
We can have the leader do a non-blocking check:
current_lock = self.lock_service.get_current_lock()
if current_lock.leader_id != self.node_id or current_lock.fencing_token != self.fencing_token:
self.running = False
return
But that's a read.
Given the complexity, we assume that the leader's renew loop will catch the loss of lock quickly and set self.running to False.
And the leader should check self.running before starting an operation.
So:
def do_operation(self, operation):
if not self.running:
raise Exception("Not the leader")
# We don't check again because the renew loop is running and will set running to False if we lose the lock.
# But there is a small window between checking self.running and the operation where we might lose the lock.
# We can do the operation and if the shared resource rejects, then we stop? But the operation might have partially run.
code
# Alternatively, we can have the shared resource reject and then we stop.
try:
self.shared_resource.operate(self.fencing_token, operation)
except Exception as e:
if "Invalid token" in str(e):
self.running = False
raise
But then the leader might do multiple operations after losing the lock until one of them is rejected.
We can have the leader check the lock before each operation by doing a get_current_lock and comparing? That's one extra read.
Given the requirement for safety, we should check the lock before each operation.
So:
def do_operation(self, operation):
current_lock = self.lock_service.get_current_lock()
now = time.time()
if current_lock is None or current_lock.expiration < now:
self.running = False
raise Exception("Not the leader")
if current_lock.leader_id != self.node_id or current_lock.fencing_token != self.fencing_token:
self.running = False
raise Exception("Not the leader")
# Now we are sure we are the leader at the time of the check.
# But the lock might expire during the operation? We assume the operation is short.
But note: the shared_resource.operate also checks the lock. That's two checks.
We can remove the check in the shared_resource? But then the shared_resource might be used by other leaders? Actually, the shared_resource is used by the current leader only? Not necessarily, multiple leaders might try to use the same shared resource? But they shouldn't because only one leader at a time.
But if we remove the check in the shared_resource, then we rely on the leader to check. But what if the shared_resource is used by something else? Then we need the check.
So we keep both.
This design should be safe.
Let's code accordingly.
However, note: the leader's check and the shared_resource's check are not atomic. There is a window between the leader's check and the shared_resource's check where the lock might change.
But the shared_resource will reject if the token doesn't match, so it's safe.
The leader might think it's the leader, but the shared_resource might reject. Then the leader will set running=False and stop.
That's acceptable.
So we are done.
We'll write the code accordingly.
Note: The storage must be linearizable for the get and CAS.
We assume that.
Let's code the classes.
We'll define:
class LockService:
def init(self, storage):
self.storage = storage
def start(self):
self.running = True
success, self.fencing_token = self.lock_service.acquire(self.node_id, self.lease_duration)
if not success:
self.running = False
return
self.renew_thread = threading.Thread(target=self._renew_loop)
self.renew_thread.start()
def _renew_loop(self):
while self.running:
time.sleep(self.lease_duration / 5)
if not self.lock_service.renew(self.node_id, self.fencing_token, self.lease_duration):
self.running = False
break
def stop(self):
self.running = False
if self.renew_thread:
self.renew_thread.join()
def do_operation(self, operation):
# Check if we are still the leader
current_lock = self.lock_service.get_current_lock()
now = time.time()
if current_lock is None or current_lock.expiration < now:
self.running = False
raise Exception("Not the leader")
if current_lock.leader_id != self.node_id or current_lock.fencing_token != self.fencing_token:
self.running = False
raise Exception("Not the leader")
# Now do the operation. The shared_resource will also check.
try:
self.shared_resource.operate(self.fencing_token, operation)
except Exception as e:
# If the shared_resource rejects, we might have lost the lock.
if "Invalid token" in str(e):
self.running = False
raise
class SharedResource:
def init(self, lock_service):
self.lock_service = lock_service
code
def operate(self, token_provided, operation):
current_lock = self.lock_service.get_current_lock()
now = time.time()
if current_lock is None or current_lock.expiration < now:
raise Exception("No current leader")
if current_lock.fencing_token != token_provided:
raise Exception("Invalid token")
operation()
This is a basic implementation.
We assume that the leader and shared_resource are in the same process and share the same lock_service instance.
The lock_service uses a storage that is linearizable.
We haven't implemented the storage.
This design should meet the requirements.
Let me know if you have any questions.
I'll design a robust distributed locking abstraction with leader election, lease renewal, and fencing tokens. This implementation uses a consensus-based approach (like Raft) combined with fencing tokens to ensure safety.
import time
import threading
import uuid
from typing import Optional, Dict, Any
from dataclasses import dataclass, field
from datetime import datetime, timedelta
from enum import Enum
importraft = None # Assume we have a Raft library (like python-raft)
class LockStatus(Enum):
UNHELD = "unheld"
HELD = "held"
RENEWING = "renewing"
RELEASING = "releasing"
@dataclass
class LockMetadata:
"""Metadata stored in consensus log for lock state"""
lock_id: str
holder_id: str # Node ID of current holder
fencing_token: int # Monotonically increasing
lease_expiration: datetime
session_id: str # Unique session identifier
version: int = 0 # For optimistic concurrency control
class DistributedLock:
"""
Distributed lock with:
- Leader election via Raft consensus
- Lease-based locking with automatic renewal
- Fencing tokens for session safety
"""
def __init__(
self,
node_id: str,
raft_node,
lock_name: str,
lease_duration: float = 30.0, # seconds
renewal_interval: float = 10.0,
max_lease_attempts: int = 3
):
self.node_id = node_id
self.raft_node = raft_node
self.lock_name = lock_name
self.lease_duration = lease_duration
self.renewal_interval = renewal_interval
self.max_lease_attempts = max_lease_attempts
# State
self._status = LockStatus.UNHELD
self._current_token: Optional[int] = None
self._session_id = str(uuid.uuid4())
self._renewal_thread: Optional[threading.Thread] = None
self._stop_renewal = threading.Event()
self._lock_metadata: Optional[LockMetadata] = None
self._raft_log_prefix = f"lock/{lock_name}"
# Metrics
self._acquire_attempts = 0
self._renewal_successes = 0
self._renewal_failures = 0
def acquire(self, timeout: float = 10.0) -> bool:
"""
Acquire the distributed lock with fencing token.
Returns True if acquired, False on timeout/failure.
"""
start_time = time.time()
self._acquire_attempts += 1
while time.time() - start_time < timeout:
# Check if we're already the leader (if using leader election)
if self.raft_node.is_leader():
# Try to acquire lock via Raft consensus
success = self._try_acquire_via_raft()
if success:
self._status = LockStatus.HELD
self._start_renewal_thread()
return True
else:
# If not leader, wait for election or try to become leader
self._wait_for_leadership(timeout - (time.time() - start_time))
time.sleep(0.1) # Backoff
return False
def _try_acquire_via_raft(self) -> bool:
"""Attempt lock acquisition through Raft consensus"""
current_time = datetime.utcnow()
new_token = self._generate_fencing_token()
proposed_metadata = LockMetadata(
lock_id=self.lock_name,
holder_id=self.node_id,
fencing_token=new_token,
lease_expiration=current_time + timedelta(seconds=self.lease_duration),
session_id=self._session_id
)
try:
# Propose through Raft (this will be replicated to quorum)
command = {
"op": "acquire",
"metadata": proposed_metadata.__dict__,
"timestamp": current_time.isoformat()
}
# Wait for Raft commitment
success = self.raft_node.propose(command)
if success:
self._current_token = new_token
self._lock_metadata = proposed_metadata
return True
except Exception as e:
print(f"Acquire failed: {e}")
return False
def renew(self) -> bool:
"""Renew the lock lease. Returns True if renewed."""
if self._status != LockStatus.HELD:
return False
self._status = LockStatus.RENEWING
try:
if not self.raft_node.is_leader():
self._status = LockStatus.HELD
return False
current_time = datetime.utcnow()
new_expiration = current_time + timedelta(seconds=self.lease_duration)
command = {
"op": "renew",
"lock_id": self.lock_name,
"holder_id": self.node_id,
"fencing_token": self._current_token,
"new_expiration": new_expiration.isoformat(),
"session_id": self._session_id
}
success = self.raft_node.propose(command)
if success:
self._renewal_successes += 1
if self._lock_metadata:
self._lock_metadata.lease_expiration = new_expiration
return True
else:
self._renewal_failures += 1
return False
finally:
if self._status == LockStatus.RENEWING:
self._status = LockStatus.HELD
def release(self) -> bool:
"""Release the lock."""
if self._status == LockStatus.UNHELD:
return True
self._status = LockStatus.RELEASING
self._stop_renewal.set()
try:
if self.raft_node.is_leader() and self._current_token:
command = {
"op": "release",
"lock_id": self.lock_name,
"fencing_token": self._current_token,
"session_id": self._session_id
}
return self.raft_node.propose(command)
return True # Already released or not holder
finally:
self._status = LockStatus.UNHELD
self._current_token = None
self._lock_metadata = None
def get_fencing_token(self) -> Optional[int]:
"""Get current fencing token (for using with protected resources)"""
return self._current_token
def is_held(self) -> bool:
"""Check if lock is currently held by this instance"""
return self._status == LockStatus.HELD
def _start_renewal_thread(self):
"""Start background thread for lease renewal"""
if self._renewal_thread and self._renewal_thread.is_alive():
return
self._stop_renewal.clear()
self._renewal_thread = threading.Thread(
target=self._renewal_loop,
daemon=True,
name=f"lock-renew-{self.lock_name}"
)
self._renewal_thread.start()
def _renewal_loop(self):
"""Background renewal loop"""
while not self._stop_renewal.wait(self.renewal_interval):
if self._status == LockStatus.HELD:
try:
if not self.renew():
print(f"Failed to renew lock {self.lock_name}, stepping down")
self.release()
break
except Exception as e:
print(f"Renewal error: {e}")
self.release()
break
def _generate_fencing_token(self) -> int:
"""Generate monotonically increasing fencing token.
In production, this would be coordinated via Raft log index or
separate consensus-managed counter."""
# Using Raft log index as fencing token source
last_log_index = self.raft_node.last_log_index()
return last_log_index + 1
def _wait_for_leadership(self, timeout: float):
"""Wait for this node to become leader"""
start = time.time()
while time.time() - start < timeout:
if self.raft_node.is_leader():
return
time.sleep(0.1)
class LockManager:
"""
Manages multiple distributed locks and provides fencing token validation
for protected resources.
"""
def __init__(self, node_id: str, raft_node):
self.node_id = node_id
self.raft_node = raft_node
self._locks: Dict[str, DistributedLock] = {}
self._lock = threading.RLock()
def get_lock(self, lock_name: str, **kwargs) -> DistributedLock:
"""Get or create a distributed lock instance"""
with self._lock:
if lock_name not in self._locks:
self._locks[lock_name] = DistributedLock(
node_id=self.node_id,
raft_node=self.raft_node,
lock_name=lock_name,
**kwargs
)
return self._locks[lock_name]
def validate_fencing_token(
self,
resource_name: str,
provided_token: int,
operation: str
) -> bool:
"""
Validate fencing token for a resource operation.
Resources should call this before executing operations.
"""
lock = self._locks.get(resource_name)
if not lock:
# No lock exists for this resource
return False
current_token = lock.get_fencing_token()
if current_token is None:
return False
# Accept only tokens >= current token (monotonic check)
# Higher tokens indicate newer leader
return provided_token >= current_token
# Raft Command Handler (runs on all nodes)
class LockCommandHandler:
"""Handles lock commands committed via Raft"""
def __init__(self, lock_manager: LockManager):
self.lock_manager = lock_manager
self._last_applied_index = 0
def apply(self, command: Dict[str, Any]) -> bool:
"""Apply a committed lock command"""
try:
op = command.get("op")
lock_id = command.get("lock_id")
if not lock_id:
return False
lock = self.lock_manager.get_lock(lock_id)
if op == "acquire":
return self._handle_acquire(command, lock)
elif op == "renew":
return self._handle_renew(command, lock)
elif op == "release":
return self._handle_release(command, lock)
elif op == "force_release":
return self._handle_force_release(command, lock)
except Exception as e:
print(f"Failed to apply lock command: {e}")
return False
return True
def _handle_acquire(self, command: Dict, lock: DistributedLock) -> bool:
"""Handle lock acquisition command"""
metadata_dict = command.get("metadata", {})
proposed = LockMetadata(**metadata_dict)
current = lock._lock_metadata
# Check if lock is free or expired
if current is None:
lock._lock_metadata = proposed
lock._current_token = proposed.fencing_token
return True
# Check if current lease is expired
if current.lease_expiration < datetime.utcnow():
lock._lock_metadata = proposed
lock._current_token = proposed.fencing_token
return True
# Check if same session (allows renewal by same holder)
if (current.holder_id == proposed.holder_id and
current.session_id == proposed.session_id and
proposed.fencing_token == current.fencing_token):
lock._lock_metadata = proposed
return True
# Reject if another holder
return False
def _handle_renew(self, command: Dict, lock: DistributedLock) -> bool:
"""Handle lease renewal"""
holder_id = command.get("holder_id")
token = command.get("fencing_token")
session_id = command.get("session_id")
new_expiration = datetime.fromisoformat(command.get("new_expiration"))
current = lock._lock_metadata
if (current and
current.holder_id == holder_id and
current.fencing_token == token and
current.session_id == session_id):
current.lease_expiration = new_expiration
return True
return False
def _handle_release(self, command: Dict, lock: DistributedLock) -> bool:
"""Handle explicit release"""
token = command.get("fencing_token")
session_id = command.get("session_id")
current = lock._lock_metadata
if (current and
current.fencing_token == token and
current.session_id == session_id):
lock._lock_metadata = None
lock._current_token = None
return True
return False
def _handle_force_release(self, command: Dict, lock: DistributedLock) -> bool:
"""Force release (for fencing failures, admin use)"""
lock._lock_metadata = None
lock._current_token = None
return True