1import math
2import secrets
3import socket
4from dataclasses import dataclass
5
6import psutil
7
8
9@dataclass
10class MemoryStat:
11 total: int
12 used: int
13 free: int
14
15
16@dataclass
17class CPUStat:
18 cores: int
19 percent: float
20
21
22def cpu_usage() -> CPUStat:
23 return CPUStat(cores=psutil.cpu_count(), percent=psutil.cpu_percent())
24
25
26def memory_usage() -> MemoryStat:
27 mem = psutil.virtual_memory()
28 return MemoryStat(total=mem.total, used=mem.used, free=mem.available)
29
30
31@dataclass
32class RealtimeBandwidth:
33 def __post_init__(self):
34 io = psutil.net_io_counters()
35 self.bytes_recv = io.bytes_recv
36 self.bytes_sent = io.bytes_sent
37 self.packets_recv = io.packets_recv
38 self.packet_sent = io.packets_sent
39
40 incoming_bytes: int
41 outgoing_bytes: int
42 incoming_packets: int
43 outgoing_packets: int
44
45 bytes_recv: int = None
46 bytes_sent: int = None
47 packets_recv: int = None
48 packet_sent: int = None
49
50
51@dataclass
52class RealtimeBandwidthStat:
53 incoming_bytes: int
54 outgoing_bytes: int
55 incoming_packets: int
56 outgoing_packets: int
57
58
59rt_bw = RealtimeBandwidth(
60 incoming_bytes=0, outgoing_bytes=0, incoming_packets=0, outgoing_packets=0
61)
62
63
64def realtime_bandwidth() -> RealtimeBandwidthStat:
65 return RealtimeBandwidthStat(
66 incoming_bytes=rt_bw.incoming_bytes,
67 outgoing_bytes=rt_bw.outgoing_bytes,
68 incoming_packets=rt_bw.incoming_packets,
69 outgoing_packets=rt_bw.outgoing_packets,
70 )
71
72
73def random_password() -> str:
74 return secrets.token_urlsafe(16)
75
76
77def check_port(port: int) -> bool:
78 s = socket.socket()
79 try:
80 s.connect(("127.0.0.1", port))
81 return True
82 except socket.error:
83 return False
84 finally:
85 s.close()
86
87
88def get_public_ip():
89 try:
90 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
91 sock.connect(("8.8.8.8", 80))
92 return sock.getsockname()[0]
93 except (socket.error, IndexError):
94 pass
95 finally:
96 sock.close()
97
98 return "127.0.0.1"
99
100
101def readable_size(size_bytes):
102 if size_bytes == 0:
103 return "0 B"
104 size_name = ("B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB")
105 i = int(math.floor(math.log(size_bytes, 1024)))
106 p = math.pow(1024, i)
107 s = round(size_bytes / p, 2)
108 return f"{s} {size_name[i]}"