import asyncio
import random
from dataclasses import dataclass
from typing import Dict, Set, Optional
# --- Data Structures ---
@dataclass
class Probe:
"""
Represents a probe message traveling the wait-for graph.
initiator: The original process checking for deadlock.
sender: The process that sent this specific probe.
target: The process receiving this probe.
"""
initiator: int
sender: int
target: int
class DistributedNode:
def __init__(self, node_id: int, network: 'Network'):
self.id = node_id
self.network = network
self.lock_holder: Optional[int] = None # Who holds the resource I want?
self.waiting_for: Optional[int] = None # Who am I currently waiting for?
self.is_active = True # If False, the transaction is aborted
self.locks_held: Set[int] = set() # IDs of resources this node holds locks on
# For deadlock resolution strategy (priority)
self.creation_time = asyncio.get_event_loop().time()
async def request_lock(self, target_node_id: int):
"""
Simulate trying to acquire a lock held by another node.
"""
if not self.is_active:
print(f"[Node {self.id}] Ignoring request, I am dead.")
return
print(f"[Node {self.id}] Requesting resource from Node {target_node_id}")
# Simulate dependency: I am waiting for target_node_id
self.waiting_for = target_node_id
# Initiate the Edge-Chasing Probe
# Format: (Initiator, Sender, Receiver) -> (Me, Me, Target)
probe = Probe(self.id, self.id, target_node_id)
await self.network.send_message(probe)
async def receive_probe(self, probe: Probe):
if not self.is_active:
return # Dead nodes don't talk
print(f"[Node {self.id}] Received Probe: Init={probe.initiator}, Sender={probe.sender}")
# --- DEADLOCK DETECTION CONDITION ---
# If the probe was initiated by me, and it came back to me, the cycle is complete.
if probe.initiator == self.id:
print(f"\n!!! DEADLOCK DETECTED at Node {self.id} !!!")
await self.resolve_deadlock(probe.initiator)
return
# --- PROBE FORWARDING ---
# If I am not the initiator, but I am blocked waiting for someone else,
# I must forward the probe to keep it traveling along the graph edges.
if self.waiting_for is not None:
new_probe = Probe(probe.initiator, self.id, self.waiting_for)
print(f"[Node {self.id}] Forwarding Probe to Node {self.waiting_for}")
await self.network.send_message(new_probe)
else:
# If I am not blocked, the chain ends here (no deadlock on this path yet)
print(f"[Node {self.id}] Not blocked. Probe chain terminates.")
async def resolve_deadlock(self, initiator_id: int):
"""
Resolution Strategy: The Victim.
Usually, we abort the youngest transaction (most recent) to save older work.
In this simplified version, the node detecting the deadlock aborts the
process with the highest ID (or itself) to break the loop.
"""
# For simplicity, let's say the detector forces the 'waiting_for'
# chain to break by aborting itself or notifying the other.
# Here we implement the "Abort Self" strategy for simplicity.
print(f"[Node {self.id}] Resolving deadlock: Aborting transaction...")
self.is_active = False
self.waiting_for = None
# In a real system, this node would release all locks now.
print(f"[Node {self.id}] Transaction ABORTED. Locks released.")
# --- Network Simulation ---
class Network:
def __init__(self):
self.nodes: Dict[int, DistributedNode] = {}
def add_node(self, node: DistributedNode):
self.nodes[node.id] = node
async def send_message(self, probe: Probe):
# Simulate network latency
latency = random.uniform(0.1, 0.5)
await asyncio.sleep(latency)
target_node = self.nodes.get(probe.target)
if target_node:
await target_node.receive_probe(probe)
# --- Scenario Runner ---
async def main():
network = Network()
# Create 3 nodes
n1 = DistributedNode(1, network)
n2 = DistributedNode(2, network)
n3 = DistributedNode(3, network)
network.add_node(n1)
network.add_node(n2)
network.add_node(n3)
print("--- Setting up Deadlock Scenario ---")
print("Topology: N1 waits for N2, N2 waits for N3, N3 waits for N1")
# 1. N1 waits for N2
# N1 sends probe (1, 1, 2)
asyncio.create_task(n1.request_lock(2))
# Allow time for setup (simulating N2 holding lock N1 needs)
await asyncio.sleep(0.2)
# 2. N2 waits for N3
# N2 sends probe (2, 2, 3)
asyncio.create_task(n2.request_lock(3))
await asyncio.sleep(0.2)
# 3. N3 waits for N1 (Closing the cycle)
# N3 sends probe (3, 3, 1)
asyncio.create_task(n3.request_lock(1))
# Wait for probes to propagate
await asyncio.sleep(3)
if __name__ == "__main__":
asyncio.run(main())