-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsimulation_manager.py
More file actions
235 lines (189 loc) · 7.35 KB
/
Copy pathsimulation_manager.py
File metadata and controls
235 lines (189 loc) · 7.35 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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
import json
import os
import random
import time
import paho.mqtt.client as mqtt
from dotenv import load_dotenv
import re
import threading
load_dotenv() # take environment variables from .env.
##### Manager
# Subscribe to all starfish/ips/##
# Scan for IPs that are older than 30 seconds. If so, clean up records.
# Send new/kill commands
#
# List all Peers.
# List all IPs
# Retrieve Peer IO port
MQTT_SERVER = os.getenv("MQTT_SERVER", "")
MQTT_PORT = int(os.getenv("MQTT_PORT", 1883))
MQTT_USER = os.getenv("MQTT_USER", "")
MQTT_PWD = os.getenv("MQTT_PWD", "")
PRUNE_TIME = 240
class SimulationOrchestrator:
def __init__(self):
self.known_ips: dict[str, float] = {}
self.known_peers: dict[str, dict[str, int | str | float]] = {}
self.known_command: dict[str, float] = {}
self.command_data: dict[str, dict[str, int | bool]] = {}
mqttc = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2)
mqttc.loop_start()
mqttc.on_connect = lambda a, b, c, d, e: self.on_connect(a, b, c, d, e)
mqttc.on_message = lambda a, b, c: self.on_message(a, b, c)
mqttc.username_pw_set(MQTT_USER, MQTT_PWD)
mqttc.connect(MQTT_SERVER, MQTT_PORT, 30)
self.client = mqttc
th_prune = threading.Thread(None, target=self.prune_task)
th_prune.start()
self.is_stopping = False
self.ip_threads = {}
def on_connect(self, client, userdata, flags, reason_code, properties):
self.client.subscribe(f"starfish/ips/#")
def is_ip_root(self, s: str) -> bool:
pattern = r"^starfish\/ips\/(?:(?:25[0-5]|2[0-4][0-9]|1?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|1?[0-9][0-9]?)$"
return re.fullmatch(pattern, s) is not None
def is_peer_msg(self, s: str) -> bool:
pattern = r"^starfish\/ips\/(?:(?:25[0-5]|2[0-4][0-9]|1?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|1?[0-9][0-9]?)\/peers\/"
return re.match(pattern, s) is not None
def is_command_msg(self, s: str) -> bool:
pattern = r"^starfish\/ips\/(?:(?:25[0-5]|2[0-4][0-9]|1?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|1?[0-9][0-9]?)\/command"
return re.match(pattern, s) is not None
def on_message(self, client, userdata, msg):
# print(msg.topic + " " + str(msg.payload))
if msg.payload == b"" and self.is_peer_msg(msg.topic):
# peer message delete
peerID = msg.topic.split("/")[-1]
if peerID in self.known_peers:
del self.known_peers[peerID]
return
elif msg.payload == b"":
return
if self.is_ip_root(msg.topic):
ip = msg.topic.split("/")[-1]
self.known_ips[ip] = float(msg.payload.decode("utf-8"))
return
elif self.is_peer_msg(msg.topic):
peerID = msg.topic.split("/")[-1]
ip = msg.topic.split("/")[-3]
s = json.loads(msg.payload.decode("utf-8"))
self.known_peers[peerID] = {
"ip": ip,
"os": s["os"],
"io": s["io"],
"time": time.time(),
}
elif self.is_command_msg(msg.topic):
ip = msg.topic.split("/")[-2]
self.known_command[ip] = time.time()
command = json.loads(msg.payload.decode("utf-8"))
self.command_data[ip] = {
"available": command["command"] == "ack",
"return": command["return"],
}
def prune(self):
ips = []
to_delete = []
for ip, last_seen in self.known_ips.items():
if last_seen < time.time() - PRUNE_TIME:
# old!
item = f"starfish/ips/{ip}"
self.client.publish(item, "", 1)
to_delete.append(ip)
else:
ips.append(ip)
for x in to_delete:
del self.known_ips[x]
to_delete = []
for x, t in self.known_command.items():
if x not in self.known_ips and t < time.time() - PRUNE_TIME:
item = f"starfish/ips/{x}/command"
self.client.publish(item, "", 1, retain=True)
to_delete.append(x)
del self.command_data[x]
for x in to_delete:
del self.known_command[x]
to_delete = []
for peer, value in self.known_peers.items():
if value["ip"] not in ips and value["time"] < time.time() - PRUNE_TIME:
ip = value["ip"]
item = f"starfish/ips/{ip}/peers/{peer}"
self.client.publish(item, "", 1, retain=True)
to_delete.append(peer)
for x in to_delete:
del self.known_peers[x]
def run_node(self, ip, peerID):
while not (self.command_data[ip]["available"]):
time.sleep(0.1)
ret = random.randint(1, (2**32) - 1)
val = {"command": "new", "peerID": peerID.hex(), "return": ret}
self.client.publish(f"starfish/ips/{ip}/command", json.dumps(val), 2)
while not (
self.command_data[ip]["available"]
and self.command_data[ip]["return"] == ret
):
time.sleep(0.1)
def kill_node(self, ip, peerID, prune=True):
while not (self.command_data[ip]["available"]):
time.sleep(0.1)
ret = random.randint(1, (2**32) - 1)
val = {"command": "kill", "peerID": peerID.hex(), "return": ret}
self.client.publish(f"starfish/ips/{ip}/command", json.dumps(val), 2)
while not (
self.command_data[ip]["available"]
and self.command_data[ip]["return"] == ret
):
time.sleep(0.1)
if prune:
self.prune()
def send_connect_command(self, ip, host, port, peerID, transport):
while not (self.command_data[ip]["available"]):
time.sleep(0.1)
ret = random.randint(1, (2**32) - 1)
val = {
"command": "tel-connect",
"host": host,
"port": port,
"peerID": peerID.hex(),
"transport": transport,
"return": ret,
}
self.client.publish(f"starfish/ips/{ip}/command", json.dumps(val), 2)
while not (
self.command_data[ip]["available"]
and self.command_data[ip]["return"] == ret
):
time.sleep(0.1)
def send_start_pgrm_command(self, ip, host, port, pgrm, user):
while not (self.command_data[ip]["available"]):
time.sleep(0.1)
ret = random.randint(1, (2**32) - 1)
val = {
"command": "tel-start",
"host": host,
"port": port,
"pgrm": pgrm,
"user": user,
"return": ret,
}
self.client.publish(f"starfish/ips/{ip}/command", json.dumps(val), 2)
while not (
self.command_data[ip]["available"]
and self.command_data[ip]["return"] == ret
):
time.sleep(0.1)
def view_peer(self, peer):
return self.known_peers[peer.hex()]
def get_ips(self):
return list(self.known_ips.keys())
def get_peers(self):
return list(self.known_peers.keys())
def prune_task(self):
time.sleep(PRUNE_TIME)
while True:
time.sleep(1)
if self.is_stopping:
break
self.prune()
def stop(self):
self.is_stopping = True
self.client.loop_stop()