-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.py
More file actions
103 lines (83 loc) · 2.71 KB
/
utils.py
File metadata and controls
103 lines (83 loc) · 2.71 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
import socket
import random
import warnings
import os
from datetime import datetime
from configs import CFG, Config
config = Config.from_json(CFG)
# global variables
used_ports = []
def set_socket(port: int) -> socket.socket:
'''
This function creates a new UDP socket
:param port: port number
:return: A socket object with an unused port number
'''
sock = socket.socket(family=socket.AF_INET, type=socket.SOCK_DGRAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind(('localhost', port))
used_ports.append(port)
return sock
def free_socket(sock: socket.socket):
'''
This function free a socket to be able to be used by others
:param sock: socket
:return:
'''
used_ports.remove(sock.getsockname()[1])
sock.close()
def generate_random_port() -> int:
'''
This function generates a new(unused) random port number
:return: a random integer in range of [1024, 65535]
'''
available_ports = config.constants.AVAILABLE_PORTS_RANGE
rand_port = random.randint(available_ports[0], available_ports[1])
while rand_port in used_ports:
rand_port = random.randint(available_ports[0], available_ports[1])
return rand_port
def parse_command(command: str):
'''
This function parses the input command
:param command: A string which is the input command.
:return: Command parts (mode, filename)
'''
parts = command.split(' ')
try:
if len(parts) == 4:
mode = parts[2]
filename = parts[3]
return mode, filename
elif len(parts) == 3:
mode = parts[2]
filename = ""
return mode, filename
except IndexError:
warnings.warn("INVALID COMMAND ENTERED. TRY ANOTHER!")
return
def log(node_id: int, content: str, is_tracker=False) -> None:
'''
This function is used for logging
:param node_id: Since each node has an individual log file to be written in
:param content: content to be written
:return:
'''
if not os.path.exists(config.directory.logs_dir):
os.makedirs(config.directory.logs_dir)
# time
now = datetime.now()
current_time = now.strftime("%H:%M:%S")
content = f"[{current_time}] {content}\n"
print(content)
if is_tracker:
node_logs_filename = config.directory.logs_dir + '_tracker.log'
else:
node_logs_filename = config.directory.logs_dir + 'node' + str(node_id) + '.log'
if not os.path.exists(node_logs_filename):
with open(node_logs_filename, 'w') as f:
f.write(content)
f.close()
else:
with open(node_logs_filename, 'a') as f:
f.write(content)
f.close()