Skip to content

Commit bc5d142

Browse files
authored
Optimize the server information retrieval (#595)
* Optimize the server information retrieval * Update import * Fix typing
1 parent 9b3425d commit bc5d142

File tree

1 file changed

+60
-43
lines changed

1 file changed

+60
-43
lines changed

backend/utils/server_info.py

+60-43
Original file line numberDiff line numberDiff line change
@@ -61,55 +61,62 @@ def fmt_timedelta(td: timedelta) -> str:
6161
:param td: 时间差对象
6262
:return:
6363
"""
64-
total_seconds = round(td.total_seconds())
65-
return ServerInfo.fmt_seconds(total_seconds)
64+
return ServerInfo.fmt_seconds(round(td.total_seconds()))
6665

6766
@staticmethod
6867
def get_cpu_info() -> dict[str, float | int]:
6968
"""获取 CPU 信息"""
70-
cpu_info = {'usage': round(psutil.cpu_percent(percpu=False), 2)} # %
69+
cpu_info = {
70+
'usage': round(psutil.cpu_percent(interval=0.1), 2), # %
71+
'logical_num': psutil.cpu_count(logical=True) or 0,
72+
'physical_num': psutil.cpu_count(logical=False) or 0,
73+
'max_freq': 0.0,
74+
'min_freq': 0.0,
75+
'current_freq': 0.0,
76+
}
7177

7278
try:
73-
# CPU 频率信息,最大、最小和当前频率
74-
cpu_freq = psutil.cpu_freq()
75-
cpu_info.update({
76-
'max_freq': round(cpu_freq.max, 2), # MHz
77-
'min_freq': round(cpu_freq.min, 2), # MHz
78-
'current_freq': round(cpu_freq.current, 2), # MHz
79-
})
79+
if hasattr(psutil, 'cpu_freq'):
80+
cpu_freq = psutil.cpu_freq()
81+
if cpu_freq: # Some systems return None
82+
cpu_info.update({
83+
'max_freq': round(cpu_freq.max, 2),
84+
'min_freq': round(cpu_freq.min, 2),
85+
'current_freq': round(cpu_freq.current, 2),
86+
})
8087
except Exception:
81-
cpu_info.update({'max_freq': 0, 'min_freq': 0, 'current_freq': 0})
88+
pass
8289

83-
# CPU 逻辑核心数,物理核心数
84-
cpu_info.update({
85-
'logical_num': psutil.cpu_count(logical=True),
86-
'physical_num': psutil.cpu_count(logical=False),
87-
})
8890
return cpu_info
8991

9092
@staticmethod
9193
def get_mem_info() -> dict[str, float]:
9294
"""获取内存信息"""
9395
mem = psutil.virtual_memory()
96+
gb_factor = 1024**3
9497
return {
95-
'total': round(mem.total / 1024 / 1024 / 1024, 2), # GB
96-
'used': round(mem.used / 1024 / 1024 / 1024, 2), # GB
97-
'free': round(mem.available / 1024 / 1024 / 1024, 2), # GB
98-
'usage': round(mem.percent, 2), # %
98+
'total': round(mem.total / gb_factor, 2),
99+
'used': round(mem.used / gb_factor, 2),
100+
'free': round(mem.available / gb_factor, 2),
101+
'usage': round(mem.percent, 2),
99102
}
100103

101104
@staticmethod
102105
def get_sys_info() -> dict[str, str]:
103106
"""获取服务器信息"""
107+
hostname = socket.gethostname()
108+
ip = '127.0.0.1'
109+
104110
try:
105-
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as sk:
106-
sk.connect(('8.8.8.8', 80))
107-
ip = sk.getsockname()[0]
108-
except socket.gaierror:
109-
ip = '127.0.0.1'
111+
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
112+
s.settimeout(0.5)
113+
s.connect(('8.8.8.8', 80))
114+
ip = s.getsockname()[0]
115+
except (socket.gaierror, socket.timeout, OSError):
116+
pass
110117

111118
return {
112-
'name': socket.gethostname(),
119+
'name': hostname,
113120
'ip': ip,
114121
'os': platform.system(),
115122
'arch': platform.machine(),
@@ -119,36 +126,46 @@ def get_sys_info() -> dict[str, str]:
119126
def get_disk_info() -> list[dict[str, str]]:
120127
"""获取磁盘信息"""
121128
disk_info = []
122-
for disk in psutil.disk_partitions():
123-
usage = psutil.disk_usage(disk.mountpoint)
124-
disk_info.append({
125-
'dir': disk.mountpoint,
126-
'type': disk.fstype,
127-
'device': disk.device,
128-
'total': ServerInfo.format_bytes(usage.total),
129-
'free': ServerInfo.format_bytes(usage.free),
130-
'used': ServerInfo.format_bytes(usage.used),
131-
'usage': f'{round(usage.percent, 2)} %',
132-
})
129+
for partition in psutil.disk_partitions(all=False):
130+
try:
131+
usage = psutil.disk_usage(partition.mountpoint)
132+
disk_info.append({
133+
'dir': partition.mountpoint,
134+
'type': partition.fstype,
135+
'device': partition.device,
136+
'total': ServerInfo.format_bytes(usage.total),
137+
'free': ServerInfo.format_bytes(usage.free),
138+
'used': ServerInfo.format_bytes(usage.used),
139+
'usage': f'{usage.percent:.2f}%',
140+
})
141+
except (PermissionError, psutil.AccessDenied):
142+
continue
133143
return disk_info
134144

135145
@staticmethod
136146
def get_service_info() -> dict[str, str | datetime]:
137147
"""获取服务信息"""
138148
process = psutil.Process(os.getpid())
139149
mem_info = process.memory_info()
140-
start_time = timezone.f_datetime(datetime.utcfromtimestamp(process.create_time()).replace(tzinfo=tz.utc))
150+
151+
try:
152+
create_time = datetime.fromtimestamp(process.create_time(), tz=tz.utc)
153+
start_time = timezone.f_datetime(create_time)
154+
except (psutil.NoSuchProcess, OSError):
155+
start_time = timezone.now()
156+
157+
elapsed = ServerInfo.fmt_timedelta(timezone.now() - start_time)
141158

142159
return {
143160
'name': 'Python3',
144161
'version': platform.python_version(),
145162
'home': sys.executable,
146-
'cpu_usage': f'{round(process.cpu_percent(interval=1), 2)} %',
147-
'mem_vms': ServerInfo.format_bytes(mem_info.vms), # 虚拟内存, 即当前进程申请的虚拟内存
148-
'mem_rss': ServerInfo.format_bytes(mem_info.rss), # 常驻内存, 即当前进程实际使用的物理内存
149-
'mem_free': ServerInfo.format_bytes(mem_info.vms - mem_info.rss), # 空闲内存
163+
'cpu_usage': f'{process.cpu_percent(interval=0.1):.2f}%',
164+
'mem_vms': ServerInfo.format_bytes(mem_info.vms),
165+
'mem_rss': ServerInfo.format_bytes(mem_info.rss),
166+
'mem_free': ServerInfo.format_bytes(mem_info.vms - mem_info.rss),
150167
'startup': start_time,
151-
'elapsed': ServerInfo.fmt_timedelta(timezone.now() - start_time),
168+
'elapsed': elapsed,
152169
}
153170

154171

0 commit comments

Comments
 (0)