entity.py 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  1. # -*- coding: utf-8 -*-
  2. # @Author : YY
  3. from datetime import datetime
  4. import json
  5. import time
  6. import os
  7. import platform
  8. import sys
  9. from flask import current_app
  10. import psutil
  11. from typing import Dict, List
  12. from typing_extensions import Annotated
  13. from pydantic import BaseModel, Field
  14. from ruoyi_common.base.model import strict_base_config
  15. from ruoyi_common.utils import IpUtil
  16. class Cpu(BaseModel):
  17. model_config = strict_base_config
  18. # 核心数
  19. cpu_num: int
  20. # CPU总的使用率
  21. total: float
  22. # CPU系统使用率
  23. sys: float
  24. # CPU用户使用率
  25. used: float
  26. # CPU当前等待率
  27. wait: float
  28. # CPU当前空闲率
  29. free: float
  30. @classmethod
  31. def from_module(cls) -> "Cpu":
  32. """
  33. 获取CPU信息
  34. Returns:
  35. Cpu: CPU信息
  36. """
  37. scputimes = psutil.cpu_times_percent(1)
  38. nice = getattr(scputimes, 'nice', 0)
  39. irq = getattr(scputimes, 'irq', 0)
  40. softirq = getattr(scputimes, 'softirq', 0)
  41. steal = getattr(scputimes, 'steal', 0)
  42. used = getattr(scputimes, 'user', 0)
  43. sys = getattr(scputimes,'system', 0)
  44. wait = getattr(scputimes, 'iowait', 0)
  45. free = getattr(scputimes, 'idle', 0)
  46. total = used + sys + wait + free + nice + irq + softirq + steal
  47. return cls(
  48. cpu_num=psutil.cpu_count(),
  49. total=total,
  50. sys=sys,
  51. used=used,
  52. wait=wait,
  53. free=free
  54. )
  55. class Memory(BaseModel):
  56. model_config = strict_base_config
  57. # 内存总量
  58. total: str
  59. # 已用内存
  60. used: str
  61. # 剩余内存
  62. free: str
  63. @classmethod
  64. def from_module(cls) -> "Memory":
  65. """
  66. 获取内存信息
  67. Returns:
  68. Memory: 内存信息
  69. """
  70. memory = psutil.virtual_memory()
  71. total = cls.bytes_to_gb(memory.total)
  72. used = cls.bytes_to_gb(memory.used)
  73. free = cls.bytes_to_gb(memory.free)
  74. return cls(total=total, used=used, free=free)
  75. @classmethod
  76. def bytes_to_gb(cls, val:int) -> str:
  77. return "{:.2f}".format(val / 1024 / 1024 / 1024)
  78. class Jvm(BaseModel):
  79. model_config = strict_base_config
  80. # 当前JVM占用的内存总数(M)
  81. total: float = 0
  82. # JVM最大可用内存总数(M)
  83. max: float = 0
  84. # JVM空闲内存(M)
  85. free: float = 0
  86. # JDK版本
  87. version: str = ""
  88. # JDK路径
  89. home: str = ""
  90. name: str = "[java示例,非python示例] 请执行 bash patch.sh upgrade",
  91. usage: float = 75.76,
  92. used: float = 1015.63,
  93. start_time: str = "2024-11-11 12:00:50",
  94. input_args: str = "[java示例,非python示例] 请执行 bash patch.sh upgrade"
  95. run_time: str = "2小时12分钟"
  96. class SystemFile(BaseModel):
  97. model_config = strict_base_config
  98. # 盘符路径
  99. dir_name: str
  100. # 盘符类型
  101. sys_type_name: str
  102. # 文件类型
  103. type_name: str
  104. # 总大小
  105. total: str
  106. # 剩余大小
  107. free: str
  108. # 已经使用量
  109. used: str
  110. # 资源的使用率
  111. usage: float
  112. class System(BaseModel):
  113. model_config = strict_base_config
  114. # 服务器名称
  115. computer_name: str
  116. # 服务器IP地址
  117. computer_ip: str
  118. # 项目路径
  119. user_dir: str
  120. # 操作系统
  121. os_name:str
  122. # 系统架构
  123. os_arch:str
  124. @classmethod
  125. def from_module(cls) -> "System":
  126. """
  127. 获取服务器系统信息
  128. Returns:
  129. System: 服务器系统信息
  130. """
  131. computer_name = platform.node()
  132. computer_ip = IpUtil.get_local_ips()[0]
  133. user_dir = current_app.extensions['flaskowl'].proot
  134. os_name = platform.system()
  135. os_arch = platform.machine()
  136. return cls(
  137. computer_name=computer_name,
  138. computer_ip=computer_ip,
  139. user_dir=user_dir,
  140. os_name=os_name,
  141. os_arch=os_arch
  142. )
  143. class PyImplementation(BaseModel):
  144. model_config = strict_base_config
  145. # 当前Python占用的内存总数(MB) ##### 虚拟数据 #####
  146. total: str
  147. # Python最大可用内存总数(MB) ##### 虚拟数据 #####
  148. max: str
  149. # Python空闲内存(MB) ##### 虚拟数据 #####
  150. free: str
  151. # Python解释器名称
  152. name: str = "CPython"
  153. # Python内存使用率 ##### 虚拟数据 #####
  154. usage: str
  155. # Python占用的内存总数 ##### 虚拟数据 #####
  156. used: str
  157. # 启动时间
  158. start_time: str = "",
  159. # 启动参数
  160. input_args: str = ""
  161. # 运行时间
  162. run_time: str = ""
  163. # Python版本
  164. version: str
  165. # Python路径
  166. home: str
  167. @classmethod
  168. def from_module(cls) -> "PyImplementation":
  169. """
  170. 获取当前Python进程信息
  171. Returns:
  172. PyImplementation: Python进程信息
  173. """
  174. proc = psutil.Process(os.getpid())
  175. memory = proc.memory_info()
  176. total = memory.rss
  177. used = total
  178. usage = "30"
  179. name = platform.python_implementation()
  180. if hasattr(proc, 'rlimit'):
  181. max = proc.rlimit(psutil.RLIMIT_AS)
  182. else:
  183. max = 0
  184. version = platform.python_version()
  185. home = sys.executable
  186. start_time = proc.create_time()
  187. run_time = time.time() - start_time
  188. input_args = json.dumps(proc.cmdline())
  189. return cls(
  190. total = cls.bytes_to_mb(total),
  191. max = cls.bytes_to_mb(max),
  192. used = cls.bytes_to_mb(used),
  193. usage = usage,
  194. name = name,
  195. free = cls.bytes_to_mb(total) if max == 0 else cls.bytes_to_mb(max - total),
  196. version=version,
  197. home=home,
  198. start_time=datetime.fromtimestamp(start_time).strftime('%Y-%m-%d %H:%M:%S'),
  199. run_time=datetime.fromtimestamp(run_time).strftime('%H小时 %M分钟 %S秒'),
  200. input_args=input_args
  201. )
  202. @classmethod
  203. def bytes_to_mb(cls, val:int) -> str:
  204. """
  205. 字节转换为MB
  206. Args:
  207. val (int): 输入
  208. Returns:
  209. str: 输出字符串
  210. """
  211. return "{:.2f}".format(val / 1024 / 1024)
  212. class Server(BaseModel):
  213. model_config = strict_base_config
  214. cpu: Cpu
  215. mem: Memory
  216. sys: System
  217. sys_files: List[SystemFile] = []
  218. pyimp: PyImplementation = None
  219. jvm: Jvm = None
  220. @classmethod
  221. def from_module(cls) -> "Server":
  222. """
  223. 获取服务器信息
  224. Returns:
  225. Server: 服务器信息
  226. """
  227. cpu = Cpu.from_module()
  228. mem = Memory.from_module()
  229. sys = System.from_module()
  230. pyimp = PyImplementation.from_module()
  231. jvm = Jvm(
  232. total=1340.5,
  233. max=3579,
  234. free=324.87,
  235. version="[java示例,非python示例] 请执行 bash patch.sh upgrade",
  236. home="[java示例,非python示例 请执行 bash patch.sh upgrade",
  237. name="[java示例,非python示例 请执行 bash patch.sh upgrade",
  238. usage=75.76,
  239. used=1015.63,
  240. start_time="[java示例,非python示例 请执行 bash patch.sh upgrade",
  241. input_args="[java示例,非python示例 请执行 bash patch.sh upgrade",
  242. run_time="[java示例,非python示例 请执行 bash patch.sh upgrade"
  243. )
  244. sys_files = []
  245. for part in psutil.disk_partitions():
  246. if os.name == 'nt':
  247. if 'cdrom' in part.opts or part.fstype == '':
  248. continue
  249. usage = psutil.disk_usage(part.mountpoint)
  250. sys_file = SystemFile(
  251. dirName=part.mountpoint,
  252. sysTypeName=part.fstype,
  253. typeName=part.device,
  254. total=cls.bytes_to_gb(usage.total),
  255. free=cls.bytes_to_gb(usage.free),
  256. used=cls.bytes_to_gb(usage.used),
  257. usage=usage.percent
  258. )
  259. sys_files.append(sys_file)
  260. return cls(cpu=cpu, mem=mem, sys=sys, sys_files=sys_files, pyimp=pyimp, jvm=jvm)
  261. @classmethod
  262. def bytes_to_gb(cls, val:int) -> str:
  263. """
  264. 字节转换为GB
  265. Args:
  266. val (int): 输入
  267. Returns:
  268. str: 输出字符串
  269. """
  270. return "{:.2f}".format(val / 1024 / 1024 / 1024) + " GB"
  271. class RedisCommandStatsOption(BaseModel):
  272. name: str
  273. value: Annotated[str, Field(coerce_numbers_to_str=True)]
  274. class RedisCache(BaseModel):
  275. model_config = strict_base_config
  276. info: Dict = {}
  277. db_size: int
  278. command_stats: List[RedisCommandStatsOption]
  279. @classmethod
  280. def from_connection(cls, connection) -> "RedisCache":
  281. """
  282. 获取Redis缓存信息
  283. Args:
  284. connection (redis.Redis): Redis连接
  285. Returns:
  286. RedisCache: Redis缓存信息
  287. """
  288. info = connection.info()
  289. db_size = connection.dbsize()
  290. _command_stats = connection.info('commandstats')
  291. command_stats = []
  292. for key,value in _command_stats.items():
  293. key = key.replace('cmdstat_', '')
  294. value = value["calls"]
  295. command_stats.append(RedisCommandStatsOption(name=key, value=value))
  296. return cls(info=info, db_size=db_size, command_stats=command_stats)