-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_node.py
More file actions
92 lines (75 loc) · 3.01 KB
/
test_node.py
File metadata and controls
92 lines (75 loc) · 3.01 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
import threading
import time
import sys
from messaging import MessagingModule
from protocol import *
from discovery import DiscoveryModule
from bully_algorithm import BullyAlgorithm, PeerInfo
def main():
if len(sys.argv) < 3:
print("Usage: python test_node.py <port> <node_id>")
return
# Listen on all interfaces to allow connections from LAN IP
my_ip = "0.0.0.0"
my_port = int(sys.argv[1])
my_id = int(sys.argv[2])
print(f"Starting Node {my_id} on {my_ip}:{my_port}")
# 1. Initialize messaging module
messenger = MessagingModule(my_ip, my_port, my_id)
# 2. Initialize Bully Algorithm (initially empty peers)
bully = BullyAlgorithm(my_id, messenger, {})
messenger.logic_handler = bully
# 3. Define callback for Discovery
def on_peers_update(discovered_peers):
# Convert DiscoveredPeer to PeerInfo
bully_peers = {}
for pid, p in discovered_peers.items():
bully_peers[pid] = PeerInfo(pid, p.host, p.port)
bully.update_peers(bully_peers)
# 4. Initialize Discovery Module
discovery = DiscoveryModule(my_id, my_port, on_peer_changed=on_peers_update)
# 5. Start threads
t_net = threading.Thread(target=messenger.start_listening, daemon=True)
t_net.start()
discovery.start()
# 6. Start status reporting thread
def report_status():
while True:
time.sleep(5)
print("\n" + "="*40)
print(f"📊 [Status Report] Node {my_id}")
print(f" - Leader: {bully.leader_id}")
print(f" - State: {'Election' if bully.in_election else 'Normal'}")
print(f" - Peers ({len(bully.peers)}): {list(bully.peers.keys())}")
# Simulate Heartbeat logic (just for reporting)
if bully.leader_id and bully.leader_id != my_id:
print(f" - ❤️ Sending Heartbeat to Leader {bully.leader_id}...")
# In a real implementation, you would call messenger.send_message here
elif bully.leader_id == my_id:
print(f" - 👑 I am Leader. Waiting for heartbeats.")
print("="*40 + "\n")
threading.Thread(target=report_status, daemon=True).start()
# User input loop
print("Commands:")
print(" e: Start Election")
print(" s: Show Status")
print(" p: Show Peers")
print(" q: Quit")
while True:
try:
cmd = input(f"Node {my_id} > ").strip().lower()
if not cmd: continue
if cmd == 'e':
bully.start_election()
elif cmd == 's':
print(f"Current Leader: {bully.leader_id}")
print(f"In Election: {bully.in_election}")
elif cmd == 'p':
print(f"Peers: {list(bully.peers.keys())}")
elif cmd == 'q':
discovery.stop()
break
except KeyboardInterrupt:
break
if __name__ == "__main__":
main()