mirror of
https://github.com/snowykami/server-status-client.git
synced 2026-01-25 13:11:54 +00:00
Compare commits
7 Commits
7cbca85a60
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| 7ee3eb377e | |||
| 90b4952ea9 | |||
| 0559212d03 | |||
| e74324e21b | |||
| 48ac46bbb3 | |||
| b5ba568a66 | |||
| b30b3429ad |
@@ -8,9 +8,25 @@ import requests
|
|||||||
|
|
||||||
from server_status.timezone import get_timezone
|
from server_status.timezone import get_timezone
|
||||||
|
|
||||||
excluded_partition_prefix = ("/var", "/boot", "/run", "/proc", "/sys", "/dev", "/tmp", "/snap")
|
excluded_partition_prefix = (
|
||||||
|
"/var",
|
||||||
|
"/boot",
|
||||||
|
"/run",
|
||||||
|
"/proc",
|
||||||
|
"/sys",
|
||||||
|
"/dev",
|
||||||
|
"/tmp",
|
||||||
|
"/snap",
|
||||||
|
|
||||||
os_name = "" # linux下为发行版名称,windows下为Windows
|
"/System",
|
||||||
|
"/Applications",
|
||||||
|
"/private",
|
||||||
|
"/Library",
|
||||||
|
)
|
||||||
|
|
||||||
|
include_partition_prefix_mac = ("/Volumes")
|
||||||
|
|
||||||
|
os_name = "" # linux下为发行版名称,windows下为Windows, macOS下为Darwin
|
||||||
os_version = "" # linux下为发行版版本,windows下为Windows版本
|
os_version = "" # linux下为发行版版本,windows下为Windows版本
|
||||||
try:
|
try:
|
||||||
# read /etc/os-release
|
# read /etc/os-release
|
||||||
@@ -19,9 +35,9 @@ try:
|
|||||||
# 找到NAME=和VERSION=的行
|
# 找到NAME=和VERSION=的行
|
||||||
for line in os_release.split("\n"):
|
for line in os_release.split("\n"):
|
||||||
if line.startswith("NAME="):
|
if line.startswith("NAME="):
|
||||||
os_name = line.split("=")[1].replace('"', '')
|
os_name = line.split("=")[1].replace('"', "")
|
||||||
elif line.startswith("VERSION_ID="):
|
elif line.startswith("VERSION_ID="):
|
||||||
os_version = line.split("=")[1].replace('"', '')
|
os_version = line.split("=")[1].replace('"', "")
|
||||||
except FileNotFoundError:
|
except FileNotFoundError:
|
||||||
os_name = platform.system()
|
os_name = platform.system()
|
||||||
os_version = platform.release()
|
os_version = platform.release()
|
||||||
@@ -131,7 +147,9 @@ class Api:
|
|||||||
"""
|
"""
|
||||||
self.headers.update(self.format(headers))
|
self.headers.update(self.format(headers))
|
||||||
|
|
||||||
def format(self, obj: str | list[str] | dict[str, Any]) -> str | list[str] | dict[str, Any]:
|
def format(
|
||||||
|
self, obj: str | list[str] | dict[str, Any]
|
||||||
|
) -> str | list[str] | dict[str, Any]:
|
||||||
if isinstance(obj, str):
|
if isinstance(obj, str):
|
||||||
obj = obj.format(**self.variables)
|
obj = obj.format(**self.variables)
|
||||||
elif isinstance(obj, dict):
|
elif isinstance(obj, dict):
|
||||||
@@ -144,8 +162,17 @@ class Api:
|
|||||||
|
|
||||||
|
|
||||||
class Client:
|
class Client:
|
||||||
def __init__(self, addr: str, token: str, client_id: str, name: str = "", location: str = "", labels: list[str] = [], link: str = "",
|
def __init__(
|
||||||
interval: int = 2):
|
self,
|
||||||
|
addr: str,
|
||||||
|
token: str,
|
||||||
|
client_id: str,
|
||||||
|
name: str = "",
|
||||||
|
location: str = "",
|
||||||
|
labels: list[str] = [],
|
||||||
|
link: str = "",
|
||||||
|
interval: int = 2,
|
||||||
|
):
|
||||||
self.api = Api(addr, {"token": token, "id": client_id})
|
self.api = Api(addr, {"token": token, "id": client_id})
|
||||||
self.api = self.api.group("/client")
|
self.api = self.api.group("/client")
|
||||||
self.api.add_headers(Authorization="{token}")
|
self.api.add_headers(Authorization="{token}")
|
||||||
@@ -159,15 +186,66 @@ class Client:
|
|||||||
self.link = link
|
self.link = link
|
||||||
self.interval = interval
|
self.interval = interval
|
||||||
|
|
||||||
self.start_time = psutil.boot_time()
|
self.start_time: float = psutil.boot_time()
|
||||||
|
|
||||||
self.hardware = Hardware()
|
self.hardware = Hardware()
|
||||||
|
|
||||||
log("Client initialized",
|
log(
|
||||||
f"Name: {self.name}({self.client_id}), Location: {self.location}, Labels: {self.labels}")
|
"Client initialized",
|
||||||
|
f"Name: {self.name}({self.client_id}), Location: {self.location}, Labels: {self.labels}",
|
||||||
|
)
|
||||||
|
|
||||||
def start(self):
|
def start(self):
|
||||||
self.observe()
|
log("Starting client")
|
||||||
|
threading.Thread(target=self._start_obs, daemon=True).start()
|
||||||
|
threading.Thread(target=self._start_post, daemon=True).start()
|
||||||
|
|
||||||
|
while True:
|
||||||
|
time.sleep(1)
|
||||||
|
|
||||||
|
def _start_obs(self):
|
||||||
|
"""启动监控记录线程"""
|
||||||
|
while True:
|
||||||
|
try:
|
||||||
|
self.hardware.mem_total = psutil.virtual_memory().total
|
||||||
|
self.hardware.mem_used = psutil.virtual_memory().used
|
||||||
|
self.hardware.swap_total = psutil.swap_memory().total
|
||||||
|
self.hardware.swap_used = psutil.swap_memory().used
|
||||||
|
self.hardware.cpu_cores = psutil.cpu_count(logical=False)
|
||||||
|
self.hardware.cpu_logics = psutil.cpu_count(logical=True)
|
||||||
|
for part in psutil.disk_partitions():
|
||||||
|
try:
|
||||||
|
usage = psutil.disk_usage(part.mountpoint)
|
||||||
|
|
||||||
|
if (
|
||||||
|
(
|
||||||
|
platform.system() in ("Linux", "Darwin")
|
||||||
|
and (
|
||||||
|
part.mountpoint.startswith(
|
||||||
|
excluded_partition_prefix
|
||||||
|
)
|
||||||
|
)
|
||||||
|
)
|
||||||
|
):
|
||||||
|
continue
|
||||||
|
|
||||||
|
self.hardware.disks[part.device] = {
|
||||||
|
"mountpoint": part.mountpoint,
|
||||||
|
"device": part.device,
|
||||||
|
"fstype": part.fstype,
|
||||||
|
"total": usage.total,
|
||||||
|
"used": usage.used,
|
||||||
|
}
|
||||||
|
except:
|
||||||
|
pass
|
||||||
|
self.hardware.cpu_percent = psutil.cpu_percent(1)
|
||||||
|
self.hardware.net_up, self.hardware.net_down = get_network_speed(1)
|
||||||
|
log("Observed")
|
||||||
|
except Exception as e:
|
||||||
|
log(f"Failed to observe: {e}")
|
||||||
|
|
||||||
|
def _start_post(self):
|
||||||
|
"""启动上报进程"""
|
||||||
while True:
|
while True:
|
||||||
try:
|
try:
|
||||||
resp = self.get_ping()
|
resp = self.get_ping()
|
||||||
@@ -175,9 +253,13 @@ class Client:
|
|||||||
log(f"Connected to server {self.addr}")
|
log(f"Connected to server {self.addr}")
|
||||||
break
|
break
|
||||||
else:
|
else:
|
||||||
log(f"Failed to connect to server {self.addr}, retrying in 5 seconds: {resp.text}")
|
log(
|
||||||
|
f"Failed to connect to server {self.addr}, retrying in 5 seconds: {resp.text}"
|
||||||
|
)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
log(f"Failed to connect to server {self.addr}, retrying in 5 seconds: {e}")
|
log(
|
||||||
|
f"Failed to connect to server {self.addr}, retrying in 5 seconds: {e}"
|
||||||
|
)
|
||||||
time.sleep(5)
|
time.sleep(5)
|
||||||
|
|
||||||
while True:
|
while True:
|
||||||
@@ -205,7 +287,8 @@ class Client:
|
|||||||
"name": self.name,
|
"name": self.name,
|
||||||
"os": {
|
"os": {
|
||||||
"name": platform.system(), # 系统类型 linux|windows|darwin
|
"name": platform.system(), # 系统类型 linux|windows|darwin
|
||||||
"version": os_name + os_version, # 系统版本复杂描述 #1 SMP PREEMPT_DYNAMIC Fri Sep 13 10:42:50 UTC 2024 (5c05eeb)
|
"version": os_name + os_version,
|
||||||
|
# 系统版本复杂描述 #1 SMP PREEMPT_DYNAMIC Fri Sep 13 10:42:50 UTC 2024 (5c05eeb)
|
||||||
"machine": platform.machine(), # 机器类型 x86_64
|
"machine": platform.machine(), # 机器类型 x86_64
|
||||||
"release": os_version, # 系统版本
|
"release": os_version, # 系统版本
|
||||||
},
|
},
|
||||||
@@ -240,42 +323,5 @@ class Client:
|
|||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
def observe(self):
|
|
||||||
"""
|
|
||||||
观察硬件状态并更新
|
|
||||||
Returns:
|
|
||||||
|
|
||||||
"""
|
|
||||||
|
|
||||||
def _observe():
|
|
||||||
while True:
|
|
||||||
self.hardware.mem_total = psutil.virtual_memory().total
|
|
||||||
self.hardware.mem_used = psutil.virtual_memory().used
|
|
||||||
self.hardware.swap_total = psutil.swap_memory().total
|
|
||||||
self.hardware.swap_used = psutil.swap_memory().used
|
|
||||||
self.hardware.cpu_cores = psutil.cpu_count(logical=False)
|
|
||||||
self.hardware.cpu_logics = psutil.cpu_count(logical=True)
|
|
||||||
for part in psutil.disk_partitions():
|
|
||||||
try:
|
|
||||||
usage = psutil.disk_usage(part.mountpoint)
|
|
||||||
|
|
||||||
if part.mountpoint.startswith(excluded_partition_prefix) or usage.total == 0:
|
|
||||||
continue
|
|
||||||
|
|
||||||
self.hardware.disks[part.device] = {
|
|
||||||
"mountpoint": part.mountpoint,
|
|
||||||
"device": part.device,
|
|
||||||
"fstype": part.fstype,
|
|
||||||
"total": usage.total,
|
|
||||||
"used": usage.used,
|
|
||||||
}
|
|
||||||
except:
|
|
||||||
pass
|
|
||||||
self.hardware.cpu_percent = psutil.cpu_percent(1)
|
|
||||||
self.hardware.net_up, self.hardware.net_down = get_network_speed(1)
|
|
||||||
log("Observed")
|
|
||||||
|
|
||||||
threading.Thread(target=_observe, daemon=True).start()
|
|
||||||
|
|
||||||
def remove(self, client_id) -> requests.Response:
|
def remove(self, client_id) -> requests.Response:
|
||||||
return self.api.delete("/host", data={"id": client_id})
|
return self.api.delete("/host", data={"id": client_id})
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ import socket
|
|||||||
|
|
||||||
from arclet.alconna import Alconna, Subcommand, Option, Args, MultiVar
|
from arclet.alconna import Alconna, Subcommand, Option, Args, MultiVar
|
||||||
|
|
||||||
server_status_alc = Alconna(
|
server_status_alc = Alconna( # type: ignore
|
||||||
"server_status",
|
"server_status",
|
||||||
Args["server", str]["token", str]["id", str],
|
Args["server", str]["token", str]["id", str],
|
||||||
Subcommand(
|
Subcommand(
|
||||||
|
|||||||
Reference in New Issue
Block a user