-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnode.py
More file actions
executable file
·365 lines (324 loc) · 14 KB
/
node.py
File metadata and controls
executable file
·365 lines (324 loc) · 14 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
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
#!/usr/sbin/python3
import socket
import _thread
import os
import sys
import json
import logging
logging.basicConfig(filename='node.log', level=logging.DEBUG,
format='%(asctime)s %(levelname)s %(name)s %(threadName)s : %(message)s')
class Node:
def __init__(self, ip, name, id_provided=None):
self.PORT = 12345
self.IP = ip
self.NAME = name
self.ID = self.generate_id(id_provided)
self.previous = {}
self.next = {}
def generate_id(self, id_provided):
if id_provided is None:
return hash(self.NAME + self.IP)
else:
return id_provided
class P2P:
def __init__(self, ip, name, id_provided=None):
self.SOCKET = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.NODE = Node(ip, name, id_provided)
self.LISTENER = _thread.start_new_thread(self.listener, ())
self.menu()
def listener(self):
orig = ("", self.NODE.PORT)
self.SOCKET.bind(orig)
logging.info(f"Node {self.NODE.ID} - {self.NODE.NAME} listening on {self.NODE.IP}:{self.NODE.PORT}")
while True:
msg, client = self.SOCKET.recvfrom(1024)
msg_decoded = msg.decode("utf-8")
logging.debug(f"Message received: {msg_decoded}")
string_dict = json.loads(msg_decoded)
if string_dict["codigo"] == 0:
self.join_response(client[0])
elif string_dict["codigo"] == 1:
self.leave_response(string_dict, client)
elif string_dict["codigo"] == 2:
self.lookup_control(string_dict)
elif string_dict["codigo"] == 3:
self.update_control(string_dict, client[0])
elif string_dict["codigo"] == 64:
self.update_request(string_dict)
elif string_dict["codigo"] == 65:
self.leave_verification(string_dict, client[0])
elif string_dict["codigo"] == 66:
self.join_request(string_dict, client[0])
elif string_dict["codigo"] == 67:
self.update_verification(string_dict, client[0])
def menu(self):
while True:
clear_console()
print("Select an option:")
print_lines(50)
print("1 - Create")
print("2 - Join")
print("3 - Leave")
print("4 - Node")
print("0 - Exit")
print_lines(50)
option = int(input("Option: "))
if option == 1:
self.create_network()
elif option == 2:
self.join_network()
elif option == 3:
self.leave_network()
elif option == 4:
self.node_info()
elif option == 0:
self.exit_program()
else:
invalid_option()
def create_network(self):
self.NODE.previous.update({"id": self.NODE.ID, "ip": self.NODE.IP})
self.NODE.next.update({"id": self.NODE.ID, "ip": self.NODE.IP})
clear_console()
print_lines(50)
print("Network Created!")
print_lines(50)
input("Press enter to continue...")
logging.debug(f"Network Created - Node IP: {self.NODE.IP}, NAME: {self.NODE.NAME}, PORT: {self.NODE.PORT}, "
f"ID: {self.NODE.ID}, previous: {self.NODE.previous}, next: {self.NODE.next}")
def join_network(self):
clear_console()
print_lines(50)
print("Enter the IP of the node you want to join")
print_lines(50)
ip = input("IP: ")
self.lookup_request(ip)
def leave_network(self):
if self.NODE.previous["id"] != self.NODE.ID != self.NODE.next["id"]:
self.leave_request()
self.NODE.previous.update({"id": None, "ip": None})
self.NODE.next.update({"id": None, "ip": None})
clear_console()
print_lines(50)
print("Network Left!")
print_lines(50)
input("Press enter to continue...")
logging.debug(f"Network Left - Node IP: {self.NODE.IP}, NAME: {self.NODE.NAME}, PORT: {self.NODE.PORT}, "
f"ID: {self.NODE.ID}, previous: {self.NODE.previous}, next: {self.NODE.next}")
def leave_request(self):
string_dict = {
"codigo": 1,
"identificador": self.NODE.ID,
"id_sucessor": self.NODE.next["id"],
"ip_sucessor": self.NODE.next["ip"],
"id_antecessor": self.NODE.previous["id"],
"ip_antecessor": self.NODE.previous["ip"]
}
json_dict = json.dumps(string_dict)
encoded_json = json_dict.encode("utf-8")
logging.debug(f"Sent Leave Request Message to successor {self.NODE.next['ip']} - {encoded_json}")
self.SOCKET.sendto(encoded_json, (self.NODE.next["ip"], self.NODE.PORT))
logging.debug(f"Sent Leave Request Message to previous {self.NODE.previous['ip']} - {encoded_json}")
self.SOCKET.sendto(encoded_json, (self.NODE.previous["ip"], self.NODE.PORT))
def leave_response(self, string_dict, client):
if string_dict["id_antecessor"] == self.NODE.ID:
self.NODE.next.update({
"id": string_dict["id_sucessor"],
"ip": string_dict["ip_sucessor"]
})
if string_dict["id_sucessor"] == self.NODE.ID:
self.NODE.previous.update({
"id": string_dict["id_antecessor"],
"ip": string_dict["ip_antecessor"]
})
logging.debug(f"Update Node IP: {self.NODE.IP}, NAME: {self.NODE.NAME}, PORT: {self.NODE.PORT}, "
f"ID: {self.NODE.ID}, previous: {self.NODE.previous}, next: {self.NODE.next}")
response_dict = {
"codigo": 65,
"identificador": self.NODE.ID
}
json_dict = json.dumps(response_dict)
encoded_json = json_dict.encode("utf-8")
logging.debug(f"Sent Leave Response Message to {client} - {encoded_json}")
self.SOCKET.sendto(encoded_json, client)
def leave_verification(self, string_dict, client):
logging.debug(f"Leave Validation Message received in Node IP {self.NODE.IP}, NAME: {self.NODE.NAME}, "
f"PORT: {self.NODE.PORT}, previous: {self.NODE.previous}, next: {self.NODE.next} "
f"from {client} - {string_dict}")
def lookup_request(self, ip_to_send, original_ip=None, original_id=None):
if original_ip is None:
original_ip = self.NODE.IP
if original_id is None:
original_id = self.NODE.ID
msg_lookup = {
"codigo": 2,
"identificador": self.NODE.ID,
"ip_origem_busca": original_ip,
"id_busca": original_id
}
msg_lookup_json = json.dumps(msg_lookup)
msg_lookup_encoded = msg_lookup_json.encode("utf-8")
logging.debug(f"Sent Lookup Request to {ip_to_send} - {msg_lookup_encoded}")
self.SOCKET.sendto(msg_lookup_encoded, (ip_to_send, self.NODE.PORT))
def lookup_response(self, request_dict):
response_dict = {
"codigo": 66,
"id_busca": self.NODE.ID,
"id_origem": request_dict["identificador"],
"ip_origem": request_dict["ip_origem_busca"],
"id_sucessor": self.NODE.next["id"],
"ip_sucessor": self.NODE.next["ip"]
}
response_json = json.dumps(response_dict)
response_encoded = response_json.encode("utf-8")
logging.debug(f"Sent Lookup Response Message - {response_encoded}")
self.SOCKET.sendto(response_encoded, (request_dict["ip_origem_busca"], self.NODE.PORT))
def lookup_control(self, request_dict):
request_id = request_dict["id_busca"]
current_id = self.NODE.ID
next_id = self.NODE.next["id"]
previous_id = self.NODE.previous["id"]
# Error message, ambiguous ID
if request_id == current_id:
ambiguous_id_error()
# Only one node in the network
elif next_id == current_id == previous_id:
self.lookup_response(request_dict)
# Cause the Node is the first in the network
elif current_id < previous_id:
# Request ID is the smallest or biggest ID in the network
if request_id < current_id or request_id > previous_id:
self.lookup_response(request_dict)
# Continue the search in the network
else:
self.lookup_request(self.NODE.next["ip"], request_dict["ip_origem_busca"], request_dict["id_busca"])
# Cause the Node is in the middle of the network
else:
# Request ID is between the current and the previous node
if current_id > request_id > previous_id:
self.lookup_response(request_dict)
# Continue the search in the network
else:
self.lookup_request(self.NODE.next["ip"], request_dict["ip_origem_busca"], request_dict["id_busca"])
def join_request(self, request_dict, ip):
string_dict = {
"codigo": 0,
"id": request_dict["id_origem"],
}
json_dict = json.dumps(string_dict)
encoded_json = json_dict.encode("utf-8")
logging.debug(f"Sent Join Request Message to {ip} - {encoded_json}")
self.SOCKET.sendto(encoded_json, (ip, self.NODE.PORT))
def join_response(self, ip):
response_dict = {
"codigo": 64,
"id_sucessor": self.NODE.ID,
"ip_sucessor": self.NODE.IP,
"id_antecessor": self.NODE.previous["id"],
"ip_antecessor": self.NODE.previous["ip"]
}
json_dict = json.dumps(response_dict)
encoded_json = json_dict.encode("utf-8")
logging.debug(f"Sent Join Response Message to {ip} - {encoded_json}")
self.SOCKET.sendto(encoded_json, (ip, self.NODE.PORT))
def update_request(self, request_dict):
self.NODE.previous.update({"id": request_dict["id_antecessor"], "ip": request_dict["ip_antecessor"]})
self.NODE.next.update({"id": request_dict["id_sucessor"], "ip": request_dict["ip_sucessor"]})
logging.debug(f"Updated Node {self.NODE.IP} - Previous: {self.NODE.previous} and next: {self.NODE.next}")
self.update_previous_request()
self.update_next_request()
def update_previous_request(self):
previous_dict = {
"codigo": 3,
"identificador": self.NODE.ID,
"id_novo_sucessor": self.NODE.ID,
"ip_novo_sucessor": self.NODE.IP
}
json_dict = json.dumps(previous_dict)
encoded_json = json_dict.encode("utf-8")
logging.debug(f"Sent Update Previous Request Message to {self.NODE.previous} - {encoded_json}")
self.SOCKET.sendto(encoded_json, (self.NODE.previous["ip"], self.NODE.PORT))
def update_next_request(self):
next_dict = {
"codigo": 3,
"identificador": self.NODE.ID,
"id_novo_antecessor": self.NODE.ID,
"ip_novo_antecessor": self.NODE.IP
}
json_dict = json.dumps(next_dict)
encoded_json = json_dict.encode("utf-8")
logging.debug(f"Sent Update Next Request Message to {self.NODE.next} - {encoded_json}")
self.SOCKET.sendto(encoded_json, (self.NODE.next["ip"], self.NODE.PORT))
def update_control(self, request_dict, ip_to_send):
if "id_novo_antecessor" in request_dict:
self.NODE.previous.update({"id": request_dict["id_novo_antecessor"],
"ip": request_dict["ip_novo_antecessor"]})
logging.debug(f"Updated Node {self.NODE.IP} - Previous: {self.NODE.previous}")
elif "id_novo_sucessor" in request_dict:
self.NODE.next.update({"id": request_dict["id_novo_sucessor"], "ip": request_dict["ip_novo_sucessor"]})
logging.debug(f"Updated Node {self.NODE.IP} - Next: {self.NODE.next}")
self.update_response(ip_to_send)
def update_response(self, ip_to_send):
response_dict = {
"codigo": 67,
"id_origem_mensagem": self.NODE.ID,
}
json_dict = json.dumps(response_dict)
encoded_json = json_dict.encode("utf-8")
logging.debug(f"Sent Update Response Message to {ip_to_send} - {encoded_json}")
self.SOCKET.sendto(encoded_json, (ip_to_send, self.NODE.PORT))
def update_verification(self, request_dict, ip_to_send):
logging.debug(f"Received Update Verification Message in {self.NODE.ID} from {ip_to_send} - {request_dict}")
def node_info(self):
clear_console()
print_lines(50)
print(f"Port: {self.NODE.PORT}")
print(f"IP: {self.NODE.IP}")
print(f"Name: {self.NODE.NAME}")
print(f"ID: {self.NODE.ID}")
print(f"Previous: {self.NODE.previous}")
print(f"Next: {self.NODE.next}")
print_lines(50)
input("Press enter to continue...")
def exit_program(self):
if self.NODE.previous or self.NODE.next != {}:
self.leave_network()
clear_console()
print_lines(50)
print("Exiting...")
print_lines(50)
input("Press enter to continue...")
clear_console()
logging.debug(f"Node {self.NODE.ID} exited")
exit(0)
def clear_console():
os.system('cls' if os.name == 'nt' else 'clear')
def print_lines(lines):
print("-" * lines)
def invalid_option():
clear_console()
print_lines(50)
print("Invalid option!")
print_lines(50)
input("Press enter to continue...")
def ambiguous_id_error():
clear_console()
print_lines(50)
print("Error: Ambiguous ID!")
print_lines(50)
input("Press enter to continue...")
clear_console()
exit(0)
def main():
if len(sys.argv) == 3:
P2P(sys.argv[1], sys.argv[2])
elif len(sys.argv) == 4:
P2P(sys.argv[1], sys.argv[2], sys.argv[3])
else:
clear_console()
print_lines(50)
print("Invalid arguments! Usage: python3 node.py <IP> <NAME> or <IP> <NAME> <ID>")
print_lines(50)
input("Press enter to continue...")
exit(0)
if __name__ == "__main__":
main()