gitscope
← marzneshin / v0.2.0 / app/utils/system.py
https://dev.kronoz.win/r/marzneshin.git
app/utils/system.py · Python
Blame Raw
  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
 63def realtime_bandwidth() -> RealtimeBandwidthStat:
 64    return RealtimeBandwidthStat(
 65        incoming_bytes=rt_bw.incoming_bytes, outgoing_bytes=rt_bw.outgoing_bytes,
 66        incoming_packets=rt_bw.incoming_packets, outgoing_packets=rt_bw.outgoing_packets)
 67
 68
 69def random_password() -> str:
 70    return secrets.token_urlsafe(16)
 71
 72
 73def check_port(port: int) -> bool:
 74    s = socket.socket()
 75    try:
 76        s.connect(('127.0.0.1', port))
 77        return True
 78    except socket.error:
 79        return False
 80    finally:
 81        s.close()
 82
 83
 84def get_public_ip():
 85    try:
 86        sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
 87        sock.connect(('8.8.8.8', 80))
 88        return sock.getsockname()[0]
 89    except (socket.error, IndexError):
 90        pass
 91    finally:
 92        sock.close()
 93
 94    return '127.0.0.1'
 95
 96
 97def readable_size(size_bytes):
 98    if size_bytes == 0:
 99        return "0 B"
100    size_name = ("B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB")
101    i = int(math.floor(math.log(size_bytes, 1024)))
102    p = math.pow(1024, i)
103    s = round(size_bytes / p, 2)
104    return f'{s} {size_name[i]}'