SystemHistoryModal.tsx 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  1. import { useCallback, useEffect, useMemo, useState } from 'react';
  2. import type { ReactNode } from 'react';
  3. import { useTranslation } from 'react-i18next';
  4. import { Modal, Select, Tabs } from 'antd';
  5. import {
  6. ApiOutlined,
  7. DashboardOutlined,
  8. DatabaseOutlined,
  9. DeploymentUnitOutlined,
  10. GlobalOutlined,
  11. HddOutlined,
  12. LineChartOutlined,
  13. PieChartOutlined,
  14. TeamOutlined,
  15. } from '@ant-design/icons';
  16. import { HttpUtil, SizeFormatter } from '@/utils';
  17. import { Sparkline } from '@/components/viz';
  18. import { useMediaQuery } from '@/hooks/useMediaQuery';
  19. import type { Status } from '@/models/status';
  20. import './SystemHistoryModal.css';
  21. interface SystemHistoryModalProps {
  22. open: boolean;
  23. status: Status;
  24. onClose: () => void;
  25. }
  26. interface MetricDef {
  27. key: string;
  28. tab: string;
  29. tabKey?: string;
  30. title: string;
  31. icon: ReactNode;
  32. valueMax: number | null;
  33. unit: string;
  34. stroke: string;
  35. key2?: string;
  36. stroke2?: string;
  37. name1?: string;
  38. name2?: string;
  39. key3?: string;
  40. stroke3?: string;
  41. name3?: string;
  42. }
  43. const METRICS: MetricDef[] = [
  44. { key: 'cpu', tab: 'CPU', tabKey: 'pages.index.cpu', title: 'pages.index.historyTitleCpu', icon: <DashboardOutlined />, valueMax: 100, unit: '%', stroke: '' },
  45. { key: 'mem', tab: 'RAM', tabKey: 'pages.index.memory', title: 'pages.index.historyTitleMem', icon: <DatabaseOutlined />, valueMax: 100, unit: '%', stroke: '#7c4dff', key2: 'swap', stroke2: '#ffa940', name1: 'pages.index.memory', name2: 'pages.index.swap' },
  46. { key: 'netUp', tab: 'Bandwidth', tabKey: 'pages.index.historyTabBandwidth', title: 'pages.index.historyTitleNetwork', icon: <GlobalOutlined />, valueMax: null, unit: 'B/s', stroke: '#1890ff', key2: 'netDown', stroke2: '#13c2c2', name1: 'Up', name2: 'Down' },
  47. { key: 'pktUp', tab: 'Packets', tabKey: 'pages.index.historyTabPackets', title: 'pages.index.historyTitlePackets', icon: <DeploymentUnitOutlined />, valueMax: null, unit: 'pkt/s', stroke: '#2f54eb', key2: 'pktDown', stroke2: '#36cfc9', name1: 'Up', name2: 'Down' },
  48. { key: 'tcpCount', tab: 'Connections', tabKey: 'pages.index.historyTabConnections', title: 'pages.index.historyTitleConnections', icon: <ApiOutlined />, valueMax: null, unit: '', stroke: '#597ef7', key2: 'udpCount', stroke2: '#73d13d', name1: 'TCP', name2: 'UDP' },
  49. { key: 'diskRead', tab: 'Disk I/O', tabKey: 'pages.index.historyTabDisk', title: 'pages.index.historyTitleDisk', icon: <HddOutlined />, valueMax: null, unit: 'B/s', stroke: '#eb2f96', key2: 'diskWrite', stroke2: '#722ed1', name1: 'Read', name2: 'Write' },
  50. { key: 'diskUsage', tab: 'Disk Usage', tabKey: 'pages.index.historyTabDiskUsage', title: 'pages.index.historyTitleDiskUsage', icon: <PieChartOutlined />, valueMax: 100, unit: '%', stroke: '#13c2c2' },
  51. { key: 'online', tab: 'Online', tabKey: 'pages.index.historyTabOnline', title: 'pages.index.historyTitleOnline', icon: <TeamOutlined />, valueMax: null, unit: '', stroke: '#52c41a' },
  52. { key: 'load1', tab: 'Load', tabKey: 'pages.index.historyTabLoad', title: 'pages.index.historyTitleLoad', icon: <LineChartOutlined />, valueMax: null, unit: '', stroke: '#fa8c16', key2: 'load5', stroke2: '#f5222d', name1: '1m', name2: '5m', key3: 'load15', stroke3: '#a0d911', name3: '15m' },
  53. ];
  54. function unitFormatter(unit: string, activeKey: string): (v: number) => string {
  55. if (unit === 'B/s') {
  56. return (v) => `${SizeFormatter.sizeFormat(Math.max(0, Number(v) || 0)).replace(/\.\d+/, '')}/s`;
  57. }
  58. if (unit === 'pkt/s') {
  59. return (v) => `${Math.round(Math.max(0, Number(v) || 0)).toLocaleString()}/s`;
  60. }
  61. if (unit === '%') {
  62. return (v) => `${Number(v).toFixed(1)}%`;
  63. }
  64. return (v) => {
  65. const n = Number(v) || 0;
  66. if (activeKey === 'online' || activeKey === 'tcpCount' || activeKey === 'udpCount') {
  67. return Math.round(n).toLocaleString();
  68. }
  69. return n.toFixed(2);
  70. };
  71. }
  72. function formatFullTimestamp(unixSec: number): string {
  73. const d = new Date(unixSec * 1000);
  74. const today = new Date();
  75. const sameDay = d.getFullYear() === today.getFullYear()
  76. && d.getMonth() === today.getMonth()
  77. && d.getDate() === today.getDate();
  78. const hh = String(d.getHours()).padStart(2, '0');
  79. const mm = String(d.getMinutes()).padStart(2, '0');
  80. const ss = String(d.getSeconds()).padStart(2, '0');
  81. const time = `${hh}:${mm}:${ss}`;
  82. if (sameDay) return time;
  83. const MM = String(d.getMonth() + 1).padStart(2, '0');
  84. const DD = String(d.getDate()).padStart(2, '0');
  85. return `${MM}-${DD} ${time}`;
  86. }
  87. export default function SystemHistoryModal({ open, status, onClose }: SystemHistoryModalProps) {
  88. const { t } = useTranslation();
  89. const { isMobile } = useMediaQuery();
  90. const [activeKey, setActiveKey] = useState('cpu');
  91. const [bucket, setBucket] = useState(2);
  92. const [points, setPoints] = useState<number[]>([]);
  93. const [points2, setPoints2] = useState<number[]>([]);
  94. const [points3, setPoints3] = useState<number[]>([]);
  95. const [labels, setLabels] = useState<string[]>([]);
  96. const [timestamps, setTimestamps] = useState<number[]>([]);
  97. const activeMetric = useMemo(() => METRICS.find((m) => m.key === activeKey), [activeKey]);
  98. const trName = (n?: string) => (n && n.startsWith('pages.') ? t(n) : n);
  99. const strokeColor = activeMetric?.stroke || status?.cpu?.color || '#008771';
  100. const yFormatter = useMemo(
  101. () => unitFormatter(activeMetric?.unit ?? '', activeKey),
  102. [activeMetric, activeKey],
  103. );
  104. const tsLookup = useMemo(() => {
  105. const m = new Map<string, number>();
  106. for (let i = 0; i < labels.length; i++) {
  107. m.set(labels[i], timestamps[i]);
  108. }
  109. return m;
  110. }, [labels, timestamps]);
  111. const tooltipLabelFormatter = useCallback(
  112. (label: string) => {
  113. const ts = tsLookup.get(label);
  114. return ts ? formatFullTimestamp(ts) : label;
  115. },
  116. [tsLookup],
  117. );
  118. const fetchBucket = useCallback(async () => {
  119. if (!activeMetric) return;
  120. try {
  121. const url = `/panel/api/server/history/${activeMetric.key}/${bucket}`;
  122. const msg = await HttpUtil.get(url);
  123. if (msg?.success && Array.isArray(msg.obj)) {
  124. const vals: number[] = [];
  125. const labs: string[] = [];
  126. const tss: number[] = [];
  127. for (const p of msg.obj) {
  128. const d = new Date(p.t * 1000);
  129. const hh = String(d.getHours()).padStart(2, '0');
  130. const mm = String(d.getMinutes()).padStart(2, '0');
  131. const ss = String(d.getSeconds()).padStart(2, '0');
  132. labs.push(bucket >= 60 ? `${hh}:${mm}` : `${hh}:${mm}:${ss}`);
  133. vals.push(Number(p.v) || 0);
  134. tss.push(Number(p.t) || 0);
  135. }
  136. setLabels(labs);
  137. setPoints(vals);
  138. setTimestamps(tss);
  139. const fetchAligned = async (key?: string): Promise<number[]> => {
  140. if (!key) return [];
  141. const m = await HttpUtil.get(`/panel/api/server/history/${key}/${bucket}`);
  142. if (m?.success && Array.isArray(m.obj)) {
  143. const byTs = new Map<number, number>();
  144. for (const p of m.obj) byTs.set(Number(p.t) || 0, Number(p.v) || 0);
  145. return tss.map((ts) => byTs.get(ts) ?? 0);
  146. }
  147. return [];
  148. };
  149. setPoints2(await fetchAligned(activeMetric.key2));
  150. setPoints3(await fetchAligned(activeMetric.key3));
  151. } else {
  152. setLabels([]);
  153. setPoints([]);
  154. setPoints2([]);
  155. setPoints3([]);
  156. setTimestamps([]);
  157. }
  158. } catch (e) {
  159. console.error('Failed to fetch history bucket', e);
  160. setLabels([]);
  161. setPoints([]);
  162. setPoints2([]);
  163. setPoints3([]);
  164. setTimestamps([]);
  165. }
  166. }, [activeMetric, bucket]);
  167. useEffect(() => {
  168. if (open) setActiveKey('cpu');
  169. }, [open]);
  170. useEffect(() => {
  171. if (open) fetchBucket();
  172. }, [open, activeKey, bucket, fetchBucket]);
  173. useEffect(() => {
  174. if (!open) return undefined;
  175. const ms = bucket <= 30 ? 2000 : 10000;
  176. const id = window.setInterval(() => fetchBucket(), ms);
  177. return () => window.clearInterval(id);
  178. }, [open, bucket, fetchBucket]);
  179. return (
  180. <Modal
  181. open={open}
  182. footer={null}
  183. width={isMobile ? '95vw' : 900}
  184. onCancel={onClose}
  185. title={
  186. <div className="metric-modal-title">
  187. <span>{t('pages.index.systemHistoryTitle')}</span>
  188. <Select
  189. value={bucket}
  190. size="small"
  191. className="bucket-select"
  192. onChange={setBucket}
  193. options={[
  194. { value: 2, label: '2m' },
  195. { value: 30, label: '30m' },
  196. { value: 60, label: '1h' },
  197. { value: 120, label: '2h' },
  198. { value: 180, label: '3h' },
  199. { value: 300, label: '5h' },
  200. ]}
  201. />
  202. </div>
  203. }
  204. >
  205. <Tabs
  206. activeKey={activeKey}
  207. onChange={setActiveKey}
  208. size="small"
  209. className="history-tabs"
  210. items={METRICS.map((m) => {
  211. const tabLabel = m.tabKey ? t(m.tabKey) : m.tab;
  212. return {
  213. key: m.key,
  214. label: isMobile ? <span title={tabLabel} aria-label={tabLabel}>{m.icon}</span> : tabLabel,
  215. };
  216. })}
  217. />
  218. <div className="cpu-chart-wrap">
  219. {activeMetric?.title && <div className="history-chart-title">{t(activeMetric.title)}</div>}
  220. <Sparkline
  221. data={points}
  222. data2={activeMetric?.key2 ? points2 : undefined}
  223. data3={activeMetric?.key3 ? points3 : undefined}
  224. stroke2={activeMetric?.stroke2}
  225. stroke3={activeMetric?.stroke3}
  226. name1={trName(activeMetric?.name1)}
  227. name2={trName(activeMetric?.name2)}
  228. name3={trName(activeMetric?.name3)}
  229. labels={labels}
  230. height={260}
  231. stroke={strokeColor}
  232. strokeWidth={2.2}
  233. showGrid
  234. showAxes
  235. tickCountX={5}
  236. maxPoints={points.length || 1}
  237. fillOpacity={0.18}
  238. markerRadius={3.2}
  239. showTooltip
  240. valueMin={0}
  241. valueMax={activeMetric?.valueMax ?? null}
  242. yFormatter={yFormatter}
  243. tooltipLabelFormatter={tooltipLabelFormatter}
  244. extrema={{ show: !activeMetric?.key2, formatter: yFormatter }}
  245. />
  246. </div>
  247. </Modal>
  248. );
  249. }